sqlite3.c 5.2 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277982789827998280982819828298283982849828598286982879828898289982909829198292982939829498295982969829798298982999830098301983029830398304983059830698307983089830998310983119831298313983149831598316983179831898319983209832198322983239832498325983269832798328983299833098331983329833398334983359833698337983389833998340983419834298343983449834598346983479834898349983509835198352983539835498355983569835798358983599836098361983629836398364983659836698367983689836998370983719837298373983749837598376983779837898379983809838198382983839838498385983869838798388983899839098391983929839398394983959839698397983989839998400984019840298403984049840598406984079840898409984109841198412984139841498415984169841798418984199842098421984229842398424984259842698427984289842998430984319843298433984349843598436984379843898439984409844198442984439844498445984469844798448984499845098451984529845398454984559845698457984589845998460984619846298463984649846598466984679846898469984709847198472984739847498475984769847798478984799848098481984829848398484984859848698487984889848998490984919849298493984949849598496984979849898499985009850198502985039850498505985069850798508985099851098511985129851398514985159851698517985189851998520985219852298523985249852598526985279852898529985309853198532985339853498535985369853798538985399854098541985429854398544985459854698547985489854998550985519855298553985549855598556985579855898559985609856198562985639856498565985669856798568985699857098571985729857398574985759857698577985789857998580985819858298583985849858598586985879858898589985909859198592985939859498595985969859798598985999860098601986029860398604986059860698607986089860998610986119861298613986149861598616986179861898619986209862198622986239862498625986269862798628986299863098631986329863398634986359863698637986389863998640986419864298643986449864598646986479864898649986509865198652986539865498655986569865798658986599866098661986629866398664986659866698667986689866998670986719867298673986749867598676986779867898679986809868198682986839868498685986869868798688986899869098691986929869398694986959869698697986989869998700987019870298703987049870598706987079870898709987109871198712987139871498715987169871798718987199872098721987229872398724987259872698727987289872998730987319873298733987349873598736987379873898739987409874198742987439874498745987469874798748987499875098751987529875398754987559875698757987589875998760987619876298763987649876598766987679876898769987709877198772987739877498775987769877798778987799878098781987829878398784987859878698787987889878998790987919879298793987949879598796987979879898799988009880198802988039880498805988069880798808988099881098811988129881398814988159881698817988189881998820988219882298823988249882598826988279882898829988309883198832988339883498835988369883798838988399884098841988429884398844988459884698847988489884998850988519885298853988549885598856988579885898859988609886198862988639886498865988669886798868988699887098871988729887398874988759887698877988789887998880988819888298883988849888598886988879888898889988909889198892988939889498895988969889798898988999890098901989029890398904989059890698907989089890998910989119891298913989149891598916989179891898919989209892198922989239892498925989269892798928989299893098931989329893398934989359893698937989389893998940989419894298943989449894598946989479894898949989509895198952989539895498955989569895798958989599896098961989629896398964989659896698967989689896998970989719897298973989749897598976989779897898979989809898198982989839898498985989869898798988989899899098991989929899398994989959899698997989989899999000990019900299003990049900599006990079900899009990109901199012990139901499015990169901799018990199902099021990229902399024990259902699027990289902999030990319903299033990349903599036990379903899039990409904199042990439904499045990469904799048990499905099051990529905399054990559905699057990589905999060990619906299063990649906599066990679906899069990709907199072990739907499075990769907799078990799908099081990829908399084990859908699087990889908999090990919909299093990949909599096990979909899099991009910199102991039910499105991069910799108991099911099111991129911399114991159911699117991189911999120991219912299123991249912599126991279912899129991309913199132991339913499135991369913799138991399914099141991429914399144991459914699147991489914999150991519915299153991549915599156991579915899159991609916199162991639916499165991669916799168991699917099171991729917399174991759917699177991789917999180991819918299183991849918599186991879918899189991909919199192991939919499195991969919799198991999920099201992029920399204992059920699207992089920999210992119921299213992149921599216992179921899219992209922199222992239922499225992269922799228992299923099231992329923399234992359923699237992389923999240992419924299243992449924599246992479924899249992509925199252992539925499255992569925799258992599926099261992629926399264992659926699267992689926999270992719927299273992749927599276992779927899279992809928199282992839928499285992869928799288992899929099291992929929399294992959929699297992989929999300993019930299303993049930599306993079930899309993109931199312993139931499315993169931799318993199932099321993229932399324993259932699327993289932999330993319933299333993349933599336993379933899339993409934199342993439934499345993469934799348993499935099351993529935399354993559935699357993589935999360993619936299363993649936599366993679936899369993709937199372993739937499375993769937799378993799938099381993829938399384993859938699387993889938999390993919939299393993949939599396993979939899399994009940199402994039940499405994069940799408994099941099411994129941399414994159941699417994189941999420994219942299423994249942599426994279942899429994309943199432994339943499435994369943799438994399944099441994429944399444994459944699447994489944999450994519945299453994549945599456994579945899459994609946199462994639946499465994669946799468994699947099471994729947399474994759947699477994789947999480994819948299483994849948599486994879948899489994909949199492994939949499495994969949799498994999950099501995029950399504995059950699507995089950999510995119951299513995149951599516995179951899519995209952199522995239952499525995269952799528995299953099531995329953399534995359953699537995389953999540995419954299543995449954599546995479954899549995509955199552995539955499555995569955799558995599956099561995629956399564995659956699567995689956999570995719957299573995749957599576995779957899579995809958199582995839958499585995869958799588995899959099591995929959399594995959959699597995989959999600996019960299603996049960599606996079960899609996109961199612996139961499615996169961799618996199962099621996229962399624996259962699627996289962999630996319963299633996349963599636996379963899639996409964199642996439964499645996469964799648996499965099651996529965399654996559965699657996589965999660996619966299663996649966599666996679966899669996709967199672996739967499675996769967799678996799968099681996829968399684996859968699687996889968999690996919969299693996949969599696996979969899699997009970199702997039970499705997069970799708997099971099711997129971399714997159971699717997189971999720997219972299723997249972599726997279972899729997309973199732997339973499735997369973799738997399974099741997429974399744997459974699747997489974999750997519975299753997549975599756997579975899759997609976199762997639976499765997669976799768997699977099771997729977399774997759977699777997789977999780997819978299783997849978599786997879978899789997909979199792997939979499795997969979799798997999980099801998029980399804998059980699807998089980999810998119981299813998149981599816998179981899819998209982199822998239982499825998269982799828998299983099831998329983399834998359983699837998389983999840998419984299843998449984599846998479984899849998509985199852998539985499855998569985799858998599986099861998629986399864998659986699867998689986999870998719987299873998749987599876998779987899879998809988199882998839988499885998869988799888998899989099891998929989399894998959989699897998989989999900999019990299903999049990599906999079990899909999109991199912999139991499915999169991799918999199992099921999229992399924999259992699927999289992999930999319993299933999349993599936999379993899939999409994199942999439994499945999469994799948999499995099951999529995399954999559995699957999589995999960999619996299963999649996599966999679996899969999709997199972999739997499975999769997799978999799998099981999829998399984999859998699987999889998999990999919999299993999949999599996999979999899999100000100001100002100003100004100005100006100007100008100009100010100011100012100013100014100015100016100017100018100019100020100021100022100023100024100025100026100027100028100029100030100031100032100033100034100035100036100037100038100039100040100041100042100043100044100045100046100047100048100049100050100051100052100053100054100055100056100057100058100059100060100061100062100063100064100065100066100067100068100069100070100071100072100073100074100075100076100077100078100079100080100081100082100083100084100085100086100087100088100089100090100091100092100093100094100095100096100097100098100099100100100101100102100103100104100105100106100107100108100109100110100111100112100113100114100115100116100117100118100119100120100121100122100123100124100125100126100127100128100129100130100131100132100133100134100135100136100137100138100139100140100141100142100143100144100145100146100147100148100149100150100151100152100153100154100155100156100157100158100159100160100161100162100163100164100165100166100167100168100169100170100171100172100173100174100175100176100177100178100179100180100181100182100183100184100185100186100187100188100189100190100191100192100193100194100195100196100197100198100199100200100201100202100203100204100205100206100207100208100209100210100211100212100213100214100215100216100217100218100219100220100221100222100223100224100225100226100227100228100229100230100231100232100233100234100235100236100237100238100239100240100241100242100243100244100245100246100247100248100249100250100251100252100253100254100255100256100257100258100259100260100261100262100263100264100265100266100267100268100269100270100271100272100273100274100275100276100277100278100279100280100281100282100283100284100285100286100287100288100289100290100291100292100293100294100295100296100297100298100299100300100301100302100303100304100305100306100307100308100309100310100311100312100313100314100315100316100317100318100319100320100321100322100323100324100325100326100327100328100329100330100331100332100333100334100335100336100337100338100339100340100341100342100343100344100345100346100347100348100349100350100351100352100353100354100355100356100357100358100359100360100361100362100363100364100365100366100367100368100369100370100371100372100373100374100375100376100377100378100379100380100381100382100383100384100385100386100387100388100389100390100391100392100393100394100395100396100397100398100399100400100401100402100403100404100405100406100407100408100409100410100411100412100413100414100415100416100417100418100419100420100421100422100423100424100425100426100427100428100429100430100431100432100433100434100435100436100437100438100439100440100441100442100443100444100445100446100447100448100449100450100451100452100453100454100455100456100457100458100459100460100461100462100463100464100465100466100467100468100469100470100471100472100473100474100475100476100477100478100479100480100481100482100483100484100485100486100487100488100489100490100491100492100493100494100495100496100497100498100499100500100501100502100503100504100505100506100507100508100509100510100511100512100513100514100515100516100517100518100519100520100521100522100523100524100525100526100527100528100529100530100531100532100533100534100535100536100537100538100539100540100541100542100543100544100545100546100547100548100549100550100551100552100553100554100555100556100557100558100559100560100561100562100563100564100565100566100567100568100569100570100571100572100573100574100575100576100577100578100579100580100581100582100583100584100585100586100587100588100589100590100591100592100593100594100595100596100597100598100599100600100601100602100603100604100605100606100607100608100609100610100611100612100613100614100615100616100617100618100619100620100621100622100623100624100625100626100627100628100629100630100631100632100633100634100635100636100637100638100639100640100641100642100643100644100645100646100647100648100649100650100651100652100653100654100655100656100657100658100659100660100661100662100663100664100665100666100667100668100669100670100671100672100673100674100675100676100677100678100679100680100681100682100683100684100685100686100687100688100689100690100691100692100693100694100695100696100697100698100699100700100701100702100703100704100705100706100707100708100709100710100711100712100713100714100715100716100717100718100719100720100721100722100723100724100725100726100727100728100729100730100731100732100733100734100735100736100737100738100739100740100741100742100743100744100745100746100747100748100749100750100751100752100753100754100755100756100757100758100759100760100761100762100763100764100765100766100767100768100769100770100771100772100773100774100775100776100777100778100779100780100781100782100783100784100785100786100787100788100789100790100791100792100793100794100795100796100797100798100799100800100801100802100803100804100805100806100807100808100809100810100811100812100813100814100815100816100817100818100819100820100821100822100823100824100825100826100827100828100829100830100831100832100833100834100835100836100837100838100839100840100841100842100843100844100845100846100847100848100849100850100851100852100853100854100855100856100857100858100859100860100861100862100863100864100865100866100867100868100869100870100871100872100873100874100875100876100877100878100879100880100881100882100883100884100885100886100887100888100889100890100891100892100893100894100895100896100897100898100899100900100901100902100903100904100905100906100907100908100909100910100911100912100913100914100915100916100917100918100919100920100921100922100923100924100925100926100927100928100929100930100931100932100933100934100935100936100937100938100939100940100941100942100943100944100945100946100947100948100949100950100951100952100953100954100955100956100957100958100959100960100961100962100963100964100965100966100967100968100969100970100971100972100973100974100975100976100977100978100979100980100981100982100983100984100985100986100987100988100989100990100991100992100993100994100995100996100997100998100999101000101001101002101003101004101005101006101007101008101009101010101011101012101013101014101015101016101017101018101019101020101021101022101023101024101025101026101027101028101029101030101031101032101033101034101035101036101037101038101039101040101041101042101043101044101045101046101047101048101049101050101051101052101053101054101055101056101057101058101059101060101061101062101063101064101065101066101067101068101069101070101071101072101073101074101075101076101077101078101079101080101081101082101083101084101085101086101087101088101089101090101091101092101093101094101095101096101097101098101099101100101101101102101103101104101105101106101107101108101109101110101111101112101113101114101115101116101117101118101119101120101121101122101123101124101125101126101127101128101129101130101131101132101133101134101135101136101137101138101139101140101141101142101143101144101145101146101147101148101149101150101151101152101153101154101155101156101157101158101159101160101161101162101163101164101165101166101167101168101169101170101171101172101173101174101175101176101177101178101179101180101181101182101183101184101185101186101187101188101189101190101191101192101193101194101195101196101197101198101199101200101201101202101203101204101205101206101207101208101209101210101211101212101213101214101215101216101217101218101219101220101221101222101223101224101225101226101227101228101229101230101231101232101233101234101235101236101237101238101239101240101241101242101243101244101245101246101247101248101249101250101251101252101253101254101255101256101257101258101259101260101261101262101263101264101265101266101267101268101269101270101271101272101273101274101275101276101277101278101279101280101281101282101283101284101285101286101287101288101289101290101291101292101293101294101295101296101297101298101299101300101301101302101303101304101305101306101307101308101309101310101311101312101313101314101315101316101317101318101319101320101321101322101323101324101325101326101327101328101329101330101331101332101333101334101335101336101337101338101339101340101341101342101343101344101345101346101347101348101349101350101351101352101353101354101355101356101357101358101359101360101361101362101363101364101365101366101367101368101369101370101371101372101373101374101375101376101377101378101379101380101381101382101383101384101385101386101387101388101389101390101391101392101393101394101395101396101397101398101399101400101401101402101403101404101405101406101407101408101409101410101411101412101413101414101415101416101417101418101419101420101421101422101423101424101425101426101427101428101429101430101431101432101433101434101435101436101437101438101439101440101441101442101443101444101445101446101447101448101449101450101451101452101453101454101455101456101457101458101459101460101461101462101463101464101465101466101467101468101469101470101471101472101473101474101475101476101477101478101479101480101481101482101483101484101485101486101487101488101489101490101491101492101493101494101495101496101497101498101499101500101501101502101503101504101505101506101507101508101509101510101511101512101513101514101515101516101517101518101519101520101521101522101523101524101525101526101527101528101529101530101531101532101533101534101535101536101537101538101539101540101541101542101543101544101545101546101547101548101549101550101551101552101553101554101555101556101557101558101559101560101561101562101563101564101565101566101567101568101569101570101571101572101573101574101575101576101577101578101579101580101581101582101583101584101585101586101587101588101589101590101591101592101593101594101595101596101597101598101599101600101601101602101603101604101605101606101607101608101609101610101611101612101613101614101615101616101617101618101619101620101621101622101623101624101625101626101627101628101629101630101631101632101633101634101635101636101637101638101639101640101641101642101643101644101645101646101647101648101649101650101651101652101653101654101655101656101657101658101659101660101661101662101663101664101665101666101667101668101669101670101671101672101673101674101675101676101677101678101679101680101681101682101683101684101685101686101687101688101689101690101691101692101693101694101695101696101697101698101699101700101701101702101703101704101705101706101707101708101709101710101711101712101713101714101715101716101717101718101719101720101721101722101723101724101725101726101727101728101729101730101731101732101733101734101735101736101737101738101739101740101741101742101743101744101745101746101747101748101749101750101751101752101753101754101755101756101757101758101759101760101761101762101763101764101765101766101767101768101769101770101771101772101773101774101775101776101777101778101779101780101781101782101783101784101785101786101787101788101789101790101791101792101793101794101795101796101797101798101799101800101801101802101803101804101805101806101807101808101809101810101811101812101813101814101815101816101817101818101819101820101821101822101823101824101825101826101827101828101829101830101831101832101833101834101835101836101837101838101839101840101841101842101843101844101845101846101847101848101849101850101851101852101853101854101855101856101857101858101859101860101861101862101863101864101865101866101867101868101869101870101871101872101873101874101875101876101877101878101879101880101881101882101883101884101885101886101887101888101889101890101891101892101893101894101895101896101897101898101899101900101901101902101903101904101905101906101907101908101909101910101911101912101913101914101915101916101917101918101919101920101921101922101923101924101925101926101927101928101929101930101931101932101933101934101935101936101937101938101939101940101941101942101943101944101945101946101947101948101949101950101951101952101953101954101955101956101957101958101959101960101961101962101963101964101965101966101967101968101969101970101971101972101973101974101975101976101977101978101979101980101981101982101983101984101985101986101987101988101989101990101991101992101993101994101995101996101997101998101999102000102001102002102003102004102005102006102007102008102009102010102011102012102013102014102015102016102017102018102019102020102021102022102023102024102025102026102027102028102029102030102031102032102033102034102035102036102037102038102039102040102041102042102043102044102045102046102047102048102049102050102051102052102053102054102055102056102057102058102059102060102061102062102063102064102065102066102067102068102069102070102071102072102073102074102075102076102077102078102079102080102081102082102083102084102085102086102087102088102089102090102091102092102093102094102095102096102097102098102099102100102101102102102103102104102105102106102107102108102109102110102111102112102113102114102115102116102117102118102119102120102121102122102123102124102125102126102127102128102129102130102131102132102133102134102135102136102137102138102139102140102141102142102143102144102145102146102147102148102149102150102151102152102153102154102155102156102157102158102159102160102161102162102163102164102165102166102167102168102169102170102171102172102173102174102175102176102177102178102179102180102181102182102183102184102185102186102187102188102189102190102191102192102193102194102195102196102197102198102199102200102201102202102203102204102205102206102207102208102209102210102211102212102213102214102215102216102217102218102219102220102221102222102223102224102225102226102227102228102229102230102231102232102233102234102235102236102237102238102239102240102241102242102243102244102245102246102247102248102249102250102251102252102253102254102255102256102257102258102259102260102261102262102263102264102265102266102267102268102269102270102271102272102273102274102275102276102277102278102279102280102281102282102283102284102285102286102287102288102289102290102291102292102293102294102295102296102297102298102299102300102301102302102303102304102305102306102307102308102309102310102311102312102313102314102315102316102317102318102319102320102321102322102323102324102325102326102327102328102329102330102331102332102333102334102335102336102337102338102339102340102341102342102343102344102345102346102347102348102349102350102351102352102353102354102355102356102357102358102359102360102361102362102363102364102365102366102367102368102369102370102371102372102373102374102375102376102377102378102379102380102381102382102383102384102385102386102387102388102389102390102391102392102393102394102395102396102397102398102399102400102401102402102403102404102405102406102407102408102409102410102411102412102413102414102415102416102417102418102419102420102421102422102423102424102425102426102427102428102429102430102431102432102433102434102435102436102437102438102439102440102441102442102443102444102445102446102447102448102449102450102451102452102453102454102455102456102457102458102459102460102461102462102463102464102465102466102467102468102469102470102471102472102473102474102475102476102477102478102479102480102481102482102483102484102485102486102487102488102489102490102491102492102493102494102495102496102497102498102499102500102501102502102503102504102505102506102507102508102509102510102511102512102513102514102515102516102517102518102519102520102521102522102523102524102525102526102527102528102529102530102531102532102533102534102535102536102537102538102539102540102541102542102543102544102545102546102547102548102549102550102551102552102553102554102555102556102557102558102559102560102561102562102563102564102565102566102567102568102569102570102571102572102573102574102575102576102577102578102579102580102581102582102583102584102585102586102587102588102589102590102591102592102593102594102595102596102597102598102599102600102601102602102603102604102605102606102607102608102609102610102611102612102613102614102615102616102617102618102619102620102621102622102623102624102625102626102627102628102629102630102631102632102633102634102635102636102637102638102639102640102641102642102643102644102645102646102647102648102649102650102651102652102653102654102655102656102657102658102659102660102661102662102663102664102665102666102667102668102669102670102671102672102673102674102675102676102677102678102679102680102681102682102683102684102685102686102687102688102689102690102691102692102693102694102695102696102697102698102699102700102701102702102703102704102705102706102707102708102709102710102711102712102713102714102715102716102717102718102719102720102721102722102723102724102725102726102727102728102729102730102731102732102733102734102735102736102737102738102739102740102741102742102743102744102745102746102747102748102749102750102751102752102753102754102755102756102757102758102759102760102761102762102763102764102765102766102767102768102769102770102771102772102773102774102775102776102777102778102779102780102781102782102783102784102785102786102787102788102789102790102791102792102793102794102795102796102797102798102799102800102801102802102803102804102805102806102807102808102809102810102811102812102813102814102815102816102817102818102819102820102821102822102823102824102825102826102827102828102829102830102831102832102833102834102835102836102837102838102839102840102841102842102843102844102845102846102847102848102849102850102851102852102853102854102855102856102857102858102859102860102861102862102863102864102865102866102867102868102869102870102871102872102873102874102875102876102877102878102879102880102881102882102883102884102885102886102887102888102889102890102891102892102893102894102895102896102897102898102899102900102901102902102903102904102905102906102907102908102909102910102911102912102913102914102915102916102917102918102919102920102921102922102923102924102925102926102927102928102929102930102931102932102933102934102935102936102937102938102939102940102941102942102943102944102945102946102947102948102949102950102951102952102953102954102955102956102957102958102959102960102961102962102963102964102965102966102967102968102969102970102971102972102973102974102975102976102977102978102979102980102981102982102983102984102985102986102987102988102989102990102991102992102993102994102995102996102997102998102999103000103001103002103003103004103005103006103007103008103009103010103011103012103013103014103015103016103017103018103019103020103021103022103023103024103025103026103027103028103029103030103031103032103033103034103035103036103037103038103039103040103041103042103043103044103045103046103047103048103049103050103051103052103053103054103055103056103057103058103059103060103061103062103063103064103065103066103067103068103069103070103071103072103073103074103075103076103077103078103079103080103081103082103083103084103085103086103087103088103089103090103091103092103093103094103095103096103097103098103099103100103101103102103103103104103105103106103107103108103109103110103111103112103113103114103115103116103117103118103119103120103121103122103123103124103125103126103127103128103129103130103131103132103133103134103135103136103137103138103139103140103141103142103143103144103145103146103147103148103149103150103151103152103153103154103155103156103157103158103159103160103161103162103163103164103165103166103167103168103169103170103171103172103173103174103175103176103177103178103179103180103181103182103183103184103185103186103187103188103189103190103191103192103193103194103195103196103197103198103199103200103201103202103203103204103205103206103207103208103209103210103211103212103213103214103215103216103217103218103219103220103221103222103223103224103225103226103227103228103229103230103231103232103233103234103235103236103237103238103239103240103241103242103243103244103245103246103247103248103249103250103251103252103253103254103255103256103257103258103259103260103261103262103263103264103265103266103267103268103269103270103271103272103273103274103275103276103277103278103279103280103281103282103283103284103285103286103287103288103289103290103291103292103293103294103295103296103297103298103299103300103301103302103303103304103305103306103307103308103309103310103311103312103313103314103315103316103317103318103319103320103321103322103323103324103325103326103327103328103329103330103331103332103333103334103335103336103337103338103339103340103341103342103343103344103345103346103347103348103349103350103351103352103353103354103355103356103357103358103359103360103361103362103363103364103365103366103367103368103369103370103371103372103373103374103375103376103377103378103379103380103381103382103383103384103385103386103387103388103389103390103391103392103393103394103395103396103397103398103399103400103401103402103403103404103405103406103407103408103409103410103411103412103413103414103415103416103417103418103419103420103421103422103423103424103425103426103427103428103429103430103431103432103433103434103435103436103437103438103439103440103441103442103443103444103445103446103447103448103449103450103451103452103453103454103455103456103457103458103459103460103461103462103463103464103465103466103467103468103469103470103471103472103473103474103475103476103477103478103479103480103481103482103483103484103485103486103487103488103489103490103491103492103493103494103495103496103497103498103499103500103501103502103503103504103505103506103507103508103509103510103511103512103513103514103515103516103517103518103519103520103521103522103523103524103525103526103527103528103529103530103531103532103533103534103535103536103537103538103539103540103541103542103543103544103545103546103547103548103549103550103551103552103553103554103555103556103557103558103559103560103561103562103563103564103565103566103567103568103569103570103571103572103573103574103575103576103577103578103579103580103581103582103583103584103585103586103587103588103589103590103591103592103593103594103595103596103597103598103599103600103601103602103603103604103605103606103607103608103609103610103611103612103613103614103615103616103617103618103619103620103621103622103623103624103625103626103627103628103629103630103631103632103633103634103635103636103637103638103639103640103641103642103643103644103645103646103647103648103649103650103651103652103653103654103655103656103657103658103659103660103661103662103663103664103665103666103667103668103669103670103671103672103673103674103675103676103677103678103679103680103681103682103683103684103685103686103687103688103689103690103691103692103693103694103695103696103697103698103699103700103701103702103703103704103705103706103707103708103709103710103711103712103713103714103715103716103717103718103719103720103721103722103723103724103725103726103727103728103729103730103731103732103733103734103735103736103737103738103739103740103741103742103743103744103745103746103747103748103749103750103751103752103753103754103755103756103757103758103759103760103761103762103763103764103765103766103767103768103769103770103771103772103773103774103775103776103777103778103779103780103781103782103783103784103785103786103787103788103789103790103791103792103793103794103795103796103797103798103799103800103801103802103803103804103805103806103807103808103809103810103811103812103813103814103815103816103817103818103819103820103821103822103823103824103825103826103827103828103829103830103831103832103833103834103835103836103837103838103839103840103841103842103843103844103845103846103847103848103849103850103851103852103853103854103855103856103857103858103859103860103861103862103863103864103865103866103867103868103869103870103871103872103873103874103875103876103877103878103879103880103881103882103883103884103885103886103887103888103889103890103891103892103893103894103895103896103897103898103899103900103901103902103903103904103905103906103907103908103909103910103911103912103913103914103915103916103917103918103919103920103921103922103923103924103925103926103927103928103929103930103931103932103933103934103935103936103937103938103939103940103941103942103943103944103945103946103947103948103949103950103951103952103953103954103955103956103957103958103959103960103961103962103963103964103965103966103967103968103969103970103971103972103973103974103975103976103977103978103979103980103981103982103983103984103985103986103987103988103989103990103991103992103993103994103995103996103997103998103999104000104001104002104003104004104005104006104007104008104009104010104011104012104013104014104015104016104017104018104019104020104021104022104023104024104025104026104027104028104029104030104031104032104033104034104035104036104037104038104039104040104041104042104043104044104045104046104047104048104049104050104051104052104053104054104055104056104057104058104059104060104061104062104063104064104065104066104067104068104069104070104071104072104073104074104075104076104077104078104079104080104081104082104083104084104085104086104087104088104089104090104091104092104093104094104095104096104097104098104099104100104101104102104103104104104105104106104107104108104109104110104111104112104113104114104115104116104117104118104119104120104121104122104123104124104125104126104127104128104129104130104131104132104133104134104135104136104137104138104139104140104141104142104143104144104145104146104147104148104149104150104151104152104153104154104155104156104157104158104159104160104161104162104163104164104165104166104167104168104169104170104171104172104173104174104175104176104177104178104179104180104181104182104183104184104185104186104187104188104189104190104191104192104193104194104195104196104197104198104199104200104201104202104203104204104205104206104207104208104209104210104211104212104213104214104215104216104217104218104219104220104221104222104223104224104225104226104227104228104229104230104231104232104233104234104235104236104237104238104239104240104241104242104243104244104245104246104247104248104249104250104251104252104253104254104255104256104257104258104259104260104261104262104263104264104265104266104267104268104269104270104271104272104273104274104275104276104277104278104279104280104281104282104283104284104285104286104287104288104289104290104291104292104293104294104295104296104297104298104299104300104301104302104303104304104305104306104307104308104309104310104311104312104313104314104315104316104317104318104319104320104321104322104323104324104325104326104327104328104329104330104331104332104333104334104335104336104337104338104339104340104341104342104343104344104345104346104347104348104349104350104351104352104353104354104355104356104357104358104359104360104361104362104363104364104365104366104367104368104369104370104371104372104373104374104375104376104377104378104379104380104381104382104383104384104385104386104387104388104389104390104391104392104393104394104395104396104397104398104399104400104401104402104403104404104405104406104407104408104409104410104411104412104413104414104415104416104417104418104419104420104421104422104423104424104425104426104427104428104429104430104431104432104433104434104435104436104437104438104439104440104441104442104443104444104445104446104447104448104449104450104451104452104453104454104455104456104457104458104459104460104461104462104463104464104465104466104467104468104469104470104471104472104473104474104475104476104477104478104479104480104481104482104483104484104485104486104487104488104489104490104491104492104493104494104495104496104497104498104499104500104501104502104503104504104505104506104507104508104509104510104511104512104513104514104515104516104517104518104519104520104521104522104523104524104525104526104527104528104529104530104531104532104533104534104535104536104537104538104539104540104541104542104543104544104545104546104547104548104549104550104551104552104553104554104555104556104557104558104559104560104561104562104563104564104565104566104567104568104569104570104571104572104573104574104575104576104577104578104579104580104581104582104583104584104585104586104587104588104589104590104591104592104593104594104595104596104597104598104599104600104601104602104603104604104605104606104607104608104609104610104611104612104613104614104615104616104617104618104619104620104621104622104623104624104625104626104627104628104629104630104631104632104633104634104635104636104637104638104639104640104641104642104643104644104645104646104647104648104649104650104651104652104653104654104655104656104657104658104659104660104661104662104663104664104665104666104667104668104669104670104671104672104673104674104675104676104677104678104679104680104681104682104683104684104685104686104687104688104689104690104691104692104693104694104695104696104697104698104699104700104701104702104703104704104705104706104707104708104709104710104711104712104713104714104715104716104717104718104719104720104721104722104723104724104725104726104727104728104729104730104731104732104733104734104735104736104737104738104739104740104741104742104743104744104745104746104747104748104749104750104751104752104753104754104755104756104757104758104759104760104761104762104763104764104765104766104767104768104769104770104771104772104773104774104775104776104777104778104779104780104781104782104783104784104785104786104787104788104789104790104791104792104793104794104795104796104797104798104799104800104801104802104803104804104805104806104807104808104809104810104811104812104813104814104815104816104817104818104819104820104821104822104823104824104825104826104827104828104829104830104831104832104833104834104835104836104837104838104839104840104841104842104843104844104845104846104847104848104849104850104851104852104853104854104855104856104857104858104859104860104861104862104863104864104865104866104867104868104869104870104871104872104873104874104875104876104877104878104879104880104881104882104883104884104885104886104887104888104889104890104891104892104893104894104895104896104897104898104899104900104901104902104903104904104905104906104907104908104909104910104911104912104913104914104915104916104917104918104919104920104921104922104923104924104925104926104927104928104929104930104931104932104933104934104935104936104937104938104939104940104941104942104943104944104945104946104947104948104949104950104951104952104953104954104955104956104957104958104959104960104961104962104963104964104965104966104967104968104969104970104971104972104973104974104975104976104977104978104979104980104981104982104983104984104985104986104987104988104989104990104991104992104993104994104995104996104997104998104999105000105001105002105003105004105005105006105007105008105009105010105011105012105013105014105015105016105017105018105019105020105021105022105023105024105025105026105027105028105029105030105031105032105033105034105035105036105037105038105039105040105041105042105043105044105045105046105047105048105049105050105051105052105053105054105055105056105057105058105059105060105061105062105063105064105065105066105067105068105069105070105071105072105073105074105075105076105077105078105079105080105081105082105083105084105085105086105087105088105089105090105091105092105093105094105095105096105097105098105099105100105101105102105103105104105105105106105107105108105109105110105111105112105113105114105115105116105117105118105119105120105121105122105123105124105125105126105127105128105129105130105131105132105133105134105135105136105137105138105139105140105141105142105143105144105145105146105147105148105149105150105151105152105153105154105155105156105157105158105159105160105161105162105163105164105165105166105167105168105169105170105171105172105173105174105175105176105177105178105179105180105181105182105183105184105185105186105187105188105189105190105191105192105193105194105195105196105197105198105199105200105201105202105203105204105205105206105207105208105209105210105211105212105213105214105215105216105217105218105219105220105221105222105223105224105225105226105227105228105229105230105231105232105233105234105235105236105237105238105239105240105241105242105243105244105245105246105247105248105249105250105251105252105253105254105255105256105257105258105259105260105261105262105263105264105265105266105267105268105269105270105271105272105273105274105275105276105277105278105279105280105281105282105283105284105285105286105287105288105289105290105291105292105293105294105295105296105297105298105299105300105301105302105303105304105305105306105307105308105309105310105311105312105313105314105315105316105317105318105319105320105321105322105323105324105325105326105327105328105329105330105331105332105333105334105335105336105337105338105339105340105341105342105343105344105345105346105347105348105349105350105351105352105353105354105355105356105357105358105359105360105361105362105363105364105365105366105367105368105369105370105371105372105373105374105375105376105377105378105379105380105381105382105383105384105385105386105387105388105389105390105391105392105393105394105395105396105397105398105399105400105401105402105403105404105405105406105407105408105409105410105411105412105413105414105415105416105417105418105419105420105421105422105423105424105425105426105427105428105429105430105431105432105433105434105435105436105437105438105439105440105441105442105443105444105445105446105447105448105449105450105451105452105453105454105455105456105457105458105459105460105461105462105463105464105465105466105467105468105469105470105471105472105473105474105475105476105477105478105479105480105481105482105483105484105485105486105487105488105489105490105491105492105493105494105495105496105497105498105499105500105501105502105503105504105505105506105507105508105509105510105511105512105513105514105515105516105517105518105519105520105521105522105523105524105525105526105527105528105529105530105531105532105533105534105535105536105537105538105539105540105541105542105543105544105545105546105547105548105549105550105551105552105553105554105555105556105557105558105559105560105561105562105563105564105565105566105567105568105569105570105571105572105573105574105575105576105577105578105579105580105581105582105583105584105585105586105587105588105589105590105591105592105593105594105595105596105597105598105599105600105601105602105603105604105605105606105607105608105609105610105611105612105613105614105615105616105617105618105619105620105621105622105623105624105625105626105627105628105629105630105631105632105633105634105635105636105637105638105639105640105641105642105643105644105645105646105647105648105649105650105651105652105653105654105655105656105657105658105659105660105661105662105663105664105665105666105667105668105669105670105671105672105673105674105675105676105677105678105679105680105681105682105683105684105685105686105687105688105689105690105691105692105693105694105695105696105697105698105699105700105701105702105703105704105705105706105707105708105709105710105711105712105713105714105715105716105717105718105719105720105721105722105723105724105725105726105727105728105729105730105731105732105733105734105735105736105737105738105739105740105741105742105743105744105745105746105747105748105749105750105751105752105753105754105755105756105757105758105759105760105761105762105763105764105765105766105767105768105769105770105771105772105773105774105775105776105777105778105779105780105781105782105783105784105785105786105787105788105789105790105791105792105793105794105795105796105797105798105799105800105801105802105803105804105805105806105807105808105809105810105811105812105813105814105815105816105817105818105819105820105821105822105823105824105825105826105827105828105829105830105831105832105833105834105835105836105837105838105839105840105841105842105843105844105845105846105847105848105849105850105851105852105853105854105855105856105857105858105859105860105861105862105863105864105865105866105867105868105869105870105871105872105873105874105875105876105877105878105879105880105881105882105883105884105885105886105887105888105889105890105891105892105893105894105895105896105897105898105899105900105901105902105903105904105905105906105907105908105909105910105911105912105913105914105915105916105917105918105919105920105921105922105923105924105925105926105927105928105929105930105931105932105933105934105935105936105937105938105939105940105941105942105943105944105945105946105947105948105949105950105951105952105953105954105955105956105957105958105959105960105961105962105963105964105965105966105967105968105969105970105971105972105973105974105975105976105977105978105979105980105981105982105983105984105985105986105987105988105989105990105991105992105993105994105995105996105997105998105999106000106001106002106003106004106005106006106007106008106009106010106011106012106013106014106015106016106017106018106019106020106021106022106023106024106025106026106027106028106029106030106031106032106033106034106035106036106037106038106039106040106041106042106043106044106045106046106047106048106049106050106051106052106053106054106055106056106057106058106059106060106061106062106063106064106065106066106067106068106069106070106071106072106073106074106075106076106077106078106079106080106081106082106083106084106085106086106087106088106089106090106091106092106093106094106095106096106097106098106099106100106101106102106103106104106105106106106107106108106109106110106111106112106113106114106115106116106117106118106119106120106121106122106123106124106125106126106127106128106129106130106131106132106133106134106135106136106137106138106139106140106141106142106143106144106145106146106147106148106149106150106151106152106153106154106155106156106157106158106159106160106161106162106163106164106165106166106167106168106169106170106171106172106173106174106175106176106177106178106179106180106181106182106183106184106185106186106187106188106189106190106191106192106193106194106195106196106197106198106199106200106201106202106203106204106205106206106207106208106209106210106211106212106213106214106215106216106217106218106219106220106221106222106223106224106225106226106227106228106229106230106231106232106233106234106235106236106237106238106239106240106241106242106243106244106245106246106247106248106249106250106251106252106253106254106255106256106257106258106259106260106261106262106263106264106265106266106267106268106269106270106271106272106273106274106275106276106277106278106279106280106281106282106283106284106285106286106287106288106289106290106291106292106293106294106295106296106297106298106299106300106301106302106303106304106305106306106307106308106309106310106311106312106313106314106315106316106317106318106319106320106321106322106323106324106325106326106327106328106329106330106331106332106333106334106335106336106337106338106339106340106341106342106343106344106345106346106347106348106349106350106351106352106353106354106355106356106357106358106359106360106361106362106363106364106365106366106367106368106369106370106371106372106373106374106375106376106377106378106379106380106381106382106383106384106385106386106387106388106389106390106391106392106393106394106395106396106397106398106399106400106401106402106403106404106405106406106407106408106409106410106411106412106413106414106415106416106417106418106419106420106421106422106423106424106425106426106427106428106429106430106431106432106433106434106435106436106437106438106439106440106441106442106443106444106445106446106447106448106449106450106451106452106453106454106455106456106457106458106459106460106461106462106463106464106465106466106467106468106469106470106471106472106473106474106475106476106477106478106479106480106481106482106483106484106485106486106487106488106489106490106491106492106493106494106495106496106497106498106499106500106501106502106503106504106505106506106507106508106509106510106511106512106513106514106515106516106517106518106519106520106521106522106523106524106525106526106527106528106529106530106531106532106533106534106535106536106537106538106539106540106541106542106543106544106545106546106547106548106549106550106551106552106553106554106555106556106557106558106559106560106561106562106563106564106565106566106567106568106569106570106571106572106573106574106575106576106577106578106579106580106581106582106583106584106585106586106587106588106589106590106591106592106593106594106595106596106597106598106599106600106601106602106603106604106605106606106607106608106609106610106611106612106613106614106615106616106617106618106619106620106621106622106623106624106625106626106627106628106629106630106631106632106633106634106635106636106637106638106639106640106641106642106643106644106645106646106647106648106649106650106651106652106653106654106655106656106657106658106659106660106661106662106663106664106665106666106667106668106669106670106671106672106673106674106675106676106677106678106679106680106681106682106683106684106685106686106687106688106689106690106691106692106693106694106695106696106697106698106699106700106701106702106703106704106705106706106707106708106709106710106711106712106713106714106715106716106717106718106719106720106721106722106723106724106725106726106727106728106729106730106731106732106733106734106735106736106737106738106739106740106741106742106743106744106745106746106747106748106749106750106751106752106753106754106755106756106757106758106759106760106761106762106763106764106765106766106767106768106769106770106771106772106773106774106775106776106777106778106779106780106781106782106783106784106785106786106787106788106789106790106791106792106793106794106795106796106797106798106799106800106801106802106803106804106805106806106807106808106809106810106811106812106813106814106815106816106817106818106819106820106821106822106823106824106825106826106827106828106829106830106831106832106833106834106835106836106837106838106839106840106841106842106843106844106845106846106847106848106849106850106851106852106853106854106855106856106857106858106859106860106861106862106863106864106865106866106867106868106869106870106871106872106873106874106875106876106877106878106879106880106881106882106883106884106885106886106887106888106889106890106891106892106893106894106895106896106897106898106899106900106901106902106903106904106905106906106907106908106909106910106911106912106913106914106915106916106917106918106919106920106921106922106923106924106925106926106927106928106929106930106931106932106933106934106935106936106937106938106939106940106941106942106943106944106945106946106947106948106949106950106951106952106953106954106955106956106957106958106959106960106961106962106963106964106965106966106967106968106969106970106971106972106973106974106975106976106977106978106979106980106981106982106983106984106985106986106987106988106989106990106991106992106993106994106995106996106997106998106999107000107001107002107003107004107005107006107007107008107009107010107011107012107013107014107015107016107017107018107019107020107021107022107023107024107025107026107027107028107029107030107031107032107033107034107035107036107037107038107039107040107041107042107043107044107045107046107047107048107049107050107051107052107053107054107055107056107057107058107059107060107061107062107063107064107065107066107067107068107069107070107071107072107073107074107075107076107077107078107079107080107081107082107083107084107085107086107087107088107089107090107091107092107093107094107095107096107097107098107099107100107101107102107103107104107105107106107107107108107109107110107111107112107113107114107115107116107117107118107119107120107121107122107123107124107125107126107127107128107129107130107131107132107133107134107135107136107137107138107139107140107141107142107143107144107145107146107147107148107149107150107151107152107153107154107155107156107157107158107159107160107161107162107163107164107165107166107167107168107169107170107171107172107173107174107175107176107177107178107179107180107181107182107183107184107185107186107187107188107189107190107191107192107193107194107195107196107197107198107199107200107201107202107203107204107205107206107207107208107209107210107211107212107213107214107215107216107217107218107219107220107221107222107223107224107225107226107227107228107229107230107231107232107233107234107235107236107237107238107239107240107241107242107243107244107245107246107247107248107249107250107251107252107253107254107255107256107257107258107259107260107261107262107263107264107265107266107267107268107269107270107271107272107273107274107275107276107277107278107279107280107281107282107283107284107285107286107287107288107289107290107291107292107293107294107295107296107297107298107299107300107301107302107303107304107305107306107307107308107309107310107311107312107313107314107315107316107317107318107319107320107321107322107323107324107325107326107327107328107329107330107331107332107333107334107335107336107337107338107339107340107341107342107343107344107345107346107347107348107349107350107351107352107353107354107355107356107357107358107359107360107361107362107363107364107365107366107367107368107369107370107371107372107373107374107375107376107377107378107379107380107381107382107383107384107385107386107387107388107389107390107391107392107393107394107395107396107397107398107399107400107401107402107403107404107405107406107407107408107409107410107411107412107413107414107415107416107417107418107419107420107421107422107423107424107425107426107427107428107429107430107431107432107433107434107435107436107437107438107439107440107441107442107443107444107445107446107447107448107449107450107451107452107453107454107455107456107457107458107459107460107461107462107463107464107465107466107467107468107469107470107471107472107473107474107475107476107477107478107479107480107481107482107483107484107485107486107487107488107489107490107491107492107493107494107495107496107497107498107499107500107501107502107503107504107505107506107507107508107509107510107511107512107513107514107515107516107517107518107519107520107521107522107523107524107525107526107527107528107529107530107531107532107533107534107535107536107537107538107539107540107541107542107543107544107545107546107547107548107549107550107551107552107553107554107555107556107557107558107559107560107561107562107563107564107565107566107567107568107569107570107571107572107573107574107575107576107577107578107579107580107581107582107583107584107585107586107587107588107589107590107591107592107593107594107595107596107597107598107599107600107601107602107603107604107605107606107607107608107609107610107611107612107613107614107615107616107617107618107619107620107621107622107623107624107625107626107627107628107629107630107631107632107633107634107635107636107637107638107639107640107641107642107643107644107645107646107647107648107649107650107651107652107653107654107655107656107657107658107659107660107661107662107663107664107665107666107667107668107669107670107671107672107673107674107675107676107677107678107679107680107681107682107683107684107685107686107687107688107689107690107691107692107693107694107695107696107697107698107699107700107701107702107703107704107705107706107707107708107709107710107711107712107713107714107715107716107717107718107719107720107721107722107723107724107725107726107727107728107729107730107731107732107733107734107735107736107737107738107739107740107741107742107743107744107745107746107747107748107749107750107751107752107753107754107755107756107757107758107759107760107761107762107763107764107765107766107767107768107769107770107771107772107773107774107775107776107777107778107779107780107781107782107783107784107785107786107787107788107789107790107791107792107793107794107795107796107797107798107799107800107801107802107803107804107805107806107807107808107809107810107811107812107813107814107815107816107817107818107819107820107821107822107823107824107825107826107827107828107829107830107831107832107833107834107835107836107837107838107839107840107841107842107843107844107845107846107847107848107849107850107851107852107853107854107855107856107857107858107859107860107861107862107863107864107865107866107867107868107869107870107871107872107873107874107875107876107877107878107879107880107881107882107883107884107885107886107887107888107889107890107891107892107893107894107895107896107897107898107899107900107901107902107903107904107905107906107907107908107909107910107911107912107913107914107915107916107917107918107919107920107921107922107923107924107925107926107927107928107929107930107931107932107933107934107935107936107937107938107939107940107941107942107943107944107945107946107947107948107949107950107951107952107953107954107955107956107957107958107959107960107961107962107963107964107965107966107967107968107969107970107971107972107973107974107975107976107977107978107979107980107981107982107983107984107985107986107987107988107989107990107991107992107993107994107995107996107997107998107999108000108001108002108003108004108005108006108007108008108009108010108011108012108013108014108015108016108017108018108019108020108021108022108023108024108025108026108027108028108029108030108031108032108033108034108035108036108037108038108039108040108041108042108043108044108045108046108047108048108049108050108051108052108053108054108055108056108057108058108059108060108061108062108063108064108065108066108067108068108069108070108071108072108073108074108075108076108077108078108079108080108081108082108083108084108085108086108087108088108089108090108091108092108093108094108095108096108097108098108099108100108101108102108103108104108105108106108107108108108109108110108111108112108113108114108115108116108117108118108119108120108121108122108123108124108125108126108127108128108129108130108131108132108133108134108135108136108137108138108139108140108141108142108143108144108145108146108147108148108149108150108151108152108153108154108155108156108157108158108159108160108161108162108163108164108165108166108167108168108169108170108171108172108173108174108175108176108177108178108179108180108181108182108183108184108185108186108187108188108189108190108191108192108193108194108195108196108197108198108199108200108201108202108203108204108205108206108207108208108209108210108211108212108213108214108215108216108217108218108219108220108221108222108223108224108225108226108227108228108229108230108231108232108233108234108235108236108237108238108239108240108241108242108243108244108245108246108247108248108249108250108251108252108253108254108255108256108257108258108259108260108261108262108263108264108265108266108267108268108269108270108271108272108273108274108275108276108277108278108279108280108281108282108283108284108285108286108287108288108289108290108291108292108293108294108295108296108297108298108299108300108301108302108303108304108305108306108307108308108309108310108311108312108313108314108315108316108317108318108319108320108321108322108323108324108325108326108327108328108329108330108331108332108333108334108335108336108337108338108339108340108341108342108343108344108345108346108347108348108349108350108351108352108353108354108355108356108357108358108359108360108361108362108363108364108365108366108367108368108369108370108371108372108373108374108375108376108377108378108379108380108381108382108383108384108385108386108387108388108389108390108391108392108393108394108395108396108397108398108399108400108401108402108403108404108405108406108407108408108409108410108411108412108413108414108415108416108417108418108419108420108421108422108423108424108425108426108427108428108429108430108431108432108433108434108435108436108437108438108439108440108441108442108443108444108445108446108447108448108449108450108451108452108453108454108455108456108457108458108459108460108461108462108463108464108465108466108467108468108469108470108471108472108473108474108475108476108477108478108479108480108481108482108483108484108485108486108487108488108489108490108491108492108493108494108495108496108497108498108499108500108501108502108503108504108505108506108507108508108509108510108511108512108513108514108515108516108517108518108519108520108521108522108523108524108525108526108527108528108529108530108531108532108533108534108535108536108537108538108539108540108541108542108543108544108545108546108547108548108549108550108551108552108553108554108555108556108557108558108559108560108561108562108563108564108565108566108567108568108569108570108571108572108573108574108575108576108577108578108579108580108581108582108583108584108585108586108587108588108589108590108591108592108593108594108595108596108597108598108599108600108601108602108603108604108605108606108607108608108609108610108611108612108613108614108615108616108617108618108619108620108621108622108623108624108625108626108627108628108629108630108631108632108633108634108635108636108637108638108639108640108641108642108643108644108645108646108647108648108649108650108651108652108653108654108655108656108657108658108659108660108661108662108663108664108665108666108667108668108669108670108671108672108673108674108675108676108677108678108679108680108681108682108683108684108685108686108687108688108689108690108691108692108693108694108695108696108697108698108699108700108701108702108703108704108705108706108707108708108709108710108711108712108713108714108715108716108717108718108719108720108721108722108723108724108725108726108727108728108729108730108731108732108733108734108735108736108737108738108739108740108741108742108743108744108745108746108747108748108749108750108751108752108753108754108755108756108757108758108759108760108761108762108763108764108765108766108767108768108769108770108771108772108773108774108775108776108777108778108779108780108781108782108783108784108785108786108787108788108789108790108791108792108793108794108795108796108797108798108799108800108801108802108803108804108805108806108807108808108809108810108811108812108813108814108815108816108817108818108819108820108821108822108823108824108825108826108827108828108829108830108831108832108833108834108835108836108837108838108839108840108841108842108843108844108845108846108847108848108849108850108851108852108853108854108855108856108857108858108859108860108861108862108863108864108865108866108867108868108869108870108871108872108873108874108875108876108877108878108879108880108881108882108883108884108885108886108887108888108889108890108891108892108893108894108895108896108897108898108899108900108901108902108903108904108905108906108907108908108909108910108911108912108913108914108915108916108917108918108919108920108921108922108923108924108925108926108927108928108929108930108931108932108933108934108935108936108937108938108939108940108941108942108943108944108945108946108947108948108949108950108951108952108953108954108955108956108957108958108959108960108961108962108963108964108965108966108967108968108969108970108971108972108973108974108975108976108977108978108979108980108981108982108983108984108985108986108987108988108989108990108991108992108993108994108995108996108997108998108999109000109001109002109003109004109005109006109007109008109009109010109011109012109013109014109015109016109017109018109019109020109021109022109023109024109025109026109027109028109029109030109031109032109033109034109035109036109037109038109039109040109041109042109043109044109045109046109047109048109049109050109051109052109053109054109055109056109057109058109059109060109061109062109063109064109065109066109067109068109069109070109071109072109073109074109075109076109077109078109079109080109081109082109083109084109085109086109087109088109089109090109091109092109093109094109095109096109097109098109099109100109101109102109103109104109105109106109107109108109109109110109111109112109113109114109115109116109117109118109119109120109121109122109123109124109125109126109127109128109129109130109131109132109133109134109135109136109137109138109139109140109141109142109143109144109145109146109147109148109149109150109151109152109153109154109155109156109157109158109159109160109161109162109163109164109165109166109167109168109169109170109171109172109173109174109175109176109177109178109179109180109181109182109183109184109185109186109187109188109189109190109191109192109193109194109195109196109197109198109199109200109201109202109203109204109205109206109207109208109209109210109211109212109213109214109215109216109217109218109219109220109221109222109223109224109225109226109227109228109229109230109231109232109233109234109235109236109237109238109239109240109241109242109243109244109245109246109247109248109249109250109251109252109253109254109255109256109257109258109259109260109261109262109263109264109265109266109267109268109269109270109271109272109273109274109275109276109277109278109279109280109281109282109283109284109285109286109287109288109289109290109291109292109293109294109295109296109297109298109299109300109301109302109303109304109305109306109307109308109309109310109311109312109313109314109315109316109317109318109319109320109321109322109323109324109325109326109327109328109329109330109331109332109333109334109335109336109337109338109339109340109341109342109343109344109345109346109347109348109349109350109351109352109353109354109355109356109357109358109359109360109361109362109363109364109365109366109367109368109369109370109371109372109373109374109375109376109377109378109379109380109381109382109383109384109385109386109387109388109389109390109391109392109393109394109395109396109397109398109399109400109401109402109403109404109405109406109407109408109409109410109411109412109413109414109415109416109417109418109419109420109421109422109423109424109425109426109427109428109429109430109431109432109433109434109435109436109437109438109439109440109441109442109443109444109445109446109447109448109449109450109451109452109453109454109455109456109457109458109459109460109461109462109463109464109465109466109467109468109469109470109471109472109473109474109475109476109477109478109479109480109481109482109483109484109485109486109487109488109489109490109491109492109493109494109495109496109497109498109499109500109501109502109503109504109505109506109507109508109509109510109511109512109513109514109515109516109517109518109519109520109521109522109523109524109525109526109527109528109529109530109531109532109533109534109535109536109537109538109539109540109541109542109543109544109545109546109547109548109549109550109551109552109553109554109555109556109557109558109559109560109561109562109563109564109565109566109567109568109569109570109571109572109573109574109575109576109577109578109579109580109581109582109583109584109585109586109587109588109589109590109591109592109593109594109595109596109597109598109599109600109601109602109603109604109605109606109607109608109609109610109611109612109613109614109615109616109617109618109619109620109621109622109623109624109625109626109627109628109629109630109631109632109633109634109635109636109637109638109639109640109641109642109643109644109645109646109647109648109649109650109651109652109653109654109655109656109657109658109659109660109661109662109663109664109665109666109667109668109669109670109671109672109673109674109675109676109677109678109679109680109681109682109683109684109685109686109687109688109689109690109691109692109693109694109695109696109697109698109699109700109701109702109703109704109705109706109707109708109709109710109711109712109713109714109715109716109717109718109719109720109721109722109723109724109725109726109727109728109729109730109731109732109733109734109735109736109737109738109739109740109741109742109743109744109745109746109747109748109749109750109751109752109753109754109755109756109757109758109759109760109761109762109763109764109765109766109767109768109769109770109771109772109773109774109775109776109777109778109779109780109781109782109783109784109785109786109787109788109789109790109791109792109793109794109795109796109797109798109799109800109801109802109803109804109805109806109807109808109809109810109811109812109813109814109815109816109817109818109819109820109821109822109823109824109825109826109827109828109829109830109831109832109833109834109835109836109837109838109839109840109841109842109843109844109845109846109847109848109849109850109851109852109853109854109855109856109857109858109859109860109861109862109863109864109865109866109867109868109869109870109871109872109873109874109875109876109877109878109879109880109881109882109883109884109885109886109887109888109889109890109891109892109893109894109895109896109897109898109899109900109901109902109903109904109905109906109907109908109909109910109911109912109913109914109915109916109917109918109919109920109921109922109923109924109925109926109927109928109929109930109931109932109933109934109935109936109937109938109939109940109941109942109943109944109945109946109947109948109949109950109951109952109953109954109955109956109957109958109959109960109961109962109963109964109965109966109967109968109969109970109971109972109973109974109975109976109977109978109979109980109981109982109983109984109985109986109987109988109989109990109991109992109993109994109995109996109997109998109999110000110001110002110003110004110005110006110007110008110009110010110011110012110013110014110015110016110017110018110019110020110021110022110023110024110025110026110027110028110029110030110031110032110033110034110035110036110037110038110039110040110041110042110043110044110045110046110047110048110049110050110051110052110053110054110055110056110057110058110059110060110061110062110063110064110065110066110067110068110069110070110071110072110073110074110075110076110077110078110079110080110081110082110083110084110085110086110087110088110089110090110091110092110093110094110095110096110097110098110099110100110101110102110103110104110105110106110107110108110109110110110111110112110113110114110115110116110117110118110119110120110121110122110123110124110125110126110127110128110129110130110131110132110133110134110135110136110137110138110139110140110141110142110143110144110145110146110147110148110149110150110151110152110153110154110155110156110157110158110159110160110161110162110163110164110165110166110167110168110169110170110171110172110173110174110175110176110177110178110179110180110181110182110183110184110185110186110187110188110189110190110191110192110193110194110195110196110197110198110199110200110201110202110203110204110205110206110207110208110209110210110211110212110213110214110215110216110217110218110219110220110221110222110223110224110225110226110227110228110229110230110231110232110233110234110235110236110237110238110239110240110241110242110243110244110245110246110247110248110249110250110251110252110253110254110255110256110257110258110259110260110261110262110263110264110265110266110267110268110269110270110271110272110273110274110275110276110277110278110279110280110281110282110283110284110285110286110287110288110289110290110291110292110293110294110295110296110297110298110299110300110301110302110303110304110305110306110307110308110309110310110311110312110313110314110315110316110317110318110319110320110321110322110323110324110325110326110327110328110329110330110331110332110333110334110335110336110337110338110339110340110341110342110343110344110345110346110347110348110349110350110351110352110353110354110355110356110357110358110359110360110361110362110363110364110365110366110367110368110369110370110371110372110373110374110375110376110377110378110379110380110381110382110383110384110385110386110387110388110389110390110391110392110393110394110395110396110397110398110399110400110401110402110403110404110405110406110407110408110409110410110411110412110413110414110415110416110417110418110419110420110421110422110423110424110425110426110427110428110429110430110431110432110433110434110435110436110437110438110439110440110441110442110443110444110445110446110447110448110449110450110451110452110453110454110455110456110457110458110459110460110461110462110463110464110465110466110467110468110469110470110471110472110473110474110475110476110477110478110479110480110481110482110483110484110485110486110487110488110489110490110491110492110493110494110495110496110497110498110499110500110501110502110503110504110505110506110507110508110509110510110511110512110513110514110515110516110517110518110519110520110521110522110523110524110525110526110527110528110529110530110531110532110533110534110535110536110537110538110539110540110541110542110543110544110545110546110547110548110549110550110551110552110553110554110555110556110557110558110559110560110561110562110563110564110565110566110567110568110569110570110571110572110573110574110575110576110577110578110579110580110581110582110583110584110585110586110587110588110589110590110591110592110593110594110595110596110597110598110599110600110601110602110603110604110605110606110607110608110609110610110611110612110613110614110615110616110617110618110619110620110621110622110623110624110625110626110627110628110629110630110631110632110633110634110635110636110637110638110639110640110641110642110643110644110645110646110647110648110649110650110651110652110653110654110655110656110657110658110659110660110661110662110663110664110665110666110667110668110669110670110671110672110673110674110675110676110677110678110679110680110681110682110683110684110685110686110687110688110689110690110691110692110693110694110695110696110697110698110699110700110701110702110703110704110705110706110707110708110709110710110711110712110713110714110715110716110717110718110719110720110721110722110723110724110725110726110727110728110729110730110731110732110733110734110735110736110737110738110739110740110741110742110743110744110745110746110747110748110749110750110751110752110753110754110755110756110757110758110759110760110761110762110763110764110765110766110767110768110769110770110771110772110773110774110775110776110777110778110779110780110781110782110783110784110785110786110787110788110789110790110791110792110793110794110795110796110797110798110799110800110801110802110803110804110805110806110807110808110809110810110811110812110813110814110815110816110817110818110819110820110821110822110823110824110825110826110827110828110829110830110831110832110833110834110835110836110837110838110839110840110841110842110843110844110845110846110847110848110849110850110851110852110853110854110855110856110857110858110859110860110861110862110863110864110865110866110867110868110869110870110871110872110873110874110875110876110877110878110879110880110881110882110883110884110885110886110887110888110889110890110891110892110893110894110895110896110897110898110899110900110901110902110903110904110905110906110907110908110909110910110911110912110913110914110915110916110917110918110919110920110921110922110923110924110925110926110927110928110929110930110931110932110933110934110935110936110937110938110939110940110941110942110943110944110945110946110947110948110949110950110951110952110953110954110955110956110957110958110959110960110961110962110963110964110965110966110967110968110969110970110971110972110973110974110975110976110977110978110979110980110981110982110983110984110985110986110987110988110989110990110991110992110993110994110995110996110997110998110999111000111001111002111003111004111005111006111007111008111009111010111011111012111013111014111015111016111017111018111019111020111021111022111023111024111025111026111027111028111029111030111031111032111033111034111035111036111037111038111039111040111041111042111043111044111045111046111047111048111049111050111051111052111053111054111055111056111057111058111059111060111061111062111063111064111065111066111067111068111069111070111071111072111073111074111075111076111077111078111079111080111081111082111083111084111085111086111087111088111089111090111091111092111093111094111095111096111097111098111099111100111101111102111103111104111105111106111107111108111109111110111111111112111113111114111115111116111117111118111119111120111121111122111123111124111125111126111127111128111129111130111131111132111133111134111135111136111137111138111139111140111141111142111143111144111145111146111147111148111149111150111151111152111153111154111155111156111157111158111159111160111161111162111163111164111165111166111167111168111169111170111171111172111173111174111175111176111177111178111179111180111181111182111183111184111185111186111187111188111189111190111191111192111193111194111195111196111197111198111199111200111201111202111203111204111205111206111207111208111209111210111211111212111213111214111215111216111217111218111219111220111221111222111223111224111225111226111227111228111229111230111231111232111233111234111235111236111237111238111239111240111241111242111243111244111245111246111247111248111249111250111251111252111253111254111255111256111257111258111259111260111261111262111263111264111265111266111267111268111269111270111271111272111273111274111275111276111277111278111279111280111281111282111283111284111285111286111287111288111289111290111291111292111293111294111295111296111297111298111299111300111301111302111303111304111305111306111307111308111309111310111311111312111313111314111315111316111317111318111319111320111321111322111323111324111325111326111327111328111329111330111331111332111333111334111335111336111337111338111339111340111341111342111343111344111345111346111347111348111349111350111351111352111353111354111355111356111357111358111359111360111361111362111363111364111365111366111367111368111369111370111371111372111373111374111375111376111377111378111379111380111381111382111383111384111385111386111387111388111389111390111391111392111393111394111395111396111397111398111399111400111401111402111403111404111405111406111407111408111409111410111411111412111413111414111415111416111417111418111419111420111421111422111423111424111425111426111427111428111429111430111431111432111433111434111435111436111437111438111439111440111441111442111443111444111445111446111447111448111449111450111451111452111453111454111455111456111457111458111459111460111461111462111463111464111465111466111467111468111469111470111471111472111473111474111475111476111477111478111479111480111481111482111483111484111485111486111487111488111489111490111491111492111493111494111495111496111497111498111499111500111501111502111503111504111505111506111507111508111509111510111511111512111513111514111515111516111517111518111519111520111521111522111523111524111525111526111527111528111529111530111531111532111533111534111535111536111537111538111539111540111541111542111543111544111545111546111547111548111549111550111551111552111553111554111555111556111557111558111559111560111561111562111563111564111565111566111567111568111569111570111571111572111573111574111575111576111577111578111579111580111581111582111583111584111585111586111587111588111589111590111591111592111593111594111595111596111597111598111599111600111601111602111603111604111605111606111607111608111609111610111611111612111613111614111615111616111617111618111619111620111621111622111623111624111625111626111627111628111629111630111631111632111633111634111635111636111637111638111639111640111641111642111643111644111645111646111647111648111649111650111651111652111653111654111655111656111657111658111659111660111661111662111663111664111665111666111667111668111669111670111671111672111673111674111675111676111677111678111679111680111681111682111683111684111685111686111687111688111689111690111691111692111693111694111695111696111697111698111699111700111701111702111703111704111705111706111707111708111709111710111711111712111713111714111715111716111717111718111719111720111721111722111723111724111725111726111727111728111729111730111731111732111733111734111735111736111737111738111739111740111741111742111743111744111745111746111747111748111749111750111751111752111753111754111755111756111757111758111759111760111761111762111763111764111765111766111767111768111769111770111771111772111773111774111775111776111777111778111779111780111781111782111783111784111785111786111787111788111789111790111791111792111793111794111795111796111797111798111799111800111801111802111803111804111805111806111807111808111809111810111811111812111813111814111815111816111817111818111819111820111821111822111823111824111825111826111827111828111829111830111831111832111833111834111835111836111837111838111839111840111841111842111843111844111845111846111847111848111849111850111851111852111853111854111855111856111857111858111859111860111861111862111863111864111865111866111867111868111869111870111871111872111873111874111875111876111877111878111879111880111881111882111883111884111885111886111887111888111889111890111891111892111893111894111895111896111897111898111899111900111901111902111903111904111905111906111907111908111909111910111911111912111913111914111915111916111917111918111919111920111921111922111923111924111925111926111927111928111929111930111931111932111933111934111935111936111937111938111939111940111941111942111943111944111945111946111947111948111949111950111951111952111953111954111955111956111957111958111959111960111961111962111963111964111965111966111967111968111969111970111971111972111973111974111975111976111977111978111979111980111981111982111983111984111985111986111987111988111989111990111991111992111993111994111995111996111997111998111999112000112001112002112003112004112005112006112007112008112009112010112011112012112013112014112015112016112017112018112019112020112021112022112023112024112025112026112027112028112029112030112031112032112033112034112035112036112037112038112039112040112041112042112043112044112045112046112047112048112049112050112051112052112053112054112055112056112057112058112059112060112061112062112063112064112065112066112067112068112069112070112071112072112073112074112075112076112077112078112079112080112081112082112083112084112085112086112087112088112089112090112091112092112093112094112095112096112097112098112099112100112101112102112103112104112105112106112107112108112109112110112111112112112113112114112115112116112117112118112119112120112121112122112123112124112125112126112127112128112129112130112131112132112133112134112135112136112137112138112139112140112141112142112143112144112145112146112147112148112149112150112151112152112153112154112155112156112157112158112159112160112161112162112163112164112165112166112167112168112169112170112171112172112173112174112175112176112177112178112179112180112181112182112183112184112185112186112187112188112189112190112191112192112193112194112195112196112197112198112199112200112201112202112203112204112205112206112207112208112209112210112211112212112213112214112215112216112217112218112219112220112221112222112223112224112225112226112227112228112229112230112231112232112233112234112235112236112237112238112239112240112241112242112243112244112245112246112247112248112249112250112251112252112253112254112255112256112257112258112259112260112261112262112263112264112265112266112267112268112269112270112271112272112273112274112275112276112277112278112279112280112281112282112283112284112285112286112287112288112289112290112291112292112293112294112295112296112297112298112299112300112301112302112303112304112305112306112307112308112309112310112311112312112313112314112315112316112317112318112319112320112321112322112323112324112325112326112327112328112329112330112331112332112333112334112335112336112337112338112339112340112341112342112343112344112345112346112347112348112349112350112351112352112353112354112355112356112357112358112359112360112361112362112363112364112365112366112367112368112369112370112371112372112373112374112375112376112377112378112379112380112381112382112383112384112385112386112387112388112389112390112391112392112393112394112395112396112397112398112399112400112401112402112403112404112405112406112407112408112409112410112411112412112413112414112415112416112417112418112419112420112421112422112423112424112425112426112427112428112429112430112431112432112433112434112435112436112437112438112439112440112441112442112443112444112445112446112447112448112449112450112451112452112453112454112455112456112457112458112459112460112461112462112463112464112465112466112467112468112469112470112471112472112473112474112475112476112477112478112479112480112481112482112483112484112485112486112487112488112489112490112491112492112493112494112495112496112497112498112499112500112501112502112503112504112505112506112507112508112509112510112511112512112513112514112515112516112517112518112519112520112521112522112523112524112525112526112527112528112529112530112531112532112533112534112535112536112537112538112539112540112541112542112543112544112545112546112547112548112549112550112551112552112553112554112555112556112557112558112559112560112561112562112563112564112565112566112567112568112569112570112571112572112573112574112575112576112577112578112579112580112581112582112583112584112585112586112587112588112589112590112591112592112593112594112595112596112597112598112599112600112601112602112603112604112605112606112607112608112609112610112611112612112613112614112615112616112617112618112619112620112621112622112623112624112625112626112627112628112629112630112631112632112633112634112635112636112637112638112639112640112641112642112643112644112645112646112647112648112649112650112651112652112653112654112655112656112657112658112659112660112661112662112663112664112665112666112667112668112669112670112671112672112673112674112675112676112677112678112679112680112681112682112683112684112685112686112687112688112689112690112691112692112693112694112695112696112697112698112699112700112701112702112703112704112705112706112707112708112709112710112711112712112713112714112715112716112717112718112719112720112721112722112723112724112725112726112727112728112729112730112731112732112733112734112735112736112737112738112739112740112741112742112743112744112745112746112747112748112749112750112751112752112753112754112755112756112757112758112759112760112761112762112763112764112765112766112767112768112769112770112771112772112773112774112775112776112777112778112779112780112781112782112783112784112785112786112787112788112789112790112791112792112793112794112795112796112797112798112799112800112801112802112803112804112805112806112807112808112809112810112811112812112813112814112815112816112817112818112819112820112821112822112823112824112825112826112827112828112829112830112831112832112833112834112835112836112837112838112839112840112841112842112843112844112845112846112847112848112849112850112851112852112853112854112855112856112857112858112859112860112861112862112863112864112865112866112867112868112869112870112871112872112873112874112875112876112877112878112879112880112881112882112883112884112885112886112887112888112889112890112891112892112893112894112895112896112897112898112899112900112901112902112903112904112905112906112907112908112909112910112911112912112913112914112915112916112917112918112919112920112921112922112923112924112925112926112927112928112929112930112931112932112933112934112935112936112937112938112939112940112941112942112943112944112945112946112947112948112949112950112951112952112953112954112955112956112957112958112959112960112961112962112963112964112965112966112967112968112969112970112971112972112973112974112975112976112977112978112979112980112981112982112983112984112985112986112987112988112989112990112991112992112993112994112995112996112997112998112999113000113001113002113003113004113005113006113007113008113009113010113011113012113013113014113015113016113017113018113019113020113021113022113023113024113025113026113027113028113029113030113031113032113033113034113035113036113037113038113039113040113041113042113043113044113045113046113047113048113049113050113051113052113053113054113055113056113057113058113059113060113061113062113063113064113065113066113067113068113069113070113071113072113073113074113075113076113077113078113079113080113081113082113083113084113085113086113087113088113089113090113091113092113093113094113095113096113097113098113099113100113101113102113103113104113105113106113107113108113109113110113111113112113113113114113115113116113117113118113119113120113121113122113123113124113125113126113127113128113129113130113131113132113133113134113135113136113137113138113139113140113141113142113143113144113145113146113147113148113149113150113151113152113153113154113155113156113157113158113159113160113161113162113163113164113165113166113167113168113169113170113171113172113173113174113175113176113177113178113179113180113181113182113183113184113185113186113187113188113189113190113191113192113193113194113195113196113197113198113199113200113201113202113203113204113205113206113207113208113209113210113211113212113213113214113215113216113217113218113219113220113221113222113223113224113225113226113227113228113229113230113231113232113233113234113235113236113237113238113239113240113241113242113243113244113245113246113247113248113249113250113251113252113253113254113255113256113257113258113259113260113261113262113263113264113265113266113267113268113269113270113271113272113273113274113275113276113277113278113279113280113281113282113283113284113285113286113287113288113289113290113291113292113293113294113295113296113297113298113299113300113301113302113303113304113305113306113307113308113309113310113311113312113313113314113315113316113317113318113319113320113321113322113323113324113325113326113327113328113329113330113331113332113333113334113335113336113337113338113339113340113341113342113343113344113345113346113347113348113349113350113351113352113353113354113355113356113357113358113359113360113361113362113363113364113365113366113367113368113369113370113371113372113373113374113375113376113377113378113379113380113381113382113383113384113385113386113387113388113389113390113391113392113393113394113395113396113397113398113399113400113401113402113403113404113405113406113407113408113409113410113411113412113413113414113415113416113417113418113419113420113421113422113423113424113425113426113427113428113429113430113431113432113433113434113435113436113437113438113439113440113441113442113443113444113445113446113447113448113449113450113451113452113453113454113455113456113457113458113459113460113461113462113463113464113465113466113467113468113469113470113471113472113473113474113475113476113477113478113479113480113481113482113483113484113485113486113487113488113489113490113491113492113493113494113495113496113497113498113499113500113501113502113503113504113505113506113507113508113509113510113511113512113513113514113515113516113517113518113519113520113521113522113523113524113525113526113527113528113529113530113531113532113533113534113535113536113537113538113539113540113541113542113543113544113545113546113547113548113549113550113551113552113553113554113555113556113557113558113559113560113561113562113563113564113565113566113567113568113569113570113571113572113573113574113575113576113577113578113579113580113581113582113583113584113585113586113587113588113589113590113591113592113593113594113595113596113597113598113599113600113601113602113603113604113605113606113607113608113609113610113611113612113613113614113615113616113617113618113619113620113621113622113623113624113625113626113627113628113629113630113631113632113633113634113635113636113637113638113639113640113641113642113643113644113645113646113647113648113649113650113651113652113653113654113655113656113657113658113659113660113661113662113663113664113665113666113667113668113669113670113671113672113673113674113675113676113677113678113679113680113681113682113683113684113685113686113687113688113689113690113691113692113693113694113695113696113697113698113699113700113701113702113703113704113705113706113707113708113709113710113711113712113713113714113715113716113717113718113719113720113721113722113723113724113725113726113727113728113729113730113731113732113733113734113735113736113737113738113739113740113741113742113743113744113745113746113747113748113749113750113751113752113753113754113755113756113757113758113759113760113761113762113763113764113765113766113767113768113769113770113771113772113773113774113775113776113777113778113779113780113781113782113783113784113785113786113787113788113789113790113791113792113793113794113795113796113797113798113799113800113801113802113803113804113805113806113807113808113809113810113811113812113813113814113815113816113817113818113819113820113821113822113823113824113825113826113827113828113829113830113831113832113833113834113835113836113837113838113839113840113841113842113843113844113845113846113847113848113849113850113851113852113853113854113855113856113857113858113859113860113861113862113863113864113865113866113867113868113869113870113871113872113873113874113875113876113877113878113879113880113881113882113883113884113885113886113887113888113889113890113891113892113893113894113895113896113897113898113899113900113901113902113903113904113905113906113907113908113909113910113911113912113913113914113915113916113917113918113919113920113921113922113923113924113925113926113927113928113929113930113931113932113933113934113935113936113937113938113939113940113941113942113943113944113945113946113947113948113949113950113951113952113953113954113955113956113957113958113959113960113961113962113963113964113965113966113967113968113969113970113971113972113973113974113975113976113977113978113979113980113981113982113983113984113985113986113987113988113989113990113991113992113993113994113995113996113997113998113999114000114001114002114003114004114005114006114007114008114009114010114011114012114013114014114015114016114017114018114019114020114021114022114023114024114025114026114027114028114029114030114031114032114033114034114035114036114037114038114039114040114041114042114043114044114045114046114047114048114049114050114051114052114053114054114055114056114057114058114059114060114061114062114063114064114065114066114067114068114069114070114071114072114073114074114075114076114077114078114079114080114081114082114083114084114085114086114087114088114089114090114091114092114093114094114095114096114097114098114099114100114101114102114103114104114105114106114107114108114109114110114111114112114113114114114115114116114117114118114119114120114121114122114123114124114125114126114127114128114129114130114131114132114133114134114135114136114137114138114139114140114141114142114143114144114145114146114147114148114149114150114151114152114153114154114155114156114157114158114159114160114161114162114163114164114165114166114167114168114169114170114171114172114173114174114175114176114177114178114179114180114181114182114183114184114185114186114187114188114189114190114191114192114193114194114195114196114197114198114199114200114201114202114203114204114205114206114207114208114209114210114211114212114213114214114215114216114217114218114219114220114221114222114223114224114225114226114227114228114229114230114231114232114233114234114235114236114237114238114239114240114241114242114243114244114245114246114247114248114249114250114251114252114253114254114255114256114257114258114259114260114261114262114263114264114265114266114267114268114269114270114271114272114273114274114275114276114277114278114279114280114281114282114283114284114285114286114287114288114289114290114291114292114293114294114295114296114297114298114299114300114301114302114303114304114305114306114307114308114309114310114311114312114313114314114315114316114317114318114319114320114321114322114323114324114325114326114327114328114329114330114331114332114333114334114335114336114337114338114339114340114341114342114343114344114345114346114347114348114349114350114351114352114353114354114355114356114357114358114359114360114361114362114363114364114365114366114367114368114369114370114371114372114373114374114375114376114377114378114379114380114381114382114383114384114385114386114387114388114389114390114391114392114393114394114395114396114397114398114399114400114401114402114403114404114405114406114407114408114409114410114411114412114413114414114415114416114417114418114419114420114421114422114423114424114425114426114427114428114429114430114431114432114433114434114435114436114437114438114439114440114441114442114443114444114445114446114447114448114449114450114451114452114453114454114455114456114457114458114459114460114461114462114463114464114465114466114467114468114469114470114471114472114473114474114475114476114477114478114479114480114481114482114483114484114485114486114487114488114489114490114491114492114493114494114495114496114497114498114499114500114501114502114503114504114505114506114507114508114509114510114511114512114513114514114515114516114517114518114519114520114521114522114523114524114525114526114527114528114529114530114531114532114533114534114535114536114537114538114539114540114541114542114543114544114545114546114547114548114549114550114551114552114553114554114555114556114557114558114559114560114561114562114563114564114565114566114567114568114569114570114571114572114573114574114575114576114577114578114579114580114581114582114583114584114585114586114587114588114589114590114591114592114593114594114595114596114597114598114599114600114601114602114603114604114605114606114607114608114609114610114611114612114613114614114615114616114617114618114619114620114621114622114623114624114625114626114627114628114629114630114631114632114633114634114635114636114637114638114639114640114641114642114643114644114645114646114647114648114649114650114651114652114653114654114655114656114657114658114659114660114661114662114663114664114665114666114667114668114669114670114671114672114673114674114675114676114677114678114679114680114681114682114683114684114685114686114687114688114689114690114691114692114693114694114695114696114697114698114699114700114701114702114703114704114705114706114707114708114709114710114711114712114713114714114715114716114717114718114719114720114721114722114723114724114725114726114727114728114729114730114731114732114733114734114735114736114737114738114739114740114741114742114743114744114745114746114747114748114749114750114751114752114753114754114755114756114757114758114759114760114761114762114763114764114765114766114767114768114769114770114771114772114773114774114775114776114777114778114779114780114781114782114783114784114785114786114787114788114789114790114791114792114793114794114795114796114797114798114799114800114801114802114803114804114805114806114807114808114809114810114811114812114813114814114815114816114817114818114819114820114821114822114823114824114825114826114827114828114829114830114831114832114833114834114835114836114837114838114839114840114841114842114843114844114845114846114847114848114849114850114851114852114853114854114855114856114857114858114859114860114861114862114863114864114865114866114867114868114869114870114871114872114873114874114875114876114877114878114879114880114881114882114883114884114885114886114887114888114889114890114891114892114893114894114895114896114897114898114899114900114901114902114903114904114905114906114907114908114909114910114911114912114913114914114915114916114917114918114919114920114921114922114923114924114925114926114927114928114929114930114931114932114933114934114935114936114937114938114939114940114941114942114943114944114945114946114947114948114949114950114951114952114953114954114955114956114957114958114959114960114961114962114963114964114965114966114967114968114969114970114971114972114973114974114975114976114977114978114979114980114981114982114983114984114985114986114987114988114989114990114991114992114993114994114995114996114997114998114999115000115001115002115003115004115005115006115007115008115009115010115011115012115013115014115015115016115017115018115019115020115021115022115023115024115025115026115027115028115029115030115031115032115033115034115035115036115037115038115039115040115041115042115043115044115045115046115047115048115049115050115051115052115053115054115055115056115057115058115059115060115061115062115063115064115065115066115067115068115069115070115071115072115073115074115075115076115077115078115079115080115081115082115083115084115085115086115087115088115089115090115091115092115093115094115095115096115097115098115099115100115101115102115103115104115105115106115107115108115109115110115111115112115113115114115115115116115117115118115119115120115121115122115123115124115125115126115127115128115129115130115131115132115133115134115135115136115137115138115139115140115141115142115143115144115145115146115147115148115149115150115151115152115153115154115155115156115157115158115159115160115161115162115163115164115165115166115167115168115169115170115171115172115173115174115175115176115177115178115179115180115181115182115183115184115185115186115187115188115189115190115191115192115193115194115195115196115197115198115199115200115201115202115203115204115205115206115207115208115209115210115211115212115213115214115215115216115217115218115219115220115221115222115223115224115225115226115227115228115229115230115231115232115233115234115235115236115237115238115239115240115241115242115243115244115245115246115247115248115249115250115251115252115253115254115255115256115257115258115259115260115261115262115263115264115265115266115267115268115269115270115271115272115273115274115275115276115277115278115279115280115281115282115283115284115285115286115287115288115289115290115291115292115293115294115295115296115297115298115299115300115301115302115303115304115305115306115307115308115309115310115311115312115313115314115315115316115317115318115319115320115321115322115323115324115325115326115327115328115329115330115331115332115333115334115335115336115337115338115339115340115341115342115343115344115345115346115347115348115349115350115351115352115353115354115355115356115357115358115359115360115361115362115363115364115365115366115367115368115369115370115371115372115373115374115375115376115377115378115379115380115381115382115383115384115385115386115387115388115389115390115391115392115393115394115395115396115397115398115399115400115401115402115403115404115405115406115407115408115409115410115411115412115413115414115415115416115417115418115419115420115421115422115423115424115425115426115427115428115429115430115431115432115433115434115435115436115437115438115439115440115441115442115443115444115445115446115447115448115449115450115451115452115453115454115455115456115457115458115459115460115461115462115463115464115465115466115467115468115469115470115471115472115473115474115475115476115477115478115479115480115481115482115483115484115485115486115487115488115489115490115491115492115493115494115495115496115497115498115499115500115501115502115503115504115505115506115507115508115509115510115511115512115513115514115515115516115517115518115519115520115521115522115523115524115525115526115527115528115529115530115531115532115533115534115535115536115537115538115539115540115541115542115543115544115545115546115547115548115549115550115551115552115553115554115555115556115557115558115559115560115561115562115563115564115565115566115567115568115569115570115571115572115573115574115575115576115577115578115579115580115581115582115583115584115585115586115587115588115589115590115591115592115593115594115595115596115597115598115599115600115601115602115603115604115605115606115607115608115609115610115611115612115613115614115615115616115617115618115619115620115621115622115623115624115625115626115627115628115629115630115631115632115633115634115635115636115637115638115639115640115641115642115643115644115645115646115647115648115649115650115651115652115653115654115655115656115657115658115659115660115661115662115663115664115665115666115667115668115669115670115671115672115673115674115675115676115677115678115679115680115681115682115683115684115685115686115687115688115689115690115691115692115693115694115695115696115697115698115699115700115701115702115703115704115705115706115707115708115709115710115711115712115713115714115715115716115717115718115719115720115721115722115723115724115725115726115727115728115729115730115731115732115733115734115735115736115737115738115739115740115741115742115743115744115745115746115747115748115749115750115751115752115753115754115755115756115757115758115759115760115761115762115763115764115765115766115767115768115769115770115771115772115773115774115775115776115777115778115779115780115781115782115783115784115785115786115787115788115789115790115791115792115793115794115795115796115797115798115799115800115801115802115803115804115805115806115807115808115809115810115811115812115813115814115815115816115817115818115819115820115821115822115823115824115825115826115827115828115829115830115831115832115833115834115835115836115837115838115839115840115841115842115843115844115845115846115847115848115849115850115851115852115853115854115855115856115857115858115859115860115861115862115863115864115865115866115867115868115869115870115871115872115873115874115875115876115877115878115879115880115881115882115883115884115885115886115887115888115889115890115891115892115893115894115895115896115897115898115899115900115901115902115903115904115905115906115907115908115909115910115911115912115913115914115915115916115917115918115919115920115921115922115923115924115925115926115927115928115929115930115931115932115933115934115935115936115937115938115939115940115941115942115943115944115945115946115947115948115949115950115951115952115953115954115955115956115957115958115959115960115961115962115963115964115965115966115967115968115969115970115971115972115973115974115975115976115977115978115979115980115981115982115983115984115985115986115987115988115989115990115991115992115993115994115995115996115997115998115999116000116001116002116003116004116005116006116007116008116009116010116011116012116013116014116015116016116017116018116019116020116021116022116023116024116025116026116027116028116029116030116031116032116033116034116035116036116037116038116039116040116041116042116043116044116045116046116047116048116049116050116051116052116053116054116055116056116057116058116059116060116061116062116063116064116065116066116067116068116069116070116071116072116073116074116075116076116077116078116079116080116081116082116083116084116085116086116087116088116089116090116091116092116093116094116095116096116097116098116099116100116101116102116103116104116105116106116107116108116109116110116111116112116113116114116115116116116117116118116119116120116121116122116123116124116125116126116127116128116129116130116131116132116133116134116135116136116137116138116139116140116141116142116143116144116145116146116147116148116149116150116151116152116153116154116155116156116157116158116159116160116161116162116163116164116165116166116167116168116169116170116171116172116173116174116175116176116177116178116179116180116181116182116183116184116185116186116187116188116189116190116191116192116193116194116195116196116197116198116199116200116201116202116203116204116205116206116207116208116209116210116211116212116213116214116215116216116217116218116219116220116221116222116223116224116225116226116227116228116229116230116231116232116233116234116235116236116237116238116239116240116241116242116243116244116245116246116247116248116249116250116251116252116253116254116255116256116257116258116259116260116261116262116263116264116265116266116267116268116269116270116271116272116273116274116275116276116277116278116279116280116281116282116283116284116285116286116287116288116289116290116291116292116293116294116295116296116297116298116299116300116301116302116303116304116305116306116307116308116309116310116311116312116313116314116315116316116317116318116319116320116321116322116323116324116325116326116327116328116329116330116331116332116333116334116335116336116337116338116339116340116341116342116343116344116345116346116347116348116349116350116351116352116353116354116355116356116357116358116359116360116361116362116363116364116365116366116367116368116369116370116371116372116373116374116375116376116377116378116379116380116381116382116383116384116385116386116387116388116389116390116391116392116393116394116395116396116397116398116399116400116401116402116403116404116405116406116407116408116409116410116411116412116413116414116415116416116417116418116419116420116421116422116423116424116425116426116427116428116429116430116431116432116433116434116435116436116437116438116439116440116441116442116443116444116445116446116447116448116449116450116451116452116453116454116455116456116457116458116459116460116461116462116463116464116465116466116467116468116469116470116471116472116473116474116475116476116477116478116479116480116481116482116483116484116485116486116487116488116489116490116491116492116493116494116495116496116497116498116499116500116501116502116503116504116505116506116507116508116509116510116511116512116513116514116515116516116517116518116519116520116521116522116523116524116525116526116527116528116529116530116531116532116533116534116535116536116537116538116539116540116541116542116543116544116545116546116547116548116549116550116551116552116553116554116555116556116557116558116559116560116561116562116563116564116565116566116567116568116569116570116571116572116573116574116575116576116577116578116579116580116581116582116583116584116585116586116587116588116589116590116591116592116593116594116595116596116597116598116599116600116601116602116603116604116605116606116607116608116609116610116611116612116613116614116615116616116617116618116619116620116621116622116623116624116625116626116627116628116629116630116631116632116633116634116635116636116637116638116639116640116641116642116643116644116645116646116647116648116649116650116651116652116653116654116655116656116657116658116659116660116661116662116663116664116665116666116667116668116669116670116671116672116673116674116675116676116677116678116679116680116681116682116683116684116685116686116687116688116689116690116691116692116693116694116695116696116697116698116699116700116701116702116703116704116705116706116707116708116709116710116711116712116713116714116715116716116717116718116719116720116721116722116723116724116725116726116727116728116729116730116731116732116733116734116735116736116737116738116739116740116741116742116743116744116745116746116747116748116749116750116751116752116753116754116755116756116757116758116759116760116761116762116763116764116765116766116767116768116769116770116771116772116773116774116775116776116777116778116779116780116781116782116783116784116785116786116787116788116789116790116791116792116793116794116795116796116797116798116799116800116801116802116803116804116805116806116807116808116809116810116811116812116813116814116815116816116817116818116819116820116821116822116823116824116825116826116827116828116829116830116831116832116833116834116835116836116837116838116839116840116841116842116843116844116845116846116847116848116849116850116851116852116853116854116855116856116857116858116859116860116861116862116863116864116865116866116867116868116869116870116871116872116873116874116875116876116877116878116879116880116881116882116883116884116885116886116887116888116889116890116891116892116893116894116895116896116897116898116899116900116901116902116903116904116905116906116907116908116909116910116911116912116913116914116915116916116917116918116919116920116921116922116923116924116925116926116927116928116929116930116931116932116933116934116935116936116937116938116939116940116941116942116943116944116945116946116947116948116949116950116951116952116953116954116955116956116957116958116959116960116961116962116963116964116965116966116967116968116969116970116971116972116973116974116975116976116977116978116979116980116981116982116983116984116985116986116987116988116989116990116991116992116993116994116995116996116997116998116999117000117001117002117003117004117005117006117007117008117009117010117011117012117013117014117015117016117017117018117019117020117021117022117023117024117025117026117027117028117029117030117031117032117033117034117035117036117037117038117039117040117041117042117043117044117045117046117047117048117049117050117051117052117053117054117055117056117057117058117059117060117061117062117063117064117065117066117067117068117069117070117071117072117073117074117075117076117077117078117079117080117081117082117083117084117085117086117087117088117089117090117091117092117093117094117095117096117097117098117099117100117101117102117103117104117105117106117107117108117109117110117111117112117113117114117115117116117117117118117119117120117121117122117123117124117125117126117127117128117129117130117131117132117133117134117135117136117137117138117139117140117141117142117143117144117145117146117147117148117149117150117151117152117153117154117155117156117157117158117159117160117161117162117163117164117165117166117167117168117169117170117171117172117173117174117175117176117177117178117179117180117181117182117183117184117185117186117187117188117189117190117191117192117193117194117195117196117197117198117199117200117201117202117203117204117205117206117207117208117209117210117211117212117213117214117215117216117217117218117219117220117221117222117223117224117225117226117227117228117229117230117231117232117233117234117235117236117237117238117239117240117241117242117243117244117245117246117247117248117249117250117251117252117253117254117255117256117257117258117259117260117261117262117263117264117265117266117267117268117269117270117271117272117273117274117275117276117277117278117279117280117281117282117283117284117285117286117287117288117289117290117291117292117293117294117295117296117297117298117299117300117301117302117303117304117305117306117307117308117309117310117311117312117313117314117315117316117317117318117319117320117321117322117323117324117325117326117327117328117329117330117331117332117333117334117335117336117337117338117339117340117341117342117343117344117345117346117347117348117349117350117351117352117353117354117355117356117357117358117359117360117361117362117363117364117365117366117367117368117369117370117371117372117373117374117375117376117377117378117379117380117381117382117383117384117385117386117387117388117389117390117391117392117393117394117395117396117397117398117399117400117401117402117403117404117405117406117407117408117409117410117411117412117413117414117415117416117417117418117419117420117421117422117423117424117425117426117427117428117429117430117431117432117433117434117435117436117437117438117439117440117441117442117443117444117445117446117447117448117449117450117451117452117453117454117455117456117457117458117459117460117461117462117463117464117465117466117467117468117469117470117471117472117473117474117475117476117477117478117479117480117481117482117483117484117485117486117487117488117489117490117491117492117493117494117495117496117497117498117499117500117501117502117503117504117505117506117507117508117509117510117511117512117513117514117515117516117517117518117519117520117521117522117523117524117525117526117527117528117529117530117531117532117533117534117535117536117537117538117539117540117541117542117543117544117545117546117547117548117549117550117551117552117553117554117555117556117557117558117559117560117561117562117563117564117565117566117567117568117569117570117571117572117573117574117575117576117577117578117579117580117581117582117583117584117585117586117587117588117589117590117591117592117593117594117595117596117597117598117599117600117601117602117603117604117605117606117607117608117609117610117611117612117613117614117615117616117617117618117619117620117621117622117623117624117625117626117627117628117629117630117631117632117633117634117635117636117637117638117639117640117641117642117643117644117645117646117647117648117649117650117651117652117653117654117655117656117657117658117659117660117661117662117663117664117665117666117667117668117669117670117671117672117673117674117675117676117677117678117679117680117681117682117683117684117685117686117687117688117689117690117691117692117693117694117695117696117697117698117699117700117701117702117703117704117705117706117707117708117709117710117711117712117713117714117715117716117717117718117719117720117721117722117723117724117725117726117727117728117729117730117731117732117733117734117735117736117737117738117739117740117741117742117743117744117745117746117747117748117749117750117751117752117753117754117755117756117757117758117759117760117761117762117763117764117765117766117767117768117769117770117771117772117773117774117775117776117777117778117779117780117781117782117783117784117785117786117787117788117789117790117791117792117793117794117795117796117797117798117799117800117801117802117803117804117805117806117807117808117809117810117811117812117813117814117815117816117817117818117819117820117821117822117823117824117825117826117827117828117829117830117831117832117833117834117835117836117837117838117839117840117841117842117843117844117845117846117847117848117849117850117851117852117853117854117855117856117857117858117859117860117861117862117863117864117865117866117867117868117869117870117871117872117873117874117875117876117877117878117879117880117881117882117883117884117885117886117887117888117889117890117891117892117893117894117895117896117897117898117899117900117901117902117903117904117905117906117907117908117909117910117911117912117913117914117915117916117917117918117919117920117921117922117923117924117925117926117927117928117929117930117931117932117933117934117935117936117937117938117939117940117941117942117943117944117945117946117947117948117949117950117951117952117953117954117955117956117957117958117959117960117961117962117963117964117965117966117967117968117969117970117971117972117973117974117975117976117977117978117979117980117981117982117983117984117985117986117987117988117989117990117991117992117993117994117995117996117997117998117999118000118001118002118003118004118005118006118007118008118009118010118011118012118013118014118015118016118017118018118019118020118021118022118023118024118025118026118027118028118029118030118031118032118033118034118035118036118037118038118039118040118041118042118043118044118045118046118047118048118049118050118051118052118053118054118055118056118057118058118059118060118061118062118063118064118065118066118067118068118069118070118071118072118073118074118075118076118077118078118079118080118081118082118083118084118085118086118087118088118089118090118091118092118093118094118095118096118097118098118099118100118101118102118103118104118105118106118107118108118109118110118111118112118113118114118115118116118117118118118119118120118121118122118123118124118125118126118127118128118129118130118131118132118133118134118135118136118137118138118139118140118141118142118143118144118145118146118147118148118149118150118151118152118153118154118155118156118157118158118159118160118161118162118163118164118165118166118167118168118169118170118171118172118173118174118175118176118177118178118179118180118181118182118183118184118185118186118187118188118189118190118191118192118193118194118195118196118197118198118199118200118201118202118203118204118205118206118207118208118209118210118211118212118213118214118215118216118217118218118219118220118221118222118223118224118225118226118227118228118229118230118231118232118233118234118235118236118237118238118239118240118241118242118243118244118245118246118247118248118249118250118251118252118253118254118255118256118257118258118259118260118261118262118263118264118265118266118267118268118269118270118271118272118273118274118275118276118277118278118279118280118281118282118283118284118285118286118287118288118289118290118291118292118293118294118295118296118297118298118299118300118301118302118303118304118305118306118307118308118309118310118311118312118313118314118315118316118317118318118319118320118321118322118323118324118325118326118327118328118329118330118331118332118333118334118335118336118337118338118339118340118341118342118343118344118345118346118347118348118349118350118351118352118353118354118355118356118357118358118359118360118361118362118363118364118365118366118367118368118369118370118371118372118373118374118375118376118377118378118379118380118381118382118383118384118385118386118387118388118389118390118391118392118393118394118395118396118397118398118399118400118401118402118403118404118405118406118407118408118409118410118411118412118413118414118415118416118417118418118419118420118421118422118423118424118425118426118427118428118429118430118431118432118433118434118435118436118437118438118439118440118441118442118443118444118445118446118447118448118449118450118451118452118453118454118455118456118457118458118459118460118461118462118463118464118465118466118467118468118469118470118471118472118473118474118475118476118477118478118479118480118481118482118483118484118485118486118487118488118489118490118491118492118493118494118495118496118497118498118499118500118501118502118503118504118505118506118507118508118509118510118511118512118513118514118515118516118517118518118519118520118521118522118523118524118525118526118527118528118529118530118531118532118533118534118535118536118537118538118539118540118541118542118543118544118545118546118547118548118549118550118551118552118553118554118555118556118557118558118559118560118561118562118563118564118565118566118567118568118569118570118571118572118573118574118575118576118577118578118579118580118581118582118583118584118585118586118587118588118589118590118591118592118593118594118595118596118597118598118599118600118601118602118603118604118605118606118607118608118609118610118611118612118613118614118615118616118617118618118619118620118621118622118623118624118625118626118627118628118629118630118631118632118633118634118635118636118637118638118639118640118641118642118643118644118645118646118647118648118649118650118651118652118653118654118655118656118657118658118659118660118661118662118663118664118665118666118667118668118669118670118671118672118673118674118675118676118677118678118679118680118681118682118683118684118685118686118687118688118689118690118691118692118693118694118695118696118697118698118699118700118701118702118703118704118705118706118707118708118709118710118711118712118713118714118715118716118717118718118719118720118721118722118723118724118725118726118727118728118729118730118731118732118733118734118735118736118737118738118739118740118741118742118743118744118745118746118747118748118749118750118751118752118753118754118755118756118757118758118759118760118761118762118763118764118765118766118767118768118769118770118771118772118773118774118775118776118777118778118779118780118781118782118783118784118785118786118787118788118789118790118791118792118793118794118795118796118797118798118799118800118801118802118803118804118805118806118807118808118809118810118811118812118813118814118815118816118817118818118819118820118821118822118823118824118825118826118827118828118829118830118831118832118833118834118835118836118837118838118839118840118841118842118843118844118845118846118847118848118849118850118851118852118853118854118855118856118857118858118859118860118861118862118863118864118865118866118867118868118869118870118871118872118873118874118875118876118877118878118879118880118881118882118883118884118885118886118887118888118889118890118891118892118893118894118895118896118897118898118899118900118901118902118903118904118905118906118907118908118909118910118911118912118913118914118915118916118917118918118919118920118921118922118923118924118925118926118927118928118929118930118931118932118933118934118935118936118937118938118939118940118941118942118943118944118945118946118947118948118949118950118951118952118953118954118955118956118957118958118959118960118961118962118963118964118965118966118967118968118969118970118971118972118973118974118975118976118977118978118979118980118981118982118983118984118985118986118987118988118989118990118991118992118993118994118995118996118997118998118999119000119001119002119003119004119005119006119007119008119009119010119011119012119013119014119015119016119017119018119019119020119021119022119023119024119025119026119027119028119029119030119031119032119033119034119035119036119037119038119039119040119041119042119043119044119045119046119047119048119049119050119051119052119053119054119055119056119057119058119059119060119061119062119063119064119065119066119067119068119069119070119071119072119073119074119075119076119077119078119079119080119081119082119083119084119085119086119087119088119089119090119091119092119093119094119095119096119097119098119099119100119101119102119103119104119105119106119107119108119109119110119111119112119113119114119115119116119117119118119119119120119121119122119123119124119125119126119127119128119129119130119131119132119133119134119135119136119137119138119139119140119141119142119143119144119145119146119147119148119149119150119151119152119153119154119155119156119157119158119159119160119161119162119163119164119165119166119167119168119169119170119171119172119173119174119175119176119177119178119179119180119181119182119183119184119185119186119187119188119189119190119191119192119193119194119195119196119197119198119199119200119201119202119203119204119205119206119207119208119209119210119211119212119213119214119215119216119217119218119219119220119221119222119223119224119225119226119227119228119229119230119231119232119233119234119235119236119237119238119239119240119241119242119243119244119245119246119247119248119249119250119251119252119253119254119255119256119257119258119259119260119261119262119263119264119265119266119267119268119269119270119271119272119273119274119275119276119277119278119279119280119281119282119283119284119285119286119287119288119289119290119291119292119293119294119295119296119297119298119299119300119301119302119303119304119305119306119307119308119309119310119311119312119313119314119315119316119317119318119319119320119321119322119323119324119325119326119327119328119329119330119331119332119333119334119335119336119337119338119339119340119341119342119343119344119345119346119347119348119349119350119351119352119353119354119355119356119357119358119359119360119361119362119363119364119365119366119367119368119369119370119371119372119373119374119375119376119377119378119379119380119381119382119383119384119385119386119387119388119389119390119391119392119393119394119395119396119397119398119399119400119401119402119403119404119405119406119407119408119409119410119411119412119413119414119415119416119417119418119419119420119421119422119423119424119425119426119427119428119429119430119431119432119433119434119435119436119437119438119439119440119441119442119443119444119445119446119447119448119449119450119451119452119453119454119455119456119457119458119459119460119461119462119463119464119465119466119467119468119469119470119471119472119473119474119475119476119477119478119479119480119481119482119483119484119485119486119487119488119489119490119491119492119493119494119495119496119497119498119499119500119501119502119503119504119505119506119507119508119509119510119511119512119513119514119515119516119517119518119519119520119521119522119523119524119525119526119527119528119529119530119531119532119533119534119535119536119537119538119539119540119541119542119543119544119545119546119547119548119549119550119551119552119553119554119555119556119557119558119559119560119561119562119563119564119565119566119567119568119569119570119571119572119573119574119575119576119577119578119579119580119581119582119583119584119585119586119587119588119589119590119591119592119593119594119595119596119597119598119599119600119601119602119603119604119605119606119607119608119609119610119611119612119613119614119615119616119617119618119619119620119621119622119623119624119625119626119627119628119629119630119631119632119633119634119635119636119637119638119639119640119641119642119643119644119645119646119647119648119649119650119651119652119653119654119655119656119657119658119659119660119661119662119663119664119665119666119667119668119669119670119671119672119673119674119675119676119677119678119679119680119681119682119683119684119685119686119687119688119689119690119691119692119693119694119695119696119697119698119699119700119701119702119703119704119705119706119707119708119709119710119711119712119713119714119715119716119717119718119719119720119721119722119723119724119725119726119727119728119729119730119731119732119733119734119735119736119737119738119739119740119741119742119743119744119745119746119747119748119749119750119751119752119753119754119755119756119757119758119759119760119761119762119763119764119765119766119767119768119769119770119771119772119773119774119775119776119777119778119779119780119781119782119783119784119785119786119787119788119789119790119791119792119793119794119795119796119797119798119799119800119801119802119803119804119805119806119807119808119809119810119811119812119813119814119815119816119817119818119819119820119821119822119823119824119825119826119827119828119829119830119831119832119833119834119835119836119837119838119839119840119841119842119843119844119845119846119847119848119849119850119851119852119853119854119855119856119857119858119859119860119861119862119863119864119865119866119867119868119869119870119871119872119873119874119875119876119877119878119879119880119881119882119883119884119885119886119887119888119889119890119891119892119893119894119895119896119897119898119899119900119901119902119903119904119905119906119907119908119909119910119911119912119913119914119915119916119917119918119919119920119921119922119923119924119925119926119927119928119929119930119931119932119933119934119935119936119937119938119939119940119941119942119943119944119945119946119947119948119949119950119951119952119953119954119955119956119957119958119959119960119961119962119963119964119965119966119967119968119969119970119971119972119973119974119975119976119977119978119979119980119981119982119983119984119985119986119987119988119989119990119991119992119993119994119995119996119997119998119999120000120001120002120003120004120005120006120007120008120009120010120011120012120013120014120015120016120017120018120019120020120021120022120023120024120025120026120027120028120029120030120031120032120033120034120035120036120037120038120039120040120041120042120043120044120045120046120047120048120049120050120051120052120053120054120055120056120057120058120059120060120061120062120063120064120065120066120067120068120069120070120071120072120073120074120075120076120077120078120079120080120081120082120083120084120085120086120087120088120089120090120091120092120093120094120095120096120097120098120099120100120101120102120103120104120105120106120107120108120109120110120111120112120113120114120115120116120117120118120119120120120121120122120123120124120125120126120127120128120129120130120131120132120133120134120135120136120137120138120139120140120141120142120143120144120145120146120147120148120149120150120151120152120153120154120155120156120157120158120159120160120161120162120163120164120165120166120167120168120169120170120171120172120173120174120175120176120177120178120179120180120181120182120183120184120185120186120187120188120189120190120191120192120193120194120195120196120197120198120199120200120201120202120203120204120205120206120207120208120209120210120211120212120213120214120215120216120217120218120219120220120221120222120223120224120225120226120227120228120229120230120231120232120233120234120235120236120237120238120239120240120241120242120243120244120245120246120247120248120249120250120251120252120253120254120255120256120257120258120259120260120261120262120263120264120265120266120267120268120269120270120271120272120273120274120275120276120277120278120279120280120281120282120283120284120285120286120287120288120289120290120291120292120293120294120295120296120297120298120299120300120301120302120303120304120305120306120307120308120309120310120311120312120313120314120315120316120317120318120319120320120321120322120323120324120325120326120327120328120329120330120331120332120333120334120335120336120337120338120339120340120341120342120343120344120345120346120347120348120349120350120351120352120353120354120355120356120357120358120359120360120361120362120363120364120365120366120367120368120369120370120371120372120373120374120375120376120377120378120379120380120381120382120383120384120385120386120387120388120389120390120391120392120393120394120395120396120397120398120399120400120401120402120403120404120405120406120407120408120409120410120411120412120413120414120415120416120417120418120419120420120421120422120423120424120425120426120427120428120429120430120431120432120433120434120435120436120437120438120439120440120441120442120443120444120445120446120447120448120449120450120451120452120453120454120455120456120457120458120459120460120461120462120463120464120465120466120467120468120469120470120471120472120473120474120475120476120477120478120479120480120481120482120483120484120485120486120487120488120489120490120491120492120493120494120495120496120497120498120499120500120501120502120503120504120505120506120507120508120509120510120511120512120513120514120515120516120517120518120519120520120521120522120523120524120525120526120527120528120529120530120531120532120533120534120535120536120537120538120539120540120541120542120543120544120545120546120547120548120549120550120551120552120553120554120555120556120557120558120559120560120561120562120563120564120565120566120567120568120569120570120571120572120573120574120575120576120577120578120579120580120581120582120583120584120585120586120587120588120589120590120591120592120593120594120595120596120597120598120599120600120601120602120603120604120605120606120607120608120609120610120611120612120613120614120615120616120617120618120619120620120621120622120623120624120625120626120627120628120629120630120631120632120633120634120635120636120637120638120639120640120641120642120643120644120645120646120647120648120649120650120651120652120653120654120655120656120657120658120659120660120661120662120663120664120665120666120667120668120669120670120671120672120673120674120675120676120677120678120679120680120681120682120683120684120685120686120687120688120689120690120691120692120693120694120695120696120697120698120699120700120701120702120703120704120705120706120707120708120709120710120711120712120713120714120715120716120717120718120719120720120721120722120723120724120725120726120727120728120729120730120731120732120733120734120735120736120737120738120739120740120741120742120743120744120745120746120747120748120749120750120751120752120753120754120755120756120757120758120759120760120761120762120763120764120765120766120767120768120769120770120771120772120773120774120775120776120777120778120779120780120781120782120783120784120785120786120787120788120789120790120791120792120793120794120795120796120797120798120799120800120801120802120803120804120805120806120807120808120809120810120811120812120813120814120815120816120817120818120819120820120821120822120823120824120825120826120827120828120829120830120831120832120833120834120835120836120837120838120839120840120841120842120843120844120845120846120847120848120849120850120851120852120853120854120855120856120857120858120859120860120861120862120863120864120865120866120867120868120869120870120871120872120873120874120875120876120877120878120879120880120881120882120883120884120885120886120887120888120889120890120891120892120893120894120895120896120897120898120899120900120901120902120903120904120905120906120907120908120909120910120911120912120913120914120915120916120917120918120919120920120921120922120923120924120925120926120927120928120929120930120931120932120933120934120935120936120937120938120939120940120941120942120943120944120945120946120947120948120949120950120951120952120953120954120955120956120957120958120959120960120961120962120963120964120965120966120967120968120969120970120971120972120973120974120975120976120977120978120979120980120981120982120983120984120985120986120987120988120989120990120991120992120993120994120995120996120997120998120999121000121001121002121003121004121005121006121007121008121009121010121011121012121013121014121015121016121017121018121019121020121021121022121023121024121025121026121027121028121029121030121031121032121033121034121035121036121037121038121039121040121041121042121043121044121045121046121047121048121049121050121051121052121053121054121055121056121057121058121059121060121061121062121063121064121065121066121067121068121069121070121071121072121073121074121075121076121077121078121079121080121081121082121083121084121085121086121087121088121089121090121091121092121093121094121095121096121097121098121099121100121101121102121103121104121105121106121107121108121109121110121111121112121113121114121115121116121117121118121119121120121121121122121123121124121125121126121127121128121129121130121131121132121133121134121135121136121137121138121139121140121141121142121143121144121145121146121147121148121149121150121151121152121153121154121155121156121157121158121159121160121161121162121163121164121165121166121167121168121169121170121171121172121173121174121175121176121177121178121179121180121181121182121183121184121185121186121187121188121189121190121191121192121193121194121195121196121197121198121199121200121201121202121203121204121205121206121207121208121209121210121211121212121213121214121215121216121217121218121219121220121221121222121223121224121225121226121227121228121229121230121231121232121233121234121235121236121237121238121239121240121241121242121243121244121245121246121247121248121249121250121251121252121253121254121255121256121257121258121259121260121261121262121263121264121265121266121267121268121269121270121271121272121273121274121275121276121277121278121279121280121281121282121283121284121285121286121287121288121289121290121291121292121293121294121295121296121297121298121299121300121301121302121303121304121305121306121307121308121309121310121311121312121313121314121315121316121317121318121319121320121321121322121323121324121325121326121327121328121329121330121331121332121333121334121335121336121337121338121339121340121341121342121343121344121345121346121347121348121349121350121351121352121353121354121355121356121357121358121359121360121361121362121363121364121365121366121367121368121369121370121371121372121373121374121375121376121377121378121379121380121381121382121383121384121385121386121387121388121389121390121391121392121393121394121395121396121397121398121399121400121401121402121403121404121405121406121407121408121409121410121411121412121413121414121415121416121417121418121419121420121421121422121423121424121425121426121427121428121429121430121431121432121433121434121435121436121437121438121439121440121441121442121443121444121445121446121447121448121449121450121451121452121453121454121455121456121457121458121459121460121461121462121463121464121465121466121467121468121469121470121471121472121473121474121475121476121477121478121479121480121481121482121483121484121485121486121487121488121489121490121491121492121493121494121495121496121497121498121499121500121501121502121503121504121505121506121507121508121509121510121511121512121513121514121515121516121517121518121519121520121521121522121523121524121525121526121527121528121529121530121531121532121533121534121535121536121537121538121539121540121541121542121543121544121545121546121547121548121549121550121551121552121553121554121555121556121557121558121559121560121561121562121563121564121565121566121567121568121569121570121571121572121573121574121575121576121577121578121579121580121581121582121583121584121585121586121587121588121589121590121591121592121593121594121595121596121597121598121599121600121601121602121603121604121605121606121607121608121609121610121611121612121613121614121615121616121617121618121619121620121621121622121623121624121625121626121627121628121629121630121631121632121633121634121635121636121637121638121639121640121641121642121643121644121645121646121647121648121649121650121651121652121653121654121655121656121657121658121659121660121661121662121663121664121665121666121667121668121669121670121671121672121673121674121675121676121677121678121679121680121681121682121683121684121685121686121687121688121689121690121691121692121693121694121695121696121697121698121699121700121701121702121703121704121705121706121707121708121709121710121711121712121713121714121715121716121717121718121719121720121721121722121723121724121725121726121727121728121729121730121731121732121733121734121735121736121737121738121739121740121741121742121743121744121745121746121747121748121749121750121751121752121753121754121755121756121757121758121759121760121761121762121763121764121765121766121767121768121769121770121771121772121773121774121775121776121777121778121779121780121781121782121783121784121785121786121787121788121789121790121791121792121793121794121795121796121797121798121799121800121801121802121803121804121805121806121807121808121809121810121811121812121813121814121815121816121817121818121819121820121821121822121823121824121825121826121827121828121829121830121831121832121833121834121835121836121837121838121839121840121841121842121843121844121845121846121847121848121849121850121851121852121853121854121855121856121857121858121859121860121861121862121863121864121865121866121867121868121869121870121871121872121873121874121875121876121877121878121879121880121881121882121883121884121885121886121887121888121889121890121891121892121893121894121895121896121897121898121899121900121901121902121903121904121905121906121907121908121909121910121911121912121913121914121915121916121917121918121919121920121921121922121923121924121925121926121927121928121929121930121931121932121933121934121935121936121937121938121939121940121941121942121943121944121945121946121947121948121949121950121951121952121953121954121955121956121957121958121959121960121961121962121963121964121965121966121967121968121969121970121971121972121973121974121975121976121977121978121979121980121981121982121983121984121985121986121987121988121989121990121991121992121993121994121995121996121997121998121999122000122001122002122003122004122005122006122007122008122009122010122011122012122013122014122015122016122017122018122019122020122021122022122023122024122025122026122027122028122029122030122031122032122033122034122035122036122037122038122039122040122041122042122043122044122045122046122047122048122049122050122051122052122053122054122055122056122057122058122059122060122061122062122063122064122065122066122067122068122069122070122071122072122073122074122075122076122077122078122079122080122081122082122083122084122085122086122087122088122089122090122091122092122093122094122095122096122097122098122099122100122101122102122103122104122105122106122107122108122109122110122111122112122113122114122115122116122117122118122119122120122121122122122123122124122125122126122127122128122129122130122131122132122133122134122135122136122137122138122139122140122141122142122143122144122145122146122147122148122149122150122151122152122153122154122155122156122157122158122159122160122161122162122163122164122165122166122167122168122169122170122171122172122173122174122175122176122177122178122179122180122181122182122183122184122185122186122187122188122189122190122191122192122193122194122195122196122197122198122199122200122201122202122203122204122205122206122207122208122209122210122211122212122213122214122215122216122217122218122219122220122221122222122223122224122225122226122227122228122229122230122231122232122233122234122235122236122237122238122239122240122241122242122243122244122245122246122247122248122249122250122251122252122253122254122255122256122257122258122259122260122261122262122263122264122265122266122267122268122269122270122271122272122273122274122275122276122277122278122279122280122281122282122283122284122285122286122287122288122289122290122291122292122293122294122295122296122297122298122299122300122301122302122303122304122305122306122307122308122309122310122311122312122313122314122315122316122317122318122319122320122321122322122323122324122325122326122327122328122329122330122331122332122333122334122335122336122337122338122339122340122341122342122343122344122345122346122347122348122349122350122351122352122353122354122355122356122357122358122359122360122361122362122363122364122365122366122367122368122369122370122371122372122373122374122375122376122377122378122379122380122381122382122383122384122385122386122387122388122389122390122391122392122393122394122395122396122397122398122399122400122401122402122403122404122405122406122407122408122409122410122411122412122413122414122415122416122417122418122419122420122421122422122423122424122425122426122427122428122429122430122431122432122433122434122435122436122437122438122439122440122441122442122443122444122445122446122447122448122449122450122451122452122453122454122455122456122457122458122459122460122461122462122463122464122465122466122467122468122469122470122471122472122473122474122475122476122477122478122479122480122481122482122483122484122485122486122487122488122489122490122491122492122493122494122495122496122497122498122499122500122501122502122503122504122505122506122507122508122509122510122511122512122513122514122515122516122517122518122519122520122521122522122523122524122525122526122527122528122529122530122531122532122533122534122535122536122537122538122539122540122541122542122543122544122545122546122547122548122549122550122551122552122553122554122555122556122557122558122559122560122561122562122563122564122565122566122567122568122569122570122571122572122573122574122575122576122577122578122579122580122581122582122583122584122585122586122587122588122589122590122591122592122593122594122595122596122597122598122599122600122601122602122603122604122605122606122607122608122609122610122611122612122613122614122615122616122617122618122619122620122621122622122623122624122625122626122627122628122629122630122631122632122633122634122635122636122637122638122639122640122641122642122643122644122645122646122647122648122649122650122651122652122653122654122655122656122657122658122659122660122661122662122663122664122665122666122667122668122669122670122671122672122673122674122675122676122677122678122679122680122681122682122683122684122685122686122687122688122689122690122691122692122693122694122695122696122697122698122699122700122701122702122703122704122705122706122707122708122709122710122711122712122713122714122715122716122717122718122719122720122721122722122723122724122725122726122727122728122729122730122731122732122733122734122735122736122737122738122739122740122741122742122743122744122745122746122747122748122749122750122751122752122753122754122755122756122757122758122759122760122761122762122763122764122765122766122767122768122769122770122771122772122773122774122775122776122777122778122779122780122781122782122783122784122785122786122787122788122789122790122791122792122793122794122795122796122797122798122799122800122801122802122803122804122805122806122807122808122809122810122811122812122813122814122815122816122817122818122819122820122821122822122823122824122825122826122827122828122829122830122831122832122833122834122835122836122837122838122839122840122841122842122843122844122845122846122847122848122849122850122851122852122853122854122855122856122857122858122859122860122861122862122863122864122865122866122867122868122869122870122871122872122873122874122875122876122877122878122879122880122881122882122883122884122885122886122887122888122889122890122891122892122893122894122895122896122897122898122899122900122901122902122903122904122905122906122907122908122909122910122911122912122913122914122915122916122917122918122919122920122921122922122923122924122925122926122927122928122929122930122931122932122933122934122935122936122937122938122939122940122941122942122943122944122945122946122947122948122949122950122951122952122953122954122955122956122957122958122959122960122961122962122963122964122965122966122967122968122969122970122971122972122973122974122975122976122977122978122979122980122981122982122983122984122985122986122987122988122989122990122991122992122993122994122995122996122997122998122999123000123001123002123003123004123005123006123007123008123009123010123011123012123013123014123015123016123017123018123019123020123021123022123023123024123025123026123027123028123029123030123031123032123033123034123035123036123037123038123039123040123041123042123043123044123045123046123047123048123049123050123051123052123053123054123055123056123057123058123059123060123061123062123063123064123065123066123067123068123069123070123071123072123073123074123075123076123077123078123079123080123081123082123083123084123085123086123087123088123089123090123091123092123093123094123095123096123097123098123099123100123101123102123103123104123105123106123107123108123109123110123111123112123113123114123115123116123117123118123119123120123121123122123123123124123125123126123127123128123129123130123131123132123133123134123135123136123137123138123139123140123141123142123143123144123145123146123147123148123149123150123151123152123153123154123155123156123157123158123159123160123161123162123163123164123165123166123167123168123169123170123171123172123173123174123175123176123177123178123179123180123181123182123183123184123185123186123187123188123189123190123191123192123193123194123195123196123197123198123199123200123201123202123203123204123205123206123207123208123209123210123211123212123213123214123215123216123217123218123219123220123221123222123223123224123225123226123227123228123229123230123231123232123233123234123235123236123237123238123239123240123241123242123243123244123245123246123247123248123249123250123251123252123253123254123255123256123257123258123259123260123261123262123263123264123265123266123267123268123269123270123271123272123273123274123275123276123277123278123279123280123281123282123283123284123285123286123287123288123289123290123291123292123293123294123295123296123297123298123299123300123301123302123303123304123305123306123307123308123309123310123311123312123313123314123315123316123317123318123319123320123321123322123323123324123325123326123327123328123329123330123331123332123333123334123335123336123337123338123339123340123341123342123343123344123345123346123347123348123349123350123351123352123353123354123355123356123357123358123359123360123361123362123363123364123365123366123367123368123369123370123371123372123373123374123375123376123377123378123379123380123381123382123383123384123385123386123387123388123389123390123391123392123393123394123395123396123397123398123399123400123401123402123403123404123405123406123407123408123409123410123411123412123413123414123415123416123417123418123419123420123421123422123423123424123425123426123427123428123429123430123431123432123433123434123435123436123437123438123439123440123441123442123443123444123445123446123447123448123449123450123451123452123453123454123455123456123457123458123459123460123461123462123463123464123465123466123467123468123469123470123471123472123473123474123475123476123477123478123479123480123481123482123483123484123485123486123487123488123489123490123491123492123493123494123495123496123497123498123499123500123501123502123503123504123505123506123507123508123509123510123511123512123513123514123515123516123517123518123519123520123521123522123523123524123525123526123527123528123529123530123531123532123533123534123535123536123537123538123539123540123541123542123543123544123545123546123547123548123549123550123551123552123553123554123555123556123557123558123559123560123561123562123563123564123565123566123567123568123569123570123571123572123573123574123575123576123577123578123579123580123581123582123583123584123585123586123587123588123589123590123591123592123593123594123595123596123597123598123599123600123601123602123603123604123605123606123607123608123609123610123611123612123613123614123615123616123617123618123619123620123621123622123623123624123625123626123627123628123629123630123631123632123633123634123635123636123637123638123639123640123641123642123643123644123645123646123647123648123649123650123651123652123653123654123655123656123657123658123659123660123661123662123663123664123665123666123667123668123669123670123671123672123673123674123675123676123677123678123679123680123681123682123683123684123685123686123687123688123689123690123691123692123693123694123695123696123697123698123699123700123701123702123703123704123705123706123707123708123709123710123711123712123713123714123715123716123717123718123719123720123721123722123723123724123725123726123727123728123729123730123731123732123733123734123735123736123737123738123739123740123741123742123743123744123745123746123747123748123749123750123751123752123753123754123755123756123757123758123759123760123761123762123763123764123765123766123767123768123769123770123771123772123773123774123775123776123777123778123779123780123781123782123783123784123785123786123787123788123789123790123791123792123793123794123795123796123797123798123799123800123801123802123803123804123805123806123807123808123809123810123811123812123813123814123815123816123817123818123819123820123821123822123823123824123825123826123827123828123829123830123831123832123833123834123835123836123837123838123839123840123841123842123843123844123845123846123847123848123849123850123851123852123853123854123855123856123857123858123859123860123861123862123863123864123865123866123867123868123869123870123871123872123873123874123875123876123877123878123879123880123881123882123883123884123885123886123887123888123889123890123891123892123893123894123895123896123897123898123899123900123901123902123903123904123905123906123907123908123909123910123911123912123913123914123915123916123917123918123919123920123921123922123923123924123925123926123927123928123929123930123931123932123933123934123935123936123937123938123939123940123941123942123943123944123945123946123947123948123949123950123951123952123953123954123955123956123957123958123959123960123961123962123963123964123965123966123967123968123969123970123971123972123973123974123975123976123977123978123979123980123981123982123983123984123985123986123987123988123989123990123991123992123993123994123995123996123997123998123999124000124001124002124003124004124005124006124007124008124009124010124011124012124013124014124015124016124017124018124019124020124021124022124023124024124025124026124027124028124029124030124031124032124033124034124035124036124037124038124039124040124041124042124043124044124045124046124047124048124049124050124051124052124053124054124055124056124057124058124059124060124061124062124063124064124065124066124067124068124069124070124071124072124073124074124075124076124077124078124079124080124081124082124083124084124085124086124087124088124089124090124091124092124093124094124095124096124097124098124099124100124101124102124103124104124105124106124107124108124109124110124111124112124113124114124115124116124117124118124119124120124121124122124123124124124125124126124127124128124129124130124131124132124133124134124135124136124137124138124139124140124141124142124143124144124145124146124147124148124149124150124151124152124153124154124155124156124157124158124159124160124161124162124163124164124165124166124167124168124169124170124171124172124173124174124175124176124177124178124179124180124181124182124183124184124185124186124187124188124189124190124191124192124193124194124195124196124197124198124199124200124201124202124203124204124205124206124207124208124209124210124211124212124213124214124215124216124217124218124219124220124221124222124223124224124225124226124227124228124229124230124231124232124233124234124235124236124237124238124239124240124241124242124243124244124245124246124247124248124249124250124251124252124253124254124255124256124257124258124259124260124261124262124263124264124265124266124267124268124269124270124271124272124273124274124275124276124277124278124279124280124281124282124283124284124285124286124287124288124289124290124291124292124293124294124295124296124297124298124299124300124301124302124303124304124305124306124307124308124309124310124311124312124313124314124315124316124317124318124319124320124321124322124323124324124325124326124327124328124329124330124331124332124333124334124335124336124337124338124339124340124341124342124343124344124345124346124347124348124349124350124351124352124353124354124355124356124357124358124359124360124361124362124363124364124365124366124367124368124369124370124371124372124373124374124375124376124377124378124379124380124381124382124383124384124385124386124387124388124389124390124391124392124393124394124395124396124397124398124399124400124401124402124403124404124405124406124407124408124409124410124411124412124413124414124415124416124417124418124419124420124421124422124423124424124425124426124427124428124429124430124431124432124433124434124435124436124437124438124439124440124441124442124443124444124445124446124447124448124449124450124451124452124453124454124455124456124457124458124459124460124461124462124463124464124465124466124467124468124469124470124471124472124473124474124475124476124477124478124479124480124481124482124483124484124485124486124487124488124489124490124491124492124493124494124495124496124497124498124499124500124501124502124503124504124505124506124507124508124509124510124511124512124513124514124515124516124517124518124519124520124521124522124523124524124525124526124527124528124529124530124531124532124533124534124535124536124537124538124539124540124541124542124543124544124545124546124547124548124549124550124551124552124553124554124555124556124557124558124559124560124561124562124563124564124565124566124567124568124569124570124571124572124573124574124575124576124577124578124579124580124581124582124583124584124585124586124587124588124589124590124591124592124593124594124595124596124597124598124599124600124601124602124603124604124605124606124607124608124609124610124611124612124613124614124615124616124617124618124619124620124621124622124623124624124625124626124627124628124629124630124631124632124633124634124635124636124637124638124639124640124641124642124643124644124645124646124647124648124649124650124651124652124653124654124655124656124657124658124659124660124661124662124663124664124665124666124667124668124669124670124671124672124673124674124675124676124677124678124679124680124681124682124683124684124685124686124687124688124689124690124691124692124693124694124695124696124697124698124699124700124701124702124703124704124705124706124707124708124709124710124711124712124713124714124715124716124717124718124719124720124721124722124723124724124725124726124727124728124729124730124731124732124733124734124735124736124737124738124739124740124741124742124743124744124745124746124747124748124749124750124751124752124753124754124755124756124757124758124759124760124761124762124763124764124765124766124767124768124769124770124771124772124773124774124775124776124777124778124779124780124781124782124783124784124785124786124787124788124789124790124791124792124793124794124795124796124797124798124799124800124801124802124803124804124805124806124807124808124809124810124811124812124813124814124815124816124817124818124819124820124821124822124823124824124825124826124827124828124829124830124831124832124833124834124835124836124837124838124839124840124841124842124843124844124845124846124847124848124849124850124851124852124853124854124855124856124857124858124859124860124861124862124863124864124865124866124867124868124869124870124871124872124873124874124875124876124877124878124879124880124881124882124883124884124885124886124887124888124889124890124891124892124893124894124895124896124897124898124899124900124901124902124903124904124905124906124907124908124909124910124911124912124913124914124915124916124917124918124919124920124921124922124923124924124925124926124927124928124929124930124931124932124933124934124935124936124937124938124939124940124941124942124943124944124945124946124947124948124949124950124951124952124953124954124955124956124957124958124959124960124961124962124963124964124965124966124967124968124969124970124971124972124973124974124975124976124977124978124979124980124981124982124983124984124985124986124987124988124989124990124991124992124993124994124995124996124997124998124999125000125001125002125003125004125005125006125007125008125009125010125011125012125013125014125015125016125017125018125019125020125021125022125023125024125025125026125027125028125029125030125031125032125033125034125035125036125037125038125039125040125041125042125043125044125045125046125047125048125049125050125051125052125053125054125055125056125057125058125059125060125061125062125063125064125065125066125067125068125069125070125071125072125073125074125075125076125077125078125079125080125081125082125083125084125085125086125087125088125089125090125091125092125093125094125095125096125097125098125099125100125101125102125103125104125105125106125107125108125109125110125111125112125113125114125115125116125117125118125119125120125121125122125123125124125125125126125127125128125129125130125131125132125133125134125135125136125137125138125139125140125141125142125143125144125145125146125147125148125149125150125151125152125153125154125155125156125157125158125159125160125161125162125163125164125165125166125167125168125169125170125171125172125173125174125175125176125177125178125179125180125181125182125183125184125185125186125187125188125189125190125191125192125193125194125195125196125197125198125199125200125201125202125203125204125205125206125207125208125209125210125211125212125213125214125215125216125217125218125219125220125221125222125223125224125225125226125227125228125229125230125231125232125233125234125235125236125237125238125239125240125241125242125243125244125245125246125247125248125249125250125251125252125253125254125255125256125257125258125259125260125261125262125263125264125265125266125267125268125269125270125271125272125273125274125275125276125277125278125279125280125281125282125283125284125285125286125287125288125289125290125291125292125293125294125295125296125297125298125299125300125301125302125303125304125305125306125307125308125309125310125311125312125313125314125315125316125317125318125319125320125321125322125323125324125325125326125327125328125329125330125331125332125333125334125335125336125337125338125339125340125341125342125343125344125345125346125347125348125349125350125351125352125353125354125355125356125357125358125359125360125361125362125363125364125365125366125367125368125369125370125371125372125373125374125375125376125377125378125379125380125381125382125383125384125385125386125387125388125389125390125391125392125393125394125395125396125397125398125399125400125401125402125403125404125405125406125407125408125409125410125411125412125413125414125415125416125417125418125419125420125421125422125423125424125425125426125427125428125429125430125431125432125433125434125435125436125437125438125439125440125441125442125443125444125445125446125447125448125449125450125451125452125453125454125455125456125457125458125459125460125461125462125463125464125465125466125467125468125469125470125471125472125473125474125475125476125477125478125479125480125481125482125483125484125485125486125487125488125489125490125491125492125493125494125495125496125497125498125499125500125501125502125503125504125505125506125507125508125509125510125511125512125513125514125515125516125517125518125519125520125521125522125523125524125525125526125527125528125529125530125531125532125533125534125535125536125537125538125539125540125541125542125543125544125545125546125547125548125549125550125551125552125553125554125555125556125557125558125559125560125561125562125563125564125565125566125567125568125569125570125571125572125573125574125575125576125577125578125579125580125581125582125583125584125585125586125587125588125589125590125591125592125593125594125595125596125597125598125599125600125601125602125603125604125605125606125607125608125609125610125611125612125613125614125615125616125617125618125619125620125621125622125623125624125625125626125627125628125629125630125631125632125633125634125635125636125637125638125639125640125641125642125643125644125645125646125647125648125649125650125651125652125653125654125655125656125657125658125659125660125661125662125663125664125665125666125667125668125669125670125671125672125673125674125675125676125677125678125679125680125681125682125683125684125685125686125687125688125689125690125691125692125693125694125695125696125697125698125699125700125701125702125703125704125705125706125707125708125709125710125711125712125713125714125715125716125717125718125719125720125721125722125723125724125725125726125727125728125729125730125731125732125733125734125735125736125737125738125739125740125741125742125743125744125745125746125747125748125749125750125751125752125753125754125755125756125757125758125759125760125761125762125763125764125765125766125767125768125769125770125771125772125773125774125775125776125777125778125779125780125781125782125783125784125785125786125787125788125789125790125791125792125793125794125795125796125797125798125799125800125801125802125803125804125805125806125807125808125809125810125811125812125813125814125815125816125817125818125819125820125821125822125823125824125825125826125827125828125829125830125831125832125833125834125835125836125837125838125839125840125841125842125843125844125845125846125847125848125849125850125851125852125853125854125855125856125857125858125859125860125861125862125863125864125865125866125867125868125869125870125871125872125873125874125875125876125877125878125879125880125881125882125883125884125885125886125887125888125889125890125891125892125893125894125895125896125897125898125899125900125901125902125903125904125905125906125907125908125909125910125911125912125913125914125915125916125917125918125919125920125921125922125923125924125925125926125927125928125929125930125931125932125933125934125935125936125937125938125939125940125941125942125943125944125945125946125947125948125949125950125951125952125953125954125955125956125957125958125959125960125961125962125963125964125965125966125967125968125969125970125971125972125973125974125975125976125977125978125979125980125981125982125983125984125985125986125987125988125989125990125991125992125993125994125995125996125997125998125999126000126001126002126003126004126005126006126007126008126009126010126011126012126013126014126015126016126017126018126019126020126021126022126023126024126025126026126027126028126029126030126031126032126033126034126035126036126037126038126039126040126041126042126043126044126045126046126047126048126049126050126051126052126053126054126055126056126057126058126059126060126061126062126063126064126065126066126067126068126069126070126071126072126073126074126075126076126077126078126079126080126081126082126083126084126085126086126087126088126089126090126091126092126093126094126095126096126097126098126099126100126101126102126103126104126105126106126107126108126109126110126111126112126113126114126115126116126117126118126119126120126121126122126123126124126125126126126127126128126129126130126131126132126133126134126135126136126137126138126139126140126141126142126143126144126145126146126147126148126149126150126151126152126153126154126155126156126157126158126159126160126161126162126163126164126165126166126167126168126169126170126171126172126173126174126175126176126177126178126179126180126181126182126183126184126185126186126187126188126189126190126191126192126193126194126195126196126197126198126199126200126201126202126203126204126205126206126207126208126209126210126211126212126213126214126215126216126217126218126219126220126221126222126223126224126225126226126227126228126229126230126231126232126233126234126235126236126237126238126239126240126241126242126243126244126245126246126247126248126249126250126251126252126253126254126255126256126257126258126259126260126261126262126263126264126265126266126267126268126269126270126271126272126273126274126275126276126277126278126279126280126281126282126283126284126285126286126287126288126289126290126291126292126293126294126295126296126297126298126299126300126301126302126303126304126305126306126307126308126309126310126311126312126313126314126315126316126317126318126319126320126321126322126323126324126325126326126327126328126329126330126331126332126333126334126335126336126337126338126339126340126341126342126343126344126345126346126347126348126349126350126351126352126353126354126355126356126357126358126359126360126361126362126363126364126365126366126367126368126369126370126371126372126373126374126375126376126377126378126379126380126381126382126383126384126385126386126387126388126389126390126391126392126393126394126395126396126397126398126399126400126401126402126403126404126405126406126407126408126409126410126411126412126413126414126415126416126417126418126419126420126421126422126423126424126425126426126427126428126429126430126431126432126433126434126435126436126437126438126439126440126441126442126443126444126445126446126447126448126449126450126451126452126453126454126455126456126457126458126459126460126461126462126463126464126465126466126467126468126469126470126471126472126473126474126475126476126477126478126479126480126481126482126483126484126485126486126487126488126489126490126491126492126493126494126495126496126497126498126499126500126501126502126503126504126505126506126507126508126509126510126511126512126513126514126515126516126517126518126519126520126521126522126523126524126525126526126527126528126529126530126531126532126533126534126535126536126537126538126539126540126541126542126543126544126545126546126547126548126549126550126551126552126553126554126555126556126557126558126559126560126561126562126563126564126565126566126567126568126569126570126571126572126573126574126575126576126577126578126579126580126581126582126583126584126585126586126587126588126589126590126591126592126593126594126595126596126597126598126599126600126601126602126603126604126605126606126607126608126609126610126611126612126613126614126615126616126617126618126619126620126621126622126623126624126625126626126627126628126629126630126631126632126633126634126635126636126637126638126639126640126641126642126643126644126645126646126647126648126649126650126651126652126653126654126655126656126657126658126659126660126661126662126663126664126665126666126667126668126669126670126671126672126673126674126675126676126677126678126679126680126681126682126683126684126685126686126687126688126689126690126691126692126693126694126695126696126697126698126699126700126701126702126703126704126705126706126707126708126709126710126711126712126713126714126715126716126717126718126719126720126721126722126723126724126725126726126727126728126729126730126731126732126733126734126735126736126737126738126739126740126741126742126743126744126745126746126747126748126749126750126751126752126753126754126755126756126757126758126759126760126761126762126763126764126765126766126767126768126769126770126771126772126773126774126775126776126777126778126779126780126781126782126783126784126785126786126787126788126789126790126791126792126793126794126795126796126797126798126799126800126801126802126803126804126805126806126807126808126809126810126811126812126813126814126815126816126817126818126819126820126821126822126823126824126825126826126827126828126829126830126831126832126833126834126835126836126837126838126839126840126841126842126843126844126845126846126847126848126849126850126851126852126853126854126855126856126857126858126859126860126861126862126863126864126865126866126867126868126869126870126871126872126873126874126875126876126877126878126879126880126881126882126883126884126885126886126887126888126889126890126891126892126893126894126895126896126897126898126899126900126901126902126903126904126905126906126907126908126909126910126911126912126913126914126915126916126917126918126919126920126921126922126923126924126925126926126927126928126929126930126931126932126933126934126935126936126937126938126939126940126941126942126943126944126945126946126947126948126949126950126951126952126953126954126955126956126957126958126959126960126961126962126963126964126965126966126967126968126969126970126971126972126973126974126975126976126977126978126979126980126981126982126983126984126985126986126987126988126989126990126991126992126993126994126995126996126997126998126999127000127001127002127003127004127005127006127007127008127009127010127011127012127013127014127015127016127017127018127019127020127021127022127023127024127025127026127027127028127029127030127031127032127033127034127035127036127037127038127039127040127041127042127043127044127045127046127047127048127049127050127051127052127053127054127055127056127057127058127059127060127061127062127063127064127065127066127067127068127069127070127071127072127073127074127075127076127077127078127079127080127081127082127083127084127085127086127087127088127089127090127091127092127093127094127095127096127097127098127099127100127101127102127103127104127105127106127107127108127109127110127111127112127113127114127115127116127117127118127119127120127121127122127123127124127125127126127127127128127129127130127131127132127133127134127135127136127137127138127139127140127141127142127143127144127145127146127147127148127149127150127151127152127153127154127155127156127157127158127159127160127161127162127163127164127165127166127167127168127169127170127171127172127173127174127175127176127177127178127179127180127181127182127183127184127185127186127187127188127189127190127191127192127193127194127195127196127197127198127199127200127201127202127203127204127205127206127207127208127209127210127211127212127213127214127215127216127217127218127219127220127221127222127223127224127225127226127227127228127229127230127231127232127233127234127235127236127237127238127239127240127241127242127243127244127245127246127247127248127249127250127251127252127253127254127255127256127257127258127259127260127261127262127263127264127265127266127267127268127269127270127271127272127273127274127275127276127277127278127279127280127281127282127283127284127285127286127287127288127289127290127291127292127293127294127295127296127297127298127299127300127301127302127303127304127305127306127307127308127309127310127311127312127313127314127315127316127317127318127319127320127321127322127323127324127325127326127327127328127329127330127331127332127333127334127335127336127337127338127339127340127341127342127343127344127345127346127347127348127349127350127351127352127353127354127355127356127357127358127359127360127361127362127363127364127365127366127367127368127369127370127371127372127373127374127375127376127377127378127379127380127381127382127383127384127385127386127387127388127389127390127391127392127393127394127395127396127397127398127399127400127401127402127403127404127405127406127407127408127409127410127411127412127413127414127415127416127417127418127419127420127421127422127423127424127425127426127427127428127429127430127431127432127433127434127435127436127437127438127439127440127441127442127443127444127445127446127447127448127449127450127451127452127453127454127455127456127457127458127459127460127461127462127463127464127465127466127467127468127469127470127471127472127473127474127475127476127477127478127479127480127481127482127483127484127485127486127487127488127489127490127491127492127493127494127495127496127497127498127499127500127501127502127503127504127505127506127507127508127509127510127511127512127513127514127515127516127517127518127519127520127521127522127523127524127525127526127527127528127529127530127531127532127533127534127535127536127537127538127539127540127541127542127543127544127545127546127547127548127549127550127551127552127553127554127555127556127557127558127559127560127561127562127563127564127565127566127567127568127569127570127571127572127573127574127575127576127577127578127579127580127581127582127583127584127585127586127587127588127589127590127591127592127593127594127595127596127597127598127599127600127601127602127603127604127605127606127607127608127609127610127611127612127613127614127615127616127617127618127619127620127621127622127623127624127625127626127627127628127629127630127631127632127633127634127635127636127637127638127639127640127641127642127643127644127645127646127647127648127649127650127651127652127653127654127655127656127657127658127659127660127661127662127663127664127665127666127667127668127669127670127671127672127673127674127675127676127677127678127679127680127681127682127683127684127685127686127687127688127689127690127691127692127693127694127695127696127697127698127699127700127701127702127703127704127705127706127707127708127709127710127711127712127713127714127715127716127717127718127719127720127721127722127723127724127725127726127727127728127729127730127731127732127733127734127735127736127737127738127739127740127741127742127743127744127745127746127747127748127749127750127751127752127753127754127755127756127757127758127759127760127761127762127763127764127765127766127767127768127769127770127771127772127773127774127775127776127777127778127779127780127781127782127783127784127785127786127787127788127789127790127791127792127793127794127795127796127797127798127799127800127801127802127803127804127805127806127807127808127809127810127811127812127813127814127815127816127817127818127819127820127821127822127823127824127825127826127827127828127829127830127831127832127833127834127835127836127837127838127839127840127841127842127843127844127845127846127847127848127849127850127851127852127853127854127855127856127857127858127859127860127861127862127863127864127865127866127867127868127869127870127871127872127873127874127875127876127877127878127879127880127881127882127883127884127885127886127887127888127889127890127891127892127893127894127895127896127897127898127899127900127901127902127903127904127905127906127907127908127909127910127911127912127913127914127915127916127917127918127919127920127921127922127923127924127925127926127927127928127929127930127931127932127933127934127935127936127937127938127939127940127941127942127943127944127945127946127947127948127949127950127951127952127953127954127955127956127957127958127959127960127961127962127963127964127965127966127967127968127969127970127971127972127973127974127975127976127977127978127979127980127981127982127983127984127985127986127987127988127989127990127991127992127993127994127995127996127997127998127999128000128001128002128003128004128005128006128007128008128009128010128011128012128013128014128015128016128017128018128019128020128021128022128023128024128025128026128027128028128029128030128031128032128033128034128035128036128037128038128039128040128041128042128043128044128045128046128047128048128049128050128051128052128053128054128055128056128057128058128059128060128061128062128063128064128065128066128067128068128069128070128071128072128073128074128075128076128077128078128079128080128081128082128083128084128085128086128087128088128089128090128091128092128093128094128095128096128097128098128099128100128101128102128103128104128105128106128107128108128109128110128111128112128113128114128115128116128117128118128119128120128121128122128123128124128125128126128127128128128129128130128131128132128133128134128135128136128137128138128139128140128141128142128143128144128145128146128147128148128149128150128151128152128153128154128155128156128157128158128159128160128161128162128163128164128165128166128167128168128169128170128171128172128173128174128175128176128177128178128179128180128181128182128183128184128185128186128187128188128189128190128191128192128193128194128195128196128197128198128199128200128201128202128203128204128205128206128207128208128209128210128211128212128213128214128215128216128217128218128219128220128221128222128223128224128225128226128227128228128229128230128231128232128233128234128235128236128237128238128239128240128241128242128243128244128245128246128247128248128249128250128251128252128253128254128255128256128257128258128259128260128261128262128263128264128265128266128267128268128269128270128271128272128273128274128275128276128277128278128279128280128281128282128283128284128285128286128287128288128289128290128291128292128293128294128295128296128297128298128299128300128301128302128303128304128305128306128307128308128309128310128311128312128313128314128315128316128317128318128319128320128321128322128323128324128325128326128327128328128329128330128331128332128333128334128335128336128337128338128339128340128341128342128343128344128345128346128347128348128349128350128351128352128353128354128355128356128357128358128359128360128361128362128363128364128365128366128367128368128369128370128371128372128373128374128375128376128377128378128379128380128381128382128383128384128385128386128387128388128389128390128391128392128393128394128395128396128397128398128399128400128401128402128403128404128405128406128407128408128409128410128411128412128413128414128415128416128417128418128419128420128421128422128423128424128425128426128427128428128429128430128431128432128433128434128435128436128437128438128439128440128441128442128443128444128445128446128447128448128449128450128451128452128453128454128455128456128457128458128459128460128461128462128463128464128465128466128467128468128469128470128471128472128473128474128475128476128477128478128479128480128481128482128483128484128485128486128487128488128489128490128491128492128493128494128495128496128497128498128499128500128501128502128503128504128505128506128507128508128509128510128511128512128513128514128515128516128517128518128519128520128521128522128523128524128525128526128527128528128529128530128531128532128533128534128535128536128537128538128539128540128541128542128543128544128545128546128547128548128549128550128551128552128553128554128555128556128557128558128559128560128561128562128563128564128565128566128567128568128569128570128571128572128573128574128575128576128577128578128579128580128581128582128583128584128585128586128587128588128589128590128591128592128593128594128595128596128597128598128599128600128601128602128603128604128605128606128607128608128609128610128611128612128613128614128615128616128617128618128619128620128621128622128623128624128625128626128627128628128629128630128631128632128633128634128635128636128637128638128639128640128641128642128643128644128645128646128647128648128649128650128651128652128653128654128655128656128657128658128659128660128661128662128663128664128665128666128667128668128669128670128671128672128673128674128675128676128677128678128679128680128681128682128683128684128685128686128687128688128689128690128691128692128693128694128695128696128697128698128699128700128701128702128703128704128705128706128707128708128709128710128711128712128713128714128715128716128717128718128719128720128721128722128723128724128725128726128727128728128729128730128731128732128733128734128735128736128737128738128739128740128741128742128743128744128745128746128747128748128749128750128751128752128753128754128755128756128757128758128759128760128761128762128763128764128765128766128767128768128769128770128771128772128773128774128775128776128777128778128779128780128781128782128783128784128785128786128787128788128789128790128791128792128793128794128795128796128797128798128799128800128801128802128803128804128805128806128807128808128809128810128811128812128813128814128815128816128817128818128819128820128821128822128823128824128825128826128827128828128829128830128831128832128833128834128835128836128837128838128839128840128841128842128843128844128845128846128847128848128849128850128851128852128853128854128855128856128857128858128859128860128861128862128863128864128865128866128867128868128869128870128871128872128873128874128875128876128877128878128879128880128881128882128883128884128885128886128887128888128889128890128891128892128893128894128895128896128897128898128899128900128901128902128903128904128905128906128907128908128909128910128911128912128913128914128915128916128917128918128919128920128921128922128923128924128925128926128927128928128929128930128931128932128933128934128935128936128937128938128939128940128941128942128943128944128945128946128947128948128949128950128951128952128953128954128955128956128957128958128959128960128961128962128963128964128965128966128967128968128969128970128971128972128973128974128975128976128977128978128979128980128981128982128983128984128985128986128987128988128989128990128991128992128993128994128995128996128997128998128999129000129001129002129003129004129005129006129007129008129009129010129011129012129013129014129015129016129017129018129019129020129021129022129023129024129025129026129027129028129029129030129031129032129033129034129035129036129037129038129039129040129041129042129043129044129045129046129047129048129049129050129051129052129053129054129055129056129057129058129059129060129061129062129063129064129065129066129067129068129069129070129071129072129073129074129075129076129077129078129079129080129081129082129083129084129085129086129087129088129089129090129091129092129093129094129095129096129097129098129099129100129101129102129103129104129105129106129107129108129109129110129111129112129113129114129115129116129117129118129119129120129121129122129123129124129125129126129127129128129129129130129131129132129133129134129135129136129137129138129139129140129141129142129143129144129145129146129147129148129149129150129151129152129153129154129155129156129157129158129159129160129161129162129163129164129165129166129167129168129169129170129171129172129173129174129175129176129177129178129179129180129181129182129183129184129185129186129187129188129189129190129191129192129193129194129195129196129197129198129199129200129201129202129203129204129205129206129207129208129209129210129211129212129213129214129215129216129217129218129219129220129221129222129223129224129225129226129227129228129229129230129231129232129233129234129235129236129237129238129239129240129241129242129243129244129245129246129247129248129249129250129251129252129253129254129255129256129257129258129259129260129261129262129263129264129265129266129267129268129269129270129271129272129273129274129275129276129277129278129279129280129281129282129283129284129285129286129287129288129289129290129291129292129293129294129295129296129297129298129299129300129301129302129303129304129305129306129307129308129309129310129311129312129313129314129315129316129317129318129319129320129321129322129323129324129325129326129327129328129329129330129331129332129333129334129335129336129337129338129339129340129341129342129343129344129345129346129347129348129349129350129351129352129353129354129355129356129357129358129359129360129361129362129363129364129365129366129367129368129369129370129371129372129373129374129375129376129377129378129379129380129381129382129383129384129385129386129387129388129389129390129391129392129393129394129395129396129397129398129399129400129401129402129403129404129405129406129407129408129409129410129411129412129413129414129415129416129417129418129419129420129421129422129423129424129425129426129427129428129429129430129431129432129433129434129435129436129437129438129439129440129441129442129443129444129445129446129447129448129449129450129451129452129453129454129455129456129457129458129459129460129461129462129463129464129465129466129467129468129469129470129471129472129473129474129475129476129477129478129479129480129481129482129483129484129485129486129487129488129489129490129491129492129493129494129495129496129497129498129499129500129501129502129503129504129505129506129507129508129509129510129511129512129513129514129515129516129517129518129519129520129521129522129523129524129525129526129527129528129529129530129531129532129533129534129535129536129537129538129539129540129541129542129543129544129545129546129547129548129549129550129551129552129553129554129555129556129557129558129559129560129561129562129563129564129565129566129567129568129569129570129571129572129573129574129575129576129577129578129579129580129581129582129583129584129585129586129587129588129589129590129591129592129593129594129595129596129597129598129599129600129601129602129603129604129605129606129607129608129609129610129611129612129613129614129615129616129617129618129619129620129621129622129623129624129625129626129627129628129629129630129631129632129633129634129635129636129637129638129639129640129641129642129643129644129645129646129647129648129649129650129651129652129653129654129655129656129657129658129659129660129661129662129663129664129665129666129667129668129669129670129671129672129673129674129675129676129677129678129679129680129681129682129683129684129685129686129687129688129689129690129691129692129693129694129695129696129697129698129699129700129701129702129703129704129705129706129707129708129709129710129711129712129713129714129715129716129717129718129719129720129721129722129723129724129725129726129727129728129729129730129731129732129733129734129735129736129737129738129739129740129741129742129743129744129745129746129747129748129749129750129751129752129753129754129755129756129757129758129759129760129761129762129763129764129765129766129767129768129769129770129771129772129773129774129775129776129777129778129779129780129781129782129783129784129785129786129787129788129789129790129791129792129793129794129795129796129797129798129799129800129801129802129803129804129805129806129807129808129809129810129811129812129813129814129815129816129817129818129819129820129821129822129823129824129825129826129827129828129829129830129831129832129833129834129835129836129837129838129839129840129841129842129843129844129845129846129847129848129849129850129851129852129853129854129855129856129857129858129859129860129861129862129863129864129865129866129867129868129869129870129871129872129873129874129875129876129877129878129879129880129881129882129883129884129885129886129887129888129889129890129891129892129893129894129895129896129897129898129899129900129901129902129903129904129905129906129907129908129909129910129911129912129913129914129915129916129917129918129919129920129921129922129923129924129925129926129927129928129929129930129931129932129933129934129935129936129937129938129939129940129941129942129943129944129945129946129947129948129949129950129951129952129953129954129955129956129957129958129959129960129961129962129963129964129965129966129967129968129969129970129971129972129973129974129975129976129977129978129979129980129981129982129983129984129985129986129987129988129989129990129991129992129993129994129995129996129997129998129999130000130001130002130003130004130005130006130007130008130009130010130011130012130013130014130015130016130017130018130019130020130021130022130023130024130025130026130027130028130029130030130031130032130033130034130035130036130037130038130039130040130041130042130043130044130045130046130047130048130049130050130051130052130053130054130055130056130057130058130059130060130061130062130063130064130065130066130067130068130069130070130071130072130073130074130075130076130077130078130079130080130081130082130083130084130085130086130087130088130089130090130091130092130093130094130095130096130097130098130099130100130101130102130103130104130105130106130107130108130109130110130111130112130113130114130115130116130117130118130119130120130121130122130123130124130125130126130127130128130129130130130131130132130133130134130135130136130137130138130139130140130141130142130143130144130145130146130147130148130149130150130151130152130153130154130155130156130157130158130159130160130161130162130163130164130165130166130167130168130169130170130171130172130173130174130175130176130177130178130179130180130181130182130183130184130185130186130187130188130189130190130191130192130193130194130195130196130197130198130199130200130201130202130203130204130205130206130207130208130209130210130211130212130213130214130215130216130217130218130219130220130221130222130223130224130225130226130227130228130229130230130231130232130233130234130235130236130237130238130239130240130241130242130243130244130245130246130247130248130249130250130251130252130253130254130255130256130257130258130259130260130261130262130263130264130265130266130267130268130269130270130271130272130273130274130275130276130277130278130279130280130281130282130283130284130285130286130287130288130289130290130291130292130293130294130295130296130297130298130299130300130301130302130303130304130305130306130307130308130309130310130311130312130313130314130315130316130317130318130319130320130321130322130323130324130325130326130327130328130329130330130331130332130333130334130335130336130337130338130339130340130341130342130343130344130345130346130347130348130349130350130351130352130353130354130355130356130357130358130359130360130361130362130363130364130365130366130367130368130369130370130371130372130373130374130375130376130377130378130379130380130381130382130383130384130385130386130387130388130389130390130391130392130393130394130395130396130397130398130399130400130401130402130403130404130405130406130407130408130409130410130411130412130413130414130415130416130417130418130419130420130421130422130423130424130425130426130427130428130429130430130431130432130433130434130435130436130437130438130439130440130441130442130443130444130445130446130447130448130449130450130451130452130453130454130455130456130457130458130459130460130461130462130463130464130465130466130467130468130469130470130471130472130473130474130475130476130477130478130479130480130481130482130483130484130485130486130487130488130489130490130491130492130493130494130495130496130497130498130499130500130501130502130503130504130505130506130507130508130509130510130511130512130513130514130515130516130517130518130519130520130521130522130523130524130525130526130527130528130529130530130531130532130533130534130535130536130537130538130539130540130541130542130543130544130545130546130547130548130549130550130551130552130553130554130555130556130557130558130559130560130561130562130563130564130565130566130567130568130569130570130571130572130573130574130575130576130577130578130579130580130581130582130583130584130585130586130587130588130589130590130591130592130593130594130595130596130597130598130599130600130601130602130603130604130605130606130607130608130609130610130611130612130613130614130615130616130617130618130619130620130621130622130623130624130625130626130627130628130629130630130631130632130633130634130635130636130637130638130639130640130641130642130643130644130645130646130647130648130649130650130651130652130653130654130655130656130657130658130659130660130661130662130663130664130665130666130667130668130669130670130671130672130673130674130675130676130677130678130679130680130681130682130683130684130685130686130687130688130689130690130691130692130693130694130695130696130697130698130699130700130701130702130703130704130705130706130707130708130709130710130711130712130713130714130715130716130717130718130719130720130721130722130723130724130725130726130727130728130729130730130731130732130733130734130735130736130737130738130739130740130741130742130743130744130745130746130747130748130749130750130751130752130753130754130755130756130757130758130759130760130761130762130763130764130765130766130767130768130769130770130771130772130773130774130775130776130777130778130779130780130781130782130783130784130785130786130787130788130789130790130791130792130793130794130795130796130797130798130799130800130801130802130803130804130805130806130807130808130809130810130811130812130813130814130815130816130817130818130819130820130821130822130823130824130825130826130827130828130829130830130831130832130833130834130835130836130837130838130839130840130841130842130843130844130845130846130847130848130849130850130851130852130853130854130855130856130857130858130859130860130861130862130863130864130865130866130867130868130869130870130871130872130873130874130875130876130877130878130879130880130881130882130883130884130885130886130887130888130889130890130891130892130893130894130895130896130897130898130899130900130901130902130903130904130905130906130907130908130909130910130911130912130913130914130915130916130917130918130919130920130921130922130923130924130925130926130927130928130929130930130931130932130933130934130935130936130937130938130939130940130941130942130943130944130945130946130947130948130949130950130951130952130953130954130955130956130957130958130959130960130961130962130963130964130965130966130967130968130969130970130971130972130973130974130975130976130977130978130979130980130981130982130983130984130985130986130987130988130989130990130991130992130993130994130995130996130997130998130999131000131001131002131003131004131005131006131007131008131009131010131011131012131013131014131015131016131017131018131019131020131021131022131023131024131025131026131027131028131029131030131031131032131033131034131035131036131037131038131039131040131041131042131043131044131045131046131047131048131049131050131051131052131053131054131055131056131057131058131059131060131061131062131063131064131065131066131067131068131069131070131071131072131073131074131075131076131077131078131079131080131081131082131083131084131085131086131087131088131089131090131091131092131093131094131095131096131097131098131099131100131101131102131103131104131105131106131107131108131109131110131111131112131113131114131115131116131117131118131119131120131121131122131123131124131125131126131127131128131129131130131131131132131133131134131135131136131137131138131139131140131141131142131143131144131145131146131147131148131149131150131151131152131153131154131155131156131157131158131159131160131161131162131163131164131165131166131167131168131169131170131171131172131173131174131175131176131177131178131179131180131181131182131183131184131185131186131187131188131189131190131191131192131193131194131195131196131197131198131199131200131201131202131203131204131205131206131207131208131209131210131211131212131213131214131215131216131217131218131219131220131221131222131223131224131225131226131227131228131229131230131231131232131233131234131235131236131237131238131239131240131241131242131243131244131245131246131247131248131249131250131251131252131253131254131255131256131257131258131259131260131261131262131263131264131265131266131267131268131269131270131271131272131273131274131275131276131277131278131279131280131281131282131283131284131285131286131287131288131289131290131291131292131293131294131295131296131297131298131299131300131301131302131303131304131305131306131307131308131309131310131311131312131313131314131315131316131317131318131319131320131321131322131323131324131325131326131327131328131329131330131331131332131333131334131335131336131337131338131339131340131341131342131343131344131345131346131347131348131349131350131351131352131353131354131355131356131357131358131359131360131361131362131363131364131365131366131367131368131369131370131371131372131373131374131375131376131377131378131379131380131381131382131383131384131385131386131387131388131389131390131391131392131393131394131395131396131397131398131399131400131401131402131403131404131405131406131407131408131409131410131411131412131413131414131415131416131417131418131419131420131421131422131423131424131425131426131427131428131429131430131431131432131433131434131435131436131437131438131439131440131441131442131443131444131445131446131447131448131449131450131451131452131453131454131455131456131457131458131459131460131461131462131463131464131465131466131467131468131469131470131471131472131473131474131475131476131477131478131479131480131481131482131483131484131485131486131487131488131489131490131491131492131493131494131495131496131497131498131499131500131501131502131503131504131505131506131507131508131509131510131511131512131513131514131515131516131517131518131519131520131521131522131523131524131525131526131527131528131529131530131531131532131533131534131535131536131537131538131539131540131541131542131543131544131545131546131547131548131549131550131551131552131553131554131555131556131557131558131559131560131561131562131563131564131565131566131567131568131569131570131571131572131573131574131575131576131577131578131579131580131581131582131583131584131585131586131587131588131589131590131591131592131593131594131595131596131597131598131599131600131601131602131603131604131605131606131607131608131609131610131611131612131613131614131615131616131617131618131619131620131621131622131623131624131625131626131627131628131629131630131631131632131633131634131635131636131637131638131639131640131641131642131643131644131645131646131647131648131649131650131651131652131653131654131655131656131657131658131659131660131661131662131663131664131665131666131667131668131669131670131671131672131673131674131675131676131677131678131679131680131681131682131683131684131685131686131687131688131689131690131691131692131693131694131695131696131697131698131699131700131701131702131703131704131705131706131707131708131709131710131711131712131713131714131715131716131717131718131719131720131721131722131723131724131725131726131727131728131729131730131731131732131733131734131735131736131737131738131739131740131741131742131743131744131745131746131747131748131749131750131751131752131753131754131755131756131757131758131759131760131761131762131763131764131765131766131767131768131769131770131771131772131773131774131775131776131777131778131779131780131781131782131783131784131785131786131787131788131789131790131791131792131793131794131795131796131797131798131799131800131801131802131803131804131805131806131807131808131809131810131811131812131813131814131815131816131817131818131819131820131821131822131823131824131825131826131827131828131829131830131831131832131833131834131835131836131837131838131839131840131841131842131843131844131845131846131847131848131849131850131851131852131853131854131855131856131857131858131859131860131861131862131863131864131865131866131867131868131869131870131871131872131873131874131875131876131877131878131879131880131881131882131883131884131885131886131887131888131889131890131891131892131893131894131895131896131897131898131899131900131901131902131903131904131905131906131907131908131909131910131911131912131913131914131915131916131917131918131919131920131921131922131923131924131925131926131927131928131929131930131931131932131933131934131935131936131937131938131939131940131941131942131943131944131945131946131947131948131949131950131951131952131953131954131955131956131957131958131959131960131961131962131963131964131965131966131967131968131969131970131971131972131973131974131975131976131977131978131979131980131981131982131983131984131985131986131987131988131989131990131991131992131993131994131995131996131997131998131999132000132001132002132003132004132005132006132007132008132009132010132011132012132013132014132015132016132017132018132019132020132021132022132023132024132025132026132027132028132029132030132031132032132033132034132035132036132037132038132039132040132041132042132043132044132045132046132047132048132049132050132051132052132053132054132055132056132057132058132059132060132061132062132063132064132065132066132067132068132069132070132071132072132073132074132075132076132077132078132079132080132081132082132083132084132085132086132087132088132089132090132091132092132093132094132095132096132097132098132099132100132101132102132103132104132105132106132107132108132109132110132111132112132113132114132115132116132117132118132119132120132121132122132123132124132125132126132127132128132129132130132131132132132133132134132135132136132137132138132139132140132141132142132143132144132145132146132147132148132149132150132151132152132153132154132155132156132157132158132159132160132161132162132163132164132165132166132167132168132169132170132171132172132173132174132175132176132177132178132179132180132181132182132183132184132185132186132187132188132189132190132191132192132193132194132195132196132197132198132199132200132201132202132203132204132205132206132207132208132209132210132211132212132213132214132215132216132217132218132219132220132221132222132223132224132225132226132227132228132229132230132231132232132233132234132235132236132237132238132239132240132241132242132243132244132245132246132247132248132249132250132251132252132253132254132255132256132257132258132259132260132261132262132263132264132265132266132267132268132269132270132271132272132273132274132275132276132277132278132279132280132281132282132283132284132285132286132287132288132289132290132291132292132293132294132295132296132297132298132299132300132301132302132303132304132305132306132307132308132309132310132311132312132313132314132315132316132317132318132319132320132321132322132323132324132325132326132327132328132329132330132331132332132333132334132335132336132337132338132339132340132341132342132343132344132345132346132347132348132349132350132351132352132353132354132355132356132357132358132359132360132361132362132363132364132365132366132367132368132369132370132371132372132373132374132375132376132377132378132379132380132381132382132383132384132385132386132387132388132389132390132391132392132393132394132395132396132397132398132399132400132401132402132403132404132405132406132407132408132409132410132411132412132413132414132415132416132417132418132419132420132421132422132423132424132425132426132427132428132429132430132431132432132433132434132435132436132437132438132439132440132441132442132443132444132445132446132447132448132449132450132451132452132453132454132455132456132457132458132459132460132461132462132463132464132465132466132467132468132469132470132471132472132473132474132475132476132477132478132479132480132481132482132483132484132485132486132487132488132489132490132491132492132493132494132495132496132497132498132499132500132501132502132503132504132505132506132507132508132509132510132511132512132513132514132515132516132517132518132519132520132521132522132523132524132525132526132527132528132529132530132531132532132533132534132535132536132537132538132539132540132541132542132543132544132545132546132547132548132549132550132551132552132553132554132555132556132557132558132559132560132561132562132563132564132565132566132567132568132569132570132571132572132573132574132575132576132577132578132579132580132581132582132583132584132585132586132587132588132589132590132591132592132593132594132595132596132597132598132599132600132601132602132603132604132605132606132607132608132609132610132611132612132613132614132615132616132617132618132619132620132621132622132623132624132625132626132627132628132629132630132631132632132633132634132635132636132637132638132639132640132641132642132643132644132645132646132647132648132649132650132651132652132653132654132655132656132657132658132659132660132661132662132663132664132665132666132667132668132669132670132671132672132673132674132675132676132677132678132679132680132681132682132683132684132685132686132687132688132689132690132691132692132693132694132695132696132697132698132699132700132701132702132703132704132705132706132707132708132709132710132711132712132713132714132715132716132717132718132719132720132721132722132723132724132725132726132727132728132729132730132731132732132733132734132735132736132737132738132739132740132741132742132743132744132745132746132747132748132749132750132751132752132753132754132755132756132757132758132759132760132761132762132763132764132765132766132767132768132769132770132771132772132773132774132775132776132777132778132779132780132781132782132783132784132785132786132787132788132789132790132791132792132793132794132795132796132797132798132799132800132801132802132803132804132805132806132807132808132809132810132811132812132813132814132815132816132817132818132819132820132821132822132823132824132825132826132827132828132829132830132831132832132833132834132835132836132837132838132839132840132841132842132843132844132845132846132847132848132849132850132851132852132853132854132855132856132857132858132859132860132861132862132863132864132865132866132867132868132869132870132871132872132873132874132875132876132877132878132879132880132881132882132883132884132885132886132887132888132889132890132891132892132893132894132895132896132897132898132899132900132901132902132903132904132905132906132907132908132909132910132911132912132913132914132915132916132917132918132919132920132921132922132923132924132925132926132927132928132929132930132931132932132933132934132935132936132937132938132939132940132941132942132943132944132945132946132947132948132949132950132951132952132953132954132955132956132957132958132959132960132961132962132963132964132965132966132967132968132969132970132971132972132973132974132975132976132977132978132979132980132981132982132983132984132985132986132987132988132989132990132991132992132993132994132995132996132997132998132999133000133001133002133003133004133005133006133007133008133009133010133011133012133013133014133015133016133017133018133019133020133021133022133023133024133025133026133027133028133029133030133031133032133033133034133035133036133037133038133039133040133041133042133043133044133045133046133047133048133049133050133051133052133053133054133055133056133057133058133059133060133061133062133063133064133065133066133067133068133069133070133071133072133073133074133075133076133077133078133079133080133081133082133083133084133085133086133087133088133089133090133091133092133093133094133095133096133097133098133099133100133101133102133103133104133105133106133107133108133109133110133111133112133113133114133115133116133117133118133119133120133121133122133123133124133125133126133127133128133129133130133131133132133133133134133135133136133137133138133139133140133141133142133143133144133145133146133147133148133149133150133151133152133153133154133155133156133157133158133159133160133161133162133163133164133165133166133167133168133169133170133171133172133173133174133175133176133177133178133179133180133181133182133183133184133185133186133187133188133189133190133191133192133193133194133195133196133197133198133199133200133201133202133203133204133205133206133207133208133209133210133211133212133213133214133215133216133217133218133219133220133221133222133223133224133225133226133227133228133229133230133231133232133233133234133235133236133237133238133239133240133241133242133243133244133245133246133247133248133249133250133251133252133253133254133255133256133257133258133259133260133261133262133263133264133265133266133267133268133269133270133271133272133273133274133275133276133277133278133279133280133281133282133283133284133285133286133287133288133289133290133291133292133293133294133295133296133297133298133299133300133301133302133303133304133305133306133307133308133309133310133311133312133313133314133315133316133317133318133319133320133321133322133323133324133325133326133327133328133329133330133331133332133333133334133335133336133337133338133339133340133341133342133343133344133345133346133347133348133349133350133351133352133353133354133355133356133357133358133359133360133361133362133363133364133365133366133367133368133369133370133371133372133373133374133375133376133377133378133379133380133381133382133383133384133385133386133387133388133389133390133391133392133393133394133395133396133397133398133399133400133401133402133403133404133405133406133407133408133409133410133411133412133413133414133415133416133417133418133419133420133421133422133423133424133425133426133427133428133429133430133431133432133433133434133435133436133437133438133439133440133441133442133443133444133445133446133447133448133449133450133451133452133453133454133455133456133457133458133459133460133461133462133463133464133465133466133467133468133469133470133471133472133473133474133475133476133477133478133479133480133481133482133483133484133485133486133487133488133489133490133491133492133493133494133495133496133497133498133499133500133501133502133503133504133505133506133507133508133509133510133511133512133513133514133515133516133517133518133519133520133521133522133523133524133525133526133527133528133529133530133531133532133533133534133535133536133537133538133539133540133541133542133543133544133545133546133547133548133549133550133551133552133553133554133555133556133557133558133559133560133561133562133563133564133565133566133567133568133569133570133571133572133573133574133575133576133577133578133579133580133581133582133583133584133585133586133587133588133589133590133591133592133593133594133595133596133597133598133599133600133601133602133603133604133605133606133607133608133609133610133611133612133613133614133615133616133617133618133619133620133621133622133623133624133625133626133627133628133629133630133631133632133633133634133635133636133637133638133639133640133641133642133643133644133645133646133647133648133649133650133651133652133653133654133655133656133657133658133659133660133661133662133663133664133665133666133667133668133669133670133671133672133673133674133675133676133677133678133679133680133681133682133683133684133685133686133687133688133689133690133691133692133693133694133695133696133697133698133699133700133701133702133703133704133705133706133707133708133709133710133711133712133713133714133715133716133717133718133719133720133721133722133723133724133725133726133727133728133729133730133731133732133733133734133735133736133737133738133739133740133741133742133743133744133745133746133747133748133749133750133751133752133753133754133755133756133757133758133759133760133761133762133763133764133765133766133767133768133769133770133771133772133773133774133775133776133777133778133779133780133781133782133783133784133785133786133787133788133789133790133791133792133793133794133795133796133797133798133799133800133801133802133803133804133805133806133807133808133809133810133811133812133813133814133815133816133817133818133819133820133821133822133823133824133825133826133827133828133829133830133831133832133833133834133835133836133837133838133839133840133841133842133843133844133845133846133847133848133849133850133851133852133853133854133855133856133857133858133859133860133861133862133863133864133865133866133867133868133869133870133871133872133873133874133875133876133877133878133879133880133881133882133883133884133885133886133887133888133889133890133891133892133893133894133895133896133897133898133899133900133901133902133903133904133905133906133907133908133909133910133911133912133913133914133915133916133917133918133919133920133921133922133923133924133925133926133927133928133929133930133931133932133933133934133935133936133937133938133939133940133941133942133943133944133945133946133947133948133949133950133951133952133953133954133955133956133957133958133959133960133961133962133963133964133965133966133967133968133969133970133971133972133973133974133975133976133977133978133979133980133981133982133983133984133985133986133987133988133989133990133991133992133993133994133995133996133997133998133999134000134001134002134003134004134005134006134007134008134009134010134011134012134013134014134015134016134017134018134019134020134021134022134023134024134025134026134027134028134029134030134031134032134033134034134035134036134037134038134039134040134041134042134043134044134045134046134047134048134049134050134051134052134053134054134055134056134057134058134059134060134061134062134063134064134065134066134067134068134069134070134071134072134073134074134075134076134077134078134079134080134081134082134083134084134085134086134087134088134089134090134091134092134093134094134095134096134097134098134099134100134101134102134103134104134105134106134107134108134109134110134111134112134113134114134115134116134117134118134119134120134121134122134123134124134125134126134127134128134129134130134131134132134133134134134135134136134137134138134139134140134141134142134143134144134145134146134147134148134149134150134151134152134153134154134155134156134157134158134159134160134161134162134163134164134165134166134167134168134169134170134171134172134173134174134175134176134177134178134179134180134181134182134183134184134185134186134187134188134189134190134191134192134193134194134195134196134197134198134199134200134201134202134203134204134205134206134207134208134209134210134211134212134213134214134215134216134217134218134219134220134221134222134223134224134225134226134227134228134229134230134231134232134233134234134235134236134237134238134239134240134241134242134243134244134245134246134247134248134249134250134251134252134253134254134255134256134257134258134259134260134261134262134263134264134265134266134267134268134269134270134271134272134273134274134275134276134277134278134279134280134281134282134283134284134285134286134287134288134289134290134291134292134293134294134295134296134297134298134299134300134301134302134303134304134305134306134307134308134309134310134311134312134313134314134315134316134317134318134319134320134321134322134323134324134325134326134327134328134329134330134331134332134333134334134335134336134337134338134339134340134341134342134343134344134345134346134347134348134349134350134351134352134353134354134355134356134357134358134359134360134361134362134363134364134365134366134367134368134369134370134371134372134373134374134375134376134377134378134379134380134381134382134383134384134385134386134387134388134389134390134391134392134393134394134395134396134397134398134399134400134401134402134403134404134405134406134407134408134409134410134411134412134413134414134415134416134417134418134419134420134421134422134423134424134425134426134427134428134429134430134431134432134433134434134435134436134437134438134439134440134441134442134443134444134445134446134447134448134449134450134451134452134453134454134455134456134457134458134459134460134461134462134463134464134465134466134467134468134469134470134471134472134473134474134475134476134477134478134479134480134481134482134483134484134485134486134487134488134489134490134491134492134493134494134495134496134497134498134499134500134501134502134503134504134505134506134507134508134509134510134511134512134513134514134515134516134517134518134519134520134521134522134523134524134525134526134527134528134529134530134531134532134533134534134535134536134537134538134539134540134541134542134543134544134545134546134547134548134549134550134551134552134553134554134555134556134557134558134559134560134561134562134563134564134565134566134567134568134569134570134571134572134573134574134575134576134577134578134579134580134581134582134583134584134585134586134587134588134589134590134591134592134593134594134595134596134597134598134599134600134601134602134603134604134605134606134607134608134609134610134611134612134613134614134615134616134617134618134619134620134621134622134623134624134625134626134627134628134629134630134631134632134633134634134635134636134637134638134639134640134641134642134643134644134645134646134647134648134649134650134651134652134653134654134655134656134657134658134659134660134661134662134663134664134665134666134667134668134669134670134671134672134673134674134675134676134677134678134679134680134681134682134683134684134685134686134687134688134689134690134691134692134693134694134695134696134697134698134699134700134701134702134703134704134705134706134707134708134709134710134711134712134713134714134715134716134717134718134719134720134721134722134723134724134725134726134727134728134729134730134731134732134733134734134735134736134737134738134739134740134741134742134743134744134745134746134747134748134749134750134751134752134753134754134755134756134757134758134759134760134761134762134763134764134765134766134767134768134769134770134771134772134773134774134775134776134777134778134779134780134781134782134783134784134785134786134787134788134789134790134791134792134793134794134795134796134797134798134799134800134801134802134803134804134805134806134807134808134809134810134811134812134813134814134815134816134817134818134819134820134821134822134823134824134825134826134827134828134829134830134831134832134833134834134835134836134837134838134839134840134841134842134843134844134845134846134847134848134849134850134851134852134853134854134855134856134857134858134859134860134861134862134863134864134865134866134867134868134869134870134871134872134873134874134875134876134877134878134879134880134881134882134883134884134885134886134887134888134889134890134891134892134893134894134895134896134897134898134899134900134901134902134903134904134905134906134907134908134909134910134911134912134913134914134915134916134917134918134919134920134921134922134923134924134925134926134927134928134929134930134931134932134933134934134935134936134937134938134939134940134941134942134943134944134945134946134947134948134949134950134951134952134953134954134955134956134957134958134959134960134961134962134963134964134965134966134967134968134969134970134971134972134973134974134975134976134977134978134979134980134981134982134983134984134985134986134987134988134989134990134991134992134993134994134995134996134997134998134999135000135001135002135003135004135005135006135007135008135009135010135011135012135013135014135015135016135017135018135019135020135021135022135023135024135025135026135027135028135029135030135031135032135033135034135035135036135037135038135039135040135041135042135043135044135045135046135047135048135049135050135051135052135053135054135055135056135057135058135059135060135061135062135063135064135065135066135067135068135069135070135071135072135073135074135075135076135077135078135079135080135081135082135083135084135085135086135087135088135089135090135091135092135093135094135095135096135097135098135099135100135101135102135103135104135105135106135107135108135109135110135111135112135113135114135115135116135117135118135119135120135121135122135123135124135125135126135127135128135129135130135131135132135133135134135135135136135137135138135139135140135141135142135143135144135145135146135147135148135149135150135151135152135153135154135155135156135157135158135159135160135161135162135163135164135165135166135167135168135169135170135171135172135173135174135175135176135177135178135179135180135181135182135183135184135185135186135187135188135189135190135191135192135193135194135195135196135197135198135199135200135201135202135203135204135205135206135207135208135209135210135211135212135213135214135215135216135217135218135219135220135221135222135223135224135225135226135227135228135229135230135231135232135233135234135235135236135237135238135239135240135241135242135243135244135245135246135247135248135249135250135251135252135253135254135255135256135257135258135259135260135261135262135263135264135265135266135267135268135269135270135271135272135273135274135275135276135277135278135279135280135281135282135283135284135285135286135287135288135289135290135291135292135293135294135295135296135297135298135299135300135301135302135303135304135305135306135307135308135309135310135311135312135313135314135315135316135317135318135319135320135321135322135323135324135325135326135327135328135329135330135331135332135333135334135335135336135337135338135339135340135341135342135343135344135345135346135347135348135349135350135351135352135353135354135355135356135357135358135359135360135361135362135363135364135365135366135367135368135369135370135371135372135373135374135375135376135377135378135379135380135381135382135383135384135385135386135387135388135389135390135391135392135393135394135395135396135397135398135399135400135401135402135403135404135405135406135407135408135409135410135411135412135413135414135415135416135417135418135419135420135421135422135423135424135425135426135427135428135429135430135431135432135433135434135435135436135437135438135439135440135441135442135443135444135445135446135447135448135449135450135451135452135453135454135455135456135457135458135459135460135461135462135463135464135465135466135467135468135469135470135471135472135473135474135475135476135477135478135479135480135481135482135483135484135485135486135487135488135489135490135491135492135493135494135495135496135497135498135499135500135501135502135503135504135505135506135507135508135509135510135511135512135513135514135515135516135517135518135519135520135521135522135523135524135525135526135527135528135529135530135531135532135533135534135535135536135537135538135539135540135541135542135543135544135545135546135547135548135549135550135551135552135553135554135555135556135557135558135559135560135561135562135563135564135565135566135567135568135569135570135571135572135573135574135575135576135577135578135579135580135581135582135583135584135585135586135587135588135589135590135591135592135593135594135595135596135597135598135599135600135601135602135603135604135605135606135607135608135609135610135611135612135613135614135615135616135617135618135619135620135621135622135623135624135625135626135627135628135629135630135631135632135633135634135635135636135637135638135639135640135641135642135643135644135645135646135647135648135649135650135651135652135653135654135655135656135657135658135659135660135661135662135663135664135665135666135667135668135669135670135671135672135673135674135675135676135677135678135679135680135681135682135683135684135685135686135687135688135689135690135691135692135693135694135695135696135697135698135699135700135701135702135703135704135705135706135707135708135709135710135711135712135713135714135715135716135717135718135719135720135721135722135723135724135725135726135727135728135729135730135731135732135733135734135735135736135737135738135739135740135741135742135743135744135745135746135747135748135749135750135751135752135753135754135755135756135757135758135759135760135761135762135763135764135765135766135767135768135769135770135771135772135773135774135775135776135777135778135779135780135781135782135783135784135785135786135787135788135789135790135791135792135793135794135795135796135797135798135799135800135801135802135803135804135805135806135807135808135809135810135811135812135813135814135815135816135817135818135819135820135821135822135823135824135825135826135827135828135829135830135831135832135833135834135835135836135837135838135839135840135841135842135843135844135845135846135847135848135849135850135851135852135853135854135855135856135857135858135859135860135861135862135863135864135865135866135867135868135869135870135871135872135873135874135875135876135877135878135879135880135881135882135883135884135885135886135887135888135889135890135891135892135893135894135895135896135897135898135899135900135901135902135903135904135905135906135907135908135909135910135911135912135913135914135915135916135917135918135919135920135921135922135923135924135925135926135927135928135929135930135931135932135933135934135935135936135937135938135939135940135941135942135943135944135945135946135947135948135949135950135951135952135953135954135955135956135957135958135959135960135961135962135963135964135965135966135967135968135969135970135971135972135973135974135975135976135977135978135979135980135981135982135983135984135985135986135987135988135989135990135991135992135993135994135995135996135997135998135999136000136001136002136003136004136005136006136007136008136009136010136011136012136013136014136015136016136017136018136019136020136021136022136023136024136025136026136027136028136029136030136031136032136033136034136035136036136037136038136039136040136041136042136043136044136045136046136047136048136049136050136051136052136053136054136055136056136057136058136059136060136061136062136063136064136065136066136067136068136069136070136071136072136073136074136075136076136077136078136079136080136081136082136083136084136085136086136087136088136089136090136091136092136093136094136095136096136097136098136099136100136101136102136103136104136105136106136107136108136109136110136111136112136113136114136115136116136117136118136119136120136121136122136123136124136125136126136127136128136129136130136131136132136133136134136135136136136137136138136139136140136141136142136143136144136145136146136147136148136149136150136151136152136153136154136155136156136157136158136159136160136161136162136163136164136165136166136167136168136169136170136171136172136173136174136175136176136177136178136179136180136181136182136183136184136185136186136187136188136189136190136191136192136193136194136195136196136197136198136199136200136201136202136203136204136205136206136207136208136209136210136211136212136213136214136215136216136217136218136219136220136221136222136223136224136225136226136227136228136229136230136231136232136233136234136235136236136237136238136239136240136241136242136243136244136245136246136247136248136249136250136251136252136253136254136255136256136257136258136259136260136261136262136263136264136265136266136267136268136269136270136271136272136273136274136275136276136277136278136279136280136281136282136283136284136285136286136287136288136289136290136291136292136293136294136295136296136297136298136299136300136301136302136303136304136305136306136307136308136309136310136311136312136313136314136315136316136317136318136319136320136321136322136323136324136325136326136327136328136329136330136331136332136333136334136335136336136337136338136339136340136341136342136343136344136345136346136347136348136349136350136351136352136353136354136355136356136357136358136359136360136361136362136363136364136365136366136367136368136369136370136371136372136373136374136375136376136377136378136379136380136381136382136383136384136385136386136387136388136389136390136391136392136393136394136395136396136397136398136399136400136401136402136403136404136405136406136407136408136409136410136411136412136413136414136415136416136417136418136419136420136421136422136423136424136425136426136427136428136429136430136431136432136433136434136435136436136437136438136439136440136441136442136443136444136445136446136447136448136449136450136451136452136453136454136455136456136457136458136459136460136461136462136463136464136465136466136467136468136469136470136471136472136473136474136475136476136477136478136479136480136481136482136483136484136485136486136487136488136489136490136491136492136493136494136495136496136497136498136499136500136501136502136503136504136505136506136507136508136509136510136511136512136513136514136515136516136517136518136519136520136521136522136523136524136525136526136527136528136529136530136531136532136533136534136535136536136537136538136539136540136541136542136543136544136545136546136547136548136549136550136551136552136553136554136555136556136557136558136559136560136561136562136563136564136565136566136567136568136569136570136571136572136573136574136575136576136577136578136579136580136581136582136583136584136585136586136587136588136589136590136591136592136593136594136595136596136597136598136599136600136601136602136603136604136605136606136607136608136609136610136611136612136613136614136615136616136617136618136619136620136621136622136623136624136625136626136627136628136629136630136631136632136633136634136635136636136637136638136639136640136641136642136643136644136645136646136647136648136649136650136651136652136653136654136655136656136657136658136659136660136661136662136663136664136665136666136667136668136669136670136671136672136673136674136675136676136677136678136679136680136681136682136683136684136685136686136687136688136689136690136691136692136693136694136695136696136697136698136699136700136701136702136703136704136705136706136707136708136709136710136711136712136713136714136715136716136717136718136719136720136721136722136723136724136725136726136727136728136729136730136731136732136733136734136735136736136737136738136739136740136741136742136743136744136745136746136747136748136749136750136751136752136753136754136755136756136757136758136759136760136761136762136763136764136765136766136767136768136769136770136771136772136773136774136775136776136777136778136779136780136781136782136783136784136785136786136787136788136789136790136791136792136793136794136795136796136797136798136799136800136801136802136803136804136805136806136807136808136809136810136811136812136813136814136815136816136817136818136819136820136821136822136823136824136825136826136827136828136829136830136831136832136833136834136835136836136837136838136839136840136841136842136843136844136845136846136847136848136849136850136851136852136853136854136855136856136857136858136859136860136861136862136863136864136865136866136867136868136869136870136871136872136873136874136875136876136877136878136879136880136881136882136883136884136885136886136887136888136889136890136891136892136893136894136895136896136897136898136899136900136901136902136903136904136905136906136907136908136909136910136911136912136913136914136915136916136917136918136919136920136921136922136923136924136925136926136927136928136929136930136931136932136933136934136935136936136937136938136939136940136941136942136943136944136945136946136947136948136949136950136951136952136953136954136955136956136957136958136959136960136961136962136963136964136965136966136967136968136969136970136971136972136973136974136975136976136977136978136979136980136981136982136983136984136985136986136987136988136989136990136991136992136993136994136995136996136997136998136999137000137001137002137003137004137005137006137007137008137009137010137011137012137013137014137015137016137017137018137019137020137021137022137023137024137025137026137027137028137029137030137031137032137033137034137035137036137037137038137039137040137041137042137043137044137045137046137047137048137049137050137051137052137053137054137055137056137057137058137059137060137061137062137063137064137065137066137067137068137069137070137071137072137073137074137075137076137077137078137079137080137081137082137083137084137085137086137087137088137089137090137091137092137093137094137095137096137097137098137099137100137101137102137103137104137105137106137107137108137109137110137111137112137113137114137115137116137117137118137119137120137121137122137123137124137125137126137127137128137129137130137131137132137133137134137135137136137137137138137139137140137141137142137143137144137145137146137147137148137149137150137151137152137153137154137155137156137157137158137159137160137161137162137163137164137165137166137167137168137169137170137171137172137173137174137175137176137177137178137179137180137181137182137183137184137185137186137187137188137189137190137191137192137193137194137195137196137197137198137199137200137201137202137203137204137205137206137207137208137209137210137211137212137213137214137215137216137217137218137219137220137221137222137223137224137225137226137227137228137229137230137231137232137233137234137235137236137237137238137239137240137241137242137243137244137245137246137247137248137249137250137251137252137253137254137255137256137257137258137259137260137261137262137263137264137265137266137267137268137269137270137271137272137273137274137275137276137277137278137279137280137281137282137283137284137285137286137287137288137289137290137291137292137293137294137295137296137297137298137299137300137301137302137303137304137305137306137307137308137309137310137311137312137313137314137315137316137317137318137319137320137321137322137323137324137325137326137327137328137329137330137331137332137333137334137335137336137337137338137339137340137341137342137343137344137345137346137347137348137349137350137351137352137353137354137355137356137357137358137359137360137361137362137363137364137365137366137367137368137369137370137371137372137373137374137375137376137377137378137379137380137381137382137383137384137385137386137387137388137389137390137391137392137393137394137395137396137397137398137399137400137401137402137403137404137405137406137407137408137409137410137411137412137413137414137415137416137417137418137419137420137421137422137423137424137425137426137427137428137429137430137431137432137433137434137435137436137437137438137439137440137441137442137443137444137445137446137447137448137449137450137451137452137453137454137455137456137457137458137459137460137461137462137463137464137465137466137467137468137469137470137471137472137473137474137475137476137477137478137479137480137481137482137483137484137485137486137487137488137489137490137491137492137493137494137495137496137497137498137499137500137501137502137503137504137505137506137507137508137509137510137511137512137513137514137515137516137517137518137519137520137521137522137523137524137525137526137527137528137529137530137531137532137533137534137535137536137537137538137539137540137541137542137543137544137545137546137547137548137549137550137551137552137553137554137555137556137557137558137559137560137561137562137563137564137565137566137567137568137569137570137571137572137573137574137575137576137577137578137579137580137581137582137583137584137585137586137587137588137589137590137591137592137593137594137595137596137597137598137599137600137601137602137603137604137605137606137607137608137609137610137611137612137613137614137615137616137617137618137619137620137621137622137623137624137625137626137627137628137629137630137631137632137633137634137635137636137637137638137639137640137641137642137643137644137645137646137647137648137649137650137651137652137653137654137655137656137657137658137659137660137661137662137663137664137665137666137667137668137669137670137671137672137673137674137675137676137677137678137679137680137681137682137683137684137685137686137687137688137689137690137691137692137693137694137695137696137697137698137699137700137701137702137703137704137705137706137707137708137709137710137711137712137713137714137715137716137717137718137719137720137721137722137723137724137725137726137727137728137729137730137731137732137733137734137735137736137737137738137739137740137741137742137743137744137745137746137747137748137749137750137751137752137753137754137755137756137757137758137759137760137761137762137763137764137765137766137767137768137769137770137771137772137773137774137775137776137777137778137779137780137781137782137783137784137785137786137787137788137789137790137791137792137793137794137795137796137797137798137799137800137801137802137803137804137805137806137807137808137809137810137811137812137813137814137815137816137817137818137819137820137821137822137823137824137825137826137827137828137829137830137831137832137833137834137835137836137837137838137839137840137841137842137843137844137845137846137847137848137849137850137851137852137853137854137855137856137857137858137859137860137861137862137863137864137865137866137867137868137869137870137871137872137873137874137875137876137877137878137879137880137881137882137883137884137885137886137887137888137889137890137891137892137893137894137895137896137897137898137899137900137901137902137903137904137905137906137907137908137909137910137911137912137913137914137915137916137917137918137919137920137921137922137923137924137925137926137927137928137929137930137931137932137933137934137935137936137937137938137939137940137941137942137943137944137945137946137947137948137949137950137951137952137953137954137955137956137957137958137959137960137961137962137963137964137965137966137967137968137969137970137971137972137973137974137975137976137977137978137979137980137981137982137983137984137985137986137987137988137989137990137991137992137993137994137995137996137997137998137999138000138001138002138003138004138005138006138007138008138009138010138011138012138013138014138015138016138017138018138019138020138021138022138023138024138025138026138027138028138029138030138031138032138033138034138035138036138037138038138039138040138041138042138043138044138045138046138047138048138049138050138051138052138053138054138055138056138057138058138059138060138061138062138063138064138065138066138067138068138069138070138071138072138073138074138075138076138077138078138079138080138081138082138083138084138085138086138087138088138089138090138091138092138093138094138095138096138097138098138099138100138101138102138103138104138105138106138107138108138109138110138111138112138113138114138115138116138117138118138119138120138121138122138123138124138125138126138127138128138129138130138131138132138133138134138135138136138137138138138139138140138141138142138143138144138145138146138147138148138149138150138151138152138153138154138155138156138157138158138159138160138161138162138163138164138165138166138167138168138169138170138171138172138173138174138175138176138177138178138179138180138181138182138183138184138185138186138187138188138189138190138191138192138193138194138195138196138197138198138199138200138201138202138203138204138205138206138207138208138209138210138211138212138213138214138215138216138217138218138219138220138221138222138223138224138225138226138227138228138229138230138231138232138233138234138235138236138237138238138239138240138241138242138243138244138245138246138247138248138249138250138251138252138253138254138255138256138257138258138259138260138261138262138263138264138265138266138267138268138269138270138271138272138273138274138275138276138277138278138279138280138281138282138283138284138285138286138287138288138289138290138291138292138293138294138295138296138297138298138299138300138301138302138303138304138305138306138307138308138309138310138311138312138313138314138315138316138317138318138319138320138321138322138323138324138325138326138327138328138329138330138331138332138333138334138335138336138337138338138339138340138341138342138343138344138345138346138347138348138349138350138351138352138353138354138355138356138357138358138359138360138361138362138363138364138365138366138367138368138369138370138371138372138373138374138375138376138377138378138379138380138381138382138383138384138385138386138387138388138389138390138391138392138393138394138395138396138397138398138399138400138401138402138403138404138405138406138407138408138409138410138411138412138413138414138415138416138417138418138419138420138421138422138423138424138425138426138427138428138429138430138431138432138433138434138435138436138437138438138439138440138441138442138443138444138445138446138447138448138449138450138451138452138453138454138455138456138457138458138459138460138461138462138463138464138465138466138467138468138469138470138471138472138473138474138475138476138477138478138479138480138481138482138483138484138485138486138487138488138489138490138491138492138493138494138495138496138497138498138499138500138501138502138503138504138505138506138507138508138509138510138511138512138513138514138515138516138517138518138519138520138521138522138523138524138525138526138527138528138529138530138531138532138533138534138535138536138537138538138539138540138541138542138543138544138545138546138547138548138549138550138551138552138553138554138555138556138557138558138559138560138561138562138563138564138565138566138567138568138569138570138571138572138573138574138575138576138577138578138579138580138581138582138583138584138585138586138587138588138589138590138591138592138593138594138595138596138597138598138599138600138601138602138603138604138605138606138607138608138609138610138611138612138613138614138615138616138617138618138619138620138621138622138623138624138625138626138627138628138629138630138631138632138633138634138635138636138637138638138639138640138641138642138643138644138645138646138647138648138649138650138651138652138653138654138655138656138657138658138659138660138661138662138663138664138665138666138667138668138669138670138671138672138673138674138675138676138677138678138679138680138681138682138683138684138685138686138687138688138689138690138691138692138693138694138695138696138697138698138699138700138701138702138703138704138705138706138707138708138709138710138711138712138713138714138715138716138717138718138719138720138721138722138723138724138725138726138727138728138729138730138731138732138733138734138735138736138737138738138739138740138741138742138743138744138745138746138747138748138749138750138751138752138753138754138755138756138757138758138759138760138761138762138763138764138765138766138767138768138769138770138771138772138773138774138775138776138777138778138779138780138781138782138783138784138785138786138787138788138789138790138791138792138793138794138795138796138797138798138799138800138801138802138803138804138805138806138807138808138809138810138811138812138813138814138815138816138817138818138819138820138821138822138823138824138825138826138827138828138829138830138831138832138833138834138835138836138837138838138839138840138841138842138843138844138845138846138847138848138849138850138851138852138853138854138855138856138857138858138859138860138861138862138863138864138865138866138867138868138869138870138871138872138873138874138875138876138877138878138879138880138881138882138883138884138885138886138887138888138889138890138891138892138893138894138895138896138897138898138899138900138901138902138903138904138905138906138907138908138909138910138911138912138913138914138915138916138917138918138919138920138921138922138923138924138925138926138927138928138929138930138931138932138933138934138935138936138937138938138939138940138941138942138943138944138945138946138947138948138949138950138951138952138953138954138955138956138957138958138959138960138961138962138963138964138965138966138967138968138969138970138971138972138973138974138975138976138977138978138979138980138981138982138983138984138985138986138987138988138989138990138991138992138993138994138995138996138997138998138999139000139001139002139003139004139005139006139007139008139009139010139011139012139013139014139015139016139017139018139019139020139021139022139023139024139025139026139027139028139029139030139031139032139033139034139035139036139037139038139039139040139041139042139043139044139045139046139047139048139049139050139051139052139053139054139055139056139057139058139059139060139061139062139063139064139065139066139067139068139069139070139071139072139073139074139075139076139077139078139079139080139081139082139083139084139085139086139087139088139089139090139091139092139093139094139095139096139097139098139099139100139101139102139103139104139105139106139107139108139109139110139111139112139113139114139115139116139117139118139119139120139121139122139123139124139125139126139127139128139129139130139131139132139133139134139135139136139137139138139139139140139141139142139143139144139145139146139147139148139149139150139151139152139153139154139155139156139157139158139159139160139161139162139163139164139165139166139167139168139169139170139171139172139173139174139175139176139177139178139179139180139181139182139183139184139185139186139187139188139189139190139191139192139193139194139195139196139197139198139199139200139201139202139203139204139205139206139207139208139209139210139211139212139213139214139215139216139217139218139219139220139221139222139223139224139225139226139227139228139229139230139231139232139233139234139235139236139237139238139239139240139241139242139243139244139245139246139247139248139249139250139251139252139253139254139255139256139257139258139259139260139261139262139263139264139265139266139267139268139269139270139271139272139273139274139275139276139277139278139279139280139281139282139283139284139285139286139287139288139289139290139291139292139293139294139295139296139297139298139299139300139301139302139303139304139305139306139307139308139309139310139311139312139313139314139315139316139317139318139319139320139321139322139323139324139325139326139327139328139329139330139331139332139333139334139335139336139337139338139339139340139341139342139343139344139345139346139347139348139349139350139351139352139353139354139355139356139357139358139359139360139361139362139363139364139365139366139367139368139369139370139371139372139373139374139375139376139377139378139379139380139381139382139383139384139385139386139387139388139389139390139391139392139393139394139395139396139397139398139399139400139401139402139403139404139405139406139407139408139409139410139411139412139413139414139415139416139417139418139419139420139421139422139423139424139425139426139427139428139429139430139431139432139433139434139435139436139437139438139439139440139441139442139443139444139445139446139447139448139449139450139451139452139453139454139455139456139457139458139459139460139461139462139463139464139465139466139467139468139469139470139471139472139473139474139475139476139477139478139479139480139481139482139483139484139485139486139487139488139489139490139491139492139493139494139495139496139497139498139499139500139501139502139503139504139505139506139507139508139509139510139511139512139513139514139515139516139517139518139519139520139521139522139523139524139525139526139527139528139529139530139531139532139533139534139535139536139537139538139539139540139541139542139543139544139545139546139547139548139549139550139551139552139553139554139555139556139557139558139559139560139561139562139563139564139565139566139567139568139569139570139571139572139573139574139575139576139577139578139579139580139581139582139583139584139585139586139587139588139589139590139591139592139593139594139595139596139597139598139599139600139601139602139603139604139605139606139607139608139609139610139611139612139613139614139615139616139617139618139619139620139621139622139623139624139625139626139627139628139629139630139631139632139633139634139635139636139637139638139639139640139641139642139643139644139645139646139647139648139649139650139651139652139653139654139655139656139657139658139659139660139661139662139663139664139665139666139667139668139669139670139671139672139673139674139675139676139677139678139679139680139681139682139683139684139685139686139687139688139689139690139691139692139693139694139695139696139697139698139699139700139701139702139703139704139705139706139707139708139709139710139711139712139713139714139715139716139717139718139719139720139721139722139723139724139725139726139727139728139729139730139731139732139733139734139735139736139737139738139739139740139741139742139743139744139745139746139747139748139749139750139751139752139753139754139755139756139757139758139759139760139761139762139763139764139765139766139767139768139769139770139771139772139773139774139775139776139777139778139779139780139781139782139783139784139785139786139787139788139789139790139791139792139793139794139795139796139797139798139799139800139801139802139803139804139805139806139807139808139809139810139811139812139813139814139815139816139817139818139819139820139821139822139823139824139825139826139827139828139829139830139831139832139833139834139835139836139837139838139839139840139841139842139843139844139845139846139847139848139849139850139851139852139853139854139855139856139857139858139859139860139861139862139863139864139865139866139867139868139869139870139871139872139873139874139875139876139877139878139879139880139881139882139883139884139885139886139887139888139889139890139891139892139893139894139895139896139897139898139899139900139901139902139903139904139905139906139907139908139909139910139911139912139913139914139915139916139917139918139919139920139921139922139923139924139925139926139927139928139929139930139931139932139933139934139935139936139937139938139939139940139941139942139943139944139945139946139947139948139949139950139951139952139953139954139955139956139957139958139959139960139961139962139963139964139965139966139967139968139969139970139971139972139973139974139975139976139977139978139979139980139981139982139983139984139985139986139987139988139989139990139991139992139993139994139995139996139997139998139999140000140001140002140003140004140005140006140007140008140009140010140011140012140013140014140015140016140017140018140019140020140021140022140023140024140025140026140027140028140029140030140031140032140033140034140035140036140037140038140039140040140041140042140043140044140045140046140047140048140049140050140051140052140053140054140055140056140057140058140059140060140061140062140063140064140065140066140067140068140069140070140071140072140073140074140075140076140077140078140079140080140081140082140083140084140085140086140087140088140089140090140091140092140093140094140095140096140097140098140099140100140101140102140103140104140105140106140107140108140109140110140111140112140113140114140115140116140117140118140119140120140121140122140123140124140125140126140127140128140129140130140131140132140133140134140135140136140137140138140139140140140141140142140143140144140145140146140147140148140149140150140151140152140153140154140155140156140157140158140159140160140161140162140163140164140165140166140167140168140169140170140171140172140173140174140175140176140177140178140179140180140181140182140183140184140185140186140187140188140189140190140191140192140193140194140195140196140197140198140199140200140201140202140203140204140205140206140207140208140209140210140211140212140213140214140215140216140217140218140219140220140221140222140223140224140225140226140227140228140229140230140231140232140233140234140235140236140237140238140239140240140241140242140243140244140245140246140247140248140249140250140251140252140253140254140255140256140257140258140259140260140261140262140263140264140265140266140267140268140269140270140271140272140273140274140275140276140277140278140279140280140281140282140283140284140285140286140287140288140289140290140291140292140293140294140295140296140297140298140299140300140301140302140303140304140305140306140307140308140309140310140311140312140313140314140315140316140317140318140319140320140321140322140323140324140325140326140327140328140329140330140331140332140333140334140335140336140337140338140339140340140341140342140343140344140345140346140347140348140349140350140351140352140353140354140355140356140357140358140359140360140361140362140363140364140365140366140367140368140369140370140371140372140373140374140375140376140377140378140379140380140381140382140383140384140385140386140387140388140389140390140391140392140393140394140395140396140397140398140399140400140401140402140403140404140405140406140407140408140409140410140411140412140413140414140415140416140417140418140419140420140421140422140423140424140425140426140427140428140429140430140431140432140433140434140435140436140437140438140439140440140441140442140443140444140445140446140447140448140449140450140451140452140453140454140455140456140457140458140459140460140461140462140463140464140465140466140467140468140469140470140471140472140473140474140475140476140477140478140479140480140481140482140483140484140485140486140487140488140489140490140491140492140493140494140495140496140497140498140499140500140501140502140503140504140505140506140507140508140509140510140511140512140513140514140515140516140517140518140519140520140521140522140523140524140525140526140527140528140529140530140531140532140533140534140535140536140537140538140539140540140541140542140543140544140545140546140547140548140549140550140551140552140553140554140555140556140557140558140559140560140561140562140563140564140565140566140567140568140569140570140571140572140573140574140575140576140577140578140579140580140581140582140583140584140585140586140587140588140589140590140591140592140593140594140595140596140597140598140599140600140601140602140603140604140605140606140607140608140609140610140611140612140613140614140615140616140617140618140619140620140621140622140623140624140625140626140627140628140629140630140631140632140633140634140635140636140637140638140639140640140641140642140643140644140645140646140647140648140649140650140651140652140653140654140655140656140657140658140659140660140661140662140663140664140665140666140667140668140669140670140671140672140673140674140675140676140677140678140679140680140681140682140683140684140685140686140687140688140689140690140691140692140693140694140695140696140697140698140699140700140701140702140703140704140705140706140707140708140709140710140711140712140713140714140715140716140717140718140719140720140721140722140723140724140725140726140727140728140729140730140731140732140733140734140735140736140737140738140739140740140741140742140743140744140745140746140747140748140749140750140751140752140753140754140755140756140757140758140759140760140761140762140763140764140765140766140767140768140769140770140771140772140773140774140775140776140777140778140779140780140781140782140783140784140785140786140787140788140789140790140791140792140793140794140795140796140797140798140799140800140801140802140803140804140805140806140807140808140809140810140811140812140813140814140815140816140817140818140819140820140821140822140823140824140825140826140827140828140829140830140831140832140833140834140835140836140837140838140839140840140841140842140843140844140845140846140847140848140849140850140851140852140853140854140855140856140857140858140859140860140861140862140863140864140865140866140867140868140869140870140871140872140873140874140875140876140877140878140879140880140881140882140883140884140885140886140887140888140889140890140891140892140893140894140895140896140897140898140899140900140901140902140903140904140905140906140907140908140909140910140911140912140913140914140915140916140917140918140919140920140921140922140923140924140925140926140927140928140929140930140931140932140933140934140935140936140937140938140939140940140941140942140943140944140945140946140947140948140949140950140951140952140953140954140955140956140957140958140959140960140961140962140963140964140965140966140967140968140969140970140971140972140973140974140975140976140977140978140979140980140981140982140983140984140985140986140987140988140989140990140991140992140993140994140995140996140997140998140999141000141001141002141003141004141005141006141007141008141009141010141011141012141013141014141015141016141017141018141019141020141021141022141023141024141025141026141027141028141029141030141031141032141033141034141035141036141037141038141039141040141041141042141043141044141045141046141047141048141049141050141051141052141053141054141055141056141057141058141059141060141061141062141063141064141065141066141067141068141069141070141071141072141073141074141075141076141077141078141079141080141081141082141083141084141085141086141087141088141089141090141091141092141093141094141095141096141097141098141099141100141101141102141103141104141105141106141107141108141109141110141111141112141113141114141115141116141117141118141119141120141121141122141123141124141125141126141127141128141129141130141131141132141133141134141135141136141137141138141139141140141141141142141143141144141145141146141147141148141149141150141151141152141153141154141155141156141157141158141159141160141161141162141163141164141165141166141167141168141169141170141171141172141173141174141175141176141177141178141179141180141181141182141183141184141185141186141187141188141189141190141191141192141193141194141195141196141197141198141199141200141201141202141203141204141205141206141207141208141209141210141211141212141213141214141215141216141217141218141219141220141221141222141223141224141225141226141227141228141229141230141231141232141233141234141235141236141237141238141239141240141241141242141243141244141245141246141247141248141249141250141251141252141253141254141255141256141257141258141259141260141261141262141263141264141265141266141267141268141269141270141271141272141273141274141275141276141277141278141279141280141281141282141283141284141285141286141287141288141289141290141291141292141293141294141295141296141297141298141299141300141301141302141303141304141305141306141307141308141309141310141311141312141313141314141315141316141317141318141319141320141321141322141323141324141325141326141327141328141329141330141331141332141333141334141335141336141337141338141339141340141341141342141343141344141345141346141347141348141349141350141351141352141353141354141355141356141357141358141359141360141361141362141363141364141365141366141367141368141369141370141371141372141373141374141375141376141377141378141379141380141381141382141383141384141385141386141387141388141389141390141391141392141393141394141395141396141397141398141399141400141401141402141403141404141405141406141407141408141409141410141411141412141413141414141415141416141417141418141419141420141421141422141423141424141425141426141427141428141429141430141431141432141433141434141435141436141437141438141439141440141441141442141443141444141445141446141447141448141449141450141451141452141453141454141455141456141457141458141459141460141461141462141463141464141465141466141467141468141469141470141471141472141473141474141475141476141477141478141479141480141481141482141483141484141485141486141487141488141489141490141491141492141493141494141495141496141497141498141499141500141501141502141503141504141505141506141507141508141509141510141511141512141513141514141515141516141517141518141519141520141521141522141523141524141525141526141527141528141529141530141531141532141533141534141535141536141537141538141539141540141541141542141543141544141545141546141547141548141549141550141551141552141553141554141555141556141557141558141559141560141561141562141563141564141565141566141567141568141569141570141571141572141573141574141575141576141577141578141579141580141581141582141583141584141585141586141587141588141589141590141591141592141593141594141595141596141597141598141599141600141601141602141603141604141605141606141607141608141609141610141611141612141613141614141615141616141617141618141619141620141621141622141623141624141625141626141627141628141629141630141631141632141633141634141635141636141637141638141639141640141641141642141643141644141645141646141647141648141649141650141651141652141653141654141655141656141657141658141659141660141661141662141663141664141665141666141667141668141669141670141671141672141673141674141675141676141677141678141679141680141681141682141683141684141685141686141687141688141689141690141691141692141693141694141695141696141697141698141699141700141701141702141703141704141705141706141707141708141709141710141711141712141713141714141715141716141717141718141719141720141721141722141723141724141725141726141727141728141729141730141731141732141733141734141735141736141737141738141739141740141741141742141743141744141745141746141747141748141749141750141751141752141753141754141755141756141757141758141759141760141761141762141763141764141765141766141767141768141769141770141771141772141773141774141775141776141777141778141779141780141781141782141783141784141785141786141787141788141789141790141791141792141793141794141795141796141797141798141799141800141801141802141803141804141805141806141807141808141809141810141811141812141813141814141815141816141817141818141819141820141821141822141823141824141825141826141827141828141829141830141831141832141833141834141835141836141837141838141839141840141841141842141843141844141845141846141847141848141849141850141851141852141853141854141855141856141857141858141859141860141861141862141863141864141865141866141867141868141869141870141871141872141873141874141875141876141877141878141879141880141881141882141883141884141885141886141887141888141889141890141891141892141893141894141895141896141897141898141899141900141901141902141903141904141905141906141907141908141909141910141911141912141913141914141915141916141917141918141919141920141921141922141923141924141925141926141927141928141929141930141931141932141933141934141935141936141937141938141939141940141941141942141943141944141945141946141947141948141949141950141951141952141953141954141955141956141957141958141959141960141961141962141963141964141965141966141967141968141969141970141971141972141973141974141975141976141977141978141979141980141981141982141983141984141985141986141987141988141989141990141991141992141993141994141995141996141997141998141999142000142001142002142003142004142005142006142007142008142009142010142011142012142013142014142015142016142017142018142019142020142021142022142023142024142025142026142027142028142029142030142031142032142033142034142035142036142037142038142039142040142041142042142043142044142045142046142047142048142049142050142051142052142053142054142055142056142057142058142059142060142061142062142063142064142065142066142067142068142069142070142071142072142073142074142075142076142077142078142079142080142081142082142083142084142085142086142087142088142089142090142091142092142093142094142095142096142097142098142099142100142101142102142103142104142105142106142107142108142109142110142111142112142113142114142115142116142117142118142119142120142121142122142123142124142125142126142127142128142129142130142131142132142133142134142135142136142137142138142139142140142141142142142143142144142145142146142147142148142149142150142151142152142153142154142155142156142157142158142159142160142161142162142163142164142165142166142167142168142169142170142171142172142173142174142175142176142177142178142179142180142181142182142183142184142185142186142187142188142189142190142191142192142193142194142195142196142197142198142199142200142201142202142203142204142205142206142207142208142209142210142211142212142213142214142215142216142217142218142219142220142221142222142223142224142225142226142227142228142229142230142231142232142233142234142235142236142237142238142239142240142241142242142243142244142245142246142247142248142249142250142251142252142253142254142255142256142257142258142259142260142261142262142263142264142265142266142267142268142269142270142271142272142273142274142275142276142277142278142279142280142281142282142283142284142285142286142287142288142289142290142291142292142293142294142295142296142297142298142299142300142301142302142303142304142305142306142307142308142309142310142311142312142313142314142315142316142317142318142319142320142321142322142323142324142325142326142327142328142329142330142331142332142333142334142335142336142337142338142339142340142341142342142343142344142345142346142347142348142349142350142351142352142353142354142355142356142357142358142359142360142361142362142363142364142365142366142367142368142369142370142371142372142373142374142375142376142377142378142379142380142381142382142383142384142385142386142387142388142389142390142391142392142393142394142395142396142397142398142399142400142401142402142403142404142405142406142407142408142409142410142411142412142413142414142415142416142417142418142419142420142421142422142423142424142425142426142427142428142429142430142431142432142433142434142435142436142437142438142439142440142441142442142443142444142445142446142447142448142449142450142451142452142453142454142455142456142457142458142459142460142461142462142463142464142465142466142467142468142469142470142471142472142473142474142475142476142477142478142479142480142481142482142483142484142485142486142487142488142489142490142491142492142493142494142495142496142497142498142499142500142501142502142503142504142505142506142507142508142509142510142511142512142513142514142515142516142517142518142519142520142521142522142523142524142525142526142527142528142529142530142531142532142533142534142535142536142537142538142539142540142541142542142543142544142545142546142547142548142549142550142551142552142553142554142555142556142557142558142559142560142561142562142563142564142565142566142567142568142569142570142571142572142573142574142575142576142577142578142579142580142581142582142583142584142585142586142587142588142589142590142591142592142593142594142595142596142597142598142599142600142601142602142603142604142605142606142607142608142609142610142611142612142613142614142615142616142617142618142619142620142621142622142623142624142625142626142627142628142629142630142631142632142633142634142635142636142637142638142639142640142641142642142643142644142645142646142647142648142649142650142651142652142653142654142655142656142657142658142659142660142661142662142663142664142665142666142667142668142669142670142671142672142673142674142675142676142677142678142679142680142681142682142683142684142685142686142687142688142689142690142691142692142693142694142695142696142697142698142699142700142701142702142703142704142705142706142707142708142709142710142711142712142713142714142715142716142717142718142719142720142721142722142723142724142725142726142727142728142729142730142731142732142733142734142735142736142737142738142739142740142741142742142743142744142745142746142747142748142749142750142751142752142753142754142755142756142757142758142759142760142761142762142763142764142765142766142767142768142769142770142771142772142773142774142775142776142777142778142779142780142781142782142783142784142785142786142787142788142789142790142791142792142793142794142795142796142797142798142799142800142801142802142803142804142805142806142807142808142809142810142811142812142813142814142815142816142817142818142819142820142821142822142823142824142825142826142827142828142829142830142831142832142833142834142835142836142837142838142839142840142841142842142843142844142845142846142847142848142849142850142851142852142853142854142855142856142857142858142859142860142861142862142863142864142865142866142867142868142869142870142871142872142873142874142875142876142877142878142879142880142881142882142883142884142885142886142887142888142889142890142891142892142893142894142895142896142897142898142899142900142901142902142903142904142905142906142907142908142909142910142911142912142913142914142915142916142917142918142919142920142921142922142923142924142925142926142927142928142929142930142931142932142933142934142935142936142937142938142939142940142941142942142943142944142945142946142947142948142949142950142951142952142953142954142955142956142957142958142959142960142961142962142963142964142965142966142967142968142969142970142971142972142973142974142975142976142977142978142979142980142981142982142983142984142985142986142987142988142989142990142991142992142993142994142995142996142997142998142999143000143001143002143003143004143005143006143007143008143009143010143011143012143013143014143015143016143017143018143019143020143021143022143023143024143025143026143027143028143029143030143031143032143033143034143035143036143037143038143039143040143041143042143043143044143045143046143047143048143049143050143051143052143053143054143055143056143057143058143059143060143061143062143063143064143065143066143067143068143069143070143071143072143073143074143075143076143077143078143079143080143081143082143083143084143085143086143087143088143089143090143091143092143093143094143095143096143097143098143099143100143101143102143103143104143105143106143107143108143109143110143111143112143113143114143115143116143117143118143119143120143121143122143123143124143125143126143127143128143129143130143131143132143133143134143135143136143137143138143139143140143141143142143143143144143145143146143147143148143149143150143151143152143153143154143155143156143157143158143159143160143161143162143163143164143165143166143167143168143169143170143171143172143173143174143175143176143177143178143179143180143181143182143183143184143185143186143187143188143189143190143191143192143193143194143195143196143197143198143199143200143201143202143203143204143205143206143207143208143209143210143211143212143213143214143215143216143217143218143219143220143221143222143223143224143225143226143227143228143229143230143231143232143233143234143235143236143237143238143239143240143241143242143243143244143245143246143247143248143249143250143251143252143253143254143255143256143257143258143259143260143261143262143263143264143265143266143267143268143269143270143271143272143273143274143275143276143277143278143279143280143281143282143283143284143285143286143287143288143289143290143291143292143293143294143295143296143297143298143299143300143301143302143303143304143305143306143307143308143309143310143311143312143313143314143315143316143317143318143319143320143321143322143323143324143325143326143327143328143329143330143331143332143333143334143335143336143337143338143339143340143341143342143343143344143345143346143347143348143349143350143351143352143353143354143355143356143357143358143359143360143361143362143363143364143365143366143367143368143369143370143371143372143373143374143375143376143377143378143379143380143381143382143383143384143385143386143387143388143389143390143391143392143393143394143395143396143397143398143399143400143401143402143403143404143405143406143407143408143409143410143411143412143413143414143415143416143417143418143419143420143421143422143423143424143425143426143427143428143429143430143431143432143433143434143435143436143437143438143439143440143441143442143443143444143445143446143447143448143449143450143451143452143453143454143455143456143457143458143459143460143461143462143463143464143465143466143467143468143469143470143471143472143473143474143475143476143477143478143479143480143481143482143483143484143485143486143487143488143489143490143491143492143493143494143495143496143497143498143499143500143501143502143503143504143505143506143507143508143509143510143511143512143513143514143515143516143517143518143519143520143521143522143523143524143525143526143527143528143529143530143531143532143533143534143535143536143537143538143539143540143541143542143543143544143545143546143547143548143549143550143551143552143553143554143555143556143557143558143559143560143561143562143563143564143565143566143567143568143569143570143571143572143573143574143575143576143577143578143579143580143581143582143583143584143585143586143587143588143589143590143591143592143593143594143595143596143597143598143599143600143601143602143603143604143605143606143607143608143609143610143611143612143613143614143615143616143617143618143619143620143621143622143623143624143625143626143627143628143629143630143631143632143633143634143635143636143637143638143639143640143641143642143643143644143645143646143647143648143649143650143651143652143653143654143655143656143657143658143659143660143661143662143663143664143665143666143667143668143669143670143671143672143673143674143675143676143677143678143679143680143681143682143683143684143685143686143687143688143689143690143691143692143693143694143695143696143697143698143699143700143701143702143703143704143705143706143707143708143709143710143711143712143713143714143715143716143717143718143719143720143721143722143723143724143725143726143727143728143729143730143731143732143733143734143735143736143737143738143739143740143741143742143743143744143745143746143747143748143749143750143751143752143753143754143755143756143757143758143759143760143761143762143763143764143765143766143767143768143769143770143771143772143773143774143775143776143777143778143779143780143781143782143783143784143785143786143787143788143789143790143791143792143793143794143795143796143797143798143799143800143801143802143803143804143805143806143807143808143809143810143811143812143813143814143815143816143817143818143819143820143821143822143823143824143825143826143827143828143829143830143831143832143833143834143835143836143837143838143839143840143841143842143843143844143845143846143847143848143849143850143851143852143853143854143855143856143857143858143859143860143861143862143863143864143865143866143867143868143869143870143871143872143873143874143875143876143877143878143879143880143881143882143883143884143885143886143887143888143889143890143891143892143893143894143895143896143897143898143899143900143901143902143903143904143905143906143907143908143909143910143911143912143913143914143915143916143917143918143919143920143921143922143923143924143925143926143927143928143929143930143931143932143933143934143935143936143937143938143939143940143941143942143943143944143945143946143947143948143949143950143951143952143953143954143955143956143957143958143959143960143961143962143963143964143965143966143967143968143969143970143971143972143973143974143975143976143977143978143979143980143981143982143983143984143985143986143987143988143989143990143991143992143993143994143995143996143997143998143999144000144001144002144003144004144005144006144007144008144009144010144011144012144013144014144015144016144017144018144019144020144021144022144023144024144025144026144027144028144029144030144031144032144033144034144035144036144037144038144039144040144041144042144043144044144045144046144047144048144049144050144051144052144053144054144055144056144057144058144059144060144061144062144063144064144065144066144067144068144069144070144071144072144073144074144075144076144077144078144079144080144081144082144083144084144085144086144087144088144089144090144091144092144093144094144095144096144097144098144099144100144101144102144103144104144105144106144107144108144109144110144111144112144113144114144115144116144117144118144119144120144121144122144123144124144125144126144127144128144129144130144131144132144133144134144135144136144137144138144139144140144141144142144143144144144145144146144147144148144149144150144151144152144153144154144155144156144157144158144159144160144161144162144163144164144165144166144167144168144169144170144171144172144173144174144175144176144177144178144179144180144181144182144183144184144185144186144187144188144189144190144191144192144193144194144195144196144197144198144199144200144201144202144203144204144205144206144207144208144209144210144211144212144213144214144215144216144217144218144219144220144221144222144223144224144225144226144227144228144229144230144231144232144233144234144235144236144237144238144239144240144241144242144243144244144245144246144247144248144249144250144251144252144253144254144255144256144257144258144259144260144261144262144263144264144265144266144267144268144269144270144271144272144273144274144275144276144277144278144279144280144281144282144283144284144285144286144287144288144289144290144291144292144293144294144295144296144297144298144299144300144301144302144303144304144305144306144307144308144309144310144311144312144313144314144315144316144317144318144319144320144321144322144323144324144325144326144327144328144329144330144331144332144333144334144335144336144337144338144339144340144341144342144343144344144345144346144347144348144349144350144351144352144353144354144355144356144357144358144359144360144361144362144363144364144365144366144367144368144369144370144371144372144373144374144375144376144377144378144379144380144381144382144383144384144385144386144387144388144389144390144391144392144393144394144395144396144397144398144399144400144401144402144403144404144405144406144407144408144409144410144411144412144413144414144415144416144417144418144419144420144421144422144423144424144425144426144427144428144429144430144431144432144433144434144435144436144437144438144439144440144441144442144443144444144445144446144447144448144449144450144451144452144453144454144455144456144457144458144459144460144461144462144463144464144465144466144467144468144469144470144471144472144473144474144475144476144477144478144479144480144481144482144483144484144485144486144487144488144489144490144491144492144493144494144495144496144497144498144499144500144501144502144503144504144505144506144507144508144509144510144511144512144513144514144515144516144517144518144519144520144521144522144523144524144525144526144527144528144529144530144531144532144533144534144535144536144537144538144539144540144541144542144543144544144545144546144547144548144549144550144551144552144553144554144555144556144557144558144559144560144561144562144563144564144565144566144567144568144569144570144571144572144573144574144575144576144577144578144579144580144581144582144583144584144585144586144587144588144589144590144591144592144593144594144595144596144597144598144599144600144601144602144603144604144605144606144607144608144609144610144611144612144613144614144615144616144617144618144619144620144621144622144623144624144625144626144627144628144629144630144631144632144633144634144635144636144637144638144639144640144641144642144643144644144645144646144647144648144649144650144651144652144653144654144655144656144657144658144659144660144661144662144663144664144665144666144667144668144669144670144671144672144673144674144675144676144677144678144679144680144681144682144683144684144685144686144687144688144689144690144691144692144693144694144695144696144697144698144699144700144701144702144703144704144705144706144707144708144709144710144711144712144713144714144715144716144717144718144719144720144721144722144723144724144725144726144727144728144729144730144731144732144733144734144735144736144737144738144739144740144741144742144743144744144745144746144747144748144749144750144751144752144753144754144755144756144757144758144759144760144761144762144763144764144765144766144767144768144769144770144771144772144773144774144775144776144777144778144779144780144781144782144783144784144785144786144787144788144789144790144791144792144793144794144795144796144797144798144799144800144801144802144803144804144805144806144807144808144809144810144811144812144813144814144815144816144817144818144819144820144821144822144823144824144825144826144827144828144829144830144831144832144833144834144835144836144837144838144839144840144841144842144843144844144845144846144847144848144849144850144851144852144853144854144855144856144857144858144859144860144861144862144863144864144865144866144867144868144869144870144871144872144873144874144875144876144877144878144879144880144881144882144883144884144885144886144887144888144889144890144891144892144893144894144895144896144897144898144899144900144901144902144903144904144905144906144907144908144909144910144911144912144913144914144915144916144917144918144919144920144921144922144923144924144925144926144927144928144929144930144931144932144933144934144935144936144937144938144939144940144941144942144943144944144945144946144947144948144949144950144951144952144953144954144955144956144957144958144959144960144961144962144963144964144965144966144967144968144969144970144971144972144973144974144975144976144977144978144979144980144981144982144983144984144985144986144987144988144989144990144991144992144993144994144995144996144997144998144999145000145001145002145003145004145005145006145007145008145009145010145011145012145013145014145015145016145017145018145019145020145021145022145023145024145025145026145027145028145029145030145031145032145033145034145035145036145037145038145039145040145041145042145043145044145045145046145047145048145049145050145051145052145053145054145055145056145057145058145059145060145061145062145063145064145065145066145067145068145069145070145071145072145073145074145075145076145077145078145079145080145081145082145083145084145085145086145087145088145089145090145091145092145093145094145095145096145097145098145099145100145101145102145103145104145105145106145107145108145109145110145111145112145113145114145115145116145117145118145119145120145121145122145123145124145125145126145127145128145129145130145131145132145133145134145135145136145137145138145139145140145141145142145143145144145145145146145147145148145149145150145151145152145153145154145155145156145157145158145159145160145161145162145163145164145165145166145167145168145169145170145171145172145173145174145175145176145177145178145179145180145181145182145183145184145185145186145187145188145189145190145191145192145193145194145195145196145197145198145199145200145201145202145203145204145205145206145207145208145209145210145211145212145213145214145215145216145217145218145219145220145221145222145223145224145225145226145227145228145229145230145231145232145233145234145235145236145237145238145239145240145241145242145243145244145245145246145247145248145249145250145251145252145253145254145255145256145257145258145259145260145261145262145263145264145265145266145267145268145269145270145271145272145273145274145275145276145277145278145279145280145281145282145283145284145285145286145287145288145289145290145291145292145293145294145295145296145297145298145299145300145301145302145303145304145305145306145307145308145309145310145311145312145313145314145315145316145317145318145319145320145321145322145323145324145325145326145327145328145329145330145331145332145333145334145335145336145337145338145339145340145341145342145343145344145345145346145347145348145349145350145351145352145353145354145355145356145357145358145359145360145361145362145363145364145365145366145367145368145369145370145371145372145373145374145375145376145377145378145379145380145381145382145383145384145385145386145387145388145389145390145391145392145393145394145395145396145397145398145399145400145401145402145403145404145405145406145407145408145409145410145411145412145413145414145415145416145417145418145419145420145421145422145423145424145425145426145427145428145429145430145431145432145433145434145435145436145437145438145439145440145441145442145443145444145445145446145447145448145449145450145451145452145453145454145455145456145457145458145459145460145461145462145463145464145465145466145467145468145469145470145471145472145473145474145475145476145477145478145479145480145481145482145483145484145485145486145487145488145489145490145491145492145493145494145495145496145497145498145499145500145501145502145503145504145505145506145507145508145509145510145511145512145513145514145515145516145517145518145519145520145521145522145523145524145525145526145527145528145529145530145531145532145533145534145535145536145537145538145539145540145541145542145543145544145545145546145547145548145549145550145551145552145553145554145555145556145557145558145559145560145561145562145563145564145565145566145567145568145569145570145571145572145573145574145575145576145577145578145579145580145581145582145583145584145585145586145587145588145589145590145591145592145593145594145595145596145597145598145599145600145601145602145603145604145605145606145607145608145609145610145611145612145613145614145615145616145617145618145619145620145621145622145623145624145625145626145627145628145629145630145631145632145633145634145635145636145637145638145639145640145641145642145643145644145645145646145647145648145649145650145651145652145653145654145655145656145657145658145659145660145661145662145663145664145665145666145667145668145669145670145671145672145673145674145675145676145677145678145679145680145681145682145683145684145685145686145687145688145689145690145691145692145693145694145695145696145697145698145699145700145701145702145703145704145705145706145707145708145709145710145711145712145713145714145715145716145717145718145719145720145721145722145723145724145725145726145727145728145729145730145731145732145733145734145735145736145737145738145739145740145741145742145743145744145745145746145747145748145749145750145751145752145753145754145755145756145757145758145759145760145761145762145763145764145765145766145767145768145769145770145771145772145773145774145775145776145777145778145779145780145781145782145783145784145785145786145787145788145789145790145791145792145793145794145795145796145797145798145799145800145801145802145803145804145805145806145807145808145809145810145811145812145813145814145815145816145817145818145819145820145821145822145823145824145825145826145827145828145829145830145831145832145833145834145835145836145837145838145839145840145841145842145843145844145845145846145847145848145849145850145851145852145853145854145855145856145857145858145859145860145861145862145863145864145865145866145867145868145869145870145871145872145873145874145875145876145877145878145879145880145881145882145883145884145885145886145887145888145889145890145891145892145893145894145895145896145897145898145899145900145901145902145903145904145905145906145907145908145909145910145911145912145913145914145915145916145917145918145919145920145921145922145923145924145925145926145927145928145929145930145931145932145933145934145935145936145937145938145939145940145941145942145943145944145945145946145947145948145949145950145951145952145953145954145955145956145957145958145959145960145961145962145963145964145965145966145967145968145969145970145971145972145973145974145975145976145977145978145979145980145981145982145983145984145985145986145987145988145989145990145991145992145993145994145995145996145997145998145999146000146001146002146003146004146005146006146007146008146009146010146011146012146013146014146015146016146017146018146019146020146021146022146023146024146025146026146027146028146029146030146031146032146033146034146035146036146037146038146039146040146041146042146043146044146045146046146047146048146049146050146051146052146053146054146055146056146057146058146059146060146061146062146063146064146065146066146067146068146069146070146071146072146073146074146075146076146077146078146079146080146081146082146083146084146085146086146087146088146089146090146091146092146093146094146095146096146097146098146099146100146101146102146103146104146105146106146107146108146109146110146111146112146113146114146115146116146117146118146119146120146121146122146123146124146125146126146127146128146129146130146131146132146133146134146135146136146137146138146139146140146141146142146143146144146145146146146147146148146149146150146151146152146153146154146155146156146157146158146159146160146161146162146163146164146165146166146167146168146169146170146171146172146173146174146175146176146177146178146179146180146181146182146183146184146185146186146187146188146189146190146191146192146193146194146195146196146197146198146199146200146201146202146203146204146205146206146207146208146209146210146211146212146213146214146215146216146217146218146219146220146221146222146223146224146225146226146227146228146229146230146231146232146233146234146235146236146237146238146239146240146241146242146243146244146245146246146247146248146249146250146251146252146253146254146255146256146257146258146259146260146261146262146263146264146265146266146267146268146269146270146271146272146273146274146275146276146277146278146279146280146281146282146283146284146285146286146287146288146289146290146291146292146293146294146295146296146297146298146299146300146301146302146303146304146305146306146307146308146309146310146311146312146313146314146315146316146317146318146319146320146321146322146323146324146325146326146327146328146329146330146331146332146333146334146335146336146337146338146339146340146341146342146343146344146345146346146347146348146349146350146351146352146353146354146355146356146357146358146359146360146361146362146363146364146365146366146367146368146369146370146371146372146373146374146375146376146377146378146379146380146381146382146383146384146385146386146387146388146389146390146391146392146393146394146395146396146397146398146399146400146401146402146403146404146405146406146407146408146409146410146411146412146413146414146415146416146417146418146419146420146421146422146423146424146425146426146427146428146429146430146431146432146433146434146435146436146437146438146439146440146441146442146443146444146445146446146447146448146449146450146451146452146453146454146455146456146457146458146459146460146461146462146463146464146465146466146467146468146469146470146471146472146473146474146475146476146477146478146479146480146481146482146483146484146485146486146487146488146489146490146491146492146493146494146495146496146497146498146499146500146501146502146503146504146505146506146507146508146509146510146511146512146513146514146515146516146517146518146519146520146521146522146523146524146525146526146527146528146529146530146531146532146533146534146535146536146537146538146539146540146541146542146543146544146545146546146547146548146549146550146551146552146553146554146555146556146557146558146559146560146561146562146563146564146565146566146567146568146569146570146571146572146573146574146575146576146577146578146579146580146581146582146583146584146585146586146587146588146589146590146591146592146593146594146595146596146597146598146599146600146601146602146603146604146605146606146607146608146609146610146611146612146613146614146615146616146617146618146619146620146621146622146623146624146625146626146627146628146629146630146631146632146633146634146635146636146637146638146639146640146641146642146643146644146645146646146647146648146649146650146651146652146653146654146655146656146657146658146659146660146661146662146663146664146665146666146667146668146669146670146671146672146673146674146675146676146677146678146679146680146681146682146683146684146685146686146687146688146689146690146691146692146693146694146695146696146697146698146699146700146701146702146703146704146705146706146707146708146709146710146711146712146713146714146715146716146717146718146719146720146721146722146723146724146725146726146727146728146729146730146731146732146733146734146735146736146737146738146739146740146741146742146743146744146745146746146747146748146749146750146751146752146753146754146755146756146757146758146759146760146761146762146763146764146765146766146767146768146769146770146771146772146773146774146775146776146777146778146779146780146781146782146783146784146785146786146787146788146789146790146791146792146793146794146795146796146797146798146799146800146801146802146803146804146805146806146807146808146809146810146811146812146813146814146815146816146817146818146819146820146821146822146823146824146825146826146827146828146829146830146831146832146833146834146835146836146837146838146839146840146841146842146843146844146845146846146847146848146849146850146851146852146853146854146855146856146857146858146859146860146861146862146863146864146865146866146867146868146869146870146871146872146873146874146875146876146877146878146879146880146881146882146883146884146885146886146887146888146889146890146891146892146893146894146895146896146897146898146899146900146901146902146903146904146905146906146907146908146909146910146911146912146913146914146915146916146917146918146919146920146921146922146923146924146925146926146927146928146929146930146931146932146933146934146935146936146937146938146939146940146941146942146943146944146945146946146947146948146949146950146951146952146953146954146955146956146957146958146959146960146961146962146963146964146965146966146967146968146969146970146971146972146973146974146975146976146977146978146979146980146981146982146983146984146985146986146987146988146989146990146991146992146993146994146995146996146997146998146999147000147001147002147003147004147005147006147007147008147009147010147011147012147013147014147015147016147017147018147019147020147021147022147023147024147025147026147027147028147029147030147031147032147033147034147035147036147037147038147039147040147041147042147043147044147045147046147047147048147049147050147051147052147053147054147055147056147057147058147059147060147061147062147063147064147065147066147067147068147069147070147071147072147073147074147075147076147077147078147079147080147081147082147083147084147085147086147087147088147089147090147091147092147093147094147095147096147097147098147099147100147101147102147103147104147105147106147107147108147109147110147111147112147113147114147115147116147117147118147119147120147121147122147123147124147125147126147127147128147129147130147131147132147133147134147135147136147137147138147139147140147141147142147143147144147145147146147147147148147149147150147151147152147153147154147155147156147157147158147159147160147161147162147163147164147165147166147167147168147169147170147171147172147173147174147175147176147177147178147179147180147181147182147183147184147185147186147187147188147189147190147191147192147193147194147195147196147197147198147199147200147201147202147203147204147205147206147207147208147209147210147211147212147213147214147215147216147217147218147219147220147221147222147223147224147225147226147227147228147229147230147231147232147233147234147235147236147237147238147239147240147241147242147243147244147245147246147247147248147249147250147251147252147253147254147255147256147257147258147259147260147261147262147263147264147265147266147267147268147269147270147271147272147273147274147275147276147277147278147279147280147281147282147283147284147285147286147287147288147289147290147291147292147293147294147295147296147297147298147299147300147301147302147303147304147305147306147307147308147309147310147311147312147313147314147315147316147317147318147319147320147321147322147323147324147325147326147327147328147329147330147331147332147333147334147335147336147337147338147339147340147341147342147343147344147345147346147347147348147349147350147351147352147353147354147355147356147357147358147359147360147361147362147363147364147365147366147367147368147369147370147371147372147373147374147375147376147377147378147379147380147381147382147383147384147385147386147387147388147389147390147391147392147393147394147395147396147397147398147399147400147401147402147403147404147405147406147407147408147409147410147411147412147413147414147415147416147417147418147419147420147421147422147423147424147425147426147427147428147429147430147431147432147433147434147435147436147437147438147439147440147441147442147443147444147445147446147447147448147449147450147451147452147453147454147455147456147457147458147459147460147461147462147463147464147465147466147467147468147469147470147471147472147473147474147475147476147477147478147479147480147481147482147483147484147485147486147487147488147489147490147491147492147493147494147495147496147497147498147499147500147501147502147503147504147505147506147507147508147509147510147511147512147513147514147515147516147517147518147519147520147521147522147523147524147525147526147527147528147529147530147531147532147533147534147535147536147537147538147539147540147541147542147543147544147545147546147547147548147549147550147551147552147553147554147555147556147557147558147559147560147561147562147563147564147565147566147567147568147569147570147571147572147573147574147575147576147577147578147579147580147581147582147583147584147585147586147587147588147589147590147591147592147593147594147595147596147597147598147599147600147601147602147603147604147605147606147607147608147609147610147611147612147613147614147615147616147617147618147619147620147621147622147623147624147625147626147627147628147629147630147631147632147633147634147635147636147637147638147639147640147641147642147643147644147645147646147647147648147649147650147651147652147653147654147655147656147657147658147659147660147661147662147663147664147665147666147667147668147669147670147671147672147673147674147675147676147677147678147679147680147681147682147683147684147685147686147687147688147689147690147691147692147693147694147695147696147697147698147699147700147701147702147703147704147705147706147707147708147709147710147711147712147713147714147715147716147717147718147719147720147721147722147723147724147725147726147727147728147729147730147731147732147733147734147735147736147737147738147739147740147741147742147743147744147745147746147747147748147749147750147751147752147753147754147755147756147757147758147759147760147761147762147763147764147765147766147767147768147769147770147771147772147773147774147775147776147777147778147779147780147781147782147783147784147785147786147787147788147789147790147791147792147793147794147795147796147797147798147799147800147801147802147803147804147805147806147807147808147809147810147811147812147813147814147815147816147817147818147819147820147821147822147823147824147825147826147827147828147829147830147831147832147833147834147835147836147837147838147839147840147841147842147843147844147845147846147847147848147849147850147851147852147853147854147855147856147857147858147859147860147861147862147863147864147865147866147867147868147869147870147871147872147873147874147875147876147877147878147879147880147881147882147883147884147885147886147887147888147889147890147891147892147893147894147895147896147897147898147899147900147901147902147903147904147905147906147907147908147909147910147911147912147913147914147915147916147917147918147919147920147921147922147923147924147925147926147927147928147929147930147931147932147933147934147935147936147937147938147939147940147941147942147943147944147945147946147947147948147949147950147951147952147953147954147955147956147957147958147959147960147961147962147963147964147965147966147967147968147969147970147971147972147973147974147975147976147977147978147979147980147981147982147983147984147985147986147987147988147989147990147991147992147993147994147995147996147997147998147999148000148001148002148003148004148005148006148007148008148009148010148011148012148013148014148015148016148017148018148019148020148021148022148023148024148025148026148027148028148029148030148031148032148033148034148035148036148037148038148039148040148041148042148043148044148045148046148047148048148049148050148051148052148053148054148055148056148057148058148059148060148061148062148063148064148065148066148067148068148069148070148071148072148073148074148075148076148077148078148079148080148081148082148083148084148085148086148087148088148089148090148091148092148093148094148095148096148097148098148099148100148101148102148103148104148105148106148107148108148109148110148111148112148113148114148115148116148117148118148119148120148121148122148123148124148125148126148127148128148129148130148131148132148133148134148135148136148137148138148139148140148141148142148143148144148145148146148147148148148149148150148151148152148153148154148155148156148157148158148159148160148161148162148163148164148165148166148167148168148169148170148171148172148173148174148175148176148177148178148179148180148181148182148183148184148185148186148187148188148189148190148191148192148193148194148195148196148197148198148199148200148201148202148203148204148205148206148207148208148209148210148211148212148213148214148215148216148217148218148219148220148221148222148223148224148225148226148227148228148229148230148231148232148233148234148235148236148237148238148239148240148241148242148243148244148245148246148247148248148249148250148251148252148253148254148255148256148257148258148259148260148261148262148263148264148265148266148267148268148269148270148271148272148273148274148275148276148277148278148279148280148281148282148283148284148285148286148287148288148289148290148291148292148293148294148295148296148297148298148299148300148301148302148303148304148305148306148307148308148309148310148311148312148313148314148315148316148317148318148319148320148321148322148323148324148325148326148327148328148329148330148331148332148333148334148335148336148337148338148339148340148341148342148343148344148345148346148347148348148349148350148351148352148353148354148355148356148357148358148359148360148361148362148363148364148365148366148367148368148369148370148371148372148373148374148375148376148377148378148379148380148381148382148383148384148385148386148387148388148389148390148391148392148393148394148395148396148397148398148399148400148401148402148403148404148405148406148407148408148409148410148411148412148413148414148415148416148417148418148419148420148421148422148423148424148425148426148427148428148429148430148431148432148433148434148435148436148437148438148439148440148441148442148443148444148445148446148447148448148449148450148451148452148453148454148455148456148457148458148459148460148461148462148463148464148465148466148467148468148469148470148471148472148473148474148475148476148477148478148479148480148481148482148483148484148485148486148487148488148489148490148491148492148493148494148495148496148497148498148499148500148501148502148503148504148505148506148507148508148509148510148511148512148513148514148515148516148517148518148519148520148521148522148523148524148525148526148527148528148529148530148531148532148533148534148535148536148537148538148539148540148541148542148543148544148545148546148547148548148549148550148551148552148553148554148555148556148557148558148559148560148561148562148563148564148565148566148567148568148569148570148571148572148573148574148575148576148577148578148579148580148581148582148583148584148585148586148587148588148589148590148591148592148593148594148595148596148597148598148599148600148601148602148603148604148605148606148607148608148609148610148611148612148613148614148615148616148617148618148619148620148621148622148623148624148625148626148627148628148629148630148631148632148633148634148635148636148637148638148639148640148641148642148643148644148645148646148647148648148649148650148651148652148653148654148655148656148657148658148659148660148661148662148663148664148665148666148667148668148669148670148671148672148673148674148675148676148677148678148679148680148681148682148683148684148685148686148687148688148689148690148691148692148693148694148695148696148697148698148699148700148701148702148703148704148705148706148707148708148709148710148711148712148713148714148715148716148717148718148719148720148721148722148723148724148725148726148727148728148729148730148731148732148733148734148735148736148737148738148739148740148741148742148743148744148745148746148747148748148749148750148751148752148753148754148755148756148757148758148759148760148761148762148763148764148765148766148767148768148769148770148771148772148773148774148775148776148777148778148779148780148781148782148783148784148785148786148787148788148789148790148791148792148793148794148795148796148797148798148799148800148801148802148803148804148805148806148807148808148809148810148811148812148813148814148815148816148817148818148819148820148821148822148823148824148825148826148827148828148829148830148831148832148833148834148835148836148837148838148839148840148841148842148843148844148845148846148847148848148849148850148851148852148853148854148855148856148857148858148859148860148861148862148863148864148865148866148867148868148869148870148871148872148873148874148875148876148877148878148879148880148881148882148883148884148885148886148887148888148889148890148891148892148893148894148895148896148897148898148899148900148901148902148903148904148905148906148907148908148909148910148911148912148913148914148915148916148917148918148919148920148921148922148923148924148925148926148927148928148929148930148931148932148933148934148935148936148937148938148939148940148941148942148943148944148945148946148947148948148949148950148951148952148953148954148955148956148957148958148959148960148961148962148963148964148965148966148967148968148969148970148971148972148973148974148975148976148977148978148979148980148981148982148983148984148985148986148987148988148989148990148991148992148993148994148995148996148997148998148999149000149001149002149003149004149005149006149007149008149009149010149011149012149013149014149015149016149017149018149019149020149021149022149023149024149025149026149027149028149029149030149031149032149033149034149035149036149037149038149039149040149041149042149043149044149045149046149047149048149049149050149051149052149053149054149055149056149057149058149059149060149061149062149063149064149065149066149067149068149069149070149071149072149073149074149075149076149077149078149079149080149081149082149083149084149085149086149087149088149089149090149091149092149093149094149095149096149097149098149099149100149101149102149103149104149105149106149107149108149109149110149111149112149113149114149115149116149117149118149119149120149121149122149123149124149125149126149127149128149129149130149131149132149133149134149135149136149137149138149139149140149141149142149143149144149145149146149147149148149149149150149151149152149153149154149155149156149157149158149159149160149161149162149163149164149165149166149167149168149169149170149171149172149173149174149175149176149177149178149179149180149181149182149183149184149185149186149187149188149189149190149191149192149193149194149195149196149197149198149199149200149201149202149203149204149205149206149207149208149209149210149211149212149213149214149215149216149217149218149219149220149221149222149223149224149225149226149227149228149229149230149231149232149233149234149235149236149237149238149239149240149241149242149243149244149245149246149247149248149249149250149251149252149253149254149255149256149257149258149259149260149261149262149263149264149265149266149267149268149269149270149271149272149273149274149275149276149277149278149279149280149281149282149283149284149285149286149287149288149289149290149291149292149293149294149295149296149297149298149299149300149301149302149303149304149305149306149307149308149309149310149311149312149313149314149315149316149317149318149319149320149321149322149323149324149325149326149327149328149329149330149331149332149333149334149335149336149337149338149339149340149341149342149343149344149345149346149347149348149349149350149351149352149353149354149355149356149357149358149359149360149361149362149363149364149365149366149367149368149369149370149371149372149373149374149375149376149377149378149379149380149381149382149383149384149385149386149387149388149389149390149391149392149393149394149395149396149397149398149399149400149401149402149403149404149405149406149407149408149409149410149411149412149413149414149415149416149417149418149419149420149421149422149423149424149425149426149427149428149429149430149431149432149433149434149435149436149437149438149439149440149441149442149443149444149445149446149447149448149449149450149451149452149453149454149455149456149457149458149459149460149461149462149463149464149465149466149467149468149469149470149471149472149473149474149475149476149477149478149479149480149481149482149483149484149485149486149487149488149489149490149491149492149493149494149495149496149497149498149499149500149501149502149503149504149505149506149507149508149509149510149511149512149513149514149515149516149517149518149519149520149521149522149523149524149525149526149527149528149529149530149531149532149533149534149535149536149537149538149539149540149541149542149543149544149545149546149547149548149549149550149551149552149553149554149555149556149557149558149559149560149561149562149563149564149565149566149567149568149569149570149571149572149573149574149575149576149577149578149579149580149581149582149583149584149585149586149587149588149589149590149591149592149593149594149595149596149597149598149599149600149601149602149603149604149605149606149607149608149609149610149611149612149613149614149615149616149617149618149619149620149621149622149623149624149625149626149627149628149629149630149631149632149633149634149635149636149637149638149639149640149641149642149643149644149645149646149647149648149649149650149651149652149653149654149655149656149657149658149659149660149661149662149663149664149665149666149667149668149669149670149671149672149673149674149675149676149677149678149679149680149681149682149683149684149685149686149687149688149689149690149691149692149693149694149695149696149697149698149699149700149701149702149703149704149705149706149707149708149709149710149711149712149713149714149715149716149717149718149719149720149721149722149723149724149725149726149727149728149729149730149731149732149733149734149735149736149737149738149739149740149741149742149743149744149745149746149747149748149749149750149751149752149753149754149755149756149757149758149759149760149761149762149763149764149765149766149767149768149769149770149771149772149773149774149775149776149777149778149779149780149781149782149783149784149785149786149787149788149789149790149791149792149793149794149795149796149797149798149799149800149801149802149803149804149805149806149807149808149809149810149811149812149813149814149815149816149817149818149819149820149821149822149823149824149825149826149827149828149829149830149831149832149833149834149835149836149837149838149839149840149841149842149843149844149845149846149847149848149849149850149851149852149853149854149855149856149857149858149859149860149861149862149863149864149865149866149867149868149869149870149871149872149873149874149875149876149877149878149879149880149881149882149883149884149885149886149887149888149889149890149891149892149893149894149895149896149897149898149899149900149901149902149903149904149905149906149907149908149909149910149911149912149913149914149915149916149917149918149919149920149921149922149923149924149925149926149927149928149929149930149931149932149933149934149935149936149937149938149939149940149941149942149943149944149945149946149947149948149949149950149951149952149953149954149955149956149957149958149959149960149961149962149963149964149965149966149967149968149969149970149971149972149973149974149975149976149977149978149979149980149981149982149983149984149985149986149987149988149989149990149991149992149993149994149995149996149997149998149999150000150001150002150003150004150005150006150007150008150009150010150011150012150013150014150015150016150017150018150019150020150021150022150023150024150025150026150027150028150029150030150031150032150033150034150035150036150037150038150039150040150041150042150043150044150045150046150047150048150049150050150051150052150053150054150055150056150057150058150059150060150061150062150063150064150065150066150067150068150069150070150071150072150073150074150075150076150077150078150079150080150081150082150083150084150085150086150087150088150089150090150091150092150093150094150095150096150097150098150099150100150101150102150103150104150105150106150107150108150109150110150111150112150113150114150115150116150117150118150119150120150121150122150123150124150125150126150127150128150129150130150131150132150133150134150135150136150137150138150139150140150141150142150143150144150145150146150147150148150149150150150151150152150153150154150155150156150157150158150159150160150161150162150163150164150165150166150167150168150169150170150171150172150173150174150175150176150177150178150179150180150181150182150183150184150185150186150187150188150189150190150191150192150193150194150195150196150197150198150199150200150201150202150203150204150205150206150207150208150209150210150211150212150213150214150215150216150217150218150219150220150221150222150223150224150225150226150227150228150229150230150231150232150233150234150235150236150237150238150239150240150241150242150243150244150245150246150247150248150249150250150251150252150253150254150255150256150257150258150259150260150261150262150263150264150265150266150267150268150269150270150271150272150273150274150275150276150277150278150279150280150281150282150283150284150285150286150287150288150289150290150291150292150293150294150295150296150297150298150299150300150301150302150303150304150305150306150307150308150309150310150311150312150313150314150315150316150317150318150319150320150321150322150323150324150325150326150327150328150329150330150331150332150333150334150335150336150337150338150339150340150341150342150343150344150345150346150347150348150349150350150351150352150353150354150355150356150357150358150359150360150361150362150363150364150365150366150367150368150369150370150371150372150373150374150375150376150377150378150379150380150381150382150383150384150385150386150387150388150389150390150391150392150393150394150395150396150397150398150399150400150401150402150403150404150405150406150407150408150409150410150411150412150413150414150415150416150417150418150419150420150421150422150423150424150425150426150427150428150429150430150431150432150433150434150435150436150437150438150439150440150441150442150443150444150445150446150447150448150449150450150451150452150453150454150455150456150457150458150459150460150461150462150463150464150465150466150467150468150469150470150471150472150473150474150475150476150477150478150479150480150481150482150483150484150485150486150487150488150489150490150491150492150493150494150495150496150497150498150499150500150501150502150503150504150505150506150507150508150509150510150511150512150513150514150515150516150517150518150519150520150521150522150523150524150525150526150527150528150529150530150531150532150533150534150535150536150537150538150539150540150541150542150543150544150545150546150547150548150549150550150551150552150553150554150555150556150557150558150559150560150561150562150563150564150565150566150567150568150569150570150571150572150573150574150575150576150577150578150579150580150581150582150583150584150585150586150587150588150589150590150591150592150593150594150595150596150597150598150599150600150601150602150603150604150605150606150607150608150609150610150611150612150613150614150615150616150617150618150619150620150621150622150623150624150625150626150627150628150629150630150631150632150633150634150635150636150637150638150639150640150641150642150643150644150645150646150647150648150649150650150651150652150653150654150655150656150657150658150659150660150661150662150663150664150665150666150667150668150669150670150671150672150673150674150675150676150677150678150679150680150681150682150683150684150685150686150687150688150689150690150691150692150693150694150695150696150697150698150699150700150701150702150703150704150705150706150707150708150709150710150711150712150713150714150715150716150717150718150719150720150721150722150723150724150725150726150727150728150729150730150731150732150733150734150735150736150737150738150739150740150741150742150743150744150745150746150747150748150749150750150751150752150753150754150755150756150757150758150759150760150761150762150763150764150765150766150767150768150769150770150771150772150773150774150775150776150777150778150779150780150781150782150783150784150785150786150787150788150789150790150791150792150793150794150795150796150797150798150799150800150801150802150803150804150805150806150807150808150809150810150811150812150813150814150815150816150817150818150819150820150821150822150823150824150825150826150827150828150829150830150831150832150833150834150835150836150837150838150839150840150841150842150843150844150845150846150847150848150849150850150851150852150853150854150855150856150857150858150859150860150861150862150863150864150865150866150867150868150869150870150871150872150873150874150875150876150877150878150879150880150881150882150883150884150885150886150887150888150889150890150891150892150893150894150895150896150897150898150899150900150901150902150903150904150905150906150907150908150909150910150911150912150913150914150915150916150917150918150919150920150921150922150923150924150925150926150927150928150929150930150931150932150933150934150935150936150937150938150939150940150941150942150943150944150945150946150947150948150949150950150951150952150953150954150955150956150957150958150959150960150961150962150963150964150965150966150967150968150969150970150971150972150973150974150975150976150977150978150979150980150981150982150983150984150985150986150987150988150989150990150991150992150993150994150995150996150997150998150999151000151001151002151003151004151005151006151007151008151009151010151011151012151013151014151015151016151017151018151019151020151021151022151023151024151025151026151027151028151029151030151031151032151033151034151035151036151037151038151039151040151041151042151043151044151045151046151047151048151049151050151051151052151053151054151055151056151057151058151059151060151061151062151063151064151065151066151067151068151069151070151071151072151073151074151075151076151077151078151079151080151081151082151083151084151085151086151087151088151089151090151091151092151093151094151095151096151097151098151099151100151101151102151103151104151105151106151107151108151109151110151111151112151113151114151115151116151117151118151119151120151121151122151123151124151125151126151127151128151129151130151131151132151133151134151135151136151137151138151139151140151141151142151143151144151145151146151147151148151149151150151151151152151153151154151155151156151157151158151159151160151161151162151163151164151165151166151167151168151169151170151171151172151173151174151175151176151177151178151179151180151181151182151183151184151185151186151187151188151189151190151191151192151193151194151195151196151197151198151199151200151201151202151203151204151205151206151207151208151209151210151211151212151213151214151215151216151217151218151219151220151221151222151223151224151225151226151227151228151229151230151231151232151233151234151235151236151237151238151239151240151241151242151243151244151245151246151247151248151249151250151251151252151253151254151255151256151257151258151259151260151261151262151263151264151265151266151267151268151269151270151271151272151273151274151275151276151277151278151279151280151281151282151283151284151285151286151287151288151289151290151291151292151293151294151295151296151297151298151299151300151301151302151303151304151305151306151307151308151309151310151311151312151313151314151315151316151317151318151319151320151321151322151323151324151325151326151327151328151329151330151331151332151333151334151335151336151337151338151339151340151341151342151343151344151345151346151347151348151349151350151351151352151353151354151355151356151357151358151359151360151361151362151363151364151365151366151367151368151369151370151371151372151373151374151375151376151377151378151379151380151381151382151383151384151385151386151387151388151389151390151391151392151393151394151395151396151397151398151399151400151401151402151403151404151405151406151407151408151409151410151411151412151413151414151415151416151417151418151419151420151421151422151423151424151425151426151427151428151429151430151431151432151433151434151435151436151437151438151439151440151441151442151443151444151445151446151447151448151449151450151451151452151453151454151455151456151457151458151459151460151461151462151463151464151465151466151467151468151469151470151471151472151473151474151475151476151477151478151479151480151481151482151483151484151485151486151487151488151489151490151491151492151493151494151495151496151497151498151499151500151501151502151503151504151505151506151507151508151509151510151511151512151513151514151515151516151517151518151519151520151521151522151523151524151525151526151527151528151529151530151531151532151533151534151535151536151537151538151539151540151541151542151543151544151545151546151547151548151549151550151551151552151553151554151555151556151557151558151559151560151561151562151563151564151565151566151567151568151569151570151571151572151573151574151575151576151577151578151579151580151581151582151583151584151585151586151587151588151589151590151591151592151593151594151595151596151597151598151599151600151601151602151603151604151605151606151607151608151609151610151611151612151613151614151615151616151617151618151619151620151621151622151623151624151625151626151627151628151629151630151631151632151633151634151635151636151637151638151639151640151641151642151643151644151645151646151647151648151649151650151651151652151653151654151655151656151657151658151659151660151661151662151663151664151665151666151667151668151669151670151671151672151673151674151675151676151677151678151679151680151681151682151683151684151685151686151687151688151689151690151691151692151693151694151695151696151697151698151699151700151701151702151703151704151705151706151707151708151709151710151711151712151713151714151715151716151717151718151719151720151721151722151723151724151725151726151727151728151729151730151731151732151733151734151735151736151737151738151739151740151741151742151743151744151745151746151747151748151749151750151751151752151753151754151755151756151757151758151759151760151761151762151763151764151765151766151767151768151769151770151771151772151773151774151775151776151777151778151779151780151781151782151783151784151785151786151787151788151789151790151791151792151793151794151795151796151797151798151799151800151801151802151803151804151805151806151807151808151809151810151811151812151813151814151815151816151817151818151819151820151821151822151823151824151825151826151827151828151829151830151831151832151833151834151835151836151837151838151839151840151841151842151843151844151845151846151847151848151849151850151851151852151853151854151855151856151857151858151859151860151861151862151863151864151865151866151867151868151869151870151871151872151873151874151875151876151877151878151879151880151881151882151883151884151885151886151887151888151889151890151891151892151893151894151895151896151897151898151899151900151901151902151903151904151905151906151907151908151909151910151911151912151913151914151915151916151917151918151919151920151921151922151923151924151925151926151927151928151929151930151931151932151933151934151935151936151937151938151939151940151941151942151943151944151945151946151947151948151949151950151951151952151953151954151955151956151957151958151959151960151961151962151963151964151965151966151967151968151969151970151971151972151973151974151975151976151977151978151979151980151981151982151983151984151985151986151987151988151989151990151991151992151993151994151995151996151997151998151999152000152001152002152003152004152005152006152007152008152009152010152011152012152013152014152015152016152017152018152019152020152021152022152023152024152025152026152027152028152029152030152031152032152033152034152035152036152037152038152039152040152041152042152043152044152045152046152047152048152049152050152051152052152053152054152055152056152057152058152059152060152061152062152063152064152065152066152067152068152069152070152071152072152073152074152075152076152077152078152079152080152081152082152083152084152085152086152087152088152089152090152091152092152093152094152095152096152097152098152099152100152101152102152103152104152105152106152107152108152109152110152111152112152113152114152115152116152117152118152119152120152121152122152123152124152125152126152127152128152129152130152131152132152133152134152135152136152137152138152139152140152141152142152143152144152145152146152147152148152149152150152151152152152153152154152155152156152157152158152159152160152161152162152163152164152165152166152167152168152169152170152171152172152173152174152175152176152177152178152179152180152181152182152183152184152185152186152187152188152189152190152191152192152193152194152195152196152197152198152199152200152201152202152203152204152205152206152207152208152209152210152211152212152213152214152215152216152217152218152219152220152221152222152223152224152225152226152227152228152229152230152231152232152233152234152235152236152237152238152239152240152241152242152243152244152245152246152247152248152249152250152251152252152253152254152255152256152257152258152259152260152261152262152263152264152265152266152267152268152269152270
  1. /******************************************************************************
  2. ** This file is an amalgamation of many separate C source files from SQLite
  3. ** version 3.8.7. 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"
  221. #define SQLITE_VERSION_NUMBER 3008007
  222. #define SQLITE_SOURCE_ID "2014-10-28 00:56:18 30f86eb3f9ac88f83ed9e23ea6cd1fccf68e0812"
  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 not use more than two scratch buffers per thread and not
  1628. ** more than one scratch buffer per thread when not performing
  1629. ** a [checkpoint] in [WAL mode].
  1630. ** ^SQLite will never request a scratch buffer that is more than 6
  1631. ** times the database page size, except when performing a [checkpoint]
  1632. ** in [WAL mode] when the scratch buffer request size is a small fraction
  1633. ** of the size of the WAL file.
  1634. ** ^If SQLite needs needs additional
  1635. ** scratch memory beyond what is provided by this configuration option, then
  1636. ** [sqlite3_malloc()] will be used to obtain the memory needed.</dd>
  1637. **
  1638. ** [[SQLITE_CONFIG_PAGECACHE]] <dt>SQLITE_CONFIG_PAGECACHE</dt>
  1639. ** <dd> ^This option specifies a static memory buffer that SQLite can use for
  1640. ** the database page cache with the default page cache implementation.
  1641. ** This configuration should not be used if an application-define page
  1642. ** cache implementation is loaded using the SQLITE_CONFIG_PCACHE2 option.
  1643. ** There are three arguments to this option: A pointer to 8-byte aligned
  1644. ** memory, the size of each page buffer (sz), and the number of pages (N).
  1645. ** The sz argument should be the size of the largest database page
  1646. ** (a power of two between 512 and 32768) plus a little extra for each
  1647. ** page header. ^The page header size is 20 to 40 bytes depending on
  1648. ** the host architecture. ^It is harmless, apart from the wasted memory,
  1649. ** to make sz a little too large. The first
  1650. ** argument should point to an allocation of at least sz*N bytes of memory.
  1651. ** ^SQLite will use the memory provided by the first argument to satisfy its
  1652. ** memory needs for the first N pages that it adds to cache. ^If additional
  1653. ** page cache memory is needed beyond what is provided by this option, then
  1654. ** SQLite goes to [sqlite3_malloc()] for the additional storage space.
  1655. ** The pointer in the first argument must
  1656. ** be aligned to an 8-byte boundary or subsequent behavior of SQLite
  1657. ** will be undefined.</dd>
  1658. **
  1659. ** [[SQLITE_CONFIG_HEAP]] <dt>SQLITE_CONFIG_HEAP</dt>
  1660. ** <dd> ^This option specifies a static memory buffer that SQLite will use
  1661. ** for all of its dynamic memory allocation needs beyond those provided
  1662. ** for by [SQLITE_CONFIG_SCRATCH] and [SQLITE_CONFIG_PAGECACHE].
  1663. ** There are three arguments: An 8-byte aligned pointer to the memory,
  1664. ** the number of bytes in the memory buffer, and the minimum allocation size.
  1665. ** ^If the first pointer (the memory pointer) is NULL, then SQLite reverts
  1666. ** to using its default memory allocator (the system malloc() implementation),
  1667. ** undoing any prior invocation of [SQLITE_CONFIG_MALLOC]. ^If the
  1668. ** memory pointer is not NULL and either [SQLITE_ENABLE_MEMSYS3] or
  1669. ** [SQLITE_ENABLE_MEMSYS5] are defined, then the alternative memory
  1670. ** allocator is engaged to handle all of SQLites memory allocation needs.
  1671. ** The first pointer (the memory pointer) must be aligned to an 8-byte
  1672. ** boundary or subsequent behavior of SQLite will be undefined.
  1673. ** The minimum allocation size is capped at 2**12. Reasonable values
  1674. ** for the minimum allocation size are 2**5 through 2**8.</dd>
  1675. **
  1676. ** [[SQLITE_CONFIG_MUTEX]] <dt>SQLITE_CONFIG_MUTEX</dt>
  1677. ** <dd> ^(This option takes a single argument which is a pointer to an
  1678. ** instance of the [sqlite3_mutex_methods] structure. The argument specifies
  1679. ** alternative low-level mutex routines to be used in place
  1680. ** the mutex routines built into SQLite.)^ ^SQLite makes a copy of the
  1681. ** content of the [sqlite3_mutex_methods] structure before the call to
  1682. ** [sqlite3_config()] returns. ^If SQLite is compiled with
  1683. ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
  1684. ** the entire mutexing subsystem is omitted from the build and hence calls to
  1685. ** [sqlite3_config()] with the SQLITE_CONFIG_MUTEX configuration option will
  1686. ** return [SQLITE_ERROR].</dd>
  1687. **
  1688. ** [[SQLITE_CONFIG_GETMUTEX]] <dt>SQLITE_CONFIG_GETMUTEX</dt>
  1689. ** <dd> ^(This option takes a single argument which is a pointer to an
  1690. ** instance of the [sqlite3_mutex_methods] structure. The
  1691. ** [sqlite3_mutex_methods]
  1692. ** structure is filled with the currently defined mutex routines.)^
  1693. ** This option can be used to overload the default mutex allocation
  1694. ** routines with a wrapper used to track mutex usage for performance
  1695. ** profiling or testing, for example. ^If SQLite is compiled with
  1696. ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
  1697. ** the entire mutexing subsystem is omitted from the build and hence calls to
  1698. ** [sqlite3_config()] with the SQLITE_CONFIG_GETMUTEX configuration option will
  1699. ** return [SQLITE_ERROR].</dd>
  1700. **
  1701. ** [[SQLITE_CONFIG_LOOKASIDE]] <dt>SQLITE_CONFIG_LOOKASIDE</dt>
  1702. ** <dd> ^(This option takes two arguments that determine the default
  1703. ** memory allocation for the lookaside memory allocator on each
  1704. ** [database connection]. The first argument is the
  1705. ** size of each lookaside buffer slot and the second is the number of
  1706. ** slots allocated to each database connection.)^ ^(This option sets the
  1707. ** <i>default</i> lookaside size. The [SQLITE_DBCONFIG_LOOKASIDE]
  1708. ** verb to [sqlite3_db_config()] can be used to change the lookaside
  1709. ** configuration on individual connections.)^ </dd>
  1710. **
  1711. ** [[SQLITE_CONFIG_PCACHE2]] <dt>SQLITE_CONFIG_PCACHE2</dt>
  1712. ** <dd> ^(This option takes a single argument which is a pointer to
  1713. ** an [sqlite3_pcache_methods2] object. This object specifies the interface
  1714. ** to a custom page cache implementation.)^ ^SQLite makes a copy of the
  1715. ** object and uses it for page cache memory allocations.</dd>
  1716. **
  1717. ** [[SQLITE_CONFIG_GETPCACHE2]] <dt>SQLITE_CONFIG_GETPCACHE2</dt>
  1718. ** <dd> ^(This option takes a single argument which is a pointer to an
  1719. ** [sqlite3_pcache_methods2] object. SQLite copies of the current
  1720. ** page cache implementation into that object.)^ </dd>
  1721. **
  1722. ** [[SQLITE_CONFIG_LOG]] <dt>SQLITE_CONFIG_LOG</dt>
  1723. ** <dd> The SQLITE_CONFIG_LOG option is used to configure the SQLite
  1724. ** global [error log].
  1725. ** (^The SQLITE_CONFIG_LOG option takes two arguments: a pointer to a
  1726. ** function with a call signature of void(*)(void*,int,const char*),
  1727. ** and a pointer to void. ^If the function pointer is not NULL, it is
  1728. ** invoked by [sqlite3_log()] to process each logging event. ^If the
  1729. ** function pointer is NULL, the [sqlite3_log()] interface becomes a no-op.
  1730. ** ^The void pointer that is the second argument to SQLITE_CONFIG_LOG is
  1731. ** passed through as the first parameter to the application-defined logger
  1732. ** function whenever that function is invoked. ^The second parameter to
  1733. ** the logger function is a copy of the first parameter to the corresponding
  1734. ** [sqlite3_log()] call and is intended to be a [result code] or an
  1735. ** [extended result code]. ^The third parameter passed to the logger is
  1736. ** log message after formatting via [sqlite3_snprintf()].
  1737. ** The SQLite logging interface is not reentrant; the logger function
  1738. ** supplied by the application must not invoke any SQLite interface.
  1739. ** In a multi-threaded application, the application-defined logger
  1740. ** function must be threadsafe. </dd>
  1741. **
  1742. ** [[SQLITE_CONFIG_URI]] <dt>SQLITE_CONFIG_URI
  1743. ** <dd>^(This option takes a single argument of type int. If non-zero, then
  1744. ** URI handling is globally enabled. If the parameter is zero, then URI handling
  1745. ** is globally disabled.)^ ^If URI handling is globally enabled, all filenames
  1746. ** passed to [sqlite3_open()], [sqlite3_open_v2()], [sqlite3_open16()] or
  1747. ** specified as part of [ATTACH] commands are interpreted as URIs, regardless
  1748. ** of whether or not the [SQLITE_OPEN_URI] flag is set when the database
  1749. ** connection is opened. ^If it is globally disabled, filenames are
  1750. ** only interpreted as URIs if the SQLITE_OPEN_URI flag is set when the
  1751. ** database connection is opened. ^(By default, URI handling is globally
  1752. ** disabled. The default value may be changed by compiling with the
  1753. ** [SQLITE_USE_URI] symbol defined.)^
  1754. **
  1755. ** [[SQLITE_CONFIG_COVERING_INDEX_SCAN]] <dt>SQLITE_CONFIG_COVERING_INDEX_SCAN
  1756. ** <dd>^This option takes a single integer argument which is interpreted as
  1757. ** a boolean in order to enable or disable the use of covering indices for
  1758. ** full table scans in the query optimizer. ^The default setting is determined
  1759. ** by the [SQLITE_ALLOW_COVERING_INDEX_SCAN] compile-time option, or is "on"
  1760. ** if that compile-time option is omitted.
  1761. ** The ability to disable the use of covering indices for full table scans
  1762. ** is because some incorrectly coded legacy applications might malfunction
  1763. ** when the optimization is enabled. Providing the ability to
  1764. ** disable the optimization allows the older, buggy application code to work
  1765. ** without change even with newer versions of SQLite.
  1766. **
  1767. ** [[SQLITE_CONFIG_PCACHE]] [[SQLITE_CONFIG_GETPCACHE]]
  1768. ** <dt>SQLITE_CONFIG_PCACHE and SQLITE_CONFIG_GETPCACHE
  1769. ** <dd> These options are obsolete and should not be used by new code.
  1770. ** They are retained for backwards compatibility but are now no-ops.
  1771. ** </dd>
  1772. **
  1773. ** [[SQLITE_CONFIG_SQLLOG]]
  1774. ** <dt>SQLITE_CONFIG_SQLLOG
  1775. ** <dd>This option is only available if sqlite is compiled with the
  1776. ** [SQLITE_ENABLE_SQLLOG] pre-processor macro defined. The first argument should
  1777. ** be a pointer to a function of type void(*)(void*,sqlite3*,const char*, int).
  1778. ** The second should be of type (void*). The callback is invoked by the library
  1779. ** in three separate circumstances, identified by the value passed as the
  1780. ** fourth parameter. If the fourth parameter is 0, then the database connection
  1781. ** passed as the second argument has just been opened. The third argument
  1782. ** points to a buffer containing the name of the main database file. If the
  1783. ** fourth parameter is 1, then the SQL statement that the third parameter
  1784. ** points to has just been executed. Or, if the fourth parameter is 2, then
  1785. ** the connection being passed as the second parameter is being closed. The
  1786. ** third parameter is passed NULL In this case. An example of using this
  1787. ** configuration option can be seen in the "test_sqllog.c" source file in
  1788. ** the canonical SQLite source tree.</dd>
  1789. **
  1790. ** [[SQLITE_CONFIG_MMAP_SIZE]]
  1791. ** <dt>SQLITE_CONFIG_MMAP_SIZE
  1792. ** <dd>^SQLITE_CONFIG_MMAP_SIZE takes two 64-bit integer (sqlite3_int64) values
  1793. ** that are the default mmap size limit (the default setting for
  1794. ** [PRAGMA mmap_size]) and the maximum allowed mmap size limit.
  1795. ** ^The default setting can be overridden by each database connection using
  1796. ** either the [PRAGMA mmap_size] command, or by using the
  1797. ** [SQLITE_FCNTL_MMAP_SIZE] file control. ^(The maximum allowed mmap size
  1798. ** cannot be changed at run-time. Nor may the maximum allowed mmap size
  1799. ** exceed the compile-time maximum mmap size set by the
  1800. ** [SQLITE_MAX_MMAP_SIZE] compile-time option.)^
  1801. ** ^If either argument to this option is negative, then that argument is
  1802. ** changed to its compile-time default.
  1803. **
  1804. ** [[SQLITE_CONFIG_WIN32_HEAPSIZE]]
  1805. ** <dt>SQLITE_CONFIG_WIN32_HEAPSIZE
  1806. ** <dd>^This option is only available if SQLite is compiled for Windows
  1807. ** with the [SQLITE_WIN32_MALLOC] pre-processor macro defined.
  1808. ** SQLITE_CONFIG_WIN32_HEAPSIZE takes a 32-bit unsigned integer value
  1809. ** that specifies the maximum size of the created heap.
  1810. ** </dl>
  1811. */
  1812. #define SQLITE_CONFIG_SINGLETHREAD 1 /* nil */
  1813. #define SQLITE_CONFIG_MULTITHREAD 2 /* nil */
  1814. #define SQLITE_CONFIG_SERIALIZED 3 /* nil */
  1815. #define SQLITE_CONFIG_MALLOC 4 /* sqlite3_mem_methods* */
  1816. #define SQLITE_CONFIG_GETMALLOC 5 /* sqlite3_mem_methods* */
  1817. #define SQLITE_CONFIG_SCRATCH 6 /* void*, int sz, int N */
  1818. #define SQLITE_CONFIG_PAGECACHE 7 /* void*, int sz, int N */
  1819. #define SQLITE_CONFIG_HEAP 8 /* void*, int nByte, int min */
  1820. #define SQLITE_CONFIG_MEMSTATUS 9 /* boolean */
  1821. #define SQLITE_CONFIG_MUTEX 10 /* sqlite3_mutex_methods* */
  1822. #define SQLITE_CONFIG_GETMUTEX 11 /* sqlite3_mutex_methods* */
  1823. /* previously SQLITE_CONFIG_CHUNKALLOC 12 which is now unused. */
  1824. #define SQLITE_CONFIG_LOOKASIDE 13 /* int int */
  1825. #define SQLITE_CONFIG_PCACHE 14 /* no-op */
  1826. #define SQLITE_CONFIG_GETPCACHE 15 /* no-op */
  1827. #define SQLITE_CONFIG_LOG 16 /* xFunc, void* */
  1828. #define SQLITE_CONFIG_URI 17 /* int */
  1829. #define SQLITE_CONFIG_PCACHE2 18 /* sqlite3_pcache_methods2* */
  1830. #define SQLITE_CONFIG_GETPCACHE2 19 /* sqlite3_pcache_methods2* */
  1831. #define SQLITE_CONFIG_COVERING_INDEX_SCAN 20 /* int */
  1832. #define SQLITE_CONFIG_SQLLOG 21 /* xSqllog, void* */
  1833. #define SQLITE_CONFIG_MMAP_SIZE 22 /* sqlite3_int64, sqlite3_int64 */
  1834. #define SQLITE_CONFIG_WIN32_HEAPSIZE 23 /* int nByte */
  1835. /*
  1836. ** CAPI3REF: Database Connection Configuration Options
  1837. **
  1838. ** These constants are the available integer configuration options that
  1839. ** can be passed as the second argument to the [sqlite3_db_config()] interface.
  1840. **
  1841. ** New configuration options may be added in future releases of SQLite.
  1842. ** Existing configuration options might be discontinued. Applications
  1843. ** should check the return code from [sqlite3_db_config()] to make sure that
  1844. ** the call worked. ^The [sqlite3_db_config()] interface will return a
  1845. ** non-zero [error code] if a discontinued or unsupported configuration option
  1846. ** is invoked.
  1847. **
  1848. ** <dl>
  1849. ** <dt>SQLITE_DBCONFIG_LOOKASIDE</dt>
  1850. ** <dd> ^This option takes three additional arguments that determine the
  1851. ** [lookaside memory allocator] configuration for the [database connection].
  1852. ** ^The first argument (the third parameter to [sqlite3_db_config()] is a
  1853. ** pointer to a memory buffer to use for lookaside memory.
  1854. ** ^The first argument after the SQLITE_DBCONFIG_LOOKASIDE verb
  1855. ** may be NULL in which case SQLite will allocate the
  1856. ** lookaside buffer itself using [sqlite3_malloc()]. ^The second argument is the
  1857. ** size of each lookaside buffer slot. ^The third argument is the number of
  1858. ** slots. The size of the buffer in the first argument must be greater than
  1859. ** or equal to the product of the second and third arguments. The buffer
  1860. ** must be aligned to an 8-byte boundary. ^If the second argument to
  1861. ** SQLITE_DBCONFIG_LOOKASIDE is not a multiple of 8, it is internally
  1862. ** rounded down to the next smaller multiple of 8. ^(The lookaside memory
  1863. ** configuration for a database connection can only be changed when that
  1864. ** connection is not currently using lookaside memory, or in other words
  1865. ** when the "current value" returned by
  1866. ** [sqlite3_db_status](D,[SQLITE_CONFIG_LOOKASIDE],...) is zero.
  1867. ** Any attempt to change the lookaside memory configuration when lookaside
  1868. ** memory is in use leaves the configuration unchanged and returns
  1869. ** [SQLITE_BUSY].)^</dd>
  1870. **
  1871. ** <dt>SQLITE_DBCONFIG_ENABLE_FKEY</dt>
  1872. ** <dd> ^This option is used to enable or disable the enforcement of
  1873. ** [foreign key constraints]. There should be two additional arguments.
  1874. ** The first argument is an integer which is 0 to disable FK enforcement,
  1875. ** positive to enable FK enforcement or negative to leave FK enforcement
  1876. ** unchanged. The second parameter is a pointer to an integer into which
  1877. ** is written 0 or 1 to indicate whether FK enforcement is off or on
  1878. ** following this call. The second parameter may be a NULL pointer, in
  1879. ** which case the FK enforcement setting is not reported back. </dd>
  1880. **
  1881. ** <dt>SQLITE_DBCONFIG_ENABLE_TRIGGER</dt>
  1882. ** <dd> ^This option is used to enable or disable [CREATE TRIGGER | triggers].
  1883. ** There should be two additional arguments.
  1884. ** The first argument is an integer which is 0 to disable triggers,
  1885. ** positive to enable triggers or negative to leave the setting unchanged.
  1886. ** The second parameter is a pointer to an integer into which
  1887. ** is written 0 or 1 to indicate whether triggers are disabled or enabled
  1888. ** following this call. The second parameter may be a NULL pointer, in
  1889. ** which case the trigger setting is not reported back. </dd>
  1890. **
  1891. ** </dl>
  1892. */
  1893. #define SQLITE_DBCONFIG_LOOKASIDE 1001 /* void* int int */
  1894. #define SQLITE_DBCONFIG_ENABLE_FKEY 1002 /* int int* */
  1895. #define SQLITE_DBCONFIG_ENABLE_TRIGGER 1003 /* int int* */
  1896. /*
  1897. ** CAPI3REF: Enable Or Disable Extended Result Codes
  1898. **
  1899. ** ^The sqlite3_extended_result_codes() routine enables or disables the
  1900. ** [extended result codes] feature of SQLite. ^The extended result
  1901. ** codes are disabled by default for historical compatibility.
  1902. */
  1903. SQLITE_API int sqlite3_extended_result_codes(sqlite3*, int onoff);
  1904. /*
  1905. ** CAPI3REF: Last Insert Rowid
  1906. **
  1907. ** ^Each entry in most SQLite tables (except for [WITHOUT ROWID] tables)
  1908. ** has a unique 64-bit signed
  1909. ** integer key called the [ROWID | "rowid"]. ^The rowid is always available
  1910. ** as an undeclared column named ROWID, OID, or _ROWID_ as long as those
  1911. ** names are not also used by explicitly declared columns. ^If
  1912. ** the table has a column of type [INTEGER PRIMARY KEY] then that column
  1913. ** is another alias for the rowid.
  1914. **
  1915. ** ^The sqlite3_last_insert_rowid(D) interface returns the [rowid] of the
  1916. ** most recent successful [INSERT] into a rowid table or [virtual table]
  1917. ** on database connection D.
  1918. ** ^Inserts into [WITHOUT ROWID] tables are not recorded.
  1919. ** ^If no successful [INSERT]s into rowid tables
  1920. ** have ever occurred on the database connection D,
  1921. ** then sqlite3_last_insert_rowid(D) returns zero.
  1922. **
  1923. ** ^(If an [INSERT] occurs within a trigger or within a [virtual table]
  1924. ** method, then this routine will return the [rowid] of the inserted
  1925. ** row as long as the trigger or virtual table method is running.
  1926. ** But once the trigger or virtual table method ends, the value returned
  1927. ** by this routine reverts to what it was before the trigger or virtual
  1928. ** table method began.)^
  1929. **
  1930. ** ^An [INSERT] that fails due to a constraint violation is not a
  1931. ** successful [INSERT] and does not change the value returned by this
  1932. ** routine. ^Thus INSERT OR FAIL, INSERT OR IGNORE, INSERT OR ROLLBACK,
  1933. ** and INSERT OR ABORT make no changes to the return value of this
  1934. ** routine when their insertion fails. ^(When INSERT OR REPLACE
  1935. ** encounters a constraint violation, it does not fail. The
  1936. ** INSERT continues to completion after deleting rows that caused
  1937. ** the constraint problem so INSERT OR REPLACE will always change
  1938. ** the return value of this interface.)^
  1939. **
  1940. ** ^For the purposes of this routine, an [INSERT] is considered to
  1941. ** be successful even if it is subsequently rolled back.
  1942. **
  1943. ** This function is accessible to SQL statements via the
  1944. ** [last_insert_rowid() SQL function].
  1945. **
  1946. ** If a separate thread performs a new [INSERT] on the same
  1947. ** database connection while the [sqlite3_last_insert_rowid()]
  1948. ** function is running and thus changes the last insert [rowid],
  1949. ** then the value returned by [sqlite3_last_insert_rowid()] is
  1950. ** unpredictable and might not equal either the old or the new
  1951. ** last insert [rowid].
  1952. */
  1953. SQLITE_API sqlite3_int64 sqlite3_last_insert_rowid(sqlite3*);
  1954. /*
  1955. ** CAPI3REF: Count The Number Of Rows Modified
  1956. **
  1957. ** ^This function returns the number of database rows that were changed
  1958. ** or inserted or deleted by the most recently completed SQL statement
  1959. ** on the [database connection] specified by the first parameter.
  1960. ** ^(Only changes that are directly specified by the [INSERT], [UPDATE],
  1961. ** or [DELETE] statement are counted. Auxiliary changes caused by
  1962. ** triggers or [foreign key actions] are not counted.)^ Use the
  1963. ** [sqlite3_total_changes()] function to find the total number of changes
  1964. ** including changes caused by triggers and foreign key actions.
  1965. **
  1966. ** ^Changes to a view that are simulated by an [INSTEAD OF trigger]
  1967. ** are not counted. Only real table changes are counted.
  1968. **
  1969. ** ^(A "row change" is a change to a single row of a single table
  1970. ** caused by an INSERT, DELETE, or UPDATE statement. Rows that
  1971. ** are changed as side effects of [REPLACE] constraint resolution,
  1972. ** rollback, ABORT processing, [DROP TABLE], or by any other
  1973. ** mechanisms do not count as direct row changes.)^
  1974. **
  1975. ** A "trigger context" is a scope of execution that begins and
  1976. ** ends with the script of a [CREATE TRIGGER | trigger].
  1977. ** Most SQL statements are
  1978. ** evaluated outside of any trigger. This is the "top level"
  1979. ** trigger context. If a trigger fires from the top level, a
  1980. ** new trigger context is entered for the duration of that one
  1981. ** trigger. Subtriggers create subcontexts for their duration.
  1982. **
  1983. ** ^Calling [sqlite3_exec()] or [sqlite3_step()] recursively does
  1984. ** not create a new trigger context.
  1985. **
  1986. ** ^This function returns the number of direct row changes in the
  1987. ** most recent INSERT, UPDATE, or DELETE statement within the same
  1988. ** trigger context.
  1989. **
  1990. ** ^Thus, when called from the top level, this function returns the
  1991. ** number of changes in the most recent INSERT, UPDATE, or DELETE
  1992. ** that also occurred at the top level. ^(Within the body of a trigger,
  1993. ** the sqlite3_changes() interface can be called to find the number of
  1994. ** changes in the most recently completed INSERT, UPDATE, or DELETE
  1995. ** statement within the body of the same trigger.
  1996. ** However, the number returned does not include changes
  1997. ** caused by subtriggers since those have their own context.)^
  1998. **
  1999. ** See also the [sqlite3_total_changes()] interface, the
  2000. ** [count_changes pragma], and the [changes() SQL function].
  2001. **
  2002. ** If a separate thread makes changes on the same database connection
  2003. ** while [sqlite3_changes()] is running then the value returned
  2004. ** is unpredictable and not meaningful.
  2005. */
  2006. SQLITE_API int sqlite3_changes(sqlite3*);
  2007. /*
  2008. ** CAPI3REF: Total Number Of Rows Modified
  2009. **
  2010. ** ^This function returns the number of row changes caused by [INSERT],
  2011. ** [UPDATE] or [DELETE] statements since the [database connection] was opened.
  2012. ** ^(The count returned by sqlite3_total_changes() includes all changes
  2013. ** from all [CREATE TRIGGER | trigger] contexts and changes made by
  2014. ** [foreign key actions]. However,
  2015. ** the count does not include changes used to implement [REPLACE] constraints,
  2016. ** do rollbacks or ABORT processing, or [DROP TABLE] processing. The
  2017. ** count does not include rows of views that fire an [INSTEAD OF trigger],
  2018. ** though if the INSTEAD OF trigger makes changes of its own, those changes
  2019. ** are counted.)^
  2020. ** ^The sqlite3_total_changes() function counts the changes as soon as
  2021. ** the statement that makes them is completed (when the statement handle
  2022. ** is passed to [sqlite3_reset()] or [sqlite3_finalize()]).
  2023. **
  2024. ** See also the [sqlite3_changes()] interface, the
  2025. ** [count_changes pragma], and the [total_changes() SQL function].
  2026. **
  2027. ** If a separate thread makes changes on the same database connection
  2028. ** while [sqlite3_total_changes()] is running then the value
  2029. ** returned is unpredictable and not meaningful.
  2030. */
  2031. SQLITE_API int sqlite3_total_changes(sqlite3*);
  2032. /*
  2033. ** CAPI3REF: Interrupt A Long-Running Query
  2034. **
  2035. ** ^This function causes any pending database operation to abort and
  2036. ** return at its earliest opportunity. This routine is typically
  2037. ** called in response to a user action such as pressing "Cancel"
  2038. ** or Ctrl-C where the user wants a long query operation to halt
  2039. ** immediately.
  2040. **
  2041. ** ^It is safe to call this routine from a thread different from the
  2042. ** thread that is currently running the database operation. But it
  2043. ** is not safe to call this routine with a [database connection] that
  2044. ** is closed or might close before sqlite3_interrupt() returns.
  2045. **
  2046. ** ^If an SQL operation is very nearly finished at the time when
  2047. ** sqlite3_interrupt() is called, then it might not have an opportunity
  2048. ** to be interrupted and might continue to completion.
  2049. **
  2050. ** ^An SQL operation that is interrupted will return [SQLITE_INTERRUPT].
  2051. ** ^If the interrupted SQL operation is an INSERT, UPDATE, or DELETE
  2052. ** that is inside an explicit transaction, then the entire transaction
  2053. ** will be rolled back automatically.
  2054. **
  2055. ** ^The sqlite3_interrupt(D) call is in effect until all currently running
  2056. ** SQL statements on [database connection] D complete. ^Any new SQL statements
  2057. ** that are started after the sqlite3_interrupt() call and before the
  2058. ** running statements reaches zero are interrupted as if they had been
  2059. ** running prior to the sqlite3_interrupt() call. ^New SQL statements
  2060. ** that are started after the running statement count reaches zero are
  2061. ** not effected by the sqlite3_interrupt().
  2062. ** ^A call to sqlite3_interrupt(D) that occurs when there are no running
  2063. ** SQL statements is a no-op and has no effect on SQL statements
  2064. ** that are started after the sqlite3_interrupt() call returns.
  2065. **
  2066. ** If the database connection closes while [sqlite3_interrupt()]
  2067. ** is running then bad things will likely happen.
  2068. */
  2069. SQLITE_API void sqlite3_interrupt(sqlite3*);
  2070. /*
  2071. ** CAPI3REF: Determine If An SQL Statement Is Complete
  2072. **
  2073. ** These routines are useful during command-line input to determine if the
  2074. ** currently entered text seems to form a complete SQL statement or
  2075. ** if additional input is needed before sending the text into
  2076. ** SQLite for parsing. ^These routines return 1 if the input string
  2077. ** appears to be a complete SQL statement. ^A statement is judged to be
  2078. ** complete if it ends with a semicolon token and is not a prefix of a
  2079. ** well-formed CREATE TRIGGER statement. ^Semicolons that are embedded within
  2080. ** string literals or quoted identifier names or comments are not
  2081. ** independent tokens (they are part of the token in which they are
  2082. ** embedded) and thus do not count as a statement terminator. ^Whitespace
  2083. ** and comments that follow the final semicolon are ignored.
  2084. **
  2085. ** ^These routines return 0 if the statement is incomplete. ^If a
  2086. ** memory allocation fails, then SQLITE_NOMEM is returned.
  2087. **
  2088. ** ^These routines do not parse the SQL statements thus
  2089. ** will not detect syntactically incorrect SQL.
  2090. **
  2091. ** ^(If SQLite has not been initialized using [sqlite3_initialize()] prior
  2092. ** to invoking sqlite3_complete16() then sqlite3_initialize() is invoked
  2093. ** automatically by sqlite3_complete16(). If that initialization fails,
  2094. ** then the return value from sqlite3_complete16() will be non-zero
  2095. ** regardless of whether or not the input SQL is complete.)^
  2096. **
  2097. ** The input to [sqlite3_complete()] must be a zero-terminated
  2098. ** UTF-8 string.
  2099. **
  2100. ** The input to [sqlite3_complete16()] must be a zero-terminated
  2101. ** UTF-16 string in native byte order.
  2102. */
  2103. SQLITE_API int sqlite3_complete(const char *sql);
  2104. SQLITE_API int sqlite3_complete16(const void *sql);
  2105. /*
  2106. ** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors
  2107. **
  2108. ** ^The sqlite3_busy_handler(D,X,P) routine sets a callback function X
  2109. ** that might be invoked with argument P whenever
  2110. ** an attempt is made to access a database table associated with
  2111. ** [database connection] D when another thread
  2112. ** or process has the table locked.
  2113. ** The sqlite3_busy_handler() interface is used to implement
  2114. ** [sqlite3_busy_timeout()] and [PRAGMA busy_timeout].
  2115. **
  2116. ** ^If the busy callback is NULL, then [SQLITE_BUSY]
  2117. ** is returned immediately upon encountering the lock. ^If the busy callback
  2118. ** is not NULL, then the callback might be invoked with two arguments.
  2119. **
  2120. ** ^The first argument to the busy handler is a copy of the void* pointer which
  2121. ** is the third argument to sqlite3_busy_handler(). ^The second argument to
  2122. ** the busy handler callback is the number of times that the busy handler has
  2123. ** been invoked for the same locking event. ^If the
  2124. ** busy callback returns 0, then no additional attempts are made to
  2125. ** access the database and [SQLITE_BUSY] is returned
  2126. ** to the application.
  2127. ** ^If the callback returns non-zero, then another attempt
  2128. ** is made to access the database and the cycle repeats.
  2129. **
  2130. ** The presence of a busy handler does not guarantee that it will be invoked
  2131. ** when there is lock contention. ^If SQLite determines that invoking the busy
  2132. ** handler could result in a deadlock, it will go ahead and return [SQLITE_BUSY]
  2133. ** to the application instead of invoking the
  2134. ** busy handler.
  2135. ** Consider a scenario where one process is holding a read lock that
  2136. ** it is trying to promote to a reserved lock and
  2137. ** a second process is holding a reserved lock that it is trying
  2138. ** to promote to an exclusive lock. The first process cannot proceed
  2139. ** because it is blocked by the second and the second process cannot
  2140. ** proceed because it is blocked by the first. If both processes
  2141. ** invoke the busy handlers, neither will make any progress. Therefore,
  2142. ** SQLite returns [SQLITE_BUSY] for the first process, hoping that this
  2143. ** will induce the first process to release its read lock and allow
  2144. ** the second process to proceed.
  2145. **
  2146. ** ^The default busy callback is NULL.
  2147. **
  2148. ** ^(There can only be a single busy handler defined for each
  2149. ** [database connection]. Setting a new busy handler clears any
  2150. ** previously set handler.)^ ^Note that calling [sqlite3_busy_timeout()]
  2151. ** or evaluating [PRAGMA busy_timeout=N] will change the
  2152. ** busy handler and thus clear any previously set busy handler.
  2153. **
  2154. ** The busy callback should not take any actions which modify the
  2155. ** database connection that invoked the busy handler. In other words,
  2156. ** the busy handler is not reentrant. Any such actions
  2157. ** result in undefined behavior.
  2158. **
  2159. ** A busy handler must not close the database connection
  2160. ** or [prepared statement] that invoked the busy handler.
  2161. */
  2162. SQLITE_API int sqlite3_busy_handler(sqlite3*, int(*)(void*,int), void*);
  2163. /*
  2164. ** CAPI3REF: Set A Busy Timeout
  2165. **
  2166. ** ^This routine sets a [sqlite3_busy_handler | busy handler] that sleeps
  2167. ** for a specified amount of time when a table is locked. ^The handler
  2168. ** will sleep multiple times until at least "ms" milliseconds of sleeping
  2169. ** have accumulated. ^After at least "ms" milliseconds of sleeping,
  2170. ** the handler returns 0 which causes [sqlite3_step()] to return
  2171. ** [SQLITE_BUSY].
  2172. **
  2173. ** ^Calling this routine with an argument less than or equal to zero
  2174. ** turns off all busy handlers.
  2175. **
  2176. ** ^(There can only be a single busy handler for a particular
  2177. ** [database connection] at any given moment. If another busy handler
  2178. ** was defined (using [sqlite3_busy_handler()]) prior to calling
  2179. ** this routine, that other busy handler is cleared.)^
  2180. **
  2181. ** See also: [PRAGMA busy_timeout]
  2182. */
  2183. SQLITE_API int sqlite3_busy_timeout(sqlite3*, int ms);
  2184. /*
  2185. ** CAPI3REF: Convenience Routines For Running Queries
  2186. **
  2187. ** This is a legacy interface that is preserved for backwards compatibility.
  2188. ** Use of this interface is not recommended.
  2189. **
  2190. ** Definition: A <b>result table</b> is memory data structure created by the
  2191. ** [sqlite3_get_table()] interface. A result table records the
  2192. ** complete query results from one or more queries.
  2193. **
  2194. ** The table conceptually has a number of rows and columns. But
  2195. ** these numbers are not part of the result table itself. These
  2196. ** numbers are obtained separately. Let N be the number of rows
  2197. ** and M be the number of columns.
  2198. **
  2199. ** A result table is an array of pointers to zero-terminated UTF-8 strings.
  2200. ** There are (N+1)*M elements in the array. The first M pointers point
  2201. ** to zero-terminated strings that contain the names of the columns.
  2202. ** The remaining entries all point to query results. NULL values result
  2203. ** in NULL pointers. All other values are in their UTF-8 zero-terminated
  2204. ** string representation as returned by [sqlite3_column_text()].
  2205. **
  2206. ** A result table might consist of one or more memory allocations.
  2207. ** It is not safe to pass a result table directly to [sqlite3_free()].
  2208. ** A result table should be deallocated using [sqlite3_free_table()].
  2209. **
  2210. ** ^(As an example of the result table format, suppose a query result
  2211. ** is as follows:
  2212. **
  2213. ** <blockquote><pre>
  2214. ** Name | Age
  2215. ** -----------------------
  2216. ** Alice | 43
  2217. ** Bob | 28
  2218. ** Cindy | 21
  2219. ** </pre></blockquote>
  2220. **
  2221. ** There are two column (M==2) and three rows (N==3). Thus the
  2222. ** result table has 8 entries. Suppose the result table is stored
  2223. ** in an array names azResult. Then azResult holds this content:
  2224. **
  2225. ** <blockquote><pre>
  2226. ** azResult&#91;0] = "Name";
  2227. ** azResult&#91;1] = "Age";
  2228. ** azResult&#91;2] = "Alice";
  2229. ** azResult&#91;3] = "43";
  2230. ** azResult&#91;4] = "Bob";
  2231. ** azResult&#91;5] = "28";
  2232. ** azResult&#91;6] = "Cindy";
  2233. ** azResult&#91;7] = "21";
  2234. ** </pre></blockquote>)^
  2235. **
  2236. ** ^The sqlite3_get_table() function evaluates one or more
  2237. ** semicolon-separated SQL statements in the zero-terminated UTF-8
  2238. ** string of its 2nd parameter and returns a result table to the
  2239. ** pointer given in its 3rd parameter.
  2240. **
  2241. ** After the application has finished with the result from sqlite3_get_table(),
  2242. ** it must pass the result table pointer to sqlite3_free_table() in order to
  2243. ** release the memory that was malloced. Because of the way the
  2244. ** [sqlite3_malloc()] happens within sqlite3_get_table(), the calling
  2245. ** function must not try to call [sqlite3_free()] directly. Only
  2246. ** [sqlite3_free_table()] is able to release the memory properly and safely.
  2247. **
  2248. ** The sqlite3_get_table() interface is implemented as a wrapper around
  2249. ** [sqlite3_exec()]. The sqlite3_get_table() routine does not have access
  2250. ** to any internal data structures of SQLite. It uses only the public
  2251. ** interface defined here. As a consequence, errors that occur in the
  2252. ** wrapper layer outside of the internal [sqlite3_exec()] call are not
  2253. ** reflected in subsequent calls to [sqlite3_errcode()] or
  2254. ** [sqlite3_errmsg()].
  2255. */
  2256. SQLITE_API int sqlite3_get_table(
  2257. sqlite3 *db, /* An open database */
  2258. const char *zSql, /* SQL to be evaluated */
  2259. char ***pazResult, /* Results of the query */
  2260. int *pnRow, /* Number of result rows written here */
  2261. int *pnColumn, /* Number of result columns written here */
  2262. char **pzErrmsg /* Error msg written here */
  2263. );
  2264. SQLITE_API void sqlite3_free_table(char **result);
  2265. /*
  2266. ** CAPI3REF: Formatted String Printing Functions
  2267. **
  2268. ** These routines are work-alikes of the "printf()" family of functions
  2269. ** from the standard C library.
  2270. **
  2271. ** ^The sqlite3_mprintf() and sqlite3_vmprintf() routines write their
  2272. ** results into memory obtained from [sqlite3_malloc()].
  2273. ** The strings returned by these two routines should be
  2274. ** released by [sqlite3_free()]. ^Both routines return a
  2275. ** NULL pointer if [sqlite3_malloc()] is unable to allocate enough
  2276. ** memory to hold the resulting string.
  2277. **
  2278. ** ^(The sqlite3_snprintf() routine is similar to "snprintf()" from
  2279. ** the standard C library. The result is written into the
  2280. ** buffer supplied as the second parameter whose size is given by
  2281. ** the first parameter. Note that the order of the
  2282. ** first two parameters is reversed from snprintf().)^ This is an
  2283. ** historical accident that cannot be fixed without breaking
  2284. ** backwards compatibility. ^(Note also that sqlite3_snprintf()
  2285. ** returns a pointer to its buffer instead of the number of
  2286. ** characters actually written into the buffer.)^ We admit that
  2287. ** the number of characters written would be a more useful return
  2288. ** value but we cannot change the implementation of sqlite3_snprintf()
  2289. ** now without breaking compatibility.
  2290. **
  2291. ** ^As long as the buffer size is greater than zero, sqlite3_snprintf()
  2292. ** guarantees that the buffer is always zero-terminated. ^The first
  2293. ** parameter "n" is the total size of the buffer, including space for
  2294. ** the zero terminator. So the longest string that can be completely
  2295. ** written will be n-1 characters.
  2296. **
  2297. ** ^The sqlite3_vsnprintf() routine is a varargs version of sqlite3_snprintf().
  2298. **
  2299. ** These routines all implement some additional formatting
  2300. ** options that are useful for constructing SQL statements.
  2301. ** All of the usual printf() formatting options apply. In addition, there
  2302. ** is are "%q", "%Q", and "%z" options.
  2303. **
  2304. ** ^(The %q option works like %s in that it substitutes a nul-terminated
  2305. ** string from the argument list. But %q also doubles every '\'' character.
  2306. ** %q is designed for use inside a string literal.)^ By doubling each '\''
  2307. ** character it escapes that character and allows it to be inserted into
  2308. ** the string.
  2309. **
  2310. ** For example, assume the string variable zText contains text as follows:
  2311. **
  2312. ** <blockquote><pre>
  2313. ** char *zText = "It's a happy day!";
  2314. ** </pre></blockquote>
  2315. **
  2316. ** One can use this text in an SQL statement as follows:
  2317. **
  2318. ** <blockquote><pre>
  2319. ** char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES('%q')", zText);
  2320. ** sqlite3_exec(db, zSQL, 0, 0, 0);
  2321. ** sqlite3_free(zSQL);
  2322. ** </pre></blockquote>
  2323. **
  2324. ** Because the %q format string is used, the '\'' character in zText
  2325. ** is escaped and the SQL generated is as follows:
  2326. **
  2327. ** <blockquote><pre>
  2328. ** INSERT INTO table1 VALUES('It''s a happy day!')
  2329. ** </pre></blockquote>
  2330. **
  2331. ** This is correct. Had we used %s instead of %q, the generated SQL
  2332. ** would have looked like this:
  2333. **
  2334. ** <blockquote><pre>
  2335. ** INSERT INTO table1 VALUES('It's a happy day!');
  2336. ** </pre></blockquote>
  2337. **
  2338. ** This second example is an SQL syntax error. As a general rule you should
  2339. ** always use %q instead of %s when inserting text into a string literal.
  2340. **
  2341. ** ^(The %Q option works like %q except it also adds single quotes around
  2342. ** the outside of the total string. Additionally, if the parameter in the
  2343. ** argument list is a NULL pointer, %Q substitutes the text "NULL" (without
  2344. ** single quotes).)^ So, for example, one could say:
  2345. **
  2346. ** <blockquote><pre>
  2347. ** char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES(%Q)", zText);
  2348. ** sqlite3_exec(db, zSQL, 0, 0, 0);
  2349. ** sqlite3_free(zSQL);
  2350. ** </pre></blockquote>
  2351. **
  2352. ** The code above will render a correct SQL statement in the zSQL
  2353. ** variable even if the zText variable is a NULL pointer.
  2354. **
  2355. ** ^(The "%z" formatting option works like "%s" but with the
  2356. ** addition that after the string has been read and copied into
  2357. ** the result, [sqlite3_free()] is called on the input string.)^
  2358. */
  2359. SQLITE_API char *sqlite3_mprintf(const char*,...);
  2360. SQLITE_API char *sqlite3_vmprintf(const char*, va_list);
  2361. SQLITE_API char *sqlite3_snprintf(int,char*,const char*, ...);
  2362. SQLITE_API char *sqlite3_vsnprintf(int,char*,const char*, va_list);
  2363. /*
  2364. ** CAPI3REF: Memory Allocation Subsystem
  2365. **
  2366. ** The SQLite core uses these three routines for all of its own
  2367. ** internal memory allocation needs. "Core" in the previous sentence
  2368. ** does not include operating-system specific VFS implementation. The
  2369. ** Windows VFS uses native malloc() and free() for some operations.
  2370. **
  2371. ** ^The sqlite3_malloc() routine returns a pointer to a block
  2372. ** of memory at least N bytes in length, where N is the parameter.
  2373. ** ^If sqlite3_malloc() is unable to obtain sufficient free
  2374. ** memory, it returns a NULL pointer. ^If the parameter N to
  2375. ** sqlite3_malloc() is zero or negative then sqlite3_malloc() returns
  2376. ** a NULL pointer.
  2377. **
  2378. ** ^The sqlite3_malloc64(N) routine works just like
  2379. ** sqlite3_malloc(N) except that N is an unsigned 64-bit integer instead
  2380. ** of a signed 32-bit integer.
  2381. **
  2382. ** ^Calling sqlite3_free() with a pointer previously returned
  2383. ** by sqlite3_malloc() or sqlite3_realloc() releases that memory so
  2384. ** that it might be reused. ^The sqlite3_free() routine is
  2385. ** a no-op if is called with a NULL pointer. Passing a NULL pointer
  2386. ** to sqlite3_free() is harmless. After being freed, memory
  2387. ** should neither be read nor written. Even reading previously freed
  2388. ** memory might result in a segmentation fault or other severe error.
  2389. ** Memory corruption, a segmentation fault, or other severe error
  2390. ** might result if sqlite3_free() is called with a non-NULL pointer that
  2391. ** was not obtained from sqlite3_malloc() or sqlite3_realloc().
  2392. **
  2393. ** ^The sqlite3_realloc(X,N) interface attempts to resize a
  2394. ** prior memory allocation X to be at least N bytes.
  2395. ** ^If the X parameter to sqlite3_realloc(X,N)
  2396. ** is a NULL pointer then its behavior is identical to calling
  2397. ** sqlite3_malloc(N).
  2398. ** ^If the N parameter to sqlite3_realloc(X,N) is zero or
  2399. ** negative then the behavior is exactly the same as calling
  2400. ** sqlite3_free(X).
  2401. ** ^sqlite3_realloc(X,N) returns a pointer to a memory allocation
  2402. ** of at least N bytes in size or NULL if insufficient memory is available.
  2403. ** ^If M is the size of the prior allocation, then min(N,M) bytes
  2404. ** of the prior allocation are copied into the beginning of buffer returned
  2405. ** by sqlite3_realloc(X,N) and the prior allocation is freed.
  2406. ** ^If sqlite3_realloc(X,N) returns NULL and N is positive, then the
  2407. ** prior allocation is not freed.
  2408. **
  2409. ** ^The sqlite3_realloc64(X,N) interfaces works the same as
  2410. ** sqlite3_realloc(X,N) except that N is a 64-bit unsigned integer instead
  2411. ** of a 32-bit signed integer.
  2412. **
  2413. ** ^If X is a memory allocation previously obtained from sqlite3_malloc(),
  2414. ** sqlite3_malloc64(), sqlite3_realloc(), or sqlite3_realloc64(), then
  2415. ** sqlite3_msize(X) returns the size of that memory allocation in bytes.
  2416. ** ^The value returned by sqlite3_msize(X) might be larger than the number
  2417. ** of bytes requested when X was allocated. ^If X is a NULL pointer then
  2418. ** sqlite3_msize(X) returns zero. If X points to something that is not
  2419. ** the beginning of memory allocation, or if it points to a formerly
  2420. ** valid memory allocation that has now been freed, then the behavior
  2421. ** of sqlite3_msize(X) is undefined and possibly harmful.
  2422. **
  2423. ** ^The memory returned by sqlite3_malloc(), sqlite3_realloc(),
  2424. ** sqlite3_malloc64(), and sqlite3_realloc64()
  2425. ** is always aligned to at least an 8 byte boundary, or to a
  2426. ** 4 byte boundary if the [SQLITE_4_BYTE_ALIGNED_MALLOC] compile-time
  2427. ** option is used.
  2428. **
  2429. ** In SQLite version 3.5.0 and 3.5.1, it was possible to define
  2430. ** the SQLITE_OMIT_MEMORY_ALLOCATION which would cause the built-in
  2431. ** implementation of these routines to be omitted. That capability
  2432. ** is no longer provided. Only built-in memory allocators can be used.
  2433. **
  2434. ** Prior to SQLite version 3.7.10, the Windows OS interface layer called
  2435. ** the system malloc() and free() directly when converting
  2436. ** filenames between the UTF-8 encoding used by SQLite
  2437. ** and whatever filename encoding is used by the particular Windows
  2438. ** installation. Memory allocation errors were detected, but
  2439. ** they were reported back as [SQLITE_CANTOPEN] or
  2440. ** [SQLITE_IOERR] rather than [SQLITE_NOMEM].
  2441. **
  2442. ** The pointer arguments to [sqlite3_free()] and [sqlite3_realloc()]
  2443. ** must be either NULL or else pointers obtained from a prior
  2444. ** invocation of [sqlite3_malloc()] or [sqlite3_realloc()] that have
  2445. ** not yet been released.
  2446. **
  2447. ** The application must not read or write any part of
  2448. ** a block of memory after it has been released using
  2449. ** [sqlite3_free()] or [sqlite3_realloc()].
  2450. */
  2451. SQLITE_API void *sqlite3_malloc(int);
  2452. SQLITE_API void *sqlite3_malloc64(sqlite3_uint64);
  2453. SQLITE_API void *sqlite3_realloc(void*, int);
  2454. SQLITE_API void *sqlite3_realloc64(void*, sqlite3_uint64);
  2455. SQLITE_API void sqlite3_free(void*);
  2456. SQLITE_API sqlite3_uint64 sqlite3_msize(void*);
  2457. /*
  2458. ** CAPI3REF: Memory Allocator Statistics
  2459. **
  2460. ** SQLite provides these two interfaces for reporting on the status
  2461. ** of the [sqlite3_malloc()], [sqlite3_free()], and [sqlite3_realloc()]
  2462. ** routines, which form the built-in memory allocation subsystem.
  2463. **
  2464. ** ^The [sqlite3_memory_used()] routine returns the number of bytes
  2465. ** of memory currently outstanding (malloced but not freed).
  2466. ** ^The [sqlite3_memory_highwater()] routine returns the maximum
  2467. ** value of [sqlite3_memory_used()] since the high-water mark
  2468. ** was last reset. ^The values returned by [sqlite3_memory_used()] and
  2469. ** [sqlite3_memory_highwater()] include any overhead
  2470. ** added by SQLite in its implementation of [sqlite3_malloc()],
  2471. ** but not overhead added by the any underlying system library
  2472. ** routines that [sqlite3_malloc()] may call.
  2473. **
  2474. ** ^The memory high-water mark is reset to the current value of
  2475. ** [sqlite3_memory_used()] if and only if the parameter to
  2476. ** [sqlite3_memory_highwater()] is true. ^The value returned
  2477. ** by [sqlite3_memory_highwater(1)] is the high-water mark
  2478. ** prior to the reset.
  2479. */
  2480. SQLITE_API sqlite3_int64 sqlite3_memory_used(void);
  2481. SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag);
  2482. /*
  2483. ** CAPI3REF: Pseudo-Random Number Generator
  2484. **
  2485. ** SQLite contains a high-quality pseudo-random number generator (PRNG) used to
  2486. ** select random [ROWID | ROWIDs] when inserting new records into a table that
  2487. ** already uses the largest possible [ROWID]. The PRNG is also used for
  2488. ** the build-in random() and randomblob() SQL functions. This interface allows
  2489. ** applications to access the same PRNG for other purposes.
  2490. **
  2491. ** ^A call to this routine stores N bytes of randomness into buffer P.
  2492. ** ^If N is less than one, then P can be a NULL pointer.
  2493. **
  2494. ** ^If this routine has not been previously called or if the previous
  2495. ** call had N less than one, then the PRNG is seeded using randomness
  2496. ** obtained from the xRandomness method of the default [sqlite3_vfs] object.
  2497. ** ^If the previous call to this routine had an N of 1 or more then
  2498. ** the pseudo-randomness is generated
  2499. ** internally and without recourse to the [sqlite3_vfs] xRandomness
  2500. ** method.
  2501. */
  2502. SQLITE_API void sqlite3_randomness(int N, void *P);
  2503. /*
  2504. ** CAPI3REF: Compile-Time Authorization Callbacks
  2505. **
  2506. ** ^This routine registers an authorizer callback with a particular
  2507. ** [database connection], supplied in the first argument.
  2508. ** ^The authorizer callback is invoked as SQL statements are being compiled
  2509. ** by [sqlite3_prepare()] or its variants [sqlite3_prepare_v2()],
  2510. ** [sqlite3_prepare16()] and [sqlite3_prepare16_v2()]. ^At various
  2511. ** points during the compilation process, as logic is being created
  2512. ** to perform various actions, the authorizer callback is invoked to
  2513. ** see if those actions are allowed. ^The authorizer callback should
  2514. ** return [SQLITE_OK] to allow the action, [SQLITE_IGNORE] to disallow the
  2515. ** specific action but allow the SQL statement to continue to be
  2516. ** compiled, or [SQLITE_DENY] to cause the entire SQL statement to be
  2517. ** rejected with an error. ^If the authorizer callback returns
  2518. ** any value other than [SQLITE_IGNORE], [SQLITE_OK], or [SQLITE_DENY]
  2519. ** then the [sqlite3_prepare_v2()] or equivalent call that triggered
  2520. ** the authorizer will fail with an error message.
  2521. **
  2522. ** When the callback returns [SQLITE_OK], that means the operation
  2523. ** requested is ok. ^When the callback returns [SQLITE_DENY], the
  2524. ** [sqlite3_prepare_v2()] or equivalent call that triggered the
  2525. ** authorizer will fail with an error message explaining that
  2526. ** access is denied.
  2527. **
  2528. ** ^The first parameter to the authorizer callback is a copy of the third
  2529. ** parameter to the sqlite3_set_authorizer() interface. ^The second parameter
  2530. ** to the callback is an integer [SQLITE_COPY | action code] that specifies
  2531. ** the particular action to be authorized. ^The third through sixth parameters
  2532. ** to the callback are zero-terminated strings that contain additional
  2533. ** details about the action to be authorized.
  2534. **
  2535. ** ^If the action code is [SQLITE_READ]
  2536. ** and the callback returns [SQLITE_IGNORE] then the
  2537. ** [prepared statement] statement is constructed to substitute
  2538. ** a NULL value in place of the table column that would have
  2539. ** been read if [SQLITE_OK] had been returned. The [SQLITE_IGNORE]
  2540. ** return can be used to deny an untrusted user access to individual
  2541. ** columns of a table.
  2542. ** ^If the action code is [SQLITE_DELETE] and the callback returns
  2543. ** [SQLITE_IGNORE] then the [DELETE] operation proceeds but the
  2544. ** [truncate optimization] is disabled and all rows are deleted individually.
  2545. **
  2546. ** An authorizer is used when [sqlite3_prepare | preparing]
  2547. ** SQL statements from an untrusted source, to ensure that the SQL statements
  2548. ** do not try to access data they are not allowed to see, or that they do not
  2549. ** try to execute malicious statements that damage the database. For
  2550. ** example, an application may allow a user to enter arbitrary
  2551. ** SQL queries for evaluation by a database. But the application does
  2552. ** not want the user to be able to make arbitrary changes to the
  2553. ** database. An authorizer could then be put in place while the
  2554. ** user-entered SQL is being [sqlite3_prepare | prepared] that
  2555. ** disallows everything except [SELECT] statements.
  2556. **
  2557. ** Applications that need to process SQL from untrusted sources
  2558. ** might also consider lowering resource limits using [sqlite3_limit()]
  2559. ** and limiting database size using the [max_page_count] [PRAGMA]
  2560. ** in addition to using an authorizer.
  2561. **
  2562. ** ^(Only a single authorizer can be in place on a database connection
  2563. ** at a time. Each call to sqlite3_set_authorizer overrides the
  2564. ** previous call.)^ ^Disable the authorizer by installing a NULL callback.
  2565. ** The authorizer is disabled by default.
  2566. **
  2567. ** The authorizer callback must not do anything that will modify
  2568. ** the database connection that invoked the authorizer callback.
  2569. ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
  2570. ** database connections for the meaning of "modify" in this paragraph.
  2571. **
  2572. ** ^When [sqlite3_prepare_v2()] is used to prepare a statement, the
  2573. ** statement might be re-prepared during [sqlite3_step()] due to a
  2574. ** schema change. Hence, the application should ensure that the
  2575. ** correct authorizer callback remains in place during the [sqlite3_step()].
  2576. **
  2577. ** ^Note that the authorizer callback is invoked only during
  2578. ** [sqlite3_prepare()] or its variants. Authorization is not
  2579. ** performed during statement evaluation in [sqlite3_step()], unless
  2580. ** as stated in the previous paragraph, sqlite3_step() invokes
  2581. ** sqlite3_prepare_v2() to reprepare a statement after a schema change.
  2582. */
  2583. SQLITE_API int sqlite3_set_authorizer(
  2584. sqlite3*,
  2585. int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
  2586. void *pUserData
  2587. );
  2588. /*
  2589. ** CAPI3REF: Authorizer Return Codes
  2590. **
  2591. ** The [sqlite3_set_authorizer | authorizer callback function] must
  2592. ** return either [SQLITE_OK] or one of these two constants in order
  2593. ** to signal SQLite whether or not the action is permitted. See the
  2594. ** [sqlite3_set_authorizer | authorizer documentation] for additional
  2595. ** information.
  2596. **
  2597. ** Note that SQLITE_IGNORE is also used as a [conflict resolution mode]
  2598. ** returned from the [sqlite3_vtab_on_conflict()] interface.
  2599. */
  2600. #define SQLITE_DENY 1 /* Abort the SQL statement with an error */
  2601. #define SQLITE_IGNORE 2 /* Don't allow access, but don't generate an error */
  2602. /*
  2603. ** CAPI3REF: Authorizer Action Codes
  2604. **
  2605. ** The [sqlite3_set_authorizer()] interface registers a callback function
  2606. ** that is invoked to authorize certain SQL statement actions. The
  2607. ** second parameter to the callback is an integer code that specifies
  2608. ** what action is being authorized. These are the integer action codes that
  2609. ** the authorizer callback may be passed.
  2610. **
  2611. ** These action code values signify what kind of operation is to be
  2612. ** authorized. The 3rd and 4th parameters to the authorization
  2613. ** callback function will be parameters or NULL depending on which of these
  2614. ** codes is used as the second parameter. ^(The 5th parameter to the
  2615. ** authorizer callback is the name of the database ("main", "temp",
  2616. ** etc.) if applicable.)^ ^The 6th parameter to the authorizer callback
  2617. ** is the name of the inner-most trigger or view that is responsible for
  2618. ** the access attempt or NULL if this access attempt is directly from
  2619. ** top-level SQL code.
  2620. */
  2621. /******************************************* 3rd ************ 4th ***********/
  2622. #define SQLITE_CREATE_INDEX 1 /* Index Name Table Name */
  2623. #define SQLITE_CREATE_TABLE 2 /* Table Name NULL */
  2624. #define SQLITE_CREATE_TEMP_INDEX 3 /* Index Name Table Name */
  2625. #define SQLITE_CREATE_TEMP_TABLE 4 /* Table Name NULL */
  2626. #define SQLITE_CREATE_TEMP_TRIGGER 5 /* Trigger Name Table Name */
  2627. #define SQLITE_CREATE_TEMP_VIEW 6 /* View Name NULL */
  2628. #define SQLITE_CREATE_TRIGGER 7 /* Trigger Name Table Name */
  2629. #define SQLITE_CREATE_VIEW 8 /* View Name NULL */
  2630. #define SQLITE_DELETE 9 /* Table Name NULL */
  2631. #define SQLITE_DROP_INDEX 10 /* Index Name Table Name */
  2632. #define SQLITE_DROP_TABLE 11 /* Table Name NULL */
  2633. #define SQLITE_DROP_TEMP_INDEX 12 /* Index Name Table Name */
  2634. #define SQLITE_DROP_TEMP_TABLE 13 /* Table Name NULL */
  2635. #define SQLITE_DROP_TEMP_TRIGGER 14 /* Trigger Name Table Name */
  2636. #define SQLITE_DROP_TEMP_VIEW 15 /* View Name NULL */
  2637. #define SQLITE_DROP_TRIGGER 16 /* Trigger Name Table Name */
  2638. #define SQLITE_DROP_VIEW 17 /* View Name NULL */
  2639. #define SQLITE_INSERT 18 /* Table Name NULL */
  2640. #define SQLITE_PRAGMA 19 /* Pragma Name 1st arg or NULL */
  2641. #define SQLITE_READ 20 /* Table Name Column Name */
  2642. #define SQLITE_SELECT 21 /* NULL NULL */
  2643. #define SQLITE_TRANSACTION 22 /* Operation NULL */
  2644. #define SQLITE_UPDATE 23 /* Table Name Column Name */
  2645. #define SQLITE_ATTACH 24 /* Filename NULL */
  2646. #define SQLITE_DETACH 25 /* Database Name NULL */
  2647. #define SQLITE_ALTER_TABLE 26 /* Database Name Table Name */
  2648. #define SQLITE_REINDEX 27 /* Index Name NULL */
  2649. #define SQLITE_ANALYZE 28 /* Table Name NULL */
  2650. #define SQLITE_CREATE_VTABLE 29 /* Table Name Module Name */
  2651. #define SQLITE_DROP_VTABLE 30 /* Table Name Module Name */
  2652. #define SQLITE_FUNCTION 31 /* NULL Function Name */
  2653. #define SQLITE_SAVEPOINT 32 /* Operation Savepoint Name */
  2654. #define SQLITE_COPY 0 /* No longer used */
  2655. #define SQLITE_RECURSIVE 33 /* NULL NULL */
  2656. /*
  2657. ** CAPI3REF: Tracing And Profiling Functions
  2658. **
  2659. ** These routines register callback functions that can be used for
  2660. ** tracing and profiling the execution of SQL statements.
  2661. **
  2662. ** ^The callback function registered by sqlite3_trace() is invoked at
  2663. ** various times when an SQL statement is being run by [sqlite3_step()].
  2664. ** ^The sqlite3_trace() callback is invoked with a UTF-8 rendering of the
  2665. ** SQL statement text as the statement first begins executing.
  2666. ** ^(Additional sqlite3_trace() callbacks might occur
  2667. ** as each triggered subprogram is entered. The callbacks for triggers
  2668. ** contain a UTF-8 SQL comment that identifies the trigger.)^
  2669. **
  2670. ** The [SQLITE_TRACE_SIZE_LIMIT] compile-time option can be used to limit
  2671. ** the length of [bound parameter] expansion in the output of sqlite3_trace().
  2672. **
  2673. ** ^The callback function registered by sqlite3_profile() is invoked
  2674. ** as each SQL statement finishes. ^The profile callback contains
  2675. ** the original statement text and an estimate of wall-clock time
  2676. ** of how long that statement took to run. ^The profile callback
  2677. ** time is in units of nanoseconds, however the current implementation
  2678. ** is only capable of millisecond resolution so the six least significant
  2679. ** digits in the time are meaningless. Future versions of SQLite
  2680. ** might provide greater resolution on the profiler callback. The
  2681. ** sqlite3_profile() function is considered experimental and is
  2682. ** subject to change in future versions of SQLite.
  2683. */
  2684. SQLITE_API void *sqlite3_trace(sqlite3*, void(*xTrace)(void*,const char*), void*);
  2685. SQLITE_API SQLITE_EXPERIMENTAL void *sqlite3_profile(sqlite3*,
  2686. void(*xProfile)(void*,const char*,sqlite3_uint64), void*);
  2687. /*
  2688. ** CAPI3REF: Query Progress Callbacks
  2689. **
  2690. ** ^The sqlite3_progress_handler(D,N,X,P) interface causes the callback
  2691. ** function X to be invoked periodically during long running calls to
  2692. ** [sqlite3_exec()], [sqlite3_step()] and [sqlite3_get_table()] for
  2693. ** database connection D. An example use for this
  2694. ** interface is to keep a GUI updated during a large query.
  2695. **
  2696. ** ^The parameter P is passed through as the only parameter to the
  2697. ** callback function X. ^The parameter N is the approximate number of
  2698. ** [virtual machine instructions] that are evaluated between successive
  2699. ** invocations of the callback X. ^If N is less than one then the progress
  2700. ** handler is disabled.
  2701. **
  2702. ** ^Only a single progress handler may be defined at one time per
  2703. ** [database connection]; setting a new progress handler cancels the
  2704. ** old one. ^Setting parameter X to NULL disables the progress handler.
  2705. ** ^The progress handler is also disabled by setting N to a value less
  2706. ** than 1.
  2707. **
  2708. ** ^If the progress callback returns non-zero, the operation is
  2709. ** interrupted. This feature can be used to implement a
  2710. ** "Cancel" button on a GUI progress dialog box.
  2711. **
  2712. ** The progress handler callback must not do anything that will modify
  2713. ** the database connection that invoked the progress handler.
  2714. ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
  2715. ** database connections for the meaning of "modify" in this paragraph.
  2716. **
  2717. */
  2718. SQLITE_API void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*);
  2719. /*
  2720. ** CAPI3REF: Opening A New Database Connection
  2721. **
  2722. ** ^These routines open an SQLite database file as specified by the
  2723. ** filename argument. ^The filename argument is interpreted as UTF-8 for
  2724. ** sqlite3_open() and sqlite3_open_v2() and as UTF-16 in the native byte
  2725. ** order for sqlite3_open16(). ^(A [database connection] handle is usually
  2726. ** returned in *ppDb, even if an error occurs. The only exception is that
  2727. ** if SQLite is unable to allocate memory to hold the [sqlite3] object,
  2728. ** a NULL will be written into *ppDb instead of a pointer to the [sqlite3]
  2729. ** object.)^ ^(If the database is opened (and/or created) successfully, then
  2730. ** [SQLITE_OK] is returned. Otherwise an [error code] is returned.)^ ^The
  2731. ** [sqlite3_errmsg()] or [sqlite3_errmsg16()] routines can be used to obtain
  2732. ** an English language description of the error following a failure of any
  2733. ** of the sqlite3_open() routines.
  2734. **
  2735. ** ^The default encoding will be UTF-8 for databases created using
  2736. ** sqlite3_open() or sqlite3_open_v2(). ^The default encoding for databases
  2737. ** created using sqlite3_open16() will be UTF-16 in the native byte order.
  2738. **
  2739. ** Whether or not an error occurs when it is opened, resources
  2740. ** associated with the [database connection] handle should be released by
  2741. ** passing it to [sqlite3_close()] when it is no longer required.
  2742. **
  2743. ** The sqlite3_open_v2() interface works like sqlite3_open()
  2744. ** except that it accepts two additional parameters for additional control
  2745. ** over the new database connection. ^(The flags parameter to
  2746. ** sqlite3_open_v2() can take one of
  2747. ** the following three values, optionally combined with the
  2748. ** [SQLITE_OPEN_NOMUTEX], [SQLITE_OPEN_FULLMUTEX], [SQLITE_OPEN_SHAREDCACHE],
  2749. ** [SQLITE_OPEN_PRIVATECACHE], and/or [SQLITE_OPEN_URI] flags:)^
  2750. **
  2751. ** <dl>
  2752. ** ^(<dt>[SQLITE_OPEN_READONLY]</dt>
  2753. ** <dd>The database is opened in read-only mode. If the database does not
  2754. ** already exist, an error is returned.</dd>)^
  2755. **
  2756. ** ^(<dt>[SQLITE_OPEN_READWRITE]</dt>
  2757. ** <dd>The database is opened for reading and writing if possible, or reading
  2758. ** only if the file is write protected by the operating system. In either
  2759. ** case the database must already exist, otherwise an error is returned.</dd>)^
  2760. **
  2761. ** ^(<dt>[SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]</dt>
  2762. ** <dd>The database is opened for reading and writing, and is created if
  2763. ** it does not already exist. This is the behavior that is always used for
  2764. ** sqlite3_open() and sqlite3_open16().</dd>)^
  2765. ** </dl>
  2766. **
  2767. ** If the 3rd parameter to sqlite3_open_v2() is not one of the
  2768. ** combinations shown above optionally combined with other
  2769. ** [SQLITE_OPEN_READONLY | SQLITE_OPEN_* bits]
  2770. ** then the behavior is undefined.
  2771. **
  2772. ** ^If the [SQLITE_OPEN_NOMUTEX] flag is set, then the database connection
  2773. ** opens in the multi-thread [threading mode] as long as the single-thread
  2774. ** mode has not been set at compile-time or start-time. ^If the
  2775. ** [SQLITE_OPEN_FULLMUTEX] flag is set then the database connection opens
  2776. ** in the serialized [threading mode] unless single-thread was
  2777. ** previously selected at compile-time or start-time.
  2778. ** ^The [SQLITE_OPEN_SHAREDCACHE] flag causes the database connection to be
  2779. ** eligible to use [shared cache mode], regardless of whether or not shared
  2780. ** cache is enabled using [sqlite3_enable_shared_cache()]. ^The
  2781. ** [SQLITE_OPEN_PRIVATECACHE] flag causes the database connection to not
  2782. ** participate in [shared cache mode] even if it is enabled.
  2783. **
  2784. ** ^The fourth parameter to sqlite3_open_v2() is the name of the
  2785. ** [sqlite3_vfs] object that defines the operating system interface that
  2786. ** the new database connection should use. ^If the fourth parameter is
  2787. ** a NULL pointer then the default [sqlite3_vfs] object is used.
  2788. **
  2789. ** ^If the filename is ":memory:", then a private, temporary in-memory database
  2790. ** is created for the connection. ^This in-memory database will vanish when
  2791. ** the database connection is closed. Future versions of SQLite might
  2792. ** make use of additional special filenames that begin with the ":" character.
  2793. ** It is recommended that when a database filename actually does begin with
  2794. ** a ":" character you should prefix the filename with a pathname such as
  2795. ** "./" to avoid ambiguity.
  2796. **
  2797. ** ^If the filename is an empty string, then a private, temporary
  2798. ** on-disk database will be created. ^This private database will be
  2799. ** automatically deleted as soon as the database connection is closed.
  2800. **
  2801. ** [[URI filenames in sqlite3_open()]] <h3>URI Filenames</h3>
  2802. **
  2803. ** ^If [URI filename] interpretation is enabled, and the filename argument
  2804. ** begins with "file:", then the filename is interpreted as a URI. ^URI
  2805. ** filename interpretation is enabled if the [SQLITE_OPEN_URI] flag is
  2806. ** set in the fourth argument to sqlite3_open_v2(), or if it has
  2807. ** been enabled globally using the [SQLITE_CONFIG_URI] option with the
  2808. ** [sqlite3_config()] method or by the [SQLITE_USE_URI] compile-time option.
  2809. ** As of SQLite version 3.7.7, URI filename interpretation is turned off
  2810. ** by default, but future releases of SQLite might enable URI filename
  2811. ** interpretation by default. See "[URI filenames]" for additional
  2812. ** information.
  2813. **
  2814. ** URI filenames are parsed according to RFC 3986. ^If the URI contains an
  2815. ** authority, then it must be either an empty string or the string
  2816. ** "localhost". ^If the authority is not an empty string or "localhost", an
  2817. ** error is returned to the caller. ^The fragment component of a URI, if
  2818. ** present, is ignored.
  2819. **
  2820. ** ^SQLite uses the path component of the URI as the name of the disk file
  2821. ** which contains the database. ^If the path begins with a '/' character,
  2822. ** then it is interpreted as an absolute path. ^If the path does not begin
  2823. ** with a '/' (meaning that the authority section is omitted from the URI)
  2824. ** then the path is interpreted as a relative path.
  2825. ** ^(On windows, the first component of an absolute path
  2826. ** is a drive specification (e.g. "C:").)^
  2827. **
  2828. ** [[core URI query parameters]]
  2829. ** The query component of a URI may contain parameters that are interpreted
  2830. ** either by SQLite itself, or by a [VFS | custom VFS implementation].
  2831. ** SQLite and its built-in [VFSes] interpret the
  2832. ** following query parameters:
  2833. **
  2834. ** <ul>
  2835. ** <li> <b>vfs</b>: ^The "vfs" parameter may be used to specify the name of
  2836. ** a VFS object that provides the operating system interface that should
  2837. ** be used to access the database file on disk. ^If this option is set to
  2838. ** an empty string the default VFS object is used. ^Specifying an unknown
  2839. ** VFS is an error. ^If sqlite3_open_v2() is used and the vfs option is
  2840. ** present, then the VFS specified by the option takes precedence over
  2841. ** the value passed as the fourth parameter to sqlite3_open_v2().
  2842. **
  2843. ** <li> <b>mode</b>: ^(The mode parameter may be set to either "ro", "rw",
  2844. ** "rwc", or "memory". Attempting to set it to any other value is
  2845. ** an error)^.
  2846. ** ^If "ro" is specified, then the database is opened for read-only
  2847. ** access, just as if the [SQLITE_OPEN_READONLY] flag had been set in the
  2848. ** third argument to sqlite3_open_v2(). ^If the mode option is set to
  2849. ** "rw", then the database is opened for read-write (but not create)
  2850. ** access, as if SQLITE_OPEN_READWRITE (but not SQLITE_OPEN_CREATE) had
  2851. ** been set. ^Value "rwc" is equivalent to setting both
  2852. ** SQLITE_OPEN_READWRITE and SQLITE_OPEN_CREATE. ^If the mode option is
  2853. ** set to "memory" then a pure [in-memory database] that never reads
  2854. ** or writes from disk is used. ^It is an error to specify a value for
  2855. ** the mode parameter that is less restrictive than that specified by
  2856. ** the flags passed in the third parameter to sqlite3_open_v2().
  2857. **
  2858. ** <li> <b>cache</b>: ^The cache parameter may be set to either "shared" or
  2859. ** "private". ^Setting it to "shared" is equivalent to setting the
  2860. ** SQLITE_OPEN_SHAREDCACHE bit in the flags argument passed to
  2861. ** sqlite3_open_v2(). ^Setting the cache parameter to "private" is
  2862. ** equivalent to setting the SQLITE_OPEN_PRIVATECACHE bit.
  2863. ** ^If sqlite3_open_v2() is used and the "cache" parameter is present in
  2864. ** a URI filename, its value overrides any behavior requested by setting
  2865. ** SQLITE_OPEN_PRIVATECACHE or SQLITE_OPEN_SHAREDCACHE flag.
  2866. **
  2867. ** <li> <b>psow</b>: ^The psow parameter indicates whether or not the
  2868. ** [powersafe overwrite] property does or does not apply to the
  2869. ** storage media on which the database file resides.
  2870. **
  2871. ** <li> <b>nolock</b>: ^The nolock parameter is a boolean query parameter
  2872. ** which if set disables file locking in rollback journal modes. This
  2873. ** is useful for accessing a database on a filesystem that does not
  2874. ** support locking. Caution: Database corruption might result if two
  2875. ** or more processes write to the same database and any one of those
  2876. ** processes uses nolock=1.
  2877. **
  2878. ** <li> <b>immutable</b>: ^The immutable parameter is a boolean query
  2879. ** parameter that indicates that the database file is stored on
  2880. ** read-only media. ^When immutable is set, SQLite assumes that the
  2881. ** database file cannot be changed, even by a process with higher
  2882. ** privilege, and so the database is opened read-only and all locking
  2883. ** and change detection is disabled. Caution: Setting the immutable
  2884. ** property on a database file that does in fact change can result
  2885. ** in incorrect query results and/or [SQLITE_CORRUPT] errors.
  2886. ** See also: [SQLITE_IOCAP_IMMUTABLE].
  2887. **
  2888. ** </ul>
  2889. **
  2890. ** ^Specifying an unknown parameter in the query component of a URI is not an
  2891. ** error. Future versions of SQLite might understand additional query
  2892. ** parameters. See "[query parameters with special meaning to SQLite]" for
  2893. ** additional information.
  2894. **
  2895. ** [[URI filename examples]] <h3>URI filename examples</h3>
  2896. **
  2897. ** <table border="1" align=center cellpadding=5>
  2898. ** <tr><th> URI filenames <th> Results
  2899. ** <tr><td> file:data.db <td>
  2900. ** Open the file "data.db" in the current directory.
  2901. ** <tr><td> file:/home/fred/data.db<br>
  2902. ** file:///home/fred/data.db <br>
  2903. ** file://localhost/home/fred/data.db <br> <td>
  2904. ** Open the database file "/home/fred/data.db".
  2905. ** <tr><td> file://darkstar/home/fred/data.db <td>
  2906. ** An error. "darkstar" is not a recognized authority.
  2907. ** <tr><td style="white-space:nowrap">
  2908. ** file:///C:/Documents%20and%20Settings/fred/Desktop/data.db
  2909. ** <td> Windows only: Open the file "data.db" on fred's desktop on drive
  2910. ** C:. Note that the %20 escaping in this example is not strictly
  2911. ** necessary - space characters can be used literally
  2912. ** in URI filenames.
  2913. ** <tr><td> file:data.db?mode=ro&cache=private <td>
  2914. ** Open file "data.db" in the current directory for read-only access.
  2915. ** Regardless of whether or not shared-cache mode is enabled by
  2916. ** default, use a private cache.
  2917. ** <tr><td> file:/home/fred/data.db?vfs=unix-dotfile <td>
  2918. ** Open file "/home/fred/data.db". Use the special VFS "unix-dotfile"
  2919. ** that uses dot-files in place of posix advisory locking.
  2920. ** <tr><td> file:data.db?mode=readonly <td>
  2921. ** An error. "readonly" is not a valid option for the "mode" parameter.
  2922. ** </table>
  2923. **
  2924. ** ^URI hexadecimal escape sequences (%HH) are supported within the path and
  2925. ** query components of a URI. A hexadecimal escape sequence consists of a
  2926. ** percent sign - "%" - followed by exactly two hexadecimal digits
  2927. ** specifying an octet value. ^Before the path or query components of a
  2928. ** URI filename are interpreted, they are encoded using UTF-8 and all
  2929. ** hexadecimal escape sequences replaced by a single byte containing the
  2930. ** corresponding octet. If this process generates an invalid UTF-8 encoding,
  2931. ** the results are undefined.
  2932. **
  2933. ** <b>Note to Windows users:</b> The encoding used for the filename argument
  2934. ** of sqlite3_open() and sqlite3_open_v2() must be UTF-8, not whatever
  2935. ** codepage is currently defined. Filenames containing international
  2936. ** characters must be converted to UTF-8 prior to passing them into
  2937. ** sqlite3_open() or sqlite3_open_v2().
  2938. **
  2939. ** <b>Note to Windows Runtime users:</b> The temporary directory must be set
  2940. ** prior to calling sqlite3_open() or sqlite3_open_v2(). Otherwise, various
  2941. ** features that require the use of temporary files may fail.
  2942. **
  2943. ** See also: [sqlite3_temp_directory]
  2944. */
  2945. SQLITE_API int sqlite3_open(
  2946. const char *filename, /* Database filename (UTF-8) */
  2947. sqlite3 **ppDb /* OUT: SQLite db handle */
  2948. );
  2949. SQLITE_API int sqlite3_open16(
  2950. const void *filename, /* Database filename (UTF-16) */
  2951. sqlite3 **ppDb /* OUT: SQLite db handle */
  2952. );
  2953. SQLITE_API int sqlite3_open_v2(
  2954. const char *filename, /* Database filename (UTF-8) */
  2955. sqlite3 **ppDb, /* OUT: SQLite db handle */
  2956. int flags, /* Flags */
  2957. const char *zVfs /* Name of VFS module to use */
  2958. );
  2959. /*
  2960. ** CAPI3REF: Obtain Values For URI Parameters
  2961. **
  2962. ** These are utility routines, useful to VFS implementations, that check
  2963. ** to see if a database file was a URI that contained a specific query
  2964. ** parameter, and if so obtains the value of that query parameter.
  2965. **
  2966. ** If F is the database filename pointer passed into the xOpen() method of
  2967. ** a VFS implementation when the flags parameter to xOpen() has one or
  2968. ** more of the [SQLITE_OPEN_URI] or [SQLITE_OPEN_MAIN_DB] bits set and
  2969. ** P is the name of the query parameter, then
  2970. ** sqlite3_uri_parameter(F,P) returns the value of the P
  2971. ** parameter if it exists or a NULL pointer if P does not appear as a
  2972. ** query parameter on F. If P is a query parameter of F
  2973. ** has no explicit value, then sqlite3_uri_parameter(F,P) returns
  2974. ** a pointer to an empty string.
  2975. **
  2976. ** The sqlite3_uri_boolean(F,P,B) routine assumes that P is a boolean
  2977. ** parameter and returns true (1) or false (0) according to the value
  2978. ** of P. The sqlite3_uri_boolean(F,P,B) routine returns true (1) if the
  2979. ** value of query parameter P is one of "yes", "true", or "on" in any
  2980. ** case or if the value begins with a non-zero number. The
  2981. ** sqlite3_uri_boolean(F,P,B) routines returns false (0) if the value of
  2982. ** query parameter P is one of "no", "false", or "off" in any case or
  2983. ** if the value begins with a numeric zero. If P is not a query
  2984. ** parameter on F or if the value of P is does not match any of the
  2985. ** above, then sqlite3_uri_boolean(F,P,B) returns (B!=0).
  2986. **
  2987. ** The sqlite3_uri_int64(F,P,D) routine converts the value of P into a
  2988. ** 64-bit signed integer and returns that integer, or D if P does not
  2989. ** exist. If the value of P is something other than an integer, then
  2990. ** zero is returned.
  2991. **
  2992. ** If F is a NULL pointer, then sqlite3_uri_parameter(F,P) returns NULL and
  2993. ** sqlite3_uri_boolean(F,P,B) returns B. If F is not a NULL pointer and
  2994. ** is not a database file pathname pointer that SQLite passed into the xOpen
  2995. ** VFS method, then the behavior of this routine is undefined and probably
  2996. ** undesirable.
  2997. */
  2998. SQLITE_API const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam);
  2999. SQLITE_API int sqlite3_uri_boolean(const char *zFile, const char *zParam, int bDefault);
  3000. SQLITE_API sqlite3_int64 sqlite3_uri_int64(const char*, const char*, sqlite3_int64);
  3001. /*
  3002. ** CAPI3REF: Error Codes And Messages
  3003. **
  3004. ** ^The sqlite3_errcode() interface returns the numeric [result code] or
  3005. ** [extended result code] for the most recent failed sqlite3_* API call
  3006. ** associated with a [database connection]. If a prior API call failed
  3007. ** but the most recent API call succeeded, the return value from
  3008. ** sqlite3_errcode() is undefined. ^The sqlite3_extended_errcode()
  3009. ** interface is the same except that it always returns the
  3010. ** [extended result code] even when extended result codes are
  3011. ** disabled.
  3012. **
  3013. ** ^The sqlite3_errmsg() and sqlite3_errmsg16() return English-language
  3014. ** text that describes the error, as either UTF-8 or UTF-16 respectively.
  3015. ** ^(Memory to hold the error message string is managed internally.
  3016. ** The application does not need to worry about freeing the result.
  3017. ** However, the error string might be overwritten or deallocated by
  3018. ** subsequent calls to other SQLite interface functions.)^
  3019. **
  3020. ** ^The sqlite3_errstr() interface returns the English-language text
  3021. ** that describes the [result code], as UTF-8.
  3022. ** ^(Memory to hold the error message string is managed internally
  3023. ** and must not be freed by the application)^.
  3024. **
  3025. ** When the serialized [threading mode] is in use, it might be the
  3026. ** case that a second error occurs on a separate thread in between
  3027. ** the time of the first error and the call to these interfaces.
  3028. ** When that happens, the second error will be reported since these
  3029. ** interfaces always report the most recent result. To avoid
  3030. ** this, each thread can obtain exclusive use of the [database connection] D
  3031. ** by invoking [sqlite3_mutex_enter]([sqlite3_db_mutex](D)) before beginning
  3032. ** to use D and invoking [sqlite3_mutex_leave]([sqlite3_db_mutex](D)) after
  3033. ** all calls to the interfaces listed here are completed.
  3034. **
  3035. ** If an interface fails with SQLITE_MISUSE, that means the interface
  3036. ** was invoked incorrectly by the application. In that case, the
  3037. ** error code and message may or may not be set.
  3038. */
  3039. SQLITE_API int sqlite3_errcode(sqlite3 *db);
  3040. SQLITE_API int sqlite3_extended_errcode(sqlite3 *db);
  3041. SQLITE_API const char *sqlite3_errmsg(sqlite3*);
  3042. SQLITE_API const void *sqlite3_errmsg16(sqlite3*);
  3043. SQLITE_API const char *sqlite3_errstr(int);
  3044. /*
  3045. ** CAPI3REF: SQL Statement Object
  3046. ** KEYWORDS: {prepared statement} {prepared statements}
  3047. **
  3048. ** An instance of this object represents a single SQL statement.
  3049. ** This object is variously known as a "prepared statement" or a
  3050. ** "compiled SQL statement" or simply as a "statement".
  3051. **
  3052. ** The life of a statement object goes something like this:
  3053. **
  3054. ** <ol>
  3055. ** <li> Create the object using [sqlite3_prepare_v2()] or a related
  3056. ** function.
  3057. ** <li> Bind values to [host parameters] using the sqlite3_bind_*()
  3058. ** interfaces.
  3059. ** <li> Run the SQL by calling [sqlite3_step()] one or more times.
  3060. ** <li> Reset the statement using [sqlite3_reset()] then go back
  3061. ** to step 2. Do this zero or more times.
  3062. ** <li> Destroy the object using [sqlite3_finalize()].
  3063. ** </ol>
  3064. **
  3065. ** Refer to documentation on individual methods above for additional
  3066. ** information.
  3067. */
  3068. typedef struct sqlite3_stmt sqlite3_stmt;
  3069. /*
  3070. ** CAPI3REF: Run-time Limits
  3071. **
  3072. ** ^(This interface allows the size of various constructs to be limited
  3073. ** on a connection by connection basis. The first parameter is the
  3074. ** [database connection] whose limit is to be set or queried. The
  3075. ** second parameter is one of the [limit categories] that define a
  3076. ** class of constructs to be size limited. The third parameter is the
  3077. ** new limit for that construct.)^
  3078. **
  3079. ** ^If the new limit is a negative number, the limit is unchanged.
  3080. ** ^(For each limit category SQLITE_LIMIT_<i>NAME</i> there is a
  3081. ** [limits | hard upper bound]
  3082. ** set at compile-time by a C preprocessor macro called
  3083. ** [limits | SQLITE_MAX_<i>NAME</i>].
  3084. ** (The "_LIMIT_" in the name is changed to "_MAX_".))^
  3085. ** ^Attempts to increase a limit above its hard upper bound are
  3086. ** silently truncated to the hard upper bound.
  3087. **
  3088. ** ^Regardless of whether or not the limit was changed, the
  3089. ** [sqlite3_limit()] interface returns the prior value of the limit.
  3090. ** ^Hence, to find the current value of a limit without changing it,
  3091. ** simply invoke this interface with the third parameter set to -1.
  3092. **
  3093. ** Run-time limits are intended for use in applications that manage
  3094. ** both their own internal database and also databases that are controlled
  3095. ** by untrusted external sources. An example application might be a
  3096. ** web browser that has its own databases for storing history and
  3097. ** separate databases controlled by JavaScript applications downloaded
  3098. ** off the Internet. The internal databases can be given the
  3099. ** large, default limits. Databases managed by external sources can
  3100. ** be given much smaller limits designed to prevent a denial of service
  3101. ** attack. Developers might also want to use the [sqlite3_set_authorizer()]
  3102. ** interface to further control untrusted SQL. The size of the database
  3103. ** created by an untrusted script can be contained using the
  3104. ** [max_page_count] [PRAGMA].
  3105. **
  3106. ** New run-time limit categories may be added in future releases.
  3107. */
  3108. SQLITE_API int sqlite3_limit(sqlite3*, int id, int newVal);
  3109. /*
  3110. ** CAPI3REF: Run-Time Limit Categories
  3111. ** KEYWORDS: {limit category} {*limit categories}
  3112. **
  3113. ** These constants define various performance limits
  3114. ** that can be lowered at run-time using [sqlite3_limit()].
  3115. ** The synopsis of the meanings of the various limits is shown below.
  3116. ** Additional information is available at [limits | Limits in SQLite].
  3117. **
  3118. ** <dl>
  3119. ** [[SQLITE_LIMIT_LENGTH]] ^(<dt>SQLITE_LIMIT_LENGTH</dt>
  3120. ** <dd>The maximum size of any string or BLOB or table row, in bytes.<dd>)^
  3121. **
  3122. ** [[SQLITE_LIMIT_SQL_LENGTH]] ^(<dt>SQLITE_LIMIT_SQL_LENGTH</dt>
  3123. ** <dd>The maximum length of an SQL statement, in bytes.</dd>)^
  3124. **
  3125. ** [[SQLITE_LIMIT_COLUMN]] ^(<dt>SQLITE_LIMIT_COLUMN</dt>
  3126. ** <dd>The maximum number of columns in a table definition or in the
  3127. ** result set of a [SELECT] or the maximum number of columns in an index
  3128. ** or in an ORDER BY or GROUP BY clause.</dd>)^
  3129. **
  3130. ** [[SQLITE_LIMIT_EXPR_DEPTH]] ^(<dt>SQLITE_LIMIT_EXPR_DEPTH</dt>
  3131. ** <dd>The maximum depth of the parse tree on any expression.</dd>)^
  3132. **
  3133. ** [[SQLITE_LIMIT_COMPOUND_SELECT]] ^(<dt>SQLITE_LIMIT_COMPOUND_SELECT</dt>
  3134. ** <dd>The maximum number of terms in a compound SELECT statement.</dd>)^
  3135. **
  3136. ** [[SQLITE_LIMIT_VDBE_OP]] ^(<dt>SQLITE_LIMIT_VDBE_OP</dt>
  3137. ** <dd>The maximum number of instructions in a virtual machine program
  3138. ** used to implement an SQL statement. This limit is not currently
  3139. ** enforced, though that might be added in some future release of
  3140. ** SQLite.</dd>)^
  3141. **
  3142. ** [[SQLITE_LIMIT_FUNCTION_ARG]] ^(<dt>SQLITE_LIMIT_FUNCTION_ARG</dt>
  3143. ** <dd>The maximum number of arguments on a function.</dd>)^
  3144. **
  3145. ** [[SQLITE_LIMIT_ATTACHED]] ^(<dt>SQLITE_LIMIT_ATTACHED</dt>
  3146. ** <dd>The maximum number of [ATTACH | attached databases].)^</dd>
  3147. **
  3148. ** [[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]]
  3149. ** ^(<dt>SQLITE_LIMIT_LIKE_PATTERN_LENGTH</dt>
  3150. ** <dd>The maximum length of the pattern argument to the [LIKE] or
  3151. ** [GLOB] operators.</dd>)^
  3152. **
  3153. ** [[SQLITE_LIMIT_VARIABLE_NUMBER]]
  3154. ** ^(<dt>SQLITE_LIMIT_VARIABLE_NUMBER</dt>
  3155. ** <dd>The maximum index number of any [parameter] in an SQL statement.)^
  3156. **
  3157. ** [[SQLITE_LIMIT_TRIGGER_DEPTH]] ^(<dt>SQLITE_LIMIT_TRIGGER_DEPTH</dt>
  3158. ** <dd>The maximum depth of recursion for triggers.</dd>)^
  3159. **
  3160. ** [[SQLITE_LIMIT_WORKER_THREADS]] ^(<dt>SQLITE_LIMIT_WORKER_THREADS</dt>
  3161. ** <dd>The maximum number of auxiliary worker threads that a single
  3162. ** [prepared statement] may start.</dd>)^
  3163. ** </dl>
  3164. */
  3165. #define SQLITE_LIMIT_LENGTH 0
  3166. #define SQLITE_LIMIT_SQL_LENGTH 1
  3167. #define SQLITE_LIMIT_COLUMN 2
  3168. #define SQLITE_LIMIT_EXPR_DEPTH 3
  3169. #define SQLITE_LIMIT_COMPOUND_SELECT 4
  3170. #define SQLITE_LIMIT_VDBE_OP 5
  3171. #define SQLITE_LIMIT_FUNCTION_ARG 6
  3172. #define SQLITE_LIMIT_ATTACHED 7
  3173. #define SQLITE_LIMIT_LIKE_PATTERN_LENGTH 8
  3174. #define SQLITE_LIMIT_VARIABLE_NUMBER 9
  3175. #define SQLITE_LIMIT_TRIGGER_DEPTH 10
  3176. #define SQLITE_LIMIT_WORKER_THREADS 11
  3177. /*
  3178. ** CAPI3REF: Compiling An SQL Statement
  3179. ** KEYWORDS: {SQL statement compiler}
  3180. **
  3181. ** To execute an SQL query, it must first be compiled into a byte-code
  3182. ** program using one of these routines.
  3183. **
  3184. ** The first argument, "db", is a [database connection] obtained from a
  3185. ** prior successful call to [sqlite3_open()], [sqlite3_open_v2()] or
  3186. ** [sqlite3_open16()]. The database connection must not have been closed.
  3187. **
  3188. ** The second argument, "zSql", is the statement to be compiled, encoded
  3189. ** as either UTF-8 or UTF-16. The sqlite3_prepare() and sqlite3_prepare_v2()
  3190. ** interfaces use UTF-8, and sqlite3_prepare16() and sqlite3_prepare16_v2()
  3191. ** use UTF-16.
  3192. **
  3193. ** ^If the nByte argument is less than zero, then zSql is read up to the
  3194. ** first zero terminator. ^If nByte is non-negative, then it is the maximum
  3195. ** number of bytes read from zSql. ^When nByte is non-negative, the
  3196. ** zSql string ends at either the first '\000' or '\u0000' character or
  3197. ** the nByte-th byte, whichever comes first. If the caller knows
  3198. ** that the supplied string is nul-terminated, then there is a small
  3199. ** performance advantage to be gained by passing an nByte parameter that
  3200. ** is equal to the number of bytes in the input string <i>including</i>
  3201. ** the nul-terminator bytes as this saves SQLite from having to
  3202. ** make a copy of the input string.
  3203. **
  3204. ** ^If pzTail is not NULL then *pzTail is made to point to the first byte
  3205. ** past the end of the first SQL statement in zSql. These routines only
  3206. ** compile the first statement in zSql, so *pzTail is left pointing to
  3207. ** what remains uncompiled.
  3208. **
  3209. ** ^*ppStmt is left pointing to a compiled [prepared statement] that can be
  3210. ** executed using [sqlite3_step()]. ^If there is an error, *ppStmt is set
  3211. ** to NULL. ^If the input text contains no SQL (if the input is an empty
  3212. ** string or a comment) then *ppStmt is set to NULL.
  3213. ** The calling procedure is responsible for deleting the compiled
  3214. ** SQL statement using [sqlite3_finalize()] after it has finished with it.
  3215. ** ppStmt may not be NULL.
  3216. **
  3217. ** ^On success, the sqlite3_prepare() family of routines return [SQLITE_OK];
  3218. ** otherwise an [error code] is returned.
  3219. **
  3220. ** The sqlite3_prepare_v2() and sqlite3_prepare16_v2() interfaces are
  3221. ** recommended for all new programs. The two older interfaces are retained
  3222. ** for backwards compatibility, but their use is discouraged.
  3223. ** ^In the "v2" interfaces, the prepared statement
  3224. ** that is returned (the [sqlite3_stmt] object) contains a copy of the
  3225. ** original SQL text. This causes the [sqlite3_step()] interface to
  3226. ** behave differently in three ways:
  3227. **
  3228. ** <ol>
  3229. ** <li>
  3230. ** ^If the database schema changes, instead of returning [SQLITE_SCHEMA] as it
  3231. ** always used to do, [sqlite3_step()] will automatically recompile the SQL
  3232. ** statement and try to run it again. As many as [SQLITE_MAX_SCHEMA_RETRY]
  3233. ** retries will occur before sqlite3_step() gives up and returns an error.
  3234. ** </li>
  3235. **
  3236. ** <li>
  3237. ** ^When an error occurs, [sqlite3_step()] will return one of the detailed
  3238. ** [error codes] or [extended error codes]. ^The legacy behavior was that
  3239. ** [sqlite3_step()] would only return a generic [SQLITE_ERROR] result code
  3240. ** and the application would have to make a second call to [sqlite3_reset()]
  3241. ** in order to find the underlying cause of the problem. With the "v2" prepare
  3242. ** interfaces, the underlying reason for the error is returned immediately.
  3243. ** </li>
  3244. **
  3245. ** <li>
  3246. ** ^If the specific value bound to [parameter | host parameter] in the
  3247. ** WHERE clause might influence the choice of query plan for a statement,
  3248. ** then the statement will be automatically recompiled, as if there had been
  3249. ** a schema change, on the first [sqlite3_step()] call following any change
  3250. ** to the [sqlite3_bind_text | bindings] of that [parameter].
  3251. ** ^The specific value of WHERE-clause [parameter] might influence the
  3252. ** choice of query plan if the parameter is the left-hand side of a [LIKE]
  3253. ** or [GLOB] operator or if the parameter is compared to an indexed column
  3254. ** and the [SQLITE_ENABLE_STAT3] compile-time option is enabled.
  3255. ** </li>
  3256. ** </ol>
  3257. */
  3258. SQLITE_API int sqlite3_prepare(
  3259. sqlite3 *db, /* Database handle */
  3260. const char *zSql, /* SQL statement, UTF-8 encoded */
  3261. int nByte, /* Maximum length of zSql in bytes. */
  3262. sqlite3_stmt **ppStmt, /* OUT: Statement handle */
  3263. const char **pzTail /* OUT: Pointer to unused portion of zSql */
  3264. );
  3265. SQLITE_API int sqlite3_prepare_v2(
  3266. sqlite3 *db, /* Database handle */
  3267. const char *zSql, /* SQL statement, UTF-8 encoded */
  3268. int nByte, /* Maximum length of zSql in bytes. */
  3269. sqlite3_stmt **ppStmt, /* OUT: Statement handle */
  3270. const char **pzTail /* OUT: Pointer to unused portion of zSql */
  3271. );
  3272. SQLITE_API int sqlite3_prepare16(
  3273. sqlite3 *db, /* Database handle */
  3274. const void *zSql, /* SQL statement, UTF-16 encoded */
  3275. int nByte, /* Maximum length of zSql in bytes. */
  3276. sqlite3_stmt **ppStmt, /* OUT: Statement handle */
  3277. const void **pzTail /* OUT: Pointer to unused portion of zSql */
  3278. );
  3279. SQLITE_API int sqlite3_prepare16_v2(
  3280. sqlite3 *db, /* Database handle */
  3281. const void *zSql, /* SQL statement, UTF-16 encoded */
  3282. int nByte, /* Maximum length of zSql in bytes. */
  3283. sqlite3_stmt **ppStmt, /* OUT: Statement handle */
  3284. const void **pzTail /* OUT: Pointer to unused portion of zSql */
  3285. );
  3286. /*
  3287. ** CAPI3REF: Retrieving Statement SQL
  3288. **
  3289. ** ^This interface can be used to retrieve a saved copy of the original
  3290. ** SQL text used to create a [prepared statement] if that statement was
  3291. ** compiled using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()].
  3292. */
  3293. SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt);
  3294. /*
  3295. ** CAPI3REF: Determine If An SQL Statement Writes The Database
  3296. **
  3297. ** ^The sqlite3_stmt_readonly(X) interface returns true (non-zero) if
  3298. ** and only if the [prepared statement] X makes no direct changes to
  3299. ** the content of the database file.
  3300. **
  3301. ** Note that [application-defined SQL functions] or
  3302. ** [virtual tables] might change the database indirectly as a side effect.
  3303. ** ^(For example, if an application defines a function "eval()" that
  3304. ** calls [sqlite3_exec()], then the following SQL statement would
  3305. ** change the database file through side-effects:
  3306. **
  3307. ** <blockquote><pre>
  3308. ** SELECT eval('DELETE FROM t1') FROM t2;
  3309. ** </pre></blockquote>
  3310. **
  3311. ** But because the [SELECT] statement does not change the database file
  3312. ** directly, sqlite3_stmt_readonly() would still return true.)^
  3313. **
  3314. ** ^Transaction control statements such as [BEGIN], [COMMIT], [ROLLBACK],
  3315. ** [SAVEPOINT], and [RELEASE] cause sqlite3_stmt_readonly() to return true,
  3316. ** since the statements themselves do not actually modify the database but
  3317. ** rather they control the timing of when other statements modify the
  3318. ** database. ^The [ATTACH] and [DETACH] statements also cause
  3319. ** sqlite3_stmt_readonly() to return true since, while those statements
  3320. ** change the configuration of a database connection, they do not make
  3321. ** changes to the content of the database files on disk.
  3322. */
  3323. SQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt);
  3324. /*
  3325. ** CAPI3REF: Determine If A Prepared Statement Has Been Reset
  3326. **
  3327. ** ^The sqlite3_stmt_busy(S) interface returns true (non-zero) if the
  3328. ** [prepared statement] S has been stepped at least once using
  3329. ** [sqlite3_step(S)] but has not run to completion and/or has not
  3330. ** been reset using [sqlite3_reset(S)]. ^The sqlite3_stmt_busy(S)
  3331. ** interface returns false if S is a NULL pointer. If S is not a
  3332. ** NULL pointer and is not a pointer to a valid [prepared statement]
  3333. ** object, then the behavior is undefined and probably undesirable.
  3334. **
  3335. ** This interface can be used in combination [sqlite3_next_stmt()]
  3336. ** to locate all prepared statements associated with a database
  3337. ** connection that are in need of being reset. This can be used,
  3338. ** for example, in diagnostic routines to search for prepared
  3339. ** statements that are holding a transaction open.
  3340. */
  3341. SQLITE_API int sqlite3_stmt_busy(sqlite3_stmt*);
  3342. /*
  3343. ** CAPI3REF: Dynamically Typed Value Object
  3344. ** KEYWORDS: {protected sqlite3_value} {unprotected sqlite3_value}
  3345. **
  3346. ** SQLite uses the sqlite3_value object to represent all values
  3347. ** that can be stored in a database table. SQLite uses dynamic typing
  3348. ** for the values it stores. ^Values stored in sqlite3_value objects
  3349. ** can be integers, floating point values, strings, BLOBs, or NULL.
  3350. **
  3351. ** An sqlite3_value object may be either "protected" or "unprotected".
  3352. ** Some interfaces require a protected sqlite3_value. Other interfaces
  3353. ** will accept either a protected or an unprotected sqlite3_value.
  3354. ** Every interface that accepts sqlite3_value arguments specifies
  3355. ** whether or not it requires a protected sqlite3_value.
  3356. **
  3357. ** The terms "protected" and "unprotected" refer to whether or not
  3358. ** a mutex is held. An internal mutex is held for a protected
  3359. ** sqlite3_value object but no mutex is held for an unprotected
  3360. ** sqlite3_value object. If SQLite is compiled to be single-threaded
  3361. ** (with [SQLITE_THREADSAFE=0] and with [sqlite3_threadsafe()] returning 0)
  3362. ** or if SQLite is run in one of reduced mutex modes
  3363. ** [SQLITE_CONFIG_SINGLETHREAD] or [SQLITE_CONFIG_MULTITHREAD]
  3364. ** then there is no distinction between protected and unprotected
  3365. ** sqlite3_value objects and they can be used interchangeably. However,
  3366. ** for maximum code portability it is recommended that applications
  3367. ** still make the distinction between protected and unprotected
  3368. ** sqlite3_value objects even when not strictly required.
  3369. **
  3370. ** ^The sqlite3_value objects that are passed as parameters into the
  3371. ** implementation of [application-defined SQL functions] are protected.
  3372. ** ^The sqlite3_value object returned by
  3373. ** [sqlite3_column_value()] is unprotected.
  3374. ** Unprotected sqlite3_value objects may only be used with
  3375. ** [sqlite3_result_value()] and [sqlite3_bind_value()].
  3376. ** The [sqlite3_value_blob | sqlite3_value_type()] family of
  3377. ** interfaces require protected sqlite3_value objects.
  3378. */
  3379. typedef struct Mem sqlite3_value;
  3380. /*
  3381. ** CAPI3REF: SQL Function Context Object
  3382. **
  3383. ** The context in which an SQL function executes is stored in an
  3384. ** sqlite3_context object. ^A pointer to an sqlite3_context object
  3385. ** is always first parameter to [application-defined SQL functions].
  3386. ** The application-defined SQL function implementation will pass this
  3387. ** pointer through into calls to [sqlite3_result_int | sqlite3_result()],
  3388. ** [sqlite3_aggregate_context()], [sqlite3_user_data()],
  3389. ** [sqlite3_context_db_handle()], [sqlite3_get_auxdata()],
  3390. ** and/or [sqlite3_set_auxdata()].
  3391. */
  3392. typedef struct sqlite3_context sqlite3_context;
  3393. /*
  3394. ** CAPI3REF: Binding Values To Prepared Statements
  3395. ** KEYWORDS: {host parameter} {host parameters} {host parameter name}
  3396. ** KEYWORDS: {SQL parameter} {SQL parameters} {parameter binding}
  3397. **
  3398. ** ^(In the SQL statement text input to [sqlite3_prepare_v2()] and its variants,
  3399. ** literals may be replaced by a [parameter] that matches one of following
  3400. ** templates:
  3401. **
  3402. ** <ul>
  3403. ** <li> ?
  3404. ** <li> ?NNN
  3405. ** <li> :VVV
  3406. ** <li> @VVV
  3407. ** <li> $VVV
  3408. ** </ul>
  3409. **
  3410. ** In the templates above, NNN represents an integer literal,
  3411. ** and VVV represents an alphanumeric identifier.)^ ^The values of these
  3412. ** parameters (also called "host parameter names" or "SQL parameters")
  3413. ** can be set using the sqlite3_bind_*() routines defined here.
  3414. **
  3415. ** ^The first argument to the sqlite3_bind_*() routines is always
  3416. ** a pointer to the [sqlite3_stmt] object returned from
  3417. ** [sqlite3_prepare_v2()] or its variants.
  3418. **
  3419. ** ^The second argument is the index of the SQL parameter to be set.
  3420. ** ^The leftmost SQL parameter has an index of 1. ^When the same named
  3421. ** SQL parameter is used more than once, second and subsequent
  3422. ** occurrences have the same index as the first occurrence.
  3423. ** ^The index for named parameters can be looked up using the
  3424. ** [sqlite3_bind_parameter_index()] API if desired. ^The index
  3425. ** for "?NNN" parameters is the value of NNN.
  3426. ** ^The NNN value must be between 1 and the [sqlite3_limit()]
  3427. ** parameter [SQLITE_LIMIT_VARIABLE_NUMBER] (default value: 999).
  3428. **
  3429. ** ^The third argument is the value to bind to the parameter.
  3430. ** ^If the third parameter to sqlite3_bind_text() or sqlite3_bind_text16()
  3431. ** or sqlite3_bind_blob() is a NULL pointer then the fourth parameter
  3432. ** is ignored and the end result is the same as sqlite3_bind_null().
  3433. **
  3434. ** ^(In those routines that have a fourth argument, its value is the
  3435. ** number of bytes in the parameter. To be clear: the value is the
  3436. ** number of <u>bytes</u> in the value, not the number of characters.)^
  3437. ** ^If the fourth parameter to sqlite3_bind_text() or sqlite3_bind_text16()
  3438. ** is negative, then the length of the string is
  3439. ** the number of bytes up to the first zero terminator.
  3440. ** If the fourth parameter to sqlite3_bind_blob() is negative, then
  3441. ** the behavior is undefined.
  3442. ** If a non-negative fourth parameter is provided to sqlite3_bind_text()
  3443. ** or sqlite3_bind_text16() or sqlite3_bind_text64() then
  3444. ** that parameter must be the byte offset
  3445. ** where the NUL terminator would occur assuming the string were NUL
  3446. ** terminated. If any NUL characters occur at byte offsets less than
  3447. ** the value of the fourth parameter then the resulting string value will
  3448. ** contain embedded NULs. The result of expressions involving strings
  3449. ** with embedded NULs is undefined.
  3450. **
  3451. ** ^The fifth argument to the BLOB and string binding interfaces
  3452. ** is a destructor used to dispose of the BLOB or
  3453. ** string after SQLite has finished with it. ^The destructor is called
  3454. ** to dispose of the BLOB or string even if the call to bind API fails.
  3455. ** ^If the fifth argument is
  3456. ** the special value [SQLITE_STATIC], then SQLite assumes that the
  3457. ** information is in static, unmanaged space and does not need to be freed.
  3458. ** ^If the fifth argument has the value [SQLITE_TRANSIENT], then
  3459. ** SQLite makes its own private copy of the data immediately, before
  3460. ** the sqlite3_bind_*() routine returns.
  3461. **
  3462. ** ^The sixth argument to sqlite3_bind_text64() must be one of
  3463. ** [SQLITE_UTF8], [SQLITE_UTF16], [SQLITE_UTF16BE], or [SQLITE_UTF16LE]
  3464. ** to specify the encoding of the text in the third parameter. If
  3465. ** the sixth argument to sqlite3_bind_text64() is not one of the
  3466. ** allowed values shown above, or if the text encoding is different
  3467. ** from the encoding specified by the sixth parameter, then the behavior
  3468. ** is undefined.
  3469. **
  3470. ** ^The sqlite3_bind_zeroblob() routine binds a BLOB of length N that
  3471. ** is filled with zeroes. ^A zeroblob uses a fixed amount of memory
  3472. ** (just an integer to hold its size) while it is being processed.
  3473. ** Zeroblobs are intended to serve as placeholders for BLOBs whose
  3474. ** content is later written using
  3475. ** [sqlite3_blob_open | incremental BLOB I/O] routines.
  3476. ** ^A negative value for the zeroblob results in a zero-length BLOB.
  3477. **
  3478. ** ^If any of the sqlite3_bind_*() routines are called with a NULL pointer
  3479. ** for the [prepared statement] or with a prepared statement for which
  3480. ** [sqlite3_step()] has been called more recently than [sqlite3_reset()],
  3481. ** then the call will return [SQLITE_MISUSE]. If any sqlite3_bind_()
  3482. ** routine is passed a [prepared statement] that has been finalized, the
  3483. ** result is undefined and probably harmful.
  3484. **
  3485. ** ^Bindings are not cleared by the [sqlite3_reset()] routine.
  3486. ** ^Unbound parameters are interpreted as NULL.
  3487. **
  3488. ** ^The sqlite3_bind_* routines return [SQLITE_OK] on success or an
  3489. ** [error code] if anything goes wrong.
  3490. ** ^[SQLITE_TOOBIG] might be returned if the size of a string or BLOB
  3491. ** exceeds limits imposed by [sqlite3_limit]([SQLITE_LIMIT_LENGTH]) or
  3492. ** [SQLITE_MAX_LENGTH].
  3493. ** ^[SQLITE_RANGE] is returned if the parameter
  3494. ** index is out of range. ^[SQLITE_NOMEM] is returned if malloc() fails.
  3495. **
  3496. ** See also: [sqlite3_bind_parameter_count()],
  3497. ** [sqlite3_bind_parameter_name()], and [sqlite3_bind_parameter_index()].
  3498. */
  3499. SQLITE_API int sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*));
  3500. SQLITE_API int sqlite3_bind_blob64(sqlite3_stmt*, int, const void*, sqlite3_uint64,
  3501. void(*)(void*));
  3502. SQLITE_API int sqlite3_bind_double(sqlite3_stmt*, int, double);
  3503. SQLITE_API int sqlite3_bind_int(sqlite3_stmt*, int, int);
  3504. SQLITE_API int sqlite3_bind_int64(sqlite3_stmt*, int, sqlite3_int64);
  3505. SQLITE_API int sqlite3_bind_null(sqlite3_stmt*, int);
  3506. SQLITE_API int sqlite3_bind_text(sqlite3_stmt*,int,const char*,int,void(*)(void*));
  3507. SQLITE_API int sqlite3_bind_text16(sqlite3_stmt*, int, const void*, int, void(*)(void*));
  3508. SQLITE_API int sqlite3_bind_text64(sqlite3_stmt*, int, const char*, sqlite3_uint64,
  3509. void(*)(void*), unsigned char encoding);
  3510. SQLITE_API int sqlite3_bind_value(sqlite3_stmt*, int, const sqlite3_value*);
  3511. SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt*, int, int n);
  3512. /*
  3513. ** CAPI3REF: Number Of SQL Parameters
  3514. **
  3515. ** ^This routine can be used to find the number of [SQL parameters]
  3516. ** in a [prepared statement]. SQL parameters are tokens of the
  3517. ** form "?", "?NNN", ":AAA", "$AAA", or "@AAA" that serve as
  3518. ** placeholders for values that are [sqlite3_bind_blob | bound]
  3519. ** to the parameters at a later time.
  3520. **
  3521. ** ^(This routine actually returns the index of the largest (rightmost)
  3522. ** parameter. For all forms except ?NNN, this will correspond to the
  3523. ** number of unique parameters. If parameters of the ?NNN form are used,
  3524. ** there may be gaps in the list.)^
  3525. **
  3526. ** See also: [sqlite3_bind_blob|sqlite3_bind()],
  3527. ** [sqlite3_bind_parameter_name()], and
  3528. ** [sqlite3_bind_parameter_index()].
  3529. */
  3530. SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt*);
  3531. /*
  3532. ** CAPI3REF: Name Of A Host Parameter
  3533. **
  3534. ** ^The sqlite3_bind_parameter_name(P,N) interface returns
  3535. ** the name of the N-th [SQL parameter] in the [prepared statement] P.
  3536. ** ^(SQL parameters of the form "?NNN" or ":AAA" or "@AAA" or "$AAA"
  3537. ** have a name which is the string "?NNN" or ":AAA" or "@AAA" or "$AAA"
  3538. ** respectively.
  3539. ** In other words, the initial ":" or "$" or "@" or "?"
  3540. ** is included as part of the name.)^
  3541. ** ^Parameters of the form "?" without a following integer have no name
  3542. ** and are referred to as "nameless" or "anonymous parameters".
  3543. **
  3544. ** ^The first host parameter has an index of 1, not 0.
  3545. **
  3546. ** ^If the value N is out of range or if the N-th parameter is
  3547. ** nameless, then NULL is returned. ^The returned string is
  3548. ** always in UTF-8 encoding even if the named parameter was
  3549. ** originally specified as UTF-16 in [sqlite3_prepare16()] or
  3550. ** [sqlite3_prepare16_v2()].
  3551. **
  3552. ** See also: [sqlite3_bind_blob|sqlite3_bind()],
  3553. ** [sqlite3_bind_parameter_count()], and
  3554. ** [sqlite3_bind_parameter_index()].
  3555. */
  3556. SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt*, int);
  3557. /*
  3558. ** CAPI3REF: Index Of A Parameter With A Given Name
  3559. **
  3560. ** ^Return the index of an SQL parameter given its name. ^The
  3561. ** index value returned is suitable for use as the second
  3562. ** parameter to [sqlite3_bind_blob|sqlite3_bind()]. ^A zero
  3563. ** is returned if no matching parameter is found. ^The parameter
  3564. ** name must be given in UTF-8 even if the original statement
  3565. ** was prepared from UTF-16 text using [sqlite3_prepare16_v2()].
  3566. **
  3567. ** See also: [sqlite3_bind_blob|sqlite3_bind()],
  3568. ** [sqlite3_bind_parameter_count()], and
  3569. ** [sqlite3_bind_parameter_index()].
  3570. */
  3571. SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName);
  3572. /*
  3573. ** CAPI3REF: Reset All Bindings On A Prepared Statement
  3574. **
  3575. ** ^Contrary to the intuition of many, [sqlite3_reset()] does not reset
  3576. ** the [sqlite3_bind_blob | bindings] on a [prepared statement].
  3577. ** ^Use this routine to reset all host parameters to NULL.
  3578. */
  3579. SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt*);
  3580. /*
  3581. ** CAPI3REF: Number Of Columns In A Result Set
  3582. **
  3583. ** ^Return the number of columns in the result set returned by the
  3584. ** [prepared statement]. ^This routine returns 0 if pStmt is an SQL
  3585. ** statement that does not return data (for example an [UPDATE]).
  3586. **
  3587. ** See also: [sqlite3_data_count()]
  3588. */
  3589. SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt);
  3590. /*
  3591. ** CAPI3REF: Column Names In A Result Set
  3592. **
  3593. ** ^These routines return the name assigned to a particular column
  3594. ** in the result set of a [SELECT] statement. ^The sqlite3_column_name()
  3595. ** interface returns a pointer to a zero-terminated UTF-8 string
  3596. ** and sqlite3_column_name16() returns a pointer to a zero-terminated
  3597. ** UTF-16 string. ^The first parameter is the [prepared statement]
  3598. ** that implements the [SELECT] statement. ^The second parameter is the
  3599. ** column number. ^The leftmost column is number 0.
  3600. **
  3601. ** ^The returned string pointer is valid until either the [prepared statement]
  3602. ** is destroyed by [sqlite3_finalize()] or until the statement is automatically
  3603. ** reprepared by the first call to [sqlite3_step()] for a particular run
  3604. ** or until the next call to
  3605. ** sqlite3_column_name() or sqlite3_column_name16() on the same column.
  3606. **
  3607. ** ^If sqlite3_malloc() fails during the processing of either routine
  3608. ** (for example during a conversion from UTF-8 to UTF-16) then a
  3609. ** NULL pointer is returned.
  3610. **
  3611. ** ^The name of a result column is the value of the "AS" clause for
  3612. ** that column, if there is an AS clause. If there is no AS clause
  3613. ** then the name of the column is unspecified and may change from
  3614. ** one release of SQLite to the next.
  3615. */
  3616. SQLITE_API const char *sqlite3_column_name(sqlite3_stmt*, int N);
  3617. SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt*, int N);
  3618. /*
  3619. ** CAPI3REF: Source Of Data In A Query Result
  3620. **
  3621. ** ^These routines provide a means to determine the database, table, and
  3622. ** table column that is the origin of a particular result column in
  3623. ** [SELECT] statement.
  3624. ** ^The name of the database or table or column can be returned as
  3625. ** either a UTF-8 or UTF-16 string. ^The _database_ routines return
  3626. ** the database name, the _table_ routines return the table name, and
  3627. ** the origin_ routines return the column name.
  3628. ** ^The returned string is valid until the [prepared statement] is destroyed
  3629. ** using [sqlite3_finalize()] or until the statement is automatically
  3630. ** reprepared by the first call to [sqlite3_step()] for a particular run
  3631. ** or until the same information is requested
  3632. ** again in a different encoding.
  3633. **
  3634. ** ^The names returned are the original un-aliased names of the
  3635. ** database, table, and column.
  3636. **
  3637. ** ^The first argument to these interfaces is a [prepared statement].
  3638. ** ^These functions return information about the Nth result column returned by
  3639. ** the statement, where N is the second function argument.
  3640. ** ^The left-most column is column 0 for these routines.
  3641. **
  3642. ** ^If the Nth column returned by the statement is an expression or
  3643. ** subquery and is not a column value, then all of these functions return
  3644. ** NULL. ^These routine might also return NULL if a memory allocation error
  3645. ** occurs. ^Otherwise, they return the name of the attached database, table,
  3646. ** or column that query result column was extracted from.
  3647. **
  3648. ** ^As with all other SQLite APIs, those whose names end with "16" return
  3649. ** UTF-16 encoded strings and the other functions return UTF-8.
  3650. **
  3651. ** ^These APIs are only available if the library was compiled with the
  3652. ** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol.
  3653. **
  3654. ** If two or more threads call one or more of these routines against the same
  3655. ** prepared statement and column at the same time then the results are
  3656. ** undefined.
  3657. **
  3658. ** If two or more threads call one or more
  3659. ** [sqlite3_column_database_name | column metadata interfaces]
  3660. ** for the same [prepared statement] and result column
  3661. ** at the same time then the results are undefined.
  3662. */
  3663. SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt*,int);
  3664. SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt*,int);
  3665. SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt*,int);
  3666. SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt*,int);
  3667. SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt*,int);
  3668. SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt*,int);
  3669. /*
  3670. ** CAPI3REF: Declared Datatype Of A Query Result
  3671. **
  3672. ** ^(The first parameter is a [prepared statement].
  3673. ** If this statement is a [SELECT] statement and the Nth column of the
  3674. ** returned result set of that [SELECT] is a table column (not an
  3675. ** expression or subquery) then the declared type of the table
  3676. ** column is returned.)^ ^If the Nth column of the result set is an
  3677. ** expression or subquery, then a NULL pointer is returned.
  3678. ** ^The returned string is always UTF-8 encoded.
  3679. **
  3680. ** ^(For example, given the database schema:
  3681. **
  3682. ** CREATE TABLE t1(c1 VARIANT);
  3683. **
  3684. ** and the following statement to be compiled:
  3685. **
  3686. ** SELECT c1 + 1, c1 FROM t1;
  3687. **
  3688. ** this routine would return the string "VARIANT" for the second result
  3689. ** column (i==1), and a NULL pointer for the first result column (i==0).)^
  3690. **
  3691. ** ^SQLite uses dynamic run-time typing. ^So just because a column
  3692. ** is declared to contain a particular type does not mean that the
  3693. ** data stored in that column is of the declared type. SQLite is
  3694. ** strongly typed, but the typing is dynamic not static. ^Type
  3695. ** is associated with individual values, not with the containers
  3696. ** used to hold those values.
  3697. */
  3698. SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt*,int);
  3699. SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt*,int);
  3700. /*
  3701. ** CAPI3REF: Evaluate An SQL Statement
  3702. **
  3703. ** After a [prepared statement] has been prepared using either
  3704. ** [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] or one of the legacy
  3705. ** interfaces [sqlite3_prepare()] or [sqlite3_prepare16()], this function
  3706. ** must be called one or more times to evaluate the statement.
  3707. **
  3708. ** The details of the behavior of the sqlite3_step() interface depend
  3709. ** on whether the statement was prepared using the newer "v2" interface
  3710. ** [sqlite3_prepare_v2()] and [sqlite3_prepare16_v2()] or the older legacy
  3711. ** interface [sqlite3_prepare()] and [sqlite3_prepare16()]. The use of the
  3712. ** new "v2" interface is recommended for new applications but the legacy
  3713. ** interface will continue to be supported.
  3714. **
  3715. ** ^In the legacy interface, the return value will be either [SQLITE_BUSY],
  3716. ** [SQLITE_DONE], [SQLITE_ROW], [SQLITE_ERROR], or [SQLITE_MISUSE].
  3717. ** ^With the "v2" interface, any of the other [result codes] or
  3718. ** [extended result codes] might be returned as well.
  3719. **
  3720. ** ^[SQLITE_BUSY] means that the database engine was unable to acquire the
  3721. ** database locks it needs to do its job. ^If the statement is a [COMMIT]
  3722. ** or occurs outside of an explicit transaction, then you can retry the
  3723. ** statement. If the statement is not a [COMMIT] and occurs within an
  3724. ** explicit transaction then you should rollback the transaction before
  3725. ** continuing.
  3726. **
  3727. ** ^[SQLITE_DONE] means that the statement has finished executing
  3728. ** successfully. sqlite3_step() should not be called again on this virtual
  3729. ** machine without first calling [sqlite3_reset()] to reset the virtual
  3730. ** machine back to its initial state.
  3731. **
  3732. ** ^If the SQL statement being executed returns any data, then [SQLITE_ROW]
  3733. ** is returned each time a new row of data is ready for processing by the
  3734. ** caller. The values may be accessed using the [column access functions].
  3735. ** sqlite3_step() is called again to retrieve the next row of data.
  3736. **
  3737. ** ^[SQLITE_ERROR] means that a run-time error (such as a constraint
  3738. ** violation) has occurred. sqlite3_step() should not be called again on
  3739. ** the VM. More information may be found by calling [sqlite3_errmsg()].
  3740. ** ^With the legacy interface, a more specific error code (for example,
  3741. ** [SQLITE_INTERRUPT], [SQLITE_SCHEMA], [SQLITE_CORRUPT], and so forth)
  3742. ** can be obtained by calling [sqlite3_reset()] on the
  3743. ** [prepared statement]. ^In the "v2" interface,
  3744. ** the more specific error code is returned directly by sqlite3_step().
  3745. **
  3746. ** [SQLITE_MISUSE] means that the this routine was called inappropriately.
  3747. ** Perhaps it was called on a [prepared statement] that has
  3748. ** already been [sqlite3_finalize | finalized] or on one that had
  3749. ** previously returned [SQLITE_ERROR] or [SQLITE_DONE]. Or it could
  3750. ** be the case that the same database connection is being used by two or
  3751. ** more threads at the same moment in time.
  3752. **
  3753. ** For all versions of SQLite up to and including 3.6.23.1, a call to
  3754. ** [sqlite3_reset()] was required after sqlite3_step() returned anything
  3755. ** other than [SQLITE_ROW] before any subsequent invocation of
  3756. ** sqlite3_step(). Failure to reset the prepared statement using
  3757. ** [sqlite3_reset()] would result in an [SQLITE_MISUSE] return from
  3758. ** sqlite3_step(). But after version 3.6.23.1, sqlite3_step() began
  3759. ** calling [sqlite3_reset()] automatically in this circumstance rather
  3760. ** than returning [SQLITE_MISUSE]. This is not considered a compatibility
  3761. ** break because any application that ever receives an SQLITE_MISUSE error
  3762. ** is broken by definition. The [SQLITE_OMIT_AUTORESET] compile-time option
  3763. ** can be used to restore the legacy behavior.
  3764. **
  3765. ** <b>Goofy Interface Alert:</b> In the legacy interface, the sqlite3_step()
  3766. ** API always returns a generic error code, [SQLITE_ERROR], following any
  3767. ** error other than [SQLITE_BUSY] and [SQLITE_MISUSE]. You must call
  3768. ** [sqlite3_reset()] or [sqlite3_finalize()] in order to find one of the
  3769. ** specific [error codes] that better describes the error.
  3770. ** We admit that this is a goofy design. The problem has been fixed
  3771. ** with the "v2" interface. If you prepare all of your SQL statements
  3772. ** using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] instead
  3773. ** of the legacy [sqlite3_prepare()] and [sqlite3_prepare16()] interfaces,
  3774. ** then the more specific [error codes] are returned directly
  3775. ** by sqlite3_step(). The use of the "v2" interface is recommended.
  3776. */
  3777. SQLITE_API int sqlite3_step(sqlite3_stmt*);
  3778. /*
  3779. ** CAPI3REF: Number of columns in a result set
  3780. **
  3781. ** ^The sqlite3_data_count(P) interface returns the number of columns in the
  3782. ** current row of the result set of [prepared statement] P.
  3783. ** ^If prepared statement P does not have results ready to return
  3784. ** (via calls to the [sqlite3_column_int | sqlite3_column_*()] of
  3785. ** interfaces) then sqlite3_data_count(P) returns 0.
  3786. ** ^The sqlite3_data_count(P) routine also returns 0 if P is a NULL pointer.
  3787. ** ^The sqlite3_data_count(P) routine returns 0 if the previous call to
  3788. ** [sqlite3_step](P) returned [SQLITE_DONE]. ^The sqlite3_data_count(P)
  3789. ** will return non-zero if previous call to [sqlite3_step](P) returned
  3790. ** [SQLITE_ROW], except in the case of the [PRAGMA incremental_vacuum]
  3791. ** where it always returns zero since each step of that multi-step
  3792. ** pragma returns 0 columns of data.
  3793. **
  3794. ** See also: [sqlite3_column_count()]
  3795. */
  3796. SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt);
  3797. /*
  3798. ** CAPI3REF: Fundamental Datatypes
  3799. ** KEYWORDS: SQLITE_TEXT
  3800. **
  3801. ** ^(Every value in SQLite has one of five fundamental datatypes:
  3802. **
  3803. ** <ul>
  3804. ** <li> 64-bit signed integer
  3805. ** <li> 64-bit IEEE floating point number
  3806. ** <li> string
  3807. ** <li> BLOB
  3808. ** <li> NULL
  3809. ** </ul>)^
  3810. **
  3811. ** These constants are codes for each of those types.
  3812. **
  3813. ** Note that the SQLITE_TEXT constant was also used in SQLite version 2
  3814. ** for a completely different meaning. Software that links against both
  3815. ** SQLite version 2 and SQLite version 3 should use SQLITE3_TEXT, not
  3816. ** SQLITE_TEXT.
  3817. */
  3818. #define SQLITE_INTEGER 1
  3819. #define SQLITE_FLOAT 2
  3820. #define SQLITE_BLOB 4
  3821. #define SQLITE_NULL 5
  3822. #ifdef SQLITE_TEXT
  3823. # undef SQLITE_TEXT
  3824. #else
  3825. # define SQLITE_TEXT 3
  3826. #endif
  3827. #define SQLITE3_TEXT 3
  3828. /*
  3829. ** CAPI3REF: Result Values From A Query
  3830. ** KEYWORDS: {column access functions}
  3831. **
  3832. ** These routines form the "result set" interface.
  3833. **
  3834. ** ^These routines return information about a single column of the current
  3835. ** result row of a query. ^In every case the first argument is a pointer
  3836. ** to the [prepared statement] that is being evaluated (the [sqlite3_stmt*]
  3837. ** that was returned from [sqlite3_prepare_v2()] or one of its variants)
  3838. ** and the second argument is the index of the column for which information
  3839. ** should be returned. ^The leftmost column of the result set has the index 0.
  3840. ** ^The number of columns in the result can be determined using
  3841. ** [sqlite3_column_count()].
  3842. **
  3843. ** If the SQL statement does not currently point to a valid row, or if the
  3844. ** column index is out of range, the result is undefined.
  3845. ** These routines may only be called when the most recent call to
  3846. ** [sqlite3_step()] has returned [SQLITE_ROW] and neither
  3847. ** [sqlite3_reset()] nor [sqlite3_finalize()] have been called subsequently.
  3848. ** If any of these routines are called after [sqlite3_reset()] or
  3849. ** [sqlite3_finalize()] or after [sqlite3_step()] has returned
  3850. ** something other than [SQLITE_ROW], the results are undefined.
  3851. ** If [sqlite3_step()] or [sqlite3_reset()] or [sqlite3_finalize()]
  3852. ** are called from a different thread while any of these routines
  3853. ** are pending, then the results are undefined.
  3854. **
  3855. ** ^The sqlite3_column_type() routine returns the
  3856. ** [SQLITE_INTEGER | datatype code] for the initial data type
  3857. ** of the result column. ^The returned value is one of [SQLITE_INTEGER],
  3858. ** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL]. The value
  3859. ** returned by sqlite3_column_type() is only meaningful if no type
  3860. ** conversions have occurred as described below. After a type conversion,
  3861. ** the value returned by sqlite3_column_type() is undefined. Future
  3862. ** versions of SQLite may change the behavior of sqlite3_column_type()
  3863. ** following a type conversion.
  3864. **
  3865. ** ^If the result is a BLOB or UTF-8 string then the sqlite3_column_bytes()
  3866. ** routine returns the number of bytes in that BLOB or string.
  3867. ** ^If the result is a UTF-16 string, then sqlite3_column_bytes() converts
  3868. ** the string to UTF-8 and then returns the number of bytes.
  3869. ** ^If the result is a numeric value then sqlite3_column_bytes() uses
  3870. ** [sqlite3_snprintf()] to convert that value to a UTF-8 string and returns
  3871. ** the number of bytes in that string.
  3872. ** ^If the result is NULL, then sqlite3_column_bytes() returns zero.
  3873. **
  3874. ** ^If the result is a BLOB or UTF-16 string then the sqlite3_column_bytes16()
  3875. ** routine returns the number of bytes in that BLOB or string.
  3876. ** ^If the result is a UTF-8 string, then sqlite3_column_bytes16() converts
  3877. ** the string to UTF-16 and then returns the number of bytes.
  3878. ** ^If the result is a numeric value then sqlite3_column_bytes16() uses
  3879. ** [sqlite3_snprintf()] to convert that value to a UTF-16 string and returns
  3880. ** the number of bytes in that string.
  3881. ** ^If the result is NULL, then sqlite3_column_bytes16() returns zero.
  3882. **
  3883. ** ^The values returned by [sqlite3_column_bytes()] and
  3884. ** [sqlite3_column_bytes16()] do not include the zero terminators at the end
  3885. ** of the string. ^For clarity: the values returned by
  3886. ** [sqlite3_column_bytes()] and [sqlite3_column_bytes16()] are the number of
  3887. ** bytes in the string, not the number of characters.
  3888. **
  3889. ** ^Strings returned by sqlite3_column_text() and sqlite3_column_text16(),
  3890. ** even empty strings, are always zero-terminated. ^The return
  3891. ** value from sqlite3_column_blob() for a zero-length BLOB is a NULL pointer.
  3892. **
  3893. ** ^The object returned by [sqlite3_column_value()] is an
  3894. ** [unprotected sqlite3_value] object. An unprotected sqlite3_value object
  3895. ** may only be used with [sqlite3_bind_value()] and [sqlite3_result_value()].
  3896. ** If the [unprotected sqlite3_value] object returned by
  3897. ** [sqlite3_column_value()] is used in any other way, including calls
  3898. ** to routines like [sqlite3_value_int()], [sqlite3_value_text()],
  3899. ** or [sqlite3_value_bytes()], then the behavior is undefined.
  3900. **
  3901. ** These routines attempt to convert the value where appropriate. ^For
  3902. ** example, if the internal representation is FLOAT and a text result
  3903. ** is requested, [sqlite3_snprintf()] is used internally to perform the
  3904. ** conversion automatically. ^(The following table details the conversions
  3905. ** that are applied:
  3906. **
  3907. ** <blockquote>
  3908. ** <table border="1">
  3909. ** <tr><th> Internal<br>Type <th> Requested<br>Type <th> Conversion
  3910. **
  3911. ** <tr><td> NULL <td> INTEGER <td> Result is 0
  3912. ** <tr><td> NULL <td> FLOAT <td> Result is 0.0
  3913. ** <tr><td> NULL <td> TEXT <td> Result is a NULL pointer
  3914. ** <tr><td> NULL <td> BLOB <td> Result is a NULL pointer
  3915. ** <tr><td> INTEGER <td> FLOAT <td> Convert from integer to float
  3916. ** <tr><td> INTEGER <td> TEXT <td> ASCII rendering of the integer
  3917. ** <tr><td> INTEGER <td> BLOB <td> Same as INTEGER->TEXT
  3918. ** <tr><td> FLOAT <td> INTEGER <td> [CAST] to INTEGER
  3919. ** <tr><td> FLOAT <td> TEXT <td> ASCII rendering of the float
  3920. ** <tr><td> FLOAT <td> BLOB <td> [CAST] to BLOB
  3921. ** <tr><td> TEXT <td> INTEGER <td> [CAST] to INTEGER
  3922. ** <tr><td> TEXT <td> FLOAT <td> [CAST] to REAL
  3923. ** <tr><td> TEXT <td> BLOB <td> No change
  3924. ** <tr><td> BLOB <td> INTEGER <td> [CAST] to INTEGER
  3925. ** <tr><td> BLOB <td> FLOAT <td> [CAST] to REAL
  3926. ** <tr><td> BLOB <td> TEXT <td> Add a zero terminator if needed
  3927. ** </table>
  3928. ** </blockquote>)^
  3929. **
  3930. ** The table above makes reference to standard C library functions atoi()
  3931. ** and atof(). SQLite does not really use these functions. It has its
  3932. ** own equivalent internal routines. The atoi() and atof() names are
  3933. ** used in the table for brevity and because they are familiar to most
  3934. ** C programmers.
  3935. **
  3936. ** Note that when type conversions occur, pointers returned by prior
  3937. ** calls to sqlite3_column_blob(), sqlite3_column_text(), and/or
  3938. ** sqlite3_column_text16() may be invalidated.
  3939. ** Type conversions and pointer invalidations might occur
  3940. ** in the following cases:
  3941. **
  3942. ** <ul>
  3943. ** <li> The initial content is a BLOB and sqlite3_column_text() or
  3944. ** sqlite3_column_text16() is called. A zero-terminator might
  3945. ** need to be added to the string.</li>
  3946. ** <li> The initial content is UTF-8 text and sqlite3_column_bytes16() or
  3947. ** sqlite3_column_text16() is called. The content must be converted
  3948. ** to UTF-16.</li>
  3949. ** <li> The initial content is UTF-16 text and sqlite3_column_bytes() or
  3950. ** sqlite3_column_text() is called. The content must be converted
  3951. ** to UTF-8.</li>
  3952. ** </ul>
  3953. **
  3954. ** ^Conversions between UTF-16be and UTF-16le are always done in place and do
  3955. ** not invalidate a prior pointer, though of course the content of the buffer
  3956. ** that the prior pointer references will have been modified. Other kinds
  3957. ** of conversion are done in place when it is possible, but sometimes they
  3958. ** are not possible and in those cases prior pointers are invalidated.
  3959. **
  3960. ** The safest and easiest to remember policy is to invoke these routines
  3961. ** in one of the following ways:
  3962. **
  3963. ** <ul>
  3964. ** <li>sqlite3_column_text() followed by sqlite3_column_bytes()</li>
  3965. ** <li>sqlite3_column_blob() followed by sqlite3_column_bytes()</li>
  3966. ** <li>sqlite3_column_text16() followed by sqlite3_column_bytes16()</li>
  3967. ** </ul>
  3968. **
  3969. ** In other words, you should call sqlite3_column_text(),
  3970. ** sqlite3_column_blob(), or sqlite3_column_text16() first to force the result
  3971. ** into the desired format, then invoke sqlite3_column_bytes() or
  3972. ** sqlite3_column_bytes16() to find the size of the result. Do not mix calls
  3973. ** to sqlite3_column_text() or sqlite3_column_blob() with calls to
  3974. ** sqlite3_column_bytes16(), and do not mix calls to sqlite3_column_text16()
  3975. ** with calls to sqlite3_column_bytes().
  3976. **
  3977. ** ^The pointers returned are valid until a type conversion occurs as
  3978. ** described above, or until [sqlite3_step()] or [sqlite3_reset()] or
  3979. ** [sqlite3_finalize()] is called. ^The memory space used to hold strings
  3980. ** and BLOBs is freed automatically. Do <b>not</b> pass the pointers returned
  3981. ** from [sqlite3_column_blob()], [sqlite3_column_text()], etc. into
  3982. ** [sqlite3_free()].
  3983. **
  3984. ** ^(If a memory allocation error occurs during the evaluation of any
  3985. ** of these routines, a default value is returned. The default value
  3986. ** is either the integer 0, the floating point number 0.0, or a NULL
  3987. ** pointer. Subsequent calls to [sqlite3_errcode()] will return
  3988. ** [SQLITE_NOMEM].)^
  3989. */
  3990. SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt*, int iCol);
  3991. SQLITE_API int sqlite3_column_bytes(sqlite3_stmt*, int iCol);
  3992. SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt*, int iCol);
  3993. SQLITE_API double sqlite3_column_double(sqlite3_stmt*, int iCol);
  3994. SQLITE_API int sqlite3_column_int(sqlite3_stmt*, int iCol);
  3995. SQLITE_API sqlite3_int64 sqlite3_column_int64(sqlite3_stmt*, int iCol);
  3996. SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt*, int iCol);
  3997. SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt*, int iCol);
  3998. SQLITE_API int sqlite3_column_type(sqlite3_stmt*, int iCol);
  3999. SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt*, int iCol);
  4000. /*
  4001. ** CAPI3REF: Destroy A Prepared Statement Object
  4002. **
  4003. ** ^The sqlite3_finalize() function is called to delete a [prepared statement].
  4004. ** ^If the most recent evaluation of the statement encountered no errors
  4005. ** or if the statement is never been evaluated, then sqlite3_finalize() returns
  4006. ** SQLITE_OK. ^If the most recent evaluation of statement S failed, then
  4007. ** sqlite3_finalize(S) returns the appropriate [error code] or
  4008. ** [extended error code].
  4009. **
  4010. ** ^The sqlite3_finalize(S) routine can be called at any point during
  4011. ** the life cycle of [prepared statement] S:
  4012. ** before statement S is ever evaluated, after
  4013. ** one or more calls to [sqlite3_reset()], or after any call
  4014. ** to [sqlite3_step()] regardless of whether or not the statement has
  4015. ** completed execution.
  4016. **
  4017. ** ^Invoking sqlite3_finalize() on a NULL pointer is a harmless no-op.
  4018. **
  4019. ** The application must finalize every [prepared statement] in order to avoid
  4020. ** resource leaks. It is a grievous error for the application to try to use
  4021. ** a prepared statement after it has been finalized. Any use of a prepared
  4022. ** statement after it has been finalized can result in undefined and
  4023. ** undesirable behavior such as segfaults and heap corruption.
  4024. */
  4025. SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt);
  4026. /*
  4027. ** CAPI3REF: Reset A Prepared Statement Object
  4028. **
  4029. ** The sqlite3_reset() function is called to reset a [prepared statement]
  4030. ** object back to its initial state, ready to be re-executed.
  4031. ** ^Any SQL statement variables that had values bound to them using
  4032. ** the [sqlite3_bind_blob | sqlite3_bind_*() API] retain their values.
  4033. ** Use [sqlite3_clear_bindings()] to reset the bindings.
  4034. **
  4035. ** ^The [sqlite3_reset(S)] interface resets the [prepared statement] S
  4036. ** back to the beginning of its program.
  4037. **
  4038. ** ^If the most recent call to [sqlite3_step(S)] for the
  4039. ** [prepared statement] S returned [SQLITE_ROW] or [SQLITE_DONE],
  4040. ** or if [sqlite3_step(S)] has never before been called on S,
  4041. ** then [sqlite3_reset(S)] returns [SQLITE_OK].
  4042. **
  4043. ** ^If the most recent call to [sqlite3_step(S)] for the
  4044. ** [prepared statement] S indicated an error, then
  4045. ** [sqlite3_reset(S)] returns an appropriate [error code].
  4046. **
  4047. ** ^The [sqlite3_reset(S)] interface does not change the values
  4048. ** of any [sqlite3_bind_blob|bindings] on the [prepared statement] S.
  4049. */
  4050. SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt);
  4051. /*
  4052. ** CAPI3REF: Create Or Redefine SQL Functions
  4053. ** KEYWORDS: {function creation routines}
  4054. ** KEYWORDS: {application-defined SQL function}
  4055. ** KEYWORDS: {application-defined SQL functions}
  4056. **
  4057. ** ^These functions (collectively known as "function creation routines")
  4058. ** are used to add SQL functions or aggregates or to redefine the behavior
  4059. ** of existing SQL functions or aggregates. The only differences between
  4060. ** these routines are the text encoding expected for
  4061. ** the second parameter (the name of the function being created)
  4062. ** and the presence or absence of a destructor callback for
  4063. ** the application data pointer.
  4064. **
  4065. ** ^The first parameter is the [database connection] to which the SQL
  4066. ** function is to be added. ^If an application uses more than one database
  4067. ** connection then application-defined SQL functions must be added
  4068. ** to each database connection separately.
  4069. **
  4070. ** ^The second parameter is the name of the SQL function to be created or
  4071. ** redefined. ^The length of the name is limited to 255 bytes in a UTF-8
  4072. ** representation, exclusive of the zero-terminator. ^Note that the name
  4073. ** length limit is in UTF-8 bytes, not characters nor UTF-16 bytes.
  4074. ** ^Any attempt to create a function with a longer name
  4075. ** will result in [SQLITE_MISUSE] being returned.
  4076. **
  4077. ** ^The third parameter (nArg)
  4078. ** is the number of arguments that the SQL function or
  4079. ** aggregate takes. ^If this parameter is -1, then the SQL function or
  4080. ** aggregate may take any number of arguments between 0 and the limit
  4081. ** set by [sqlite3_limit]([SQLITE_LIMIT_FUNCTION_ARG]). If the third
  4082. ** parameter is less than -1 or greater than 127 then the behavior is
  4083. ** undefined.
  4084. **
  4085. ** ^The fourth parameter, eTextRep, specifies what
  4086. ** [SQLITE_UTF8 | text encoding] this SQL function prefers for
  4087. ** its parameters. The application should set this parameter to
  4088. ** [SQLITE_UTF16LE] if the function implementation invokes
  4089. ** [sqlite3_value_text16le()] on an input, or [SQLITE_UTF16BE] if the
  4090. ** implementation invokes [sqlite3_value_text16be()] on an input, or
  4091. ** [SQLITE_UTF16] if [sqlite3_value_text16()] is used, or [SQLITE_UTF8]
  4092. ** otherwise. ^The same SQL function may be registered multiple times using
  4093. ** different preferred text encodings, with different implementations for
  4094. ** each encoding.
  4095. ** ^When multiple implementations of the same function are available, SQLite
  4096. ** will pick the one that involves the least amount of data conversion.
  4097. **
  4098. ** ^The fourth parameter may optionally be ORed with [SQLITE_DETERMINISTIC]
  4099. ** to signal that the function will always return the same result given
  4100. ** the same inputs within a single SQL statement. Most SQL functions are
  4101. ** deterministic. The built-in [random()] SQL function is an example of a
  4102. ** function that is not deterministic. The SQLite query planner is able to
  4103. ** perform additional optimizations on deterministic functions, so use
  4104. ** of the [SQLITE_DETERMINISTIC] flag is recommended where possible.
  4105. **
  4106. ** ^(The fifth parameter is an arbitrary pointer. The implementation of the
  4107. ** function can gain access to this pointer using [sqlite3_user_data()].)^
  4108. **
  4109. ** ^The sixth, seventh and eighth parameters, xFunc, xStep and xFinal, are
  4110. ** pointers to C-language functions that implement the SQL function or
  4111. ** aggregate. ^A scalar SQL function requires an implementation of the xFunc
  4112. ** callback only; NULL pointers must be passed as the xStep and xFinal
  4113. ** parameters. ^An aggregate SQL function requires an implementation of xStep
  4114. ** and xFinal and NULL pointer must be passed for xFunc. ^To delete an existing
  4115. ** SQL function or aggregate, pass NULL pointers for all three function
  4116. ** callbacks.
  4117. **
  4118. ** ^(If the ninth parameter to sqlite3_create_function_v2() is not NULL,
  4119. ** then it is destructor for the application data pointer.
  4120. ** The destructor is invoked when the function is deleted, either by being
  4121. ** overloaded or when the database connection closes.)^
  4122. ** ^The destructor is also invoked if the call to
  4123. ** sqlite3_create_function_v2() fails.
  4124. ** ^When the destructor callback of the tenth parameter is invoked, it
  4125. ** is passed a single argument which is a copy of the application data
  4126. ** pointer which was the fifth parameter to sqlite3_create_function_v2().
  4127. **
  4128. ** ^It is permitted to register multiple implementations of the same
  4129. ** functions with the same name but with either differing numbers of
  4130. ** arguments or differing preferred text encodings. ^SQLite will use
  4131. ** the implementation that most closely matches the way in which the
  4132. ** SQL function is used. ^A function implementation with a non-negative
  4133. ** nArg parameter is a better match than a function implementation with
  4134. ** a negative nArg. ^A function where the preferred text encoding
  4135. ** matches the database encoding is a better
  4136. ** match than a function where the encoding is different.
  4137. ** ^A function where the encoding difference is between UTF16le and UTF16be
  4138. ** is a closer match than a function where the encoding difference is
  4139. ** between UTF8 and UTF16.
  4140. **
  4141. ** ^Built-in functions may be overloaded by new application-defined functions.
  4142. **
  4143. ** ^An application-defined function is permitted to call other
  4144. ** SQLite interfaces. However, such calls must not
  4145. ** close the database connection nor finalize or reset the prepared
  4146. ** statement in which the function is running.
  4147. */
  4148. SQLITE_API int sqlite3_create_function(
  4149. sqlite3 *db,
  4150. const char *zFunctionName,
  4151. int nArg,
  4152. int eTextRep,
  4153. void *pApp,
  4154. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  4155. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  4156. void (*xFinal)(sqlite3_context*)
  4157. );
  4158. SQLITE_API int sqlite3_create_function16(
  4159. sqlite3 *db,
  4160. const void *zFunctionName,
  4161. int nArg,
  4162. int eTextRep,
  4163. void *pApp,
  4164. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  4165. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  4166. void (*xFinal)(sqlite3_context*)
  4167. );
  4168. SQLITE_API int sqlite3_create_function_v2(
  4169. sqlite3 *db,
  4170. const char *zFunctionName,
  4171. int nArg,
  4172. int eTextRep,
  4173. void *pApp,
  4174. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  4175. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  4176. void (*xFinal)(sqlite3_context*),
  4177. void(*xDestroy)(void*)
  4178. );
  4179. /*
  4180. ** CAPI3REF: Text Encodings
  4181. **
  4182. ** These constant define integer codes that represent the various
  4183. ** text encodings supported by SQLite.
  4184. */
  4185. #define SQLITE_UTF8 1
  4186. #define SQLITE_UTF16LE 2
  4187. #define SQLITE_UTF16BE 3
  4188. #define SQLITE_UTF16 4 /* Use native byte order */
  4189. #define SQLITE_ANY 5 /* Deprecated */
  4190. #define SQLITE_UTF16_ALIGNED 8 /* sqlite3_create_collation only */
  4191. /*
  4192. ** CAPI3REF: Function Flags
  4193. **
  4194. ** These constants may be ORed together with the
  4195. ** [SQLITE_UTF8 | preferred text encoding] as the fourth argument
  4196. ** to [sqlite3_create_function()], [sqlite3_create_function16()], or
  4197. ** [sqlite3_create_function_v2()].
  4198. */
  4199. #define SQLITE_DETERMINISTIC 0x800
  4200. /*
  4201. ** CAPI3REF: Deprecated Functions
  4202. ** DEPRECATED
  4203. **
  4204. ** These functions are [deprecated]. In order to maintain
  4205. ** backwards compatibility with older code, these functions continue
  4206. ** to be supported. However, new applications should avoid
  4207. ** the use of these functions. To help encourage people to avoid
  4208. ** using these functions, we are not going to tell you what they do.
  4209. */
  4210. #ifndef SQLITE_OMIT_DEPRECATED
  4211. SQLITE_API SQLITE_DEPRECATED int sqlite3_aggregate_count(sqlite3_context*);
  4212. SQLITE_API SQLITE_DEPRECATED int sqlite3_expired(sqlite3_stmt*);
  4213. SQLITE_API SQLITE_DEPRECATED int sqlite3_transfer_bindings(sqlite3_stmt*, sqlite3_stmt*);
  4214. SQLITE_API SQLITE_DEPRECATED int sqlite3_global_recover(void);
  4215. SQLITE_API SQLITE_DEPRECATED void sqlite3_thread_cleanup(void);
  4216. SQLITE_API SQLITE_DEPRECATED int sqlite3_memory_alarm(void(*)(void*,sqlite3_int64,int),
  4217. void*,sqlite3_int64);
  4218. #endif
  4219. /*
  4220. ** CAPI3REF: Obtaining SQL Function Parameter Values
  4221. **
  4222. ** The C-language implementation of SQL functions and aggregates uses
  4223. ** this set of interface routines to access the parameter values on
  4224. ** the function or aggregate.
  4225. **
  4226. ** The xFunc (for scalar functions) or xStep (for aggregates) parameters
  4227. ** to [sqlite3_create_function()] and [sqlite3_create_function16()]
  4228. ** define callbacks that implement the SQL functions and aggregates.
  4229. ** The 3rd parameter to these callbacks is an array of pointers to
  4230. ** [protected sqlite3_value] objects. There is one [sqlite3_value] object for
  4231. ** each parameter to the SQL function. These routines are used to
  4232. ** extract values from the [sqlite3_value] objects.
  4233. **
  4234. ** These routines work only with [protected sqlite3_value] objects.
  4235. ** Any attempt to use these routines on an [unprotected sqlite3_value]
  4236. ** object results in undefined behavior.
  4237. **
  4238. ** ^These routines work just like the corresponding [column access functions]
  4239. ** except that these routines take a single [protected sqlite3_value] object
  4240. ** pointer instead of a [sqlite3_stmt*] pointer and an integer column number.
  4241. **
  4242. ** ^The sqlite3_value_text16() interface extracts a UTF-16 string
  4243. ** in the native byte-order of the host machine. ^The
  4244. ** sqlite3_value_text16be() and sqlite3_value_text16le() interfaces
  4245. ** extract UTF-16 strings as big-endian and little-endian respectively.
  4246. **
  4247. ** ^(The sqlite3_value_numeric_type() interface attempts to apply
  4248. ** numeric affinity to the value. This means that an attempt is
  4249. ** made to convert the value to an integer or floating point. If
  4250. ** such a conversion is possible without loss of information (in other
  4251. ** words, if the value is a string that looks like a number)
  4252. ** then the conversion is performed. Otherwise no conversion occurs.
  4253. ** The [SQLITE_INTEGER | datatype] after conversion is returned.)^
  4254. **
  4255. ** Please pay particular attention to the fact that the pointer returned
  4256. ** from [sqlite3_value_blob()], [sqlite3_value_text()], or
  4257. ** [sqlite3_value_text16()] can be invalidated by a subsequent call to
  4258. ** [sqlite3_value_bytes()], [sqlite3_value_bytes16()], [sqlite3_value_text()],
  4259. ** or [sqlite3_value_text16()].
  4260. **
  4261. ** These routines must be called from the same thread as
  4262. ** the SQL function that supplied the [sqlite3_value*] parameters.
  4263. */
  4264. SQLITE_API const void *sqlite3_value_blob(sqlite3_value*);
  4265. SQLITE_API int sqlite3_value_bytes(sqlite3_value*);
  4266. SQLITE_API int sqlite3_value_bytes16(sqlite3_value*);
  4267. SQLITE_API double sqlite3_value_double(sqlite3_value*);
  4268. SQLITE_API int sqlite3_value_int(sqlite3_value*);
  4269. SQLITE_API sqlite3_int64 sqlite3_value_int64(sqlite3_value*);
  4270. SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value*);
  4271. SQLITE_API const void *sqlite3_value_text16(sqlite3_value*);
  4272. SQLITE_API const void *sqlite3_value_text16le(sqlite3_value*);
  4273. SQLITE_API const void *sqlite3_value_text16be(sqlite3_value*);
  4274. SQLITE_API int sqlite3_value_type(sqlite3_value*);
  4275. SQLITE_API int sqlite3_value_numeric_type(sqlite3_value*);
  4276. /*
  4277. ** CAPI3REF: Obtain Aggregate Function Context
  4278. **
  4279. ** Implementations of aggregate SQL functions use this
  4280. ** routine to allocate memory for storing their state.
  4281. **
  4282. ** ^The first time the sqlite3_aggregate_context(C,N) routine is called
  4283. ** for a particular aggregate function, SQLite
  4284. ** allocates N of memory, zeroes out that memory, and returns a pointer
  4285. ** to the new memory. ^On second and subsequent calls to
  4286. ** sqlite3_aggregate_context() for the same aggregate function instance,
  4287. ** the same buffer is returned. Sqlite3_aggregate_context() is normally
  4288. ** called once for each invocation of the xStep callback and then one
  4289. ** last time when the xFinal callback is invoked. ^(When no rows match
  4290. ** an aggregate query, the xStep() callback of the aggregate function
  4291. ** implementation is never called and xFinal() is called exactly once.
  4292. ** In those cases, sqlite3_aggregate_context() might be called for the
  4293. ** first time from within xFinal().)^
  4294. **
  4295. ** ^The sqlite3_aggregate_context(C,N) routine returns a NULL pointer
  4296. ** when first called if N is less than or equal to zero or if a memory
  4297. ** allocate error occurs.
  4298. **
  4299. ** ^(The amount of space allocated by sqlite3_aggregate_context(C,N) is
  4300. ** determined by the N parameter on first successful call. Changing the
  4301. ** value of N in subsequent call to sqlite3_aggregate_context() within
  4302. ** the same aggregate function instance will not resize the memory
  4303. ** allocation.)^ Within the xFinal callback, it is customary to set
  4304. ** N=0 in calls to sqlite3_aggregate_context(C,N) so that no
  4305. ** pointless memory allocations occur.
  4306. **
  4307. ** ^SQLite automatically frees the memory allocated by
  4308. ** sqlite3_aggregate_context() when the aggregate query concludes.
  4309. **
  4310. ** The first parameter must be a copy of the
  4311. ** [sqlite3_context | SQL function context] that is the first parameter
  4312. ** to the xStep or xFinal callback routine that implements the aggregate
  4313. ** function.
  4314. **
  4315. ** This routine must be called from the same thread in which
  4316. ** the aggregate SQL function is running.
  4317. */
  4318. SQLITE_API void *sqlite3_aggregate_context(sqlite3_context*, int nBytes);
  4319. /*
  4320. ** CAPI3REF: User Data For Functions
  4321. **
  4322. ** ^The sqlite3_user_data() interface returns a copy of
  4323. ** the pointer that was the pUserData parameter (the 5th parameter)
  4324. ** of the [sqlite3_create_function()]
  4325. ** and [sqlite3_create_function16()] routines that originally
  4326. ** registered the application defined function.
  4327. **
  4328. ** This routine must be called from the same thread in which
  4329. ** the application-defined function is running.
  4330. */
  4331. SQLITE_API void *sqlite3_user_data(sqlite3_context*);
  4332. /*
  4333. ** CAPI3REF: Database Connection For Functions
  4334. **
  4335. ** ^The sqlite3_context_db_handle() interface returns a copy of
  4336. ** the pointer to the [database connection] (the 1st parameter)
  4337. ** of the [sqlite3_create_function()]
  4338. ** and [sqlite3_create_function16()] routines that originally
  4339. ** registered the application defined function.
  4340. */
  4341. SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context*);
  4342. /*
  4343. ** CAPI3REF: Function Auxiliary Data
  4344. **
  4345. ** These functions may be used by (non-aggregate) SQL functions to
  4346. ** associate metadata with argument values. If the same value is passed to
  4347. ** multiple invocations of the same SQL function during query execution, under
  4348. ** some circumstances the associated metadata may be preserved. An example
  4349. ** of where this might be useful is in a regular-expression matching
  4350. ** function. The compiled version of the regular expression can be stored as
  4351. ** metadata associated with the pattern string.
  4352. ** Then as long as the pattern string remains the same,
  4353. ** the compiled regular expression can be reused on multiple
  4354. ** invocations of the same function.
  4355. **
  4356. ** ^The sqlite3_get_auxdata() interface returns a pointer to the metadata
  4357. ** associated by the sqlite3_set_auxdata() function with the Nth argument
  4358. ** value to the application-defined function. ^If there is no metadata
  4359. ** associated with the function argument, this sqlite3_get_auxdata() interface
  4360. ** returns a NULL pointer.
  4361. **
  4362. ** ^The sqlite3_set_auxdata(C,N,P,X) interface saves P as metadata for the N-th
  4363. ** argument of the application-defined function. ^Subsequent
  4364. ** calls to sqlite3_get_auxdata(C,N) return P from the most recent
  4365. ** sqlite3_set_auxdata(C,N,P,X) call if the metadata is still valid or
  4366. ** NULL if the metadata has been discarded.
  4367. ** ^After each call to sqlite3_set_auxdata(C,N,P,X) where X is not NULL,
  4368. ** SQLite will invoke the destructor function X with parameter P exactly
  4369. ** once, when the metadata is discarded.
  4370. ** SQLite is free to discard the metadata at any time, including: <ul>
  4371. ** <li> when the corresponding function parameter changes, or
  4372. ** <li> when [sqlite3_reset()] or [sqlite3_finalize()] is called for the
  4373. ** SQL statement, or
  4374. ** <li> when sqlite3_set_auxdata() is invoked again on the same parameter, or
  4375. ** <li> during the original sqlite3_set_auxdata() call when a memory
  4376. ** allocation error occurs. </ul>)^
  4377. **
  4378. ** Note the last bullet in particular. The destructor X in
  4379. ** sqlite3_set_auxdata(C,N,P,X) might be called immediately, before the
  4380. ** sqlite3_set_auxdata() interface even returns. Hence sqlite3_set_auxdata()
  4381. ** should be called near the end of the function implementation and the
  4382. ** function implementation should not make any use of P after
  4383. ** sqlite3_set_auxdata() has been called.
  4384. **
  4385. ** ^(In practice, metadata is preserved between function calls for
  4386. ** function parameters that are compile-time constants, including literal
  4387. ** values and [parameters] and expressions composed from the same.)^
  4388. **
  4389. ** These routines must be called from the same thread in which
  4390. ** the SQL function is running.
  4391. */
  4392. SQLITE_API void *sqlite3_get_auxdata(sqlite3_context*, int N);
  4393. SQLITE_API void sqlite3_set_auxdata(sqlite3_context*, int N, void*, void (*)(void*));
  4394. /*
  4395. ** CAPI3REF: Constants Defining Special Destructor Behavior
  4396. **
  4397. ** These are special values for the destructor that is passed in as the
  4398. ** final argument to routines like [sqlite3_result_blob()]. ^If the destructor
  4399. ** argument is SQLITE_STATIC, it means that the content pointer is constant
  4400. ** and will never change. It does not need to be destroyed. ^The
  4401. ** SQLITE_TRANSIENT value means that the content will likely change in
  4402. ** the near future and that SQLite should make its own private copy of
  4403. ** the content before returning.
  4404. **
  4405. ** The typedef is necessary to work around problems in certain
  4406. ** C++ compilers.
  4407. */
  4408. typedef void (*sqlite3_destructor_type)(void*);
  4409. #define SQLITE_STATIC ((sqlite3_destructor_type)0)
  4410. #define SQLITE_TRANSIENT ((sqlite3_destructor_type)-1)
  4411. /*
  4412. ** CAPI3REF: Setting The Result Of An SQL Function
  4413. **
  4414. ** These routines are used by the xFunc or xFinal callbacks that
  4415. ** implement SQL functions and aggregates. See
  4416. ** [sqlite3_create_function()] and [sqlite3_create_function16()]
  4417. ** for additional information.
  4418. **
  4419. ** These functions work very much like the [parameter binding] family of
  4420. ** functions used to bind values to host parameters in prepared statements.
  4421. ** Refer to the [SQL parameter] documentation for additional information.
  4422. **
  4423. ** ^The sqlite3_result_blob() interface sets the result from
  4424. ** an application-defined function to be the BLOB whose content is pointed
  4425. ** to by the second parameter and which is N bytes long where N is the
  4426. ** third parameter.
  4427. **
  4428. ** ^The sqlite3_result_zeroblob() interfaces set the result of
  4429. ** the application-defined function to be a BLOB containing all zero
  4430. ** bytes and N bytes in size, where N is the value of the 2nd parameter.
  4431. **
  4432. ** ^The sqlite3_result_double() interface sets the result from
  4433. ** an application-defined function to be a floating point value specified
  4434. ** by its 2nd argument.
  4435. **
  4436. ** ^The sqlite3_result_error() and sqlite3_result_error16() functions
  4437. ** cause the implemented SQL function to throw an exception.
  4438. ** ^SQLite uses the string pointed to by the
  4439. ** 2nd parameter of sqlite3_result_error() or sqlite3_result_error16()
  4440. ** as the text of an error message. ^SQLite interprets the error
  4441. ** message string from sqlite3_result_error() as UTF-8. ^SQLite
  4442. ** interprets the string from sqlite3_result_error16() as UTF-16 in native
  4443. ** byte order. ^If the third parameter to sqlite3_result_error()
  4444. ** or sqlite3_result_error16() is negative then SQLite takes as the error
  4445. ** message all text up through the first zero character.
  4446. ** ^If the third parameter to sqlite3_result_error() or
  4447. ** sqlite3_result_error16() is non-negative then SQLite takes that many
  4448. ** bytes (not characters) from the 2nd parameter as the error message.
  4449. ** ^The sqlite3_result_error() and sqlite3_result_error16()
  4450. ** routines make a private copy of the error message text before
  4451. ** they return. Hence, the calling function can deallocate or
  4452. ** modify the text after they return without harm.
  4453. ** ^The sqlite3_result_error_code() function changes the error code
  4454. ** returned by SQLite as a result of an error in a function. ^By default,
  4455. ** the error code is SQLITE_ERROR. ^A subsequent call to sqlite3_result_error()
  4456. ** or sqlite3_result_error16() resets the error code to SQLITE_ERROR.
  4457. **
  4458. ** ^The sqlite3_result_error_toobig() interface causes SQLite to throw an
  4459. ** error indicating that a string or BLOB is too long to represent.
  4460. **
  4461. ** ^The sqlite3_result_error_nomem() interface causes SQLite to throw an
  4462. ** error indicating that a memory allocation failed.
  4463. **
  4464. ** ^The sqlite3_result_int() interface sets the return value
  4465. ** of the application-defined function to be the 32-bit signed integer
  4466. ** value given in the 2nd argument.
  4467. ** ^The sqlite3_result_int64() interface sets the return value
  4468. ** of the application-defined function to be the 64-bit signed integer
  4469. ** value given in the 2nd argument.
  4470. **
  4471. ** ^The sqlite3_result_null() interface sets the return value
  4472. ** of the application-defined function to be NULL.
  4473. **
  4474. ** ^The sqlite3_result_text(), sqlite3_result_text16(),
  4475. ** sqlite3_result_text16le(), and sqlite3_result_text16be() interfaces
  4476. ** set the return value of the application-defined function to be
  4477. ** a text string which is represented as UTF-8, UTF-16 native byte order,
  4478. ** UTF-16 little endian, or UTF-16 big endian, respectively.
  4479. ** ^The sqlite3_result_text64() interface sets the return value of an
  4480. ** application-defined function to be a text string in an encoding
  4481. ** specified by the fifth (and last) parameter, which must be one
  4482. ** of [SQLITE_UTF8], [SQLITE_UTF16], [SQLITE_UTF16BE], or [SQLITE_UTF16LE].
  4483. ** ^SQLite takes the text result from the application from
  4484. ** the 2nd parameter of the sqlite3_result_text* interfaces.
  4485. ** ^If the 3rd parameter to the sqlite3_result_text* interfaces
  4486. ** is negative, then SQLite takes result text from the 2nd parameter
  4487. ** through the first zero character.
  4488. ** ^If the 3rd parameter to the sqlite3_result_text* interfaces
  4489. ** is non-negative, then as many bytes (not characters) of the text
  4490. ** pointed to by the 2nd parameter are taken as the application-defined
  4491. ** function result. If the 3rd parameter is non-negative, then it
  4492. ** must be the byte offset into the string where the NUL terminator would
  4493. ** appear if the string where NUL terminated. If any NUL characters occur
  4494. ** in the string at a byte offset that is less than the value of the 3rd
  4495. ** parameter, then the resulting string will contain embedded NULs and the
  4496. ** result of expressions operating on strings with embedded NULs is undefined.
  4497. ** ^If the 4th parameter to the sqlite3_result_text* interfaces
  4498. ** or sqlite3_result_blob is a non-NULL pointer, then SQLite calls that
  4499. ** function as the destructor on the text or BLOB result when it has
  4500. ** finished using that result.
  4501. ** ^If the 4th parameter to the sqlite3_result_text* interfaces or to
  4502. ** sqlite3_result_blob is the special constant SQLITE_STATIC, then SQLite
  4503. ** assumes that the text or BLOB result is in constant space and does not
  4504. ** copy the content of the parameter nor call a destructor on the content
  4505. ** when it has finished using that result.
  4506. ** ^If the 4th parameter to the sqlite3_result_text* interfaces
  4507. ** or sqlite3_result_blob is the special constant SQLITE_TRANSIENT
  4508. ** then SQLite makes a copy of the result into space obtained from
  4509. ** from [sqlite3_malloc()] before it returns.
  4510. **
  4511. ** ^The sqlite3_result_value() interface sets the result of
  4512. ** the application-defined function to be a copy the
  4513. ** [unprotected sqlite3_value] object specified by the 2nd parameter. ^The
  4514. ** sqlite3_result_value() interface makes a copy of the [sqlite3_value]
  4515. ** so that the [sqlite3_value] specified in the parameter may change or
  4516. ** be deallocated after sqlite3_result_value() returns without harm.
  4517. ** ^A [protected sqlite3_value] object may always be used where an
  4518. ** [unprotected sqlite3_value] object is required, so either
  4519. ** kind of [sqlite3_value] object can be used with this interface.
  4520. **
  4521. ** If these routines are called from within the different thread
  4522. ** than the one containing the application-defined function that received
  4523. ** the [sqlite3_context] pointer, the results are undefined.
  4524. */
  4525. SQLITE_API void sqlite3_result_blob(sqlite3_context*, const void*, int, void(*)(void*));
  4526. SQLITE_API void sqlite3_result_blob64(sqlite3_context*,const void*,sqlite3_uint64,void(*)(void*));
  4527. SQLITE_API void sqlite3_result_double(sqlite3_context*, double);
  4528. SQLITE_API void sqlite3_result_error(sqlite3_context*, const char*, int);
  4529. SQLITE_API void sqlite3_result_error16(sqlite3_context*, const void*, int);
  4530. SQLITE_API void sqlite3_result_error_toobig(sqlite3_context*);
  4531. SQLITE_API void sqlite3_result_error_nomem(sqlite3_context*);
  4532. SQLITE_API void sqlite3_result_error_code(sqlite3_context*, int);
  4533. SQLITE_API void sqlite3_result_int(sqlite3_context*, int);
  4534. SQLITE_API void sqlite3_result_int64(sqlite3_context*, sqlite3_int64);
  4535. SQLITE_API void sqlite3_result_null(sqlite3_context*);
  4536. SQLITE_API void sqlite3_result_text(sqlite3_context*, const char*, int, void(*)(void*));
  4537. SQLITE_API void sqlite3_result_text64(sqlite3_context*, const char*,sqlite3_uint64,
  4538. void(*)(void*), unsigned char encoding);
  4539. SQLITE_API void sqlite3_result_text16(sqlite3_context*, const void*, int, void(*)(void*));
  4540. SQLITE_API void sqlite3_result_text16le(sqlite3_context*, const void*, int,void(*)(void*));
  4541. SQLITE_API void sqlite3_result_text16be(sqlite3_context*, const void*, int,void(*)(void*));
  4542. SQLITE_API void sqlite3_result_value(sqlite3_context*, sqlite3_value*);
  4543. SQLITE_API void sqlite3_result_zeroblob(sqlite3_context*, int n);
  4544. /*
  4545. ** CAPI3REF: Define New Collating Sequences
  4546. **
  4547. ** ^These functions add, remove, or modify a [collation] associated
  4548. ** with the [database connection] specified as the first argument.
  4549. **
  4550. ** ^The name of the collation is a UTF-8 string
  4551. ** for sqlite3_create_collation() and sqlite3_create_collation_v2()
  4552. ** and a UTF-16 string in native byte order for sqlite3_create_collation16().
  4553. ** ^Collation names that compare equal according to [sqlite3_strnicmp()] are
  4554. ** considered to be the same name.
  4555. **
  4556. ** ^(The third argument (eTextRep) must be one of the constants:
  4557. ** <ul>
  4558. ** <li> [SQLITE_UTF8],
  4559. ** <li> [SQLITE_UTF16LE],
  4560. ** <li> [SQLITE_UTF16BE],
  4561. ** <li> [SQLITE_UTF16], or
  4562. ** <li> [SQLITE_UTF16_ALIGNED].
  4563. ** </ul>)^
  4564. ** ^The eTextRep argument determines the encoding of strings passed
  4565. ** to the collating function callback, xCallback.
  4566. ** ^The [SQLITE_UTF16] and [SQLITE_UTF16_ALIGNED] values for eTextRep
  4567. ** force strings to be UTF16 with native byte order.
  4568. ** ^The [SQLITE_UTF16_ALIGNED] value for eTextRep forces strings to begin
  4569. ** on an even byte address.
  4570. **
  4571. ** ^The fourth argument, pArg, is an application data pointer that is passed
  4572. ** through as the first argument to the collating function callback.
  4573. **
  4574. ** ^The fifth argument, xCallback, is a pointer to the collating function.
  4575. ** ^Multiple collating functions can be registered using the same name but
  4576. ** with different eTextRep parameters and SQLite will use whichever
  4577. ** function requires the least amount of data transformation.
  4578. ** ^If the xCallback argument is NULL then the collating function is
  4579. ** deleted. ^When all collating functions having the same name are deleted,
  4580. ** that collation is no longer usable.
  4581. **
  4582. ** ^The collating function callback is invoked with a copy of the pArg
  4583. ** application data pointer and with two strings in the encoding specified
  4584. ** by the eTextRep argument. The collating function must return an
  4585. ** integer that is negative, zero, or positive
  4586. ** if the first string is less than, equal to, or greater than the second,
  4587. ** respectively. A collating function must always return the same answer
  4588. ** given the same inputs. If two or more collating functions are registered
  4589. ** to the same collation name (using different eTextRep values) then all
  4590. ** must give an equivalent answer when invoked with equivalent strings.
  4591. ** The collating function must obey the following properties for all
  4592. ** strings A, B, and C:
  4593. **
  4594. ** <ol>
  4595. ** <li> If A==B then B==A.
  4596. ** <li> If A==B and B==C then A==C.
  4597. ** <li> If A&lt;B THEN B&gt;A.
  4598. ** <li> If A&lt;B and B&lt;C then A&lt;C.
  4599. ** </ol>
  4600. **
  4601. ** If a collating function fails any of the above constraints and that
  4602. ** collating function is registered and used, then the behavior of SQLite
  4603. ** is undefined.
  4604. **
  4605. ** ^The sqlite3_create_collation_v2() works like sqlite3_create_collation()
  4606. ** with the addition that the xDestroy callback is invoked on pArg when
  4607. ** the collating function is deleted.
  4608. ** ^Collating functions are deleted when they are overridden by later
  4609. ** calls to the collation creation functions or when the
  4610. ** [database connection] is closed using [sqlite3_close()].
  4611. **
  4612. ** ^The xDestroy callback is <u>not</u> called if the
  4613. ** sqlite3_create_collation_v2() function fails. Applications that invoke
  4614. ** sqlite3_create_collation_v2() with a non-NULL xDestroy argument should
  4615. ** check the return code and dispose of the application data pointer
  4616. ** themselves rather than expecting SQLite to deal with it for them.
  4617. ** This is different from every other SQLite interface. The inconsistency
  4618. ** is unfortunate but cannot be changed without breaking backwards
  4619. ** compatibility.
  4620. **
  4621. ** See also: [sqlite3_collation_needed()] and [sqlite3_collation_needed16()].
  4622. */
  4623. SQLITE_API int sqlite3_create_collation(
  4624. sqlite3*,
  4625. const char *zName,
  4626. int eTextRep,
  4627. void *pArg,
  4628. int(*xCompare)(void*,int,const void*,int,const void*)
  4629. );
  4630. SQLITE_API int sqlite3_create_collation_v2(
  4631. sqlite3*,
  4632. const char *zName,
  4633. int eTextRep,
  4634. void *pArg,
  4635. int(*xCompare)(void*,int,const void*,int,const void*),
  4636. void(*xDestroy)(void*)
  4637. );
  4638. SQLITE_API int sqlite3_create_collation16(
  4639. sqlite3*,
  4640. const void *zName,
  4641. int eTextRep,
  4642. void *pArg,
  4643. int(*xCompare)(void*,int,const void*,int,const void*)
  4644. );
  4645. /*
  4646. ** CAPI3REF: Collation Needed Callbacks
  4647. **
  4648. ** ^To avoid having to register all collation sequences before a database
  4649. ** can be used, a single callback function may be registered with the
  4650. ** [database connection] to be invoked whenever an undefined collation
  4651. ** sequence is required.
  4652. **
  4653. ** ^If the function is registered using the sqlite3_collation_needed() API,
  4654. ** then it is passed the names of undefined collation sequences as strings
  4655. ** encoded in UTF-8. ^If sqlite3_collation_needed16() is used,
  4656. ** the names are passed as UTF-16 in machine native byte order.
  4657. ** ^A call to either function replaces the existing collation-needed callback.
  4658. **
  4659. ** ^(When the callback is invoked, the first argument passed is a copy
  4660. ** of the second argument to sqlite3_collation_needed() or
  4661. ** sqlite3_collation_needed16(). The second argument is the database
  4662. ** connection. The third argument is one of [SQLITE_UTF8], [SQLITE_UTF16BE],
  4663. ** or [SQLITE_UTF16LE], indicating the most desirable form of the collation
  4664. ** sequence function required. The fourth parameter is the name of the
  4665. ** required collation sequence.)^
  4666. **
  4667. ** The callback function should register the desired collation using
  4668. ** [sqlite3_create_collation()], [sqlite3_create_collation16()], or
  4669. ** [sqlite3_create_collation_v2()].
  4670. */
  4671. SQLITE_API int sqlite3_collation_needed(
  4672. sqlite3*,
  4673. void*,
  4674. void(*)(void*,sqlite3*,int eTextRep,const char*)
  4675. );
  4676. SQLITE_API int sqlite3_collation_needed16(
  4677. sqlite3*,
  4678. void*,
  4679. void(*)(void*,sqlite3*,int eTextRep,const void*)
  4680. );
  4681. #ifdef SQLITE_HAS_CODEC
  4682. /*
  4683. ** Specify the key for an encrypted database. This routine should be
  4684. ** called right after sqlite3_open().
  4685. **
  4686. ** The code to implement this API is not available in the public release
  4687. ** of SQLite.
  4688. */
  4689. SQLITE_API int sqlite3_key(
  4690. sqlite3 *db, /* Database to be rekeyed */
  4691. const void *pKey, int nKey /* The key */
  4692. );
  4693. SQLITE_API int sqlite3_key_v2(
  4694. sqlite3 *db, /* Database to be rekeyed */
  4695. const char *zDbName, /* Name of the database */
  4696. const void *pKey, int nKey /* The key */
  4697. );
  4698. /*
  4699. ** Change the key on an open database. If the current database is not
  4700. ** encrypted, this routine will encrypt it. If pNew==0 or nNew==0, the
  4701. ** database is decrypted.
  4702. **
  4703. ** The code to implement this API is not available in the public release
  4704. ** of SQLite.
  4705. */
  4706. SQLITE_API int sqlite3_rekey(
  4707. sqlite3 *db, /* Database to be rekeyed */
  4708. const void *pKey, int nKey /* The new key */
  4709. );
  4710. SQLITE_API int sqlite3_rekey_v2(
  4711. sqlite3 *db, /* Database to be rekeyed */
  4712. const char *zDbName, /* Name of the database */
  4713. const void *pKey, int nKey /* The new key */
  4714. );
  4715. /*
  4716. ** Specify the activation key for a SEE database. Unless
  4717. ** activated, none of the SEE routines will work.
  4718. */
  4719. SQLITE_API void sqlite3_activate_see(
  4720. const char *zPassPhrase /* Activation phrase */
  4721. );
  4722. #endif
  4723. #ifdef SQLITE_ENABLE_CEROD
  4724. /*
  4725. ** Specify the activation key for a CEROD database. Unless
  4726. ** activated, none of the CEROD routines will work.
  4727. */
  4728. SQLITE_API void sqlite3_activate_cerod(
  4729. const char *zPassPhrase /* Activation phrase */
  4730. );
  4731. #endif
  4732. /*
  4733. ** CAPI3REF: Suspend Execution For A Short Time
  4734. **
  4735. ** The sqlite3_sleep() function causes the current thread to suspend execution
  4736. ** for at least a number of milliseconds specified in its parameter.
  4737. **
  4738. ** If the operating system does not support sleep requests with
  4739. ** millisecond time resolution, then the time will be rounded up to
  4740. ** the nearest second. The number of milliseconds of sleep actually
  4741. ** requested from the operating system is returned.
  4742. **
  4743. ** ^SQLite implements this interface by calling the xSleep()
  4744. ** method of the default [sqlite3_vfs] object. If the xSleep() method
  4745. ** of the default VFS is not implemented correctly, or not implemented at
  4746. ** all, then the behavior of sqlite3_sleep() may deviate from the description
  4747. ** in the previous paragraphs.
  4748. */
  4749. SQLITE_API int sqlite3_sleep(int);
  4750. /*
  4751. ** CAPI3REF: Name Of The Folder Holding Temporary Files
  4752. **
  4753. ** ^(If this global variable is made to point to a string which is
  4754. ** the name of a folder (a.k.a. directory), then all temporary files
  4755. ** created by SQLite when using a built-in [sqlite3_vfs | VFS]
  4756. ** will be placed in that directory.)^ ^If this variable
  4757. ** is a NULL pointer, then SQLite performs a search for an appropriate
  4758. ** temporary file directory.
  4759. **
  4760. ** Applications are strongly discouraged from using this global variable.
  4761. ** It is required to set a temporary folder on Windows Runtime (WinRT).
  4762. ** But for all other platforms, it is highly recommended that applications
  4763. ** neither read nor write this variable. This global variable is a relic
  4764. ** that exists for backwards compatibility of legacy applications and should
  4765. ** be avoided in new projects.
  4766. **
  4767. ** It is not safe to read or modify this variable in more than one
  4768. ** thread at a time. It is not safe to read or modify this variable
  4769. ** if a [database connection] is being used at the same time in a separate
  4770. ** thread.
  4771. ** It is intended that this variable be set once
  4772. ** as part of process initialization and before any SQLite interface
  4773. ** routines have been called and that this variable remain unchanged
  4774. ** thereafter.
  4775. **
  4776. ** ^The [temp_store_directory pragma] may modify this variable and cause
  4777. ** it to point to memory obtained from [sqlite3_malloc]. ^Furthermore,
  4778. ** the [temp_store_directory pragma] always assumes that any string
  4779. ** that this variable points to is held in memory obtained from
  4780. ** [sqlite3_malloc] and the pragma may attempt to free that memory
  4781. ** using [sqlite3_free].
  4782. ** Hence, if this variable is modified directly, either it should be
  4783. ** made NULL or made to point to memory obtained from [sqlite3_malloc]
  4784. ** or else the use of the [temp_store_directory pragma] should be avoided.
  4785. ** Except when requested by the [temp_store_directory pragma], SQLite
  4786. ** does not free the memory that sqlite3_temp_directory points to. If
  4787. ** the application wants that memory to be freed, it must do
  4788. ** so itself, taking care to only do so after all [database connection]
  4789. ** objects have been destroyed.
  4790. **
  4791. ** <b>Note to Windows Runtime users:</b> The temporary directory must be set
  4792. ** prior to calling [sqlite3_open] or [sqlite3_open_v2]. Otherwise, various
  4793. ** features that require the use of temporary files may fail. Here is an
  4794. ** example of how to do this using C++ with the Windows Runtime:
  4795. **
  4796. ** <blockquote><pre>
  4797. ** LPCWSTR zPath = Windows::Storage::ApplicationData::Current->
  4798. ** &nbsp; TemporaryFolder->Path->Data();
  4799. ** char zPathBuf&#91;MAX_PATH + 1&#93;;
  4800. ** memset(zPathBuf, 0, sizeof(zPathBuf));
  4801. ** WideCharToMultiByte(CP_UTF8, 0, zPath, -1, zPathBuf, sizeof(zPathBuf),
  4802. ** &nbsp; NULL, NULL);
  4803. ** sqlite3_temp_directory = sqlite3_mprintf("%s", zPathBuf);
  4804. ** </pre></blockquote>
  4805. */
  4806. SQLITE_API char *sqlite3_temp_directory;
  4807. /*
  4808. ** CAPI3REF: Name Of The Folder Holding Database Files
  4809. **
  4810. ** ^(If this global variable is made to point to a string which is
  4811. ** the name of a folder (a.k.a. directory), then all database files
  4812. ** specified with a relative pathname and created or accessed by
  4813. ** SQLite when using a built-in windows [sqlite3_vfs | VFS] will be assumed
  4814. ** to be relative to that directory.)^ ^If this variable is a NULL
  4815. ** pointer, then SQLite assumes that all database files specified
  4816. ** with a relative pathname are relative to the current directory
  4817. ** for the process. Only the windows VFS makes use of this global
  4818. ** variable; it is ignored by the unix VFS.
  4819. **
  4820. ** Changing the value of this variable while a database connection is
  4821. ** open can result in a corrupt database.
  4822. **
  4823. ** It is not safe to read or modify this variable in more than one
  4824. ** thread at a time. It is not safe to read or modify this variable
  4825. ** if a [database connection] is being used at the same time in a separate
  4826. ** thread.
  4827. ** It is intended that this variable be set once
  4828. ** as part of process initialization and before any SQLite interface
  4829. ** routines have been called and that this variable remain unchanged
  4830. ** thereafter.
  4831. **
  4832. ** ^The [data_store_directory pragma] may modify this variable and cause
  4833. ** it to point to memory obtained from [sqlite3_malloc]. ^Furthermore,
  4834. ** the [data_store_directory pragma] always assumes that any string
  4835. ** that this variable points to is held in memory obtained from
  4836. ** [sqlite3_malloc] and the pragma may attempt to free that memory
  4837. ** using [sqlite3_free].
  4838. ** Hence, if this variable is modified directly, either it should be
  4839. ** made NULL or made to point to memory obtained from [sqlite3_malloc]
  4840. ** or else the use of the [data_store_directory pragma] should be avoided.
  4841. */
  4842. SQLITE_API char *sqlite3_data_directory;
  4843. /*
  4844. ** CAPI3REF: Test For Auto-Commit Mode
  4845. ** KEYWORDS: {autocommit mode}
  4846. **
  4847. ** ^The sqlite3_get_autocommit() interface returns non-zero or
  4848. ** zero if the given database connection is or is not in autocommit mode,
  4849. ** respectively. ^Autocommit mode is on by default.
  4850. ** ^Autocommit mode is disabled by a [BEGIN] statement.
  4851. ** ^Autocommit mode is re-enabled by a [COMMIT] or [ROLLBACK].
  4852. **
  4853. ** If certain kinds of errors occur on a statement within a multi-statement
  4854. ** transaction (errors including [SQLITE_FULL], [SQLITE_IOERR],
  4855. ** [SQLITE_NOMEM], [SQLITE_BUSY], and [SQLITE_INTERRUPT]) then the
  4856. ** transaction might be rolled back automatically. The only way to
  4857. ** find out whether SQLite automatically rolled back the transaction after
  4858. ** an error is to use this function.
  4859. **
  4860. ** If another thread changes the autocommit status of the database
  4861. ** connection while this routine is running, then the return value
  4862. ** is undefined.
  4863. */
  4864. SQLITE_API int sqlite3_get_autocommit(sqlite3*);
  4865. /*
  4866. ** CAPI3REF: Find The Database Handle Of A Prepared Statement
  4867. **
  4868. ** ^The sqlite3_db_handle interface returns the [database connection] handle
  4869. ** to which a [prepared statement] belongs. ^The [database connection]
  4870. ** returned by sqlite3_db_handle is the same [database connection]
  4871. ** that was the first argument
  4872. ** to the [sqlite3_prepare_v2()] call (or its variants) that was used to
  4873. ** create the statement in the first place.
  4874. */
  4875. SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt*);
  4876. /*
  4877. ** CAPI3REF: Return The Filename For A Database Connection
  4878. **
  4879. ** ^The sqlite3_db_filename(D,N) interface returns a pointer to a filename
  4880. ** associated with database N of connection D. ^The main database file
  4881. ** has the name "main". If there is no attached database N on the database
  4882. ** connection D, or if database N is a temporary or in-memory database, then
  4883. ** a NULL pointer is returned.
  4884. **
  4885. ** ^The filename returned by this function is the output of the
  4886. ** xFullPathname method of the [VFS]. ^In other words, the filename
  4887. ** will be an absolute pathname, even if the filename used
  4888. ** to open the database originally was a URI or relative pathname.
  4889. */
  4890. SQLITE_API const char *sqlite3_db_filename(sqlite3 *db, const char *zDbName);
  4891. /*
  4892. ** CAPI3REF: Determine if a database is read-only
  4893. **
  4894. ** ^The sqlite3_db_readonly(D,N) interface returns 1 if the database N
  4895. ** of connection D is read-only, 0 if it is read/write, or -1 if N is not
  4896. ** the name of a database on connection D.
  4897. */
  4898. SQLITE_API int sqlite3_db_readonly(sqlite3 *db, const char *zDbName);
  4899. /*
  4900. ** CAPI3REF: Find the next prepared statement
  4901. **
  4902. ** ^This interface returns a pointer to the next [prepared statement] after
  4903. ** pStmt associated with the [database connection] pDb. ^If pStmt is NULL
  4904. ** then this interface returns a pointer to the first prepared statement
  4905. ** associated with the database connection pDb. ^If no prepared statement
  4906. ** satisfies the conditions of this routine, it returns NULL.
  4907. **
  4908. ** The [database connection] pointer D in a call to
  4909. ** [sqlite3_next_stmt(D,S)] must refer to an open database
  4910. ** connection and in particular must not be a NULL pointer.
  4911. */
  4912. SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt);
  4913. /*
  4914. ** CAPI3REF: Commit And Rollback Notification Callbacks
  4915. **
  4916. ** ^The sqlite3_commit_hook() interface registers a callback
  4917. ** function to be invoked whenever a transaction is [COMMIT | committed].
  4918. ** ^Any callback set by a previous call to sqlite3_commit_hook()
  4919. ** for the same database connection is overridden.
  4920. ** ^The sqlite3_rollback_hook() interface registers a callback
  4921. ** function to be invoked whenever a transaction is [ROLLBACK | rolled back].
  4922. ** ^Any callback set by a previous call to sqlite3_rollback_hook()
  4923. ** for the same database connection is overridden.
  4924. ** ^The pArg argument is passed through to the callback.
  4925. ** ^If the callback on a commit hook function returns non-zero,
  4926. ** then the commit is converted into a rollback.
  4927. **
  4928. ** ^The sqlite3_commit_hook(D,C,P) and sqlite3_rollback_hook(D,C,P) functions
  4929. ** return the P argument from the previous call of the same function
  4930. ** on the same [database connection] D, or NULL for
  4931. ** the first call for each function on D.
  4932. **
  4933. ** The commit and rollback hook callbacks are not reentrant.
  4934. ** The callback implementation must not do anything that will modify
  4935. ** the database connection that invoked the callback. Any actions
  4936. ** to modify the database connection must be deferred until after the
  4937. ** completion of the [sqlite3_step()] call that triggered the commit
  4938. ** or rollback hook in the first place.
  4939. ** Note that running any other SQL statements, including SELECT statements,
  4940. ** or merely calling [sqlite3_prepare_v2()] and [sqlite3_step()] will modify
  4941. ** the database connections for the meaning of "modify" in this paragraph.
  4942. **
  4943. ** ^Registering a NULL function disables the callback.
  4944. **
  4945. ** ^When the commit hook callback routine returns zero, the [COMMIT]
  4946. ** operation is allowed to continue normally. ^If the commit hook
  4947. ** returns non-zero, then the [COMMIT] is converted into a [ROLLBACK].
  4948. ** ^The rollback hook is invoked on a rollback that results from a commit
  4949. ** hook returning non-zero, just as it would be with any other rollback.
  4950. **
  4951. ** ^For the purposes of this API, a transaction is said to have been
  4952. ** rolled back if an explicit "ROLLBACK" statement is executed, or
  4953. ** an error or constraint causes an implicit rollback to occur.
  4954. ** ^The rollback callback is not invoked if a transaction is
  4955. ** automatically rolled back because the database connection is closed.
  4956. **
  4957. ** See also the [sqlite3_update_hook()] interface.
  4958. */
  4959. SQLITE_API void *sqlite3_commit_hook(sqlite3*, int(*)(void*), void*);
  4960. SQLITE_API void *sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*);
  4961. /*
  4962. ** CAPI3REF: Data Change Notification Callbacks
  4963. **
  4964. ** ^The sqlite3_update_hook() interface registers a callback function
  4965. ** with the [database connection] identified by the first argument
  4966. ** to be invoked whenever a row is updated, inserted or deleted in
  4967. ** a rowid table.
  4968. ** ^Any callback set by a previous call to this function
  4969. ** for the same database connection is overridden.
  4970. **
  4971. ** ^The second argument is a pointer to the function to invoke when a
  4972. ** row is updated, inserted or deleted in a rowid table.
  4973. ** ^The first argument to the callback is a copy of the third argument
  4974. ** to sqlite3_update_hook().
  4975. ** ^The second callback argument is one of [SQLITE_INSERT], [SQLITE_DELETE],
  4976. ** or [SQLITE_UPDATE], depending on the operation that caused the callback
  4977. ** to be invoked.
  4978. ** ^The third and fourth arguments to the callback contain pointers to the
  4979. ** database and table name containing the affected row.
  4980. ** ^The final callback parameter is the [rowid] of the row.
  4981. ** ^In the case of an update, this is the [rowid] after the update takes place.
  4982. **
  4983. ** ^(The update hook is not invoked when internal system tables are
  4984. ** modified (i.e. sqlite_master and sqlite_sequence).)^
  4985. ** ^The update hook is not invoked when [WITHOUT ROWID] tables are modified.
  4986. **
  4987. ** ^In the current implementation, the update hook
  4988. ** is not invoked when duplication rows are deleted because of an
  4989. ** [ON CONFLICT | ON CONFLICT REPLACE] clause. ^Nor is the update hook
  4990. ** invoked when rows are deleted using the [truncate optimization].
  4991. ** The exceptions defined in this paragraph might change in a future
  4992. ** release of SQLite.
  4993. **
  4994. ** The update hook implementation must not do anything that will modify
  4995. ** the database connection that invoked the update hook. Any actions
  4996. ** to modify the database connection must be deferred until after the
  4997. ** completion of the [sqlite3_step()] call that triggered the update hook.
  4998. ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
  4999. ** database connections for the meaning of "modify" in this paragraph.
  5000. **
  5001. ** ^The sqlite3_update_hook(D,C,P) function
  5002. ** returns the P argument from the previous call
  5003. ** on the same [database connection] D, or NULL for
  5004. ** the first call on D.
  5005. **
  5006. ** See also the [sqlite3_commit_hook()] and [sqlite3_rollback_hook()]
  5007. ** interfaces.
  5008. */
  5009. SQLITE_API void *sqlite3_update_hook(
  5010. sqlite3*,
  5011. void(*)(void *,int ,char const *,char const *,sqlite3_int64),
  5012. void*
  5013. );
  5014. /*
  5015. ** CAPI3REF: Enable Or Disable Shared Pager Cache
  5016. **
  5017. ** ^(This routine enables or disables the sharing of the database cache
  5018. ** and schema data structures between [database connection | connections]
  5019. ** to the same database. Sharing is enabled if the argument is true
  5020. ** and disabled if the argument is false.)^
  5021. **
  5022. ** ^Cache sharing is enabled and disabled for an entire process.
  5023. ** This is a change as of SQLite version 3.5.0. In prior versions of SQLite,
  5024. ** sharing was enabled or disabled for each thread separately.
  5025. **
  5026. ** ^(The cache sharing mode set by this interface effects all subsequent
  5027. ** calls to [sqlite3_open()], [sqlite3_open_v2()], and [sqlite3_open16()].
  5028. ** Existing database connections continue use the sharing mode
  5029. ** that was in effect at the time they were opened.)^
  5030. **
  5031. ** ^(This routine returns [SQLITE_OK] if shared cache was enabled or disabled
  5032. ** successfully. An [error code] is returned otherwise.)^
  5033. **
  5034. ** ^Shared cache is disabled by default. But this might change in
  5035. ** future releases of SQLite. Applications that care about shared
  5036. ** cache setting should set it explicitly.
  5037. **
  5038. ** This interface is threadsafe on processors where writing a
  5039. ** 32-bit integer is atomic.
  5040. **
  5041. ** See Also: [SQLite Shared-Cache Mode]
  5042. */
  5043. SQLITE_API int sqlite3_enable_shared_cache(int);
  5044. /*
  5045. ** CAPI3REF: Attempt To Free Heap Memory
  5046. **
  5047. ** ^The sqlite3_release_memory() interface attempts to free N bytes
  5048. ** of heap memory by deallocating non-essential memory allocations
  5049. ** held by the database library. Memory used to cache database
  5050. ** pages to improve performance is an example of non-essential memory.
  5051. ** ^sqlite3_release_memory() returns the number of bytes actually freed,
  5052. ** which might be more or less than the amount requested.
  5053. ** ^The sqlite3_release_memory() routine is a no-op returning zero
  5054. ** if SQLite is not compiled with [SQLITE_ENABLE_MEMORY_MANAGEMENT].
  5055. **
  5056. ** See also: [sqlite3_db_release_memory()]
  5057. */
  5058. SQLITE_API int sqlite3_release_memory(int);
  5059. /*
  5060. ** CAPI3REF: Free Memory Used By A Database Connection
  5061. **
  5062. ** ^The sqlite3_db_release_memory(D) interface attempts to free as much heap
  5063. ** memory as possible from database connection D. Unlike the
  5064. ** [sqlite3_release_memory()] interface, this interface is in effect even
  5065. ** when the [SQLITE_ENABLE_MEMORY_MANAGEMENT] compile-time option is
  5066. ** omitted.
  5067. **
  5068. ** See also: [sqlite3_release_memory()]
  5069. */
  5070. SQLITE_API int sqlite3_db_release_memory(sqlite3*);
  5071. /*
  5072. ** CAPI3REF: Impose A Limit On Heap Size
  5073. **
  5074. ** ^The sqlite3_soft_heap_limit64() interface sets and/or queries the
  5075. ** soft limit on the amount of heap memory that may be allocated by SQLite.
  5076. ** ^SQLite strives to keep heap memory utilization below the soft heap
  5077. ** limit by reducing the number of pages held in the page cache
  5078. ** as heap memory usages approaches the limit.
  5079. ** ^The soft heap limit is "soft" because even though SQLite strives to stay
  5080. ** below the limit, it will exceed the limit rather than generate
  5081. ** an [SQLITE_NOMEM] error. In other words, the soft heap limit
  5082. ** is advisory only.
  5083. **
  5084. ** ^The return value from sqlite3_soft_heap_limit64() is the size of
  5085. ** the soft heap limit prior to the call, or negative in the case of an
  5086. ** error. ^If the argument N is negative
  5087. ** then no change is made to the soft heap limit. Hence, the current
  5088. ** size of the soft heap limit can be determined by invoking
  5089. ** sqlite3_soft_heap_limit64() with a negative argument.
  5090. **
  5091. ** ^If the argument N is zero then the soft heap limit is disabled.
  5092. **
  5093. ** ^(The soft heap limit is not enforced in the current implementation
  5094. ** if one or more of following conditions are true:
  5095. **
  5096. ** <ul>
  5097. ** <li> The soft heap limit is set to zero.
  5098. ** <li> Memory accounting is disabled using a combination of the
  5099. ** [sqlite3_config]([SQLITE_CONFIG_MEMSTATUS],...) start-time option and
  5100. ** the [SQLITE_DEFAULT_MEMSTATUS] compile-time option.
  5101. ** <li> An alternative page cache implementation is specified using
  5102. ** [sqlite3_config]([SQLITE_CONFIG_PCACHE2],...).
  5103. ** <li> The page cache allocates from its own memory pool supplied
  5104. ** by [sqlite3_config]([SQLITE_CONFIG_PAGECACHE],...) rather than
  5105. ** from the heap.
  5106. ** </ul>)^
  5107. **
  5108. ** Beginning with SQLite version 3.7.3, the soft heap limit is enforced
  5109. ** regardless of whether or not the [SQLITE_ENABLE_MEMORY_MANAGEMENT]
  5110. ** compile-time option is invoked. With [SQLITE_ENABLE_MEMORY_MANAGEMENT],
  5111. ** the soft heap limit is enforced on every memory allocation. Without
  5112. ** [SQLITE_ENABLE_MEMORY_MANAGEMENT], the soft heap limit is only enforced
  5113. ** when memory is allocated by the page cache. Testing suggests that because
  5114. ** the page cache is the predominate memory user in SQLite, most
  5115. ** applications will achieve adequate soft heap limit enforcement without
  5116. ** the use of [SQLITE_ENABLE_MEMORY_MANAGEMENT].
  5117. **
  5118. ** The circumstances under which SQLite will enforce the soft heap limit may
  5119. ** changes in future releases of SQLite.
  5120. */
  5121. SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 N);
  5122. /*
  5123. ** CAPI3REF: Deprecated Soft Heap Limit Interface
  5124. ** DEPRECATED
  5125. **
  5126. ** This is a deprecated version of the [sqlite3_soft_heap_limit64()]
  5127. ** interface. This routine is provided for historical compatibility
  5128. ** only. All new applications should use the
  5129. ** [sqlite3_soft_heap_limit64()] interface rather than this one.
  5130. */
  5131. SQLITE_API SQLITE_DEPRECATED void sqlite3_soft_heap_limit(int N);
  5132. /*
  5133. ** CAPI3REF: Extract Metadata About A Column Of A Table
  5134. **
  5135. ** ^This routine returns metadata about a specific column of a specific
  5136. ** database table accessible using the [database connection] handle
  5137. ** passed as the first function argument.
  5138. **
  5139. ** ^The column is identified by the second, third and fourth parameters to
  5140. ** this function. ^The second parameter is either the name of the database
  5141. ** (i.e. "main", "temp", or an attached database) containing the specified
  5142. ** table or NULL. ^If it is NULL, then all attached databases are searched
  5143. ** for the table using the same algorithm used by the database engine to
  5144. ** resolve unqualified table references.
  5145. **
  5146. ** ^The third and fourth parameters to this function are the table and column
  5147. ** name of the desired column, respectively. Neither of these parameters
  5148. ** may be NULL.
  5149. **
  5150. ** ^Metadata is returned by writing to the memory locations passed as the 5th
  5151. ** and subsequent parameters to this function. ^Any of these arguments may be
  5152. ** NULL, in which case the corresponding element of metadata is omitted.
  5153. **
  5154. ** ^(<blockquote>
  5155. ** <table border="1">
  5156. ** <tr><th> Parameter <th> Output<br>Type <th> Description
  5157. **
  5158. ** <tr><td> 5th <td> const char* <td> Data type
  5159. ** <tr><td> 6th <td> const char* <td> Name of default collation sequence
  5160. ** <tr><td> 7th <td> int <td> True if column has a NOT NULL constraint
  5161. ** <tr><td> 8th <td> int <td> True if column is part of the PRIMARY KEY
  5162. ** <tr><td> 9th <td> int <td> True if column is [AUTOINCREMENT]
  5163. ** </table>
  5164. ** </blockquote>)^
  5165. **
  5166. ** ^The memory pointed to by the character pointers returned for the
  5167. ** declaration type and collation sequence is valid only until the next
  5168. ** call to any SQLite API function.
  5169. **
  5170. ** ^If the specified table is actually a view, an [error code] is returned.
  5171. **
  5172. ** ^If the specified column is "rowid", "oid" or "_rowid_" and an
  5173. ** [INTEGER PRIMARY KEY] column has been explicitly declared, then the output
  5174. ** parameters are set for the explicitly declared column. ^(If there is no
  5175. ** explicitly declared [INTEGER PRIMARY KEY] column, then the output
  5176. ** parameters are set as follows:
  5177. **
  5178. ** <pre>
  5179. ** data type: "INTEGER"
  5180. ** collation sequence: "BINARY"
  5181. ** not null: 0
  5182. ** primary key: 1
  5183. ** auto increment: 0
  5184. ** </pre>)^
  5185. **
  5186. ** ^(This function may load one or more schemas from database files. If an
  5187. ** error occurs during this process, or if the requested table or column
  5188. ** cannot be found, an [error code] is returned and an error message left
  5189. ** in the [database connection] (to be retrieved using sqlite3_errmsg()).)^
  5190. **
  5191. ** ^This API is only available if the library was compiled with the
  5192. ** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol defined.
  5193. */
  5194. SQLITE_API int sqlite3_table_column_metadata(
  5195. sqlite3 *db, /* Connection handle */
  5196. const char *zDbName, /* Database name or NULL */
  5197. const char *zTableName, /* Table name */
  5198. const char *zColumnName, /* Column name */
  5199. char const **pzDataType, /* OUTPUT: Declared data type */
  5200. char const **pzCollSeq, /* OUTPUT: Collation sequence name */
  5201. int *pNotNull, /* OUTPUT: True if NOT NULL constraint exists */
  5202. int *pPrimaryKey, /* OUTPUT: True if column part of PK */
  5203. int *pAutoinc /* OUTPUT: True if column is auto-increment */
  5204. );
  5205. /*
  5206. ** CAPI3REF: Load An Extension
  5207. **
  5208. ** ^This interface loads an SQLite extension library from the named file.
  5209. **
  5210. ** ^The sqlite3_load_extension() interface attempts to load an
  5211. ** [SQLite extension] library contained in the file zFile. If
  5212. ** the file cannot be loaded directly, attempts are made to load
  5213. ** with various operating-system specific extensions added.
  5214. ** So for example, if "samplelib" cannot be loaded, then names like
  5215. ** "samplelib.so" or "samplelib.dylib" or "samplelib.dll" might
  5216. ** be tried also.
  5217. **
  5218. ** ^The entry point is zProc.
  5219. ** ^(zProc may be 0, in which case SQLite will try to come up with an
  5220. ** entry point name on its own. It first tries "sqlite3_extension_init".
  5221. ** If that does not work, it constructs a name "sqlite3_X_init" where the
  5222. ** X is consists of the lower-case equivalent of all ASCII alphabetic
  5223. ** characters in the filename from the last "/" to the first following
  5224. ** "." and omitting any initial "lib".)^
  5225. ** ^The sqlite3_load_extension() interface returns
  5226. ** [SQLITE_OK] on success and [SQLITE_ERROR] if something goes wrong.
  5227. ** ^If an error occurs and pzErrMsg is not 0, then the
  5228. ** [sqlite3_load_extension()] interface shall attempt to
  5229. ** fill *pzErrMsg with error message text stored in memory
  5230. ** obtained from [sqlite3_malloc()]. The calling function
  5231. ** should free this memory by calling [sqlite3_free()].
  5232. **
  5233. ** ^Extension loading must be enabled using
  5234. ** [sqlite3_enable_load_extension()] prior to calling this API,
  5235. ** otherwise an error will be returned.
  5236. **
  5237. ** See also the [load_extension() SQL function].
  5238. */
  5239. SQLITE_API int sqlite3_load_extension(
  5240. sqlite3 *db, /* Load the extension into this database connection */
  5241. const char *zFile, /* Name of the shared library containing extension */
  5242. const char *zProc, /* Entry point. Derived from zFile if 0 */
  5243. char **pzErrMsg /* Put error message here if not 0 */
  5244. );
  5245. /*
  5246. ** CAPI3REF: Enable Or Disable Extension Loading
  5247. **
  5248. ** ^So as not to open security holes in older applications that are
  5249. ** unprepared to deal with [extension loading], and as a means of disabling
  5250. ** [extension loading] while evaluating user-entered SQL, the following API
  5251. ** is provided to turn the [sqlite3_load_extension()] mechanism on and off.
  5252. **
  5253. ** ^Extension loading is off by default.
  5254. ** ^Call the sqlite3_enable_load_extension() routine with onoff==1
  5255. ** to turn extension loading on and call it with onoff==0 to turn
  5256. ** it back off again.
  5257. */
  5258. SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff);
  5259. /*
  5260. ** CAPI3REF: Automatically Load Statically Linked Extensions
  5261. **
  5262. ** ^This interface causes the xEntryPoint() function to be invoked for
  5263. ** each new [database connection] that is created. The idea here is that
  5264. ** xEntryPoint() is the entry point for a statically linked [SQLite extension]
  5265. ** that is to be automatically loaded into all new database connections.
  5266. **
  5267. ** ^(Even though the function prototype shows that xEntryPoint() takes
  5268. ** no arguments and returns void, SQLite invokes xEntryPoint() with three
  5269. ** arguments and expects and integer result as if the signature of the
  5270. ** entry point where as follows:
  5271. **
  5272. ** <blockquote><pre>
  5273. ** &nbsp; int xEntryPoint(
  5274. ** &nbsp; sqlite3 *db,
  5275. ** &nbsp; const char **pzErrMsg,
  5276. ** &nbsp; const struct sqlite3_api_routines *pThunk
  5277. ** &nbsp; );
  5278. ** </pre></blockquote>)^
  5279. **
  5280. ** If the xEntryPoint routine encounters an error, it should make *pzErrMsg
  5281. ** point to an appropriate error message (obtained from [sqlite3_mprintf()])
  5282. ** and return an appropriate [error code]. ^SQLite ensures that *pzErrMsg
  5283. ** is NULL before calling the xEntryPoint(). ^SQLite will invoke
  5284. ** [sqlite3_free()] on *pzErrMsg after xEntryPoint() returns. ^If any
  5285. ** xEntryPoint() returns an error, the [sqlite3_open()], [sqlite3_open16()],
  5286. ** or [sqlite3_open_v2()] call that provoked the xEntryPoint() will fail.
  5287. **
  5288. ** ^Calling sqlite3_auto_extension(X) with an entry point X that is already
  5289. ** on the list of automatic extensions is a harmless no-op. ^No entry point
  5290. ** will be called more than once for each database connection that is opened.
  5291. **
  5292. ** See also: [sqlite3_reset_auto_extension()]
  5293. ** and [sqlite3_cancel_auto_extension()]
  5294. */
  5295. SQLITE_API int sqlite3_auto_extension(void (*xEntryPoint)(void));
  5296. /*
  5297. ** CAPI3REF: Cancel Automatic Extension Loading
  5298. **
  5299. ** ^The [sqlite3_cancel_auto_extension(X)] interface unregisters the
  5300. ** initialization routine X that was registered using a prior call to
  5301. ** [sqlite3_auto_extension(X)]. ^The [sqlite3_cancel_auto_extension(X)]
  5302. ** routine returns 1 if initialization routine X was successfully
  5303. ** unregistered and it returns 0 if X was not on the list of initialization
  5304. ** routines.
  5305. */
  5306. SQLITE_API int sqlite3_cancel_auto_extension(void (*xEntryPoint)(void));
  5307. /*
  5308. ** CAPI3REF: Reset Automatic Extension Loading
  5309. **
  5310. ** ^This interface disables all automatic extensions previously
  5311. ** registered using [sqlite3_auto_extension()].
  5312. */
  5313. SQLITE_API void sqlite3_reset_auto_extension(void);
  5314. /*
  5315. ** The interface to the virtual-table mechanism is currently considered
  5316. ** to be experimental. The interface might change in incompatible ways.
  5317. ** If this is a problem for you, do not use the interface at this time.
  5318. **
  5319. ** When the virtual-table mechanism stabilizes, we will declare the
  5320. ** interface fixed, support it indefinitely, and remove this comment.
  5321. */
  5322. /*
  5323. ** Structures used by the virtual table interface
  5324. */
  5325. typedef struct sqlite3_vtab sqlite3_vtab;
  5326. typedef struct sqlite3_index_info sqlite3_index_info;
  5327. typedef struct sqlite3_vtab_cursor sqlite3_vtab_cursor;
  5328. typedef struct sqlite3_module sqlite3_module;
  5329. /*
  5330. ** CAPI3REF: Virtual Table Object
  5331. ** KEYWORDS: sqlite3_module {virtual table module}
  5332. **
  5333. ** This structure, sometimes called a "virtual table module",
  5334. ** defines the implementation of a [virtual tables].
  5335. ** This structure consists mostly of methods for the module.
  5336. **
  5337. ** ^A virtual table module is created by filling in a persistent
  5338. ** instance of this structure and passing a pointer to that instance
  5339. ** to [sqlite3_create_module()] or [sqlite3_create_module_v2()].
  5340. ** ^The registration remains valid until it is replaced by a different
  5341. ** module or until the [database connection] closes. The content
  5342. ** of this structure must not change while it is registered with
  5343. ** any database connection.
  5344. */
  5345. struct sqlite3_module {
  5346. int iVersion;
  5347. int (*xCreate)(sqlite3*, void *pAux,
  5348. int argc, const char *const*argv,
  5349. sqlite3_vtab **ppVTab, char**);
  5350. int (*xConnect)(sqlite3*, void *pAux,
  5351. int argc, const char *const*argv,
  5352. sqlite3_vtab **ppVTab, char**);
  5353. int (*xBestIndex)(sqlite3_vtab *pVTab, sqlite3_index_info*);
  5354. int (*xDisconnect)(sqlite3_vtab *pVTab);
  5355. int (*xDestroy)(sqlite3_vtab *pVTab);
  5356. int (*xOpen)(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor);
  5357. int (*xClose)(sqlite3_vtab_cursor*);
  5358. int (*xFilter)(sqlite3_vtab_cursor*, int idxNum, const char *idxStr,
  5359. int argc, sqlite3_value **argv);
  5360. int (*xNext)(sqlite3_vtab_cursor*);
  5361. int (*xEof)(sqlite3_vtab_cursor*);
  5362. int (*xColumn)(sqlite3_vtab_cursor*, sqlite3_context*, int);
  5363. int (*xRowid)(sqlite3_vtab_cursor*, sqlite3_int64 *pRowid);
  5364. int (*xUpdate)(sqlite3_vtab *, int, sqlite3_value **, sqlite3_int64 *);
  5365. int (*xBegin)(sqlite3_vtab *pVTab);
  5366. int (*xSync)(sqlite3_vtab *pVTab);
  5367. int (*xCommit)(sqlite3_vtab *pVTab);
  5368. int (*xRollback)(sqlite3_vtab *pVTab);
  5369. int (*xFindFunction)(sqlite3_vtab *pVtab, int nArg, const char *zName,
  5370. void (**pxFunc)(sqlite3_context*,int,sqlite3_value**),
  5371. void **ppArg);
  5372. int (*xRename)(sqlite3_vtab *pVtab, const char *zNew);
  5373. /* The methods above are in version 1 of the sqlite_module object. Those
  5374. ** below are for version 2 and greater. */
  5375. int (*xSavepoint)(sqlite3_vtab *pVTab, int);
  5376. int (*xRelease)(sqlite3_vtab *pVTab, int);
  5377. int (*xRollbackTo)(sqlite3_vtab *pVTab, int);
  5378. };
  5379. /*
  5380. ** CAPI3REF: Virtual Table Indexing Information
  5381. ** KEYWORDS: sqlite3_index_info
  5382. **
  5383. ** The sqlite3_index_info structure and its substructures is used as part
  5384. ** of the [virtual table] interface to
  5385. ** pass information into and receive the reply from the [xBestIndex]
  5386. ** method of a [virtual table module]. The fields under **Inputs** are the
  5387. ** inputs to xBestIndex and are read-only. xBestIndex inserts its
  5388. ** results into the **Outputs** fields.
  5389. **
  5390. ** ^(The aConstraint[] array records WHERE clause constraints of the form:
  5391. **
  5392. ** <blockquote>column OP expr</blockquote>
  5393. **
  5394. ** where OP is =, &lt;, &lt;=, &gt;, or &gt;=.)^ ^(The particular operator is
  5395. ** stored in aConstraint[].op using one of the
  5396. ** [SQLITE_INDEX_CONSTRAINT_EQ | SQLITE_INDEX_CONSTRAINT_ values].)^
  5397. ** ^(The index of the column is stored in
  5398. ** aConstraint[].iColumn.)^ ^(aConstraint[].usable is TRUE if the
  5399. ** expr on the right-hand side can be evaluated (and thus the constraint
  5400. ** is usable) and false if it cannot.)^
  5401. **
  5402. ** ^The optimizer automatically inverts terms of the form "expr OP column"
  5403. ** and makes other simplifications to the WHERE clause in an attempt to
  5404. ** get as many WHERE clause terms into the form shown above as possible.
  5405. ** ^The aConstraint[] array only reports WHERE clause terms that are
  5406. ** relevant to the particular virtual table being queried.
  5407. **
  5408. ** ^Information about the ORDER BY clause is stored in aOrderBy[].
  5409. ** ^Each term of aOrderBy records a column of the ORDER BY clause.
  5410. **
  5411. ** The [xBestIndex] method must fill aConstraintUsage[] with information
  5412. ** about what parameters to pass to xFilter. ^If argvIndex>0 then
  5413. ** the right-hand side of the corresponding aConstraint[] is evaluated
  5414. ** and becomes the argvIndex-th entry in argv. ^(If aConstraintUsage[].omit
  5415. ** is true, then the constraint is assumed to be fully handled by the
  5416. ** virtual table and is not checked again by SQLite.)^
  5417. **
  5418. ** ^The idxNum and idxPtr values are recorded and passed into the
  5419. ** [xFilter] method.
  5420. ** ^[sqlite3_free()] is used to free idxPtr if and only if
  5421. ** needToFreeIdxPtr is true.
  5422. **
  5423. ** ^The orderByConsumed means that output from [xFilter]/[xNext] will occur in
  5424. ** the correct order to satisfy the ORDER BY clause so that no separate
  5425. ** sorting step is required.
  5426. **
  5427. ** ^The estimatedCost value is an estimate of the cost of a particular
  5428. ** strategy. A cost of N indicates that the cost of the strategy is similar
  5429. ** to a linear scan of an SQLite table with N rows. A cost of log(N)
  5430. ** indicates that the expense of the operation is similar to that of a
  5431. ** binary search on a unique indexed field of an SQLite table with N rows.
  5432. **
  5433. ** ^The estimatedRows value is an estimate of the number of rows that
  5434. ** will be returned by the strategy.
  5435. **
  5436. ** IMPORTANT: The estimatedRows field was added to the sqlite3_index_info
  5437. ** structure for SQLite version 3.8.2. If a virtual table extension is
  5438. ** used with an SQLite version earlier than 3.8.2, the results of attempting
  5439. ** to read or write the estimatedRows field are undefined (but are likely
  5440. ** to included crashing the application). The estimatedRows field should
  5441. ** therefore only be used if [sqlite3_libversion_number()] returns a
  5442. ** value greater than or equal to 3008002.
  5443. */
  5444. struct sqlite3_index_info {
  5445. /* Inputs */
  5446. int nConstraint; /* Number of entries in aConstraint */
  5447. struct sqlite3_index_constraint {
  5448. int iColumn; /* Column on left-hand side of constraint */
  5449. unsigned char op; /* Constraint operator */
  5450. unsigned char usable; /* True if this constraint is usable */
  5451. int iTermOffset; /* Used internally - xBestIndex should ignore */
  5452. } *aConstraint; /* Table of WHERE clause constraints */
  5453. int nOrderBy; /* Number of terms in the ORDER BY clause */
  5454. struct sqlite3_index_orderby {
  5455. int iColumn; /* Column number */
  5456. unsigned char desc; /* True for DESC. False for ASC. */
  5457. } *aOrderBy; /* The ORDER BY clause */
  5458. /* Outputs */
  5459. struct sqlite3_index_constraint_usage {
  5460. int argvIndex; /* if >0, constraint is part of argv to xFilter */
  5461. unsigned char omit; /* Do not code a test for this constraint */
  5462. } *aConstraintUsage;
  5463. int idxNum; /* Number used to identify the index */
  5464. char *idxStr; /* String, possibly obtained from sqlite3_malloc */
  5465. int needToFreeIdxStr; /* Free idxStr using sqlite3_free() if true */
  5466. int orderByConsumed; /* True if output is already ordered */
  5467. double estimatedCost; /* Estimated cost of using this index */
  5468. /* Fields below are only available in SQLite 3.8.2 and later */
  5469. sqlite3_int64 estimatedRows; /* Estimated number of rows returned */
  5470. };
  5471. /*
  5472. ** CAPI3REF: Virtual Table Constraint Operator Codes
  5473. **
  5474. ** These macros defined the allowed values for the
  5475. ** [sqlite3_index_info].aConstraint[].op field. Each value represents
  5476. ** an operator that is part of a constraint term in the wHERE clause of
  5477. ** a query that uses a [virtual table].
  5478. */
  5479. #define SQLITE_INDEX_CONSTRAINT_EQ 2
  5480. #define SQLITE_INDEX_CONSTRAINT_GT 4
  5481. #define SQLITE_INDEX_CONSTRAINT_LE 8
  5482. #define SQLITE_INDEX_CONSTRAINT_LT 16
  5483. #define SQLITE_INDEX_CONSTRAINT_GE 32
  5484. #define SQLITE_INDEX_CONSTRAINT_MATCH 64
  5485. /*
  5486. ** CAPI3REF: Register A Virtual Table Implementation
  5487. **
  5488. ** ^These routines are used to register a new [virtual table module] name.
  5489. ** ^Module names must be registered before
  5490. ** creating a new [virtual table] using the module and before using a
  5491. ** preexisting [virtual table] for the module.
  5492. **
  5493. ** ^The module name is registered on the [database connection] specified
  5494. ** by the first parameter. ^The name of the module is given by the
  5495. ** second parameter. ^The third parameter is a pointer to
  5496. ** the implementation of the [virtual table module]. ^The fourth
  5497. ** parameter is an arbitrary client data pointer that is passed through
  5498. ** into the [xCreate] and [xConnect] methods of the virtual table module
  5499. ** when a new virtual table is be being created or reinitialized.
  5500. **
  5501. ** ^The sqlite3_create_module_v2() interface has a fifth parameter which
  5502. ** is a pointer to a destructor for the pClientData. ^SQLite will
  5503. ** invoke the destructor function (if it is not NULL) when SQLite
  5504. ** no longer needs the pClientData pointer. ^The destructor will also
  5505. ** be invoked if the call to sqlite3_create_module_v2() fails.
  5506. ** ^The sqlite3_create_module()
  5507. ** interface is equivalent to sqlite3_create_module_v2() with a NULL
  5508. ** destructor.
  5509. */
  5510. SQLITE_API int sqlite3_create_module(
  5511. sqlite3 *db, /* SQLite connection to register module with */
  5512. const char *zName, /* Name of the module */
  5513. const sqlite3_module *p, /* Methods for the module */
  5514. void *pClientData /* Client data for xCreate/xConnect */
  5515. );
  5516. SQLITE_API int sqlite3_create_module_v2(
  5517. sqlite3 *db, /* SQLite connection to register module with */
  5518. const char *zName, /* Name of the module */
  5519. const sqlite3_module *p, /* Methods for the module */
  5520. void *pClientData, /* Client data for xCreate/xConnect */
  5521. void(*xDestroy)(void*) /* Module destructor function */
  5522. );
  5523. /*
  5524. ** CAPI3REF: Virtual Table Instance Object
  5525. ** KEYWORDS: sqlite3_vtab
  5526. **
  5527. ** Every [virtual table module] implementation uses a subclass
  5528. ** of this object to describe a particular instance
  5529. ** of the [virtual table]. Each subclass will
  5530. ** be tailored to the specific needs of the module implementation.
  5531. ** The purpose of this superclass is to define certain fields that are
  5532. ** common to all module implementations.
  5533. **
  5534. ** ^Virtual tables methods can set an error message by assigning a
  5535. ** string obtained from [sqlite3_mprintf()] to zErrMsg. The method should
  5536. ** take care that any prior string is freed by a call to [sqlite3_free()]
  5537. ** prior to assigning a new string to zErrMsg. ^After the error message
  5538. ** is delivered up to the client application, the string will be automatically
  5539. ** freed by sqlite3_free() and the zErrMsg field will be zeroed.
  5540. */
  5541. struct sqlite3_vtab {
  5542. const sqlite3_module *pModule; /* The module for this virtual table */
  5543. int nRef; /* NO LONGER USED */
  5544. char *zErrMsg; /* Error message from sqlite3_mprintf() */
  5545. /* Virtual table implementations will typically add additional fields */
  5546. };
  5547. /*
  5548. ** CAPI3REF: Virtual Table Cursor Object
  5549. ** KEYWORDS: sqlite3_vtab_cursor {virtual table cursor}
  5550. **
  5551. ** Every [virtual table module] implementation uses a subclass of the
  5552. ** following structure to describe cursors that point into the
  5553. ** [virtual table] and are used
  5554. ** to loop through the virtual table. Cursors are created using the
  5555. ** [sqlite3_module.xOpen | xOpen] method of the module and are destroyed
  5556. ** by the [sqlite3_module.xClose | xClose] method. Cursors are used
  5557. ** by the [xFilter], [xNext], [xEof], [xColumn], and [xRowid] methods
  5558. ** of the module. Each module implementation will define
  5559. ** the content of a cursor structure to suit its own needs.
  5560. **
  5561. ** This superclass exists in order to define fields of the cursor that
  5562. ** are common to all implementations.
  5563. */
  5564. struct sqlite3_vtab_cursor {
  5565. sqlite3_vtab *pVtab; /* Virtual table of this cursor */
  5566. /* Virtual table implementations will typically add additional fields */
  5567. };
  5568. /*
  5569. ** CAPI3REF: Declare The Schema Of A Virtual Table
  5570. **
  5571. ** ^The [xCreate] and [xConnect] methods of a
  5572. ** [virtual table module] call this interface
  5573. ** to declare the format (the names and datatypes of the columns) of
  5574. ** the virtual tables they implement.
  5575. */
  5576. SQLITE_API int sqlite3_declare_vtab(sqlite3*, const char *zSQL);
  5577. /*
  5578. ** CAPI3REF: Overload A Function For A Virtual Table
  5579. **
  5580. ** ^(Virtual tables can provide alternative implementations of functions
  5581. ** using the [xFindFunction] method of the [virtual table module].
  5582. ** But global versions of those functions
  5583. ** must exist in order to be overloaded.)^
  5584. **
  5585. ** ^(This API makes sure a global version of a function with a particular
  5586. ** name and number of parameters exists. If no such function exists
  5587. ** before this API is called, a new function is created.)^ ^The implementation
  5588. ** of the new function always causes an exception to be thrown. So
  5589. ** the new function is not good for anything by itself. Its only
  5590. ** purpose is to be a placeholder function that can be overloaded
  5591. ** by a [virtual table].
  5592. */
  5593. SQLITE_API int sqlite3_overload_function(sqlite3*, const char *zFuncName, int nArg);
  5594. /*
  5595. ** The interface to the virtual-table mechanism defined above (back up
  5596. ** to a comment remarkably similar to this one) is currently considered
  5597. ** to be experimental. The interface might change in incompatible ways.
  5598. ** If this is a problem for you, do not use the interface at this time.
  5599. **
  5600. ** When the virtual-table mechanism stabilizes, we will declare the
  5601. ** interface fixed, support it indefinitely, and remove this comment.
  5602. */
  5603. /*
  5604. ** CAPI3REF: A Handle To An Open BLOB
  5605. ** KEYWORDS: {BLOB handle} {BLOB handles}
  5606. **
  5607. ** An instance of this object represents an open BLOB on which
  5608. ** [sqlite3_blob_open | incremental BLOB I/O] can be performed.
  5609. ** ^Objects of this type are created by [sqlite3_blob_open()]
  5610. ** and destroyed by [sqlite3_blob_close()].
  5611. ** ^The [sqlite3_blob_read()] and [sqlite3_blob_write()] interfaces
  5612. ** can be used to read or write small subsections of the BLOB.
  5613. ** ^The [sqlite3_blob_bytes()] interface returns the size of the BLOB in bytes.
  5614. */
  5615. typedef struct sqlite3_blob sqlite3_blob;
  5616. /*
  5617. ** CAPI3REF: Open A BLOB For Incremental I/O
  5618. **
  5619. ** ^(This interfaces opens a [BLOB handle | handle] to the BLOB located
  5620. ** in row iRow, column zColumn, table zTable in database zDb;
  5621. ** in other words, the same BLOB that would be selected by:
  5622. **
  5623. ** <pre>
  5624. ** SELECT zColumn FROM zDb.zTable WHERE [rowid] = iRow;
  5625. ** </pre>)^
  5626. **
  5627. ** ^If the flags parameter is non-zero, then the BLOB is opened for read
  5628. ** and write access. ^If it is zero, the BLOB is opened for read access.
  5629. ** ^It is not possible to open a column that is part of an index or primary
  5630. ** key for writing. ^If [foreign key constraints] are enabled, it is
  5631. ** not possible to open a column that is part of a [child key] for writing.
  5632. **
  5633. ** ^Note that the database name is not the filename that contains
  5634. ** the database but rather the symbolic name of the database that
  5635. ** appears after the AS keyword when the database is connected using [ATTACH].
  5636. ** ^For the main database file, the database name is "main".
  5637. ** ^For TEMP tables, the database name is "temp".
  5638. **
  5639. ** ^(On success, [SQLITE_OK] is returned and the new [BLOB handle] is written
  5640. ** to *ppBlob. Otherwise an [error code] is returned and *ppBlob is set
  5641. ** to be a null pointer.)^
  5642. ** ^This function sets the [database connection] error code and message
  5643. ** accessible via [sqlite3_errcode()] and [sqlite3_errmsg()] and related
  5644. ** functions. ^Note that the *ppBlob variable is always initialized in a
  5645. ** way that makes it safe to invoke [sqlite3_blob_close()] on *ppBlob
  5646. ** regardless of the success or failure of this routine.
  5647. **
  5648. ** ^(If the row that a BLOB handle points to is modified by an
  5649. ** [UPDATE], [DELETE], or by [ON CONFLICT] side-effects
  5650. ** then the BLOB handle is marked as "expired".
  5651. ** This is true if any column of the row is changed, even a column
  5652. ** other than the one the BLOB handle is open on.)^
  5653. ** ^Calls to [sqlite3_blob_read()] and [sqlite3_blob_write()] for
  5654. ** an expired BLOB handle fail with a return code of [SQLITE_ABORT].
  5655. ** ^(Changes written into a BLOB prior to the BLOB expiring are not
  5656. ** rolled back by the expiration of the BLOB. Such changes will eventually
  5657. ** commit if the transaction continues to completion.)^
  5658. **
  5659. ** ^Use the [sqlite3_blob_bytes()] interface to determine the size of
  5660. ** the opened blob. ^The size of a blob may not be changed by this
  5661. ** interface. Use the [UPDATE] SQL command to change the size of a
  5662. ** blob.
  5663. **
  5664. ** ^The [sqlite3_blob_open()] interface will fail for a [WITHOUT ROWID]
  5665. ** table. Incremental BLOB I/O is not possible on [WITHOUT ROWID] tables.
  5666. **
  5667. ** ^The [sqlite3_bind_zeroblob()] and [sqlite3_result_zeroblob()] interfaces
  5668. ** and the built-in [zeroblob] SQL function can be used, if desired,
  5669. ** to create an empty, zero-filled blob in which to read or write using
  5670. ** this interface.
  5671. **
  5672. ** To avoid a resource leak, every open [BLOB handle] should eventually
  5673. ** be released by a call to [sqlite3_blob_close()].
  5674. */
  5675. SQLITE_API int sqlite3_blob_open(
  5676. sqlite3*,
  5677. const char *zDb,
  5678. const char *zTable,
  5679. const char *zColumn,
  5680. sqlite3_int64 iRow,
  5681. int flags,
  5682. sqlite3_blob **ppBlob
  5683. );
  5684. /*
  5685. ** CAPI3REF: Move a BLOB Handle to a New Row
  5686. **
  5687. ** ^This function is used to move an existing blob handle so that it points
  5688. ** to a different row of the same database table. ^The new row is identified
  5689. ** by the rowid value passed as the second argument. Only the row can be
  5690. ** changed. ^The database, table and column on which the blob handle is open
  5691. ** remain the same. Moving an existing blob handle to a new row can be
  5692. ** faster than closing the existing handle and opening a new one.
  5693. **
  5694. ** ^(The new row must meet the same criteria as for [sqlite3_blob_open()] -
  5695. ** it must exist and there must be either a blob or text value stored in
  5696. ** the nominated column.)^ ^If the new row is not present in the table, or if
  5697. ** it does not contain a blob or text value, or if another error occurs, an
  5698. ** SQLite error code is returned and the blob handle is considered aborted.
  5699. ** ^All subsequent calls to [sqlite3_blob_read()], [sqlite3_blob_write()] or
  5700. ** [sqlite3_blob_reopen()] on an aborted blob handle immediately return
  5701. ** SQLITE_ABORT. ^Calling [sqlite3_blob_bytes()] on an aborted blob handle
  5702. ** always returns zero.
  5703. **
  5704. ** ^This function sets the database handle error code and message.
  5705. */
  5706. SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_blob_reopen(sqlite3_blob *, sqlite3_int64);
  5707. /*
  5708. ** CAPI3REF: Close A BLOB Handle
  5709. **
  5710. ** ^Closes an open [BLOB handle].
  5711. **
  5712. ** ^Closing a BLOB shall cause the current transaction to commit
  5713. ** if there are no other BLOBs, no pending prepared statements, and the
  5714. ** database connection is in [autocommit mode].
  5715. ** ^If any writes were made to the BLOB, they might be held in cache
  5716. ** until the close operation if they will fit.
  5717. **
  5718. ** ^(Closing the BLOB often forces the changes
  5719. ** out to disk and so if any I/O errors occur, they will likely occur
  5720. ** at the time when the BLOB is closed. Any errors that occur during
  5721. ** closing are reported as a non-zero return value.)^
  5722. **
  5723. ** ^(The BLOB is closed unconditionally. Even if this routine returns
  5724. ** an error code, the BLOB is still closed.)^
  5725. **
  5726. ** ^Calling this routine with a null pointer (such as would be returned
  5727. ** by a failed call to [sqlite3_blob_open()]) is a harmless no-op.
  5728. */
  5729. SQLITE_API int sqlite3_blob_close(sqlite3_blob *);
  5730. /*
  5731. ** CAPI3REF: Return The Size Of An Open BLOB
  5732. **
  5733. ** ^Returns the size in bytes of the BLOB accessible via the
  5734. ** successfully opened [BLOB handle] in its only argument. ^The
  5735. ** incremental blob I/O routines can only read or overwriting existing
  5736. ** blob content; they cannot change the size of a blob.
  5737. **
  5738. ** This routine only works on a [BLOB handle] which has been created
  5739. ** by a prior successful call to [sqlite3_blob_open()] and which has not
  5740. ** been closed by [sqlite3_blob_close()]. Passing any other pointer in
  5741. ** to this routine results in undefined and probably undesirable behavior.
  5742. */
  5743. SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *);
  5744. /*
  5745. ** CAPI3REF: Read Data From A BLOB Incrementally
  5746. **
  5747. ** ^(This function is used to read data from an open [BLOB handle] into a
  5748. ** caller-supplied buffer. N bytes of data are copied into buffer Z
  5749. ** from the open BLOB, starting at offset iOffset.)^
  5750. **
  5751. ** ^If offset iOffset is less than N bytes from the end of the BLOB,
  5752. ** [SQLITE_ERROR] is returned and no data is read. ^If N or iOffset is
  5753. ** less than zero, [SQLITE_ERROR] is returned and no data is read.
  5754. ** ^The size of the blob (and hence the maximum value of N+iOffset)
  5755. ** can be determined using the [sqlite3_blob_bytes()] interface.
  5756. **
  5757. ** ^An attempt to read from an expired [BLOB handle] fails with an
  5758. ** error code of [SQLITE_ABORT].
  5759. **
  5760. ** ^(On success, sqlite3_blob_read() returns SQLITE_OK.
  5761. ** Otherwise, an [error code] or an [extended error code] is returned.)^
  5762. **
  5763. ** This routine only works on a [BLOB handle] which has been created
  5764. ** by a prior successful call to [sqlite3_blob_open()] and which has not
  5765. ** been closed by [sqlite3_blob_close()]. Passing any other pointer in
  5766. ** to this routine results in undefined and probably undesirable behavior.
  5767. **
  5768. ** See also: [sqlite3_blob_write()].
  5769. */
  5770. SQLITE_API int sqlite3_blob_read(sqlite3_blob *, void *Z, int N, int iOffset);
  5771. /*
  5772. ** CAPI3REF: Write Data Into A BLOB Incrementally
  5773. **
  5774. ** ^This function is used to write data into an open [BLOB handle] from a
  5775. ** caller-supplied buffer. ^N bytes of data are copied from the buffer Z
  5776. ** into the open BLOB, starting at offset iOffset.
  5777. **
  5778. ** ^If the [BLOB handle] passed as the first argument was not opened for
  5779. ** writing (the flags parameter to [sqlite3_blob_open()] was zero),
  5780. ** this function returns [SQLITE_READONLY].
  5781. **
  5782. ** ^This function may only modify the contents of the BLOB; it is
  5783. ** not possible to increase the size of a BLOB using this API.
  5784. ** ^If offset iOffset is less than N bytes from the end of the BLOB,
  5785. ** [SQLITE_ERROR] is returned and no data is written. ^If N is
  5786. ** less than zero [SQLITE_ERROR] is returned and no data is written.
  5787. ** The size of the BLOB (and hence the maximum value of N+iOffset)
  5788. ** can be determined using the [sqlite3_blob_bytes()] interface.
  5789. **
  5790. ** ^An attempt to write to an expired [BLOB handle] fails with an
  5791. ** error code of [SQLITE_ABORT]. ^Writes to the BLOB that occurred
  5792. ** before the [BLOB handle] expired are not rolled back by the
  5793. ** expiration of the handle, though of course those changes might
  5794. ** have been overwritten by the statement that expired the BLOB handle
  5795. ** or by other independent statements.
  5796. **
  5797. ** ^(On success, sqlite3_blob_write() returns SQLITE_OK.
  5798. ** Otherwise, an [error code] or an [extended error code] is returned.)^
  5799. **
  5800. ** This routine only works on a [BLOB handle] which has been created
  5801. ** by a prior successful call to [sqlite3_blob_open()] and which has not
  5802. ** been closed by [sqlite3_blob_close()]. Passing any other pointer in
  5803. ** to this routine results in undefined and probably undesirable behavior.
  5804. **
  5805. ** See also: [sqlite3_blob_read()].
  5806. */
  5807. SQLITE_API int sqlite3_blob_write(sqlite3_blob *, const void *z, int n, int iOffset);
  5808. /*
  5809. ** CAPI3REF: Virtual File System Objects
  5810. **
  5811. ** A virtual filesystem (VFS) is an [sqlite3_vfs] object
  5812. ** that SQLite uses to interact
  5813. ** with the underlying operating system. Most SQLite builds come with a
  5814. ** single default VFS that is appropriate for the host computer.
  5815. ** New VFSes can be registered and existing VFSes can be unregistered.
  5816. ** The following interfaces are provided.
  5817. **
  5818. ** ^The sqlite3_vfs_find() interface returns a pointer to a VFS given its name.
  5819. ** ^Names are case sensitive.
  5820. ** ^Names are zero-terminated UTF-8 strings.
  5821. ** ^If there is no match, a NULL pointer is returned.
  5822. ** ^If zVfsName is NULL then the default VFS is returned.
  5823. **
  5824. ** ^New VFSes are registered with sqlite3_vfs_register().
  5825. ** ^Each new VFS becomes the default VFS if the makeDflt flag is set.
  5826. ** ^The same VFS can be registered multiple times without injury.
  5827. ** ^To make an existing VFS into the default VFS, register it again
  5828. ** with the makeDflt flag set. If two different VFSes with the
  5829. ** same name are registered, the behavior is undefined. If a
  5830. ** VFS is registered with a name that is NULL or an empty string,
  5831. ** then the behavior is undefined.
  5832. **
  5833. ** ^Unregister a VFS with the sqlite3_vfs_unregister() interface.
  5834. ** ^(If the default VFS is unregistered, another VFS is chosen as
  5835. ** the default. The choice for the new VFS is arbitrary.)^
  5836. */
  5837. SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfsName);
  5838. SQLITE_API int sqlite3_vfs_register(sqlite3_vfs*, int makeDflt);
  5839. SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs*);
  5840. /*
  5841. ** CAPI3REF: Mutexes
  5842. **
  5843. ** The SQLite core uses these routines for thread
  5844. ** synchronization. Though they are intended for internal
  5845. ** use by SQLite, code that links against SQLite is
  5846. ** permitted to use any of these routines.
  5847. **
  5848. ** The SQLite source code contains multiple implementations
  5849. ** of these mutex routines. An appropriate implementation
  5850. ** is selected automatically at compile-time. ^(The following
  5851. ** implementations are available in the SQLite core:
  5852. **
  5853. ** <ul>
  5854. ** <li> SQLITE_MUTEX_PTHREADS
  5855. ** <li> SQLITE_MUTEX_W32
  5856. ** <li> SQLITE_MUTEX_NOOP
  5857. ** </ul>)^
  5858. **
  5859. ** ^The SQLITE_MUTEX_NOOP implementation is a set of routines
  5860. ** that does no real locking and is appropriate for use in
  5861. ** a single-threaded application. ^The SQLITE_MUTEX_PTHREADS and
  5862. ** SQLITE_MUTEX_W32 implementations are appropriate for use on Unix
  5863. ** and Windows.
  5864. **
  5865. ** ^(If SQLite is compiled with the SQLITE_MUTEX_APPDEF preprocessor
  5866. ** macro defined (with "-DSQLITE_MUTEX_APPDEF=1"), then no mutex
  5867. ** implementation is included with the library. In this case the
  5868. ** application must supply a custom mutex implementation using the
  5869. ** [SQLITE_CONFIG_MUTEX] option of the sqlite3_config() function
  5870. ** before calling sqlite3_initialize() or any other public sqlite3_
  5871. ** function that calls sqlite3_initialize().)^
  5872. **
  5873. ** ^The sqlite3_mutex_alloc() routine allocates a new
  5874. ** mutex and returns a pointer to it. ^If it returns NULL
  5875. ** that means that a mutex could not be allocated. ^SQLite
  5876. ** will unwind its stack and return an error. ^(The argument
  5877. ** to sqlite3_mutex_alloc() is one of these integer constants:
  5878. **
  5879. ** <ul>
  5880. ** <li> SQLITE_MUTEX_FAST
  5881. ** <li> SQLITE_MUTEX_RECURSIVE
  5882. ** <li> SQLITE_MUTEX_STATIC_MASTER
  5883. ** <li> SQLITE_MUTEX_STATIC_MEM
  5884. ** <li> SQLITE_MUTEX_STATIC_OPEN
  5885. ** <li> SQLITE_MUTEX_STATIC_PRNG
  5886. ** <li> SQLITE_MUTEX_STATIC_LRU
  5887. ** <li> SQLITE_MUTEX_STATIC_PMEM
  5888. ** <li> SQLITE_MUTEX_STATIC_APP1
  5889. ** <li> SQLITE_MUTEX_STATIC_APP2
  5890. ** </ul>)^
  5891. **
  5892. ** ^The first two constants (SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE)
  5893. ** cause sqlite3_mutex_alloc() to create
  5894. ** a new mutex. ^The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
  5895. ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
  5896. ** The mutex implementation does not need to make a distinction
  5897. ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
  5898. ** not want to. ^SQLite will only request a recursive mutex in
  5899. ** cases where it really needs one. ^If a faster non-recursive mutex
  5900. ** implementation is available on the host platform, the mutex subsystem
  5901. ** might return such a mutex in response to SQLITE_MUTEX_FAST.
  5902. **
  5903. ** ^The other allowed parameters to sqlite3_mutex_alloc() (anything other
  5904. ** than SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE) each return
  5905. ** a pointer to a static preexisting mutex. ^Six static mutexes are
  5906. ** used by the current version of SQLite. Future versions of SQLite
  5907. ** may add additional static mutexes. Static mutexes are for internal
  5908. ** use by SQLite only. Applications that use SQLite mutexes should
  5909. ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
  5910. ** SQLITE_MUTEX_RECURSIVE.
  5911. **
  5912. ** ^Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
  5913. ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
  5914. ** returns a different mutex on every call. ^But for the static
  5915. ** mutex types, the same mutex is returned on every call that has
  5916. ** the same type number.
  5917. **
  5918. ** ^The sqlite3_mutex_free() routine deallocates a previously
  5919. ** allocated dynamic mutex. ^SQLite is careful to deallocate every
  5920. ** dynamic mutex that it allocates. The dynamic mutexes must not be in
  5921. ** use when they are deallocated. Attempting to deallocate a static
  5922. ** mutex results in undefined behavior. ^SQLite never deallocates
  5923. ** a static mutex.
  5924. **
  5925. ** ^The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
  5926. ** to enter a mutex. ^If another thread is already within the mutex,
  5927. ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
  5928. ** SQLITE_BUSY. ^The sqlite3_mutex_try() interface returns [SQLITE_OK]
  5929. ** upon successful entry. ^(Mutexes created using
  5930. ** SQLITE_MUTEX_RECURSIVE can be entered multiple times by the same thread.
  5931. ** In such cases the,
  5932. ** mutex must be exited an equal number of times before another thread
  5933. ** can enter.)^ ^(If the same thread tries to enter any other
  5934. ** kind of mutex more than once, the behavior is undefined.
  5935. ** SQLite will never exhibit
  5936. ** such behavior in its own use of mutexes.)^
  5937. **
  5938. ** ^(Some systems (for example, Windows 95) do not support the operation
  5939. ** implemented by sqlite3_mutex_try(). On those systems, sqlite3_mutex_try()
  5940. ** will always return SQLITE_BUSY. The SQLite core only ever uses
  5941. ** sqlite3_mutex_try() as an optimization so this is acceptable behavior.)^
  5942. **
  5943. ** ^The sqlite3_mutex_leave() routine exits a mutex that was
  5944. ** previously entered by the same thread. ^(The behavior
  5945. ** is undefined if the mutex is not currently entered by the
  5946. ** calling thread or is not currently allocated. SQLite will
  5947. ** never do either.)^
  5948. **
  5949. ** ^If the argument to sqlite3_mutex_enter(), sqlite3_mutex_try(), or
  5950. ** sqlite3_mutex_leave() is a NULL pointer, then all three routines
  5951. ** behave as no-ops.
  5952. **
  5953. ** See also: [sqlite3_mutex_held()] and [sqlite3_mutex_notheld()].
  5954. */
  5955. SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int);
  5956. SQLITE_API void sqlite3_mutex_free(sqlite3_mutex*);
  5957. SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex*);
  5958. SQLITE_API int sqlite3_mutex_try(sqlite3_mutex*);
  5959. SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex*);
  5960. /*
  5961. ** CAPI3REF: Mutex Methods Object
  5962. **
  5963. ** An instance of this structure defines the low-level routines
  5964. ** used to allocate and use mutexes.
  5965. **
  5966. ** Usually, the default mutex implementations provided by SQLite are
  5967. ** sufficient, however the user has the option of substituting a custom
  5968. ** implementation for specialized deployments or systems for which SQLite
  5969. ** does not provide a suitable implementation. In this case, the user
  5970. ** creates and populates an instance of this structure to pass
  5971. ** to sqlite3_config() along with the [SQLITE_CONFIG_MUTEX] option.
  5972. ** Additionally, an instance of this structure can be used as an
  5973. ** output variable when querying the system for the current mutex
  5974. ** implementation, using the [SQLITE_CONFIG_GETMUTEX] option.
  5975. **
  5976. ** ^The xMutexInit method defined by this structure is invoked as
  5977. ** part of system initialization by the sqlite3_initialize() function.
  5978. ** ^The xMutexInit routine is called by SQLite exactly once for each
  5979. ** effective call to [sqlite3_initialize()].
  5980. **
  5981. ** ^The xMutexEnd method defined by this structure is invoked as
  5982. ** part of system shutdown by the sqlite3_shutdown() function. The
  5983. ** implementation of this method is expected to release all outstanding
  5984. ** resources obtained by the mutex methods implementation, especially
  5985. ** those obtained by the xMutexInit method. ^The xMutexEnd()
  5986. ** interface is invoked exactly once for each call to [sqlite3_shutdown()].
  5987. **
  5988. ** ^(The remaining seven methods defined by this structure (xMutexAlloc,
  5989. ** xMutexFree, xMutexEnter, xMutexTry, xMutexLeave, xMutexHeld and
  5990. ** xMutexNotheld) implement the following interfaces (respectively):
  5991. **
  5992. ** <ul>
  5993. ** <li> [sqlite3_mutex_alloc()] </li>
  5994. ** <li> [sqlite3_mutex_free()] </li>
  5995. ** <li> [sqlite3_mutex_enter()] </li>
  5996. ** <li> [sqlite3_mutex_try()] </li>
  5997. ** <li> [sqlite3_mutex_leave()] </li>
  5998. ** <li> [sqlite3_mutex_held()] </li>
  5999. ** <li> [sqlite3_mutex_notheld()] </li>
  6000. ** </ul>)^
  6001. **
  6002. ** The only difference is that the public sqlite3_XXX functions enumerated
  6003. ** above silently ignore any invocations that pass a NULL pointer instead
  6004. ** of a valid mutex handle. The implementations of the methods defined
  6005. ** by this structure are not required to handle this case, the results
  6006. ** of passing a NULL pointer instead of a valid mutex handle are undefined
  6007. ** (i.e. it is acceptable to provide an implementation that segfaults if
  6008. ** it is passed a NULL pointer).
  6009. **
  6010. ** The xMutexInit() method must be threadsafe. ^It must be harmless to
  6011. ** invoke xMutexInit() multiple times within the same process and without
  6012. ** intervening calls to xMutexEnd(). Second and subsequent calls to
  6013. ** xMutexInit() must be no-ops.
  6014. **
  6015. ** ^xMutexInit() must not use SQLite memory allocation ([sqlite3_malloc()]
  6016. ** and its associates). ^Similarly, xMutexAlloc() must not use SQLite memory
  6017. ** allocation for a static mutex. ^However xMutexAlloc() may use SQLite
  6018. ** memory allocation for a fast or recursive mutex.
  6019. **
  6020. ** ^SQLite will invoke the xMutexEnd() method when [sqlite3_shutdown()] is
  6021. ** called, but only if the prior call to xMutexInit returned SQLITE_OK.
  6022. ** If xMutexInit fails in any way, it is expected to clean up after itself
  6023. ** prior to returning.
  6024. */
  6025. typedef struct sqlite3_mutex_methods sqlite3_mutex_methods;
  6026. struct sqlite3_mutex_methods {
  6027. int (*xMutexInit)(void);
  6028. int (*xMutexEnd)(void);
  6029. sqlite3_mutex *(*xMutexAlloc)(int);
  6030. void (*xMutexFree)(sqlite3_mutex *);
  6031. void (*xMutexEnter)(sqlite3_mutex *);
  6032. int (*xMutexTry)(sqlite3_mutex *);
  6033. void (*xMutexLeave)(sqlite3_mutex *);
  6034. int (*xMutexHeld)(sqlite3_mutex *);
  6035. int (*xMutexNotheld)(sqlite3_mutex *);
  6036. };
  6037. /*
  6038. ** CAPI3REF: Mutex Verification Routines
  6039. **
  6040. ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routines
  6041. ** are intended for use inside assert() statements. ^The SQLite core
  6042. ** never uses these routines except inside an assert() and applications
  6043. ** are advised to follow the lead of the core. ^The SQLite core only
  6044. ** provides implementations for these routines when it is compiled
  6045. ** with the SQLITE_DEBUG flag. ^External mutex implementations
  6046. ** are only required to provide these routines if SQLITE_DEBUG is
  6047. ** defined and if NDEBUG is not defined.
  6048. **
  6049. ** ^These routines should return true if the mutex in their argument
  6050. ** is held or not held, respectively, by the calling thread.
  6051. **
  6052. ** ^The implementation is not required to provide versions of these
  6053. ** routines that actually work. If the implementation does not provide working
  6054. ** versions of these routines, it should at least provide stubs that always
  6055. ** return true so that one does not get spurious assertion failures.
  6056. **
  6057. ** ^If the argument to sqlite3_mutex_held() is a NULL pointer then
  6058. ** the routine should return 1. This seems counter-intuitive since
  6059. ** clearly the mutex cannot be held if it does not exist. But
  6060. ** the reason the mutex does not exist is because the build is not
  6061. ** using mutexes. And we do not want the assert() containing the
  6062. ** call to sqlite3_mutex_held() to fail, so a non-zero return is
  6063. ** the appropriate thing to do. ^The sqlite3_mutex_notheld()
  6064. ** interface should also return 1 when given a NULL pointer.
  6065. */
  6066. #ifndef NDEBUG
  6067. SQLITE_API int sqlite3_mutex_held(sqlite3_mutex*);
  6068. SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex*);
  6069. #endif
  6070. /*
  6071. ** CAPI3REF: Mutex Types
  6072. **
  6073. ** The [sqlite3_mutex_alloc()] interface takes a single argument
  6074. ** which is one of these integer constants.
  6075. **
  6076. ** The set of static mutexes may change from one SQLite release to the
  6077. ** next. Applications that override the built-in mutex logic must be
  6078. ** prepared to accommodate additional static mutexes.
  6079. */
  6080. #define SQLITE_MUTEX_FAST 0
  6081. #define SQLITE_MUTEX_RECURSIVE 1
  6082. #define SQLITE_MUTEX_STATIC_MASTER 2
  6083. #define SQLITE_MUTEX_STATIC_MEM 3 /* sqlite3_malloc() */
  6084. #define SQLITE_MUTEX_STATIC_MEM2 4 /* NOT USED */
  6085. #define SQLITE_MUTEX_STATIC_OPEN 4 /* sqlite3BtreeOpen() */
  6086. #define SQLITE_MUTEX_STATIC_PRNG 5 /* sqlite3_random() */
  6087. #define SQLITE_MUTEX_STATIC_LRU 6 /* lru page list */
  6088. #define SQLITE_MUTEX_STATIC_LRU2 7 /* NOT USED */
  6089. #define SQLITE_MUTEX_STATIC_PMEM 7 /* sqlite3PageMalloc() */
  6090. #define SQLITE_MUTEX_STATIC_APP1 8 /* For use by application */
  6091. #define SQLITE_MUTEX_STATIC_APP2 9 /* For use by application */
  6092. #define SQLITE_MUTEX_STATIC_APP3 10 /* For use by application */
  6093. /*
  6094. ** CAPI3REF: Retrieve the mutex for a database connection
  6095. **
  6096. ** ^This interface returns a pointer the [sqlite3_mutex] object that
  6097. ** serializes access to the [database connection] given in the argument
  6098. ** when the [threading mode] is Serialized.
  6099. ** ^If the [threading mode] is Single-thread or Multi-thread then this
  6100. ** routine returns a NULL pointer.
  6101. */
  6102. SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3*);
  6103. /*
  6104. ** CAPI3REF: Low-Level Control Of Database Files
  6105. **
  6106. ** ^The [sqlite3_file_control()] interface makes a direct call to the
  6107. ** xFileControl method for the [sqlite3_io_methods] object associated
  6108. ** with a particular database identified by the second argument. ^The
  6109. ** name of the database is "main" for the main database or "temp" for the
  6110. ** TEMP database, or the name that appears after the AS keyword for
  6111. ** databases that are added using the [ATTACH] SQL command.
  6112. ** ^A NULL pointer can be used in place of "main" to refer to the
  6113. ** main database file.
  6114. ** ^The third and fourth parameters to this routine
  6115. ** are passed directly through to the second and third parameters of
  6116. ** the xFileControl method. ^The return value of the xFileControl
  6117. ** method becomes the return value of this routine.
  6118. **
  6119. ** ^The SQLITE_FCNTL_FILE_POINTER value for the op parameter causes
  6120. ** a pointer to the underlying [sqlite3_file] object to be written into
  6121. ** the space pointed to by the 4th parameter. ^The SQLITE_FCNTL_FILE_POINTER
  6122. ** case is a short-circuit path which does not actually invoke the
  6123. ** underlying sqlite3_io_methods.xFileControl method.
  6124. **
  6125. ** ^If the second parameter (zDbName) does not match the name of any
  6126. ** open database file, then SQLITE_ERROR is returned. ^This error
  6127. ** code is not remembered and will not be recalled by [sqlite3_errcode()]
  6128. ** or [sqlite3_errmsg()]. The underlying xFileControl method might
  6129. ** also return SQLITE_ERROR. There is no way to distinguish between
  6130. ** an incorrect zDbName and an SQLITE_ERROR return from the underlying
  6131. ** xFileControl method.
  6132. **
  6133. ** See also: [SQLITE_FCNTL_LOCKSTATE]
  6134. */
  6135. SQLITE_API int sqlite3_file_control(sqlite3*, const char *zDbName, int op, void*);
  6136. /*
  6137. ** CAPI3REF: Testing Interface
  6138. **
  6139. ** ^The sqlite3_test_control() interface is used to read out internal
  6140. ** state of SQLite and to inject faults into SQLite for testing
  6141. ** purposes. ^The first parameter is an operation code that determines
  6142. ** the number, meaning, and operation of all subsequent parameters.
  6143. **
  6144. ** This interface is not for use by applications. It exists solely
  6145. ** for verifying the correct operation of the SQLite library. Depending
  6146. ** on how the SQLite library is compiled, this interface might not exist.
  6147. **
  6148. ** The details of the operation codes, their meanings, the parameters
  6149. ** they take, and what they do are all subject to change without notice.
  6150. ** Unlike most of the SQLite API, this function is not guaranteed to
  6151. ** operate consistently from one release to the next.
  6152. */
  6153. SQLITE_API int sqlite3_test_control(int op, ...);
  6154. /*
  6155. ** CAPI3REF: Testing Interface Operation Codes
  6156. **
  6157. ** These constants are the valid operation code parameters used
  6158. ** as the first argument to [sqlite3_test_control()].
  6159. **
  6160. ** These parameters and their meanings are subject to change
  6161. ** without notice. These values are for testing purposes only.
  6162. ** Applications should not use any of these parameters or the
  6163. ** [sqlite3_test_control()] interface.
  6164. */
  6165. #define SQLITE_TESTCTRL_FIRST 5
  6166. #define SQLITE_TESTCTRL_PRNG_SAVE 5
  6167. #define SQLITE_TESTCTRL_PRNG_RESTORE 6
  6168. #define SQLITE_TESTCTRL_PRNG_RESET 7
  6169. #define SQLITE_TESTCTRL_BITVEC_TEST 8
  6170. #define SQLITE_TESTCTRL_FAULT_INSTALL 9
  6171. #define SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS 10
  6172. #define SQLITE_TESTCTRL_PENDING_BYTE 11
  6173. #define SQLITE_TESTCTRL_ASSERT 12
  6174. #define SQLITE_TESTCTRL_ALWAYS 13
  6175. #define SQLITE_TESTCTRL_RESERVE 14
  6176. #define SQLITE_TESTCTRL_OPTIMIZATIONS 15
  6177. #define SQLITE_TESTCTRL_ISKEYWORD 16
  6178. #define SQLITE_TESTCTRL_SCRATCHMALLOC 17
  6179. #define SQLITE_TESTCTRL_LOCALTIME_FAULT 18
  6180. #define SQLITE_TESTCTRL_EXPLAIN_STMT 19 /* NOT USED */
  6181. #define SQLITE_TESTCTRL_NEVER_CORRUPT 20
  6182. #define SQLITE_TESTCTRL_VDBE_COVERAGE 21
  6183. #define SQLITE_TESTCTRL_BYTEORDER 22
  6184. #define SQLITE_TESTCTRL_ISINIT 23
  6185. #define SQLITE_TESTCTRL_SORTER_MMAP 24
  6186. #define SQLITE_TESTCTRL_LAST 24
  6187. /*
  6188. ** CAPI3REF: SQLite Runtime Status
  6189. **
  6190. ** ^This interface is used to retrieve runtime status information
  6191. ** about the performance of SQLite, and optionally to reset various
  6192. ** highwater marks. ^The first argument is an integer code for
  6193. ** the specific parameter to measure. ^(Recognized integer codes
  6194. ** are of the form [status parameters | SQLITE_STATUS_...].)^
  6195. ** ^The current value of the parameter is returned into *pCurrent.
  6196. ** ^The highest recorded value is returned in *pHighwater. ^If the
  6197. ** resetFlag is true, then the highest record value is reset after
  6198. ** *pHighwater is written. ^(Some parameters do not record the highest
  6199. ** value. For those parameters
  6200. ** nothing is written into *pHighwater and the resetFlag is ignored.)^
  6201. ** ^(Other parameters record only the highwater mark and not the current
  6202. ** value. For these latter parameters nothing is written into *pCurrent.)^
  6203. **
  6204. ** ^The sqlite3_status() routine returns SQLITE_OK on success and a
  6205. ** non-zero [error code] on failure.
  6206. **
  6207. ** This routine is threadsafe but is not atomic. This routine can be
  6208. ** called while other threads are running the same or different SQLite
  6209. ** interfaces. However the values returned in *pCurrent and
  6210. ** *pHighwater reflect the status of SQLite at different points in time
  6211. ** and it is possible that another thread might change the parameter
  6212. ** in between the times when *pCurrent and *pHighwater are written.
  6213. **
  6214. ** See also: [sqlite3_db_status()]
  6215. */
  6216. SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag);
  6217. /*
  6218. ** CAPI3REF: Status Parameters
  6219. ** KEYWORDS: {status parameters}
  6220. **
  6221. ** These integer constants designate various run-time status parameters
  6222. ** that can be returned by [sqlite3_status()].
  6223. **
  6224. ** <dl>
  6225. ** [[SQLITE_STATUS_MEMORY_USED]] ^(<dt>SQLITE_STATUS_MEMORY_USED</dt>
  6226. ** <dd>This parameter is the current amount of memory checked out
  6227. ** using [sqlite3_malloc()], either directly or indirectly. The
  6228. ** figure includes calls made to [sqlite3_malloc()] by the application
  6229. ** and internal memory usage by the SQLite library. Scratch memory
  6230. ** controlled by [SQLITE_CONFIG_SCRATCH] and auxiliary page-cache
  6231. ** memory controlled by [SQLITE_CONFIG_PAGECACHE] is not included in
  6232. ** this parameter. The amount returned is the sum of the allocation
  6233. ** sizes as reported by the xSize method in [sqlite3_mem_methods].</dd>)^
  6234. **
  6235. ** [[SQLITE_STATUS_MALLOC_SIZE]] ^(<dt>SQLITE_STATUS_MALLOC_SIZE</dt>
  6236. ** <dd>This parameter records the largest memory allocation request
  6237. ** handed to [sqlite3_malloc()] or [sqlite3_realloc()] (or their
  6238. ** internal equivalents). Only the value returned in the
  6239. ** *pHighwater parameter to [sqlite3_status()] is of interest.
  6240. ** The value written into the *pCurrent parameter is undefined.</dd>)^
  6241. **
  6242. ** [[SQLITE_STATUS_MALLOC_COUNT]] ^(<dt>SQLITE_STATUS_MALLOC_COUNT</dt>
  6243. ** <dd>This parameter records the number of separate memory allocations
  6244. ** currently checked out.</dd>)^
  6245. **
  6246. ** [[SQLITE_STATUS_PAGECACHE_USED]] ^(<dt>SQLITE_STATUS_PAGECACHE_USED</dt>
  6247. ** <dd>This parameter returns the number of pages used out of the
  6248. ** [pagecache memory allocator] that was configured using
  6249. ** [SQLITE_CONFIG_PAGECACHE]. The
  6250. ** value returned is in pages, not in bytes.</dd>)^
  6251. **
  6252. ** [[SQLITE_STATUS_PAGECACHE_OVERFLOW]]
  6253. ** ^(<dt>SQLITE_STATUS_PAGECACHE_OVERFLOW</dt>
  6254. ** <dd>This parameter returns the number of bytes of page cache
  6255. ** allocation which could not be satisfied by the [SQLITE_CONFIG_PAGECACHE]
  6256. ** buffer and where forced to overflow to [sqlite3_malloc()]. The
  6257. ** returned value includes allocations that overflowed because they
  6258. ** where too large (they were larger than the "sz" parameter to
  6259. ** [SQLITE_CONFIG_PAGECACHE]) and allocations that overflowed because
  6260. ** no space was left in the page cache.</dd>)^
  6261. **
  6262. ** [[SQLITE_STATUS_PAGECACHE_SIZE]] ^(<dt>SQLITE_STATUS_PAGECACHE_SIZE</dt>
  6263. ** <dd>This parameter records the largest memory allocation request
  6264. ** handed to [pagecache memory allocator]. Only the value returned in the
  6265. ** *pHighwater parameter to [sqlite3_status()] is of interest.
  6266. ** The value written into the *pCurrent parameter is undefined.</dd>)^
  6267. **
  6268. ** [[SQLITE_STATUS_SCRATCH_USED]] ^(<dt>SQLITE_STATUS_SCRATCH_USED</dt>
  6269. ** <dd>This parameter returns the number of allocations used out of the
  6270. ** [scratch memory allocator] configured using
  6271. ** [SQLITE_CONFIG_SCRATCH]. The value returned is in allocations, not
  6272. ** in bytes. Since a single thread may only have one scratch allocation
  6273. ** outstanding at time, this parameter also reports the number of threads
  6274. ** using scratch memory at the same time.</dd>)^
  6275. **
  6276. ** [[SQLITE_STATUS_SCRATCH_OVERFLOW]] ^(<dt>SQLITE_STATUS_SCRATCH_OVERFLOW</dt>
  6277. ** <dd>This parameter returns the number of bytes of scratch memory
  6278. ** allocation which could not be satisfied by the [SQLITE_CONFIG_SCRATCH]
  6279. ** buffer and where forced to overflow to [sqlite3_malloc()]. The values
  6280. ** returned include overflows because the requested allocation was too
  6281. ** larger (that is, because the requested allocation was larger than the
  6282. ** "sz" parameter to [SQLITE_CONFIG_SCRATCH]) and because no scratch buffer
  6283. ** slots were available.
  6284. ** </dd>)^
  6285. **
  6286. ** [[SQLITE_STATUS_SCRATCH_SIZE]] ^(<dt>SQLITE_STATUS_SCRATCH_SIZE</dt>
  6287. ** <dd>This parameter records the largest memory allocation request
  6288. ** handed to [scratch memory allocator]. Only the value returned in the
  6289. ** *pHighwater parameter to [sqlite3_status()] is of interest.
  6290. ** The value written into the *pCurrent parameter is undefined.</dd>)^
  6291. **
  6292. ** [[SQLITE_STATUS_PARSER_STACK]] ^(<dt>SQLITE_STATUS_PARSER_STACK</dt>
  6293. ** <dd>This parameter records the deepest parser stack. It is only
  6294. ** meaningful if SQLite is compiled with [YYTRACKMAXSTACKDEPTH].</dd>)^
  6295. ** </dl>
  6296. **
  6297. ** New status parameters may be added from time to time.
  6298. */
  6299. #define SQLITE_STATUS_MEMORY_USED 0
  6300. #define SQLITE_STATUS_PAGECACHE_USED 1
  6301. #define SQLITE_STATUS_PAGECACHE_OVERFLOW 2
  6302. #define SQLITE_STATUS_SCRATCH_USED 3
  6303. #define SQLITE_STATUS_SCRATCH_OVERFLOW 4
  6304. #define SQLITE_STATUS_MALLOC_SIZE 5
  6305. #define SQLITE_STATUS_PARSER_STACK 6
  6306. #define SQLITE_STATUS_PAGECACHE_SIZE 7
  6307. #define SQLITE_STATUS_SCRATCH_SIZE 8
  6308. #define SQLITE_STATUS_MALLOC_COUNT 9
  6309. /*
  6310. ** CAPI3REF: Database Connection Status
  6311. **
  6312. ** ^This interface is used to retrieve runtime status information
  6313. ** about a single [database connection]. ^The first argument is the
  6314. ** database connection object to be interrogated. ^The second argument
  6315. ** is an integer constant, taken from the set of
  6316. ** [SQLITE_DBSTATUS options], that
  6317. ** determines the parameter to interrogate. The set of
  6318. ** [SQLITE_DBSTATUS options] is likely
  6319. ** to grow in future releases of SQLite.
  6320. **
  6321. ** ^The current value of the requested parameter is written into *pCur
  6322. ** and the highest instantaneous value is written into *pHiwtr. ^If
  6323. ** the resetFlg is true, then the highest instantaneous value is
  6324. ** reset back down to the current value.
  6325. **
  6326. ** ^The sqlite3_db_status() routine returns SQLITE_OK on success and a
  6327. ** non-zero [error code] on failure.
  6328. **
  6329. ** See also: [sqlite3_status()] and [sqlite3_stmt_status()].
  6330. */
  6331. SQLITE_API int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int resetFlg);
  6332. /*
  6333. ** CAPI3REF: Status Parameters for database connections
  6334. ** KEYWORDS: {SQLITE_DBSTATUS options}
  6335. **
  6336. ** These constants are the available integer "verbs" that can be passed as
  6337. ** the second argument to the [sqlite3_db_status()] interface.
  6338. **
  6339. ** New verbs may be added in future releases of SQLite. Existing verbs
  6340. ** might be discontinued. Applications should check the return code from
  6341. ** [sqlite3_db_status()] to make sure that the call worked.
  6342. ** The [sqlite3_db_status()] interface will return a non-zero error code
  6343. ** if a discontinued or unsupported verb is invoked.
  6344. **
  6345. ** <dl>
  6346. ** [[SQLITE_DBSTATUS_LOOKASIDE_USED]] ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_USED</dt>
  6347. ** <dd>This parameter returns the number of lookaside memory slots currently
  6348. ** checked out.</dd>)^
  6349. **
  6350. ** [[SQLITE_DBSTATUS_LOOKASIDE_HIT]] ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_HIT</dt>
  6351. ** <dd>This parameter returns the number malloc attempts that were
  6352. ** satisfied using lookaside memory. Only the high-water value is meaningful;
  6353. ** the current value is always zero.)^
  6354. **
  6355. ** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE]]
  6356. ** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE</dt>
  6357. ** <dd>This parameter returns the number malloc attempts that might have
  6358. ** been satisfied using lookaside memory but failed due to the amount of
  6359. ** memory requested being larger than the lookaside slot size.
  6360. ** Only the high-water value is meaningful;
  6361. ** the current value is always zero.)^
  6362. **
  6363. ** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL]]
  6364. ** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL</dt>
  6365. ** <dd>This parameter returns the number malloc attempts that might have
  6366. ** been satisfied using lookaside memory but failed due to all lookaside
  6367. ** memory already being in use.
  6368. ** Only the high-water value is meaningful;
  6369. ** the current value is always zero.)^
  6370. **
  6371. ** [[SQLITE_DBSTATUS_CACHE_USED]] ^(<dt>SQLITE_DBSTATUS_CACHE_USED</dt>
  6372. ** <dd>This parameter returns the approximate number of bytes of heap
  6373. ** memory used by all pager caches associated with the database connection.)^
  6374. ** ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_USED is always 0.
  6375. **
  6376. ** [[SQLITE_DBSTATUS_SCHEMA_USED]] ^(<dt>SQLITE_DBSTATUS_SCHEMA_USED</dt>
  6377. ** <dd>This parameter returns the approximate number of bytes of heap
  6378. ** memory used to store the schema for all databases associated
  6379. ** with the connection - main, temp, and any [ATTACH]-ed databases.)^
  6380. ** ^The full amount of memory used by the schemas is reported, even if the
  6381. ** schema memory is shared with other database connections due to
  6382. ** [shared cache mode] being enabled.
  6383. ** ^The highwater mark associated with SQLITE_DBSTATUS_SCHEMA_USED is always 0.
  6384. **
  6385. ** [[SQLITE_DBSTATUS_STMT_USED]] ^(<dt>SQLITE_DBSTATUS_STMT_USED</dt>
  6386. ** <dd>This parameter returns the approximate number of bytes of heap
  6387. ** and lookaside memory used by all prepared statements associated with
  6388. ** the database connection.)^
  6389. ** ^The highwater mark associated with SQLITE_DBSTATUS_STMT_USED is always 0.
  6390. ** </dd>
  6391. **
  6392. ** [[SQLITE_DBSTATUS_CACHE_HIT]] ^(<dt>SQLITE_DBSTATUS_CACHE_HIT</dt>
  6393. ** <dd>This parameter returns the number of pager cache hits that have
  6394. ** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_HIT
  6395. ** is always 0.
  6396. ** </dd>
  6397. **
  6398. ** [[SQLITE_DBSTATUS_CACHE_MISS]] ^(<dt>SQLITE_DBSTATUS_CACHE_MISS</dt>
  6399. ** <dd>This parameter returns the number of pager cache misses that have
  6400. ** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_MISS
  6401. ** is always 0.
  6402. ** </dd>
  6403. **
  6404. ** [[SQLITE_DBSTATUS_CACHE_WRITE]] ^(<dt>SQLITE_DBSTATUS_CACHE_WRITE</dt>
  6405. ** <dd>This parameter returns the number of dirty cache entries that have
  6406. ** been written to disk. Specifically, the number of pages written to the
  6407. ** wal file in wal mode databases, or the number of pages written to the
  6408. ** database file in rollback mode databases. Any pages written as part of
  6409. ** transaction rollback or database recovery operations are not included.
  6410. ** If an IO or other error occurs while writing a page to disk, the effect
  6411. ** on subsequent SQLITE_DBSTATUS_CACHE_WRITE requests is undefined.)^ ^The
  6412. ** highwater mark associated with SQLITE_DBSTATUS_CACHE_WRITE is always 0.
  6413. ** </dd>
  6414. **
  6415. ** [[SQLITE_DBSTATUS_DEFERRED_FKS]] ^(<dt>SQLITE_DBSTATUS_DEFERRED_FKS</dt>
  6416. ** <dd>This parameter returns zero for the current value if and only if
  6417. ** all foreign key constraints (deferred or immediate) have been
  6418. ** resolved.)^ ^The highwater mark is always 0.
  6419. ** </dd>
  6420. ** </dl>
  6421. */
  6422. #define SQLITE_DBSTATUS_LOOKASIDE_USED 0
  6423. #define SQLITE_DBSTATUS_CACHE_USED 1
  6424. #define SQLITE_DBSTATUS_SCHEMA_USED 2
  6425. #define SQLITE_DBSTATUS_STMT_USED 3
  6426. #define SQLITE_DBSTATUS_LOOKASIDE_HIT 4
  6427. #define SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE 5
  6428. #define SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL 6
  6429. #define SQLITE_DBSTATUS_CACHE_HIT 7
  6430. #define SQLITE_DBSTATUS_CACHE_MISS 8
  6431. #define SQLITE_DBSTATUS_CACHE_WRITE 9
  6432. #define SQLITE_DBSTATUS_DEFERRED_FKS 10
  6433. #define SQLITE_DBSTATUS_MAX 10 /* Largest defined DBSTATUS */
  6434. /*
  6435. ** CAPI3REF: Prepared Statement Status
  6436. **
  6437. ** ^(Each prepared statement maintains various
  6438. ** [SQLITE_STMTSTATUS counters] that measure the number
  6439. ** of times it has performed specific operations.)^ These counters can
  6440. ** be used to monitor the performance characteristics of the prepared
  6441. ** statements. For example, if the number of table steps greatly exceeds
  6442. ** the number of table searches or result rows, that would tend to indicate
  6443. ** that the prepared statement is using a full table scan rather than
  6444. ** an index.
  6445. **
  6446. ** ^(This interface is used to retrieve and reset counter values from
  6447. ** a [prepared statement]. The first argument is the prepared statement
  6448. ** object to be interrogated. The second argument
  6449. ** is an integer code for a specific [SQLITE_STMTSTATUS counter]
  6450. ** to be interrogated.)^
  6451. ** ^The current value of the requested counter is returned.
  6452. ** ^If the resetFlg is true, then the counter is reset to zero after this
  6453. ** interface call returns.
  6454. **
  6455. ** See also: [sqlite3_status()] and [sqlite3_db_status()].
  6456. */
  6457. SQLITE_API int sqlite3_stmt_status(sqlite3_stmt*, int op,int resetFlg);
  6458. /*
  6459. ** CAPI3REF: Status Parameters for prepared statements
  6460. ** KEYWORDS: {SQLITE_STMTSTATUS counter} {SQLITE_STMTSTATUS counters}
  6461. **
  6462. ** These preprocessor macros define integer codes that name counter
  6463. ** values associated with the [sqlite3_stmt_status()] interface.
  6464. ** The meanings of the various counters are as follows:
  6465. **
  6466. ** <dl>
  6467. ** [[SQLITE_STMTSTATUS_FULLSCAN_STEP]] <dt>SQLITE_STMTSTATUS_FULLSCAN_STEP</dt>
  6468. ** <dd>^This is the number of times that SQLite has stepped forward in
  6469. ** a table as part of a full table scan. Large numbers for this counter
  6470. ** may indicate opportunities for performance improvement through
  6471. ** careful use of indices.</dd>
  6472. **
  6473. ** [[SQLITE_STMTSTATUS_SORT]] <dt>SQLITE_STMTSTATUS_SORT</dt>
  6474. ** <dd>^This is the number of sort operations that have occurred.
  6475. ** A non-zero value in this counter may indicate an opportunity to
  6476. ** improvement performance through careful use of indices.</dd>
  6477. **
  6478. ** [[SQLITE_STMTSTATUS_AUTOINDEX]] <dt>SQLITE_STMTSTATUS_AUTOINDEX</dt>
  6479. ** <dd>^This is the number of rows inserted into transient indices that
  6480. ** were created automatically in order to help joins run faster.
  6481. ** A non-zero value in this counter may indicate an opportunity to
  6482. ** improvement performance by adding permanent indices that do not
  6483. ** need to be reinitialized each time the statement is run.</dd>
  6484. **
  6485. ** [[SQLITE_STMTSTATUS_VM_STEP]] <dt>SQLITE_STMTSTATUS_VM_STEP</dt>
  6486. ** <dd>^This is the number of virtual machine operations executed
  6487. ** by the prepared statement if that number is less than or equal
  6488. ** to 2147483647. The number of virtual machine operations can be
  6489. ** used as a proxy for the total work done by the prepared statement.
  6490. ** If the number of virtual machine operations exceeds 2147483647
  6491. ** then the value returned by this statement status code is undefined.
  6492. ** </dd>
  6493. ** </dl>
  6494. */
  6495. #define SQLITE_STMTSTATUS_FULLSCAN_STEP 1
  6496. #define SQLITE_STMTSTATUS_SORT 2
  6497. #define SQLITE_STMTSTATUS_AUTOINDEX 3
  6498. #define SQLITE_STMTSTATUS_VM_STEP 4
  6499. /*
  6500. ** CAPI3REF: Custom Page Cache Object
  6501. **
  6502. ** The sqlite3_pcache type is opaque. It is implemented by
  6503. ** the pluggable module. The SQLite core has no knowledge of
  6504. ** its size or internal structure and never deals with the
  6505. ** sqlite3_pcache object except by holding and passing pointers
  6506. ** to the object.
  6507. **
  6508. ** See [sqlite3_pcache_methods2] for additional information.
  6509. */
  6510. typedef struct sqlite3_pcache sqlite3_pcache;
  6511. /*
  6512. ** CAPI3REF: Custom Page Cache Object
  6513. **
  6514. ** The sqlite3_pcache_page object represents a single page in the
  6515. ** page cache. The page cache will allocate instances of this
  6516. ** object. Various methods of the page cache use pointers to instances
  6517. ** of this object as parameters or as their return value.
  6518. **
  6519. ** See [sqlite3_pcache_methods2] for additional information.
  6520. */
  6521. typedef struct sqlite3_pcache_page sqlite3_pcache_page;
  6522. struct sqlite3_pcache_page {
  6523. void *pBuf; /* The content of the page */
  6524. void *pExtra; /* Extra information associated with the page */
  6525. };
  6526. /*
  6527. ** CAPI3REF: Application Defined Page Cache.
  6528. ** KEYWORDS: {page cache}
  6529. **
  6530. ** ^(The [sqlite3_config]([SQLITE_CONFIG_PCACHE2], ...) interface can
  6531. ** register an alternative page cache implementation by passing in an
  6532. ** instance of the sqlite3_pcache_methods2 structure.)^
  6533. ** In many applications, most of the heap memory allocated by
  6534. ** SQLite is used for the page cache.
  6535. ** By implementing a
  6536. ** custom page cache using this API, an application can better control
  6537. ** the amount of memory consumed by SQLite, the way in which
  6538. ** that memory is allocated and released, and the policies used to
  6539. ** determine exactly which parts of a database file are cached and for
  6540. ** how long.
  6541. **
  6542. ** The alternative page cache mechanism is an
  6543. ** extreme measure that is only needed by the most demanding applications.
  6544. ** The built-in page cache is recommended for most uses.
  6545. **
  6546. ** ^(The contents of the sqlite3_pcache_methods2 structure are copied to an
  6547. ** internal buffer by SQLite within the call to [sqlite3_config]. Hence
  6548. ** the application may discard the parameter after the call to
  6549. ** [sqlite3_config()] returns.)^
  6550. **
  6551. ** [[the xInit() page cache method]]
  6552. ** ^(The xInit() method is called once for each effective
  6553. ** call to [sqlite3_initialize()])^
  6554. ** (usually only once during the lifetime of the process). ^(The xInit()
  6555. ** method is passed a copy of the sqlite3_pcache_methods2.pArg value.)^
  6556. ** The intent of the xInit() method is to set up global data structures
  6557. ** required by the custom page cache implementation.
  6558. ** ^(If the xInit() method is NULL, then the
  6559. ** built-in default page cache is used instead of the application defined
  6560. ** page cache.)^
  6561. **
  6562. ** [[the xShutdown() page cache method]]
  6563. ** ^The xShutdown() method is called by [sqlite3_shutdown()].
  6564. ** It can be used to clean up
  6565. ** any outstanding resources before process shutdown, if required.
  6566. ** ^The xShutdown() method may be NULL.
  6567. **
  6568. ** ^SQLite automatically serializes calls to the xInit method,
  6569. ** so the xInit method need not be threadsafe. ^The
  6570. ** xShutdown method is only called from [sqlite3_shutdown()] so it does
  6571. ** not need to be threadsafe either. All other methods must be threadsafe
  6572. ** in multithreaded applications.
  6573. **
  6574. ** ^SQLite will never invoke xInit() more than once without an intervening
  6575. ** call to xShutdown().
  6576. **
  6577. ** [[the xCreate() page cache methods]]
  6578. ** ^SQLite invokes the xCreate() method to construct a new cache instance.
  6579. ** SQLite will typically create one cache instance for each open database file,
  6580. ** though this is not guaranteed. ^The
  6581. ** first parameter, szPage, is the size in bytes of the pages that must
  6582. ** be allocated by the cache. ^szPage will always a power of two. ^The
  6583. ** second parameter szExtra is a number of bytes of extra storage
  6584. ** associated with each page cache entry. ^The szExtra parameter will
  6585. ** a number less than 250. SQLite will use the
  6586. ** extra szExtra bytes on each page to store metadata about the underlying
  6587. ** database page on disk. The value passed into szExtra depends
  6588. ** on the SQLite version, the target platform, and how SQLite was compiled.
  6589. ** ^The third argument to xCreate(), bPurgeable, is true if the cache being
  6590. ** created will be used to cache database pages of a file stored on disk, or
  6591. ** false if it is used for an in-memory database. The cache implementation
  6592. ** does not have to do anything special based with the value of bPurgeable;
  6593. ** it is purely advisory. ^On a cache where bPurgeable is false, SQLite will
  6594. ** never invoke xUnpin() except to deliberately delete a page.
  6595. ** ^In other words, calls to xUnpin() on a cache with bPurgeable set to
  6596. ** false will always have the "discard" flag set to true.
  6597. ** ^Hence, a cache created with bPurgeable false will
  6598. ** never contain any unpinned pages.
  6599. **
  6600. ** [[the xCachesize() page cache method]]
  6601. ** ^(The xCachesize() method may be called at any time by SQLite to set the
  6602. ** suggested maximum cache-size (number of pages stored by) the cache
  6603. ** instance passed as the first argument. This is the value configured using
  6604. ** the SQLite "[PRAGMA cache_size]" command.)^ As with the bPurgeable
  6605. ** parameter, the implementation is not required to do anything with this
  6606. ** value; it is advisory only.
  6607. **
  6608. ** [[the xPagecount() page cache methods]]
  6609. ** The xPagecount() method must return the number of pages currently
  6610. ** stored in the cache, both pinned and unpinned.
  6611. **
  6612. ** [[the xFetch() page cache methods]]
  6613. ** The xFetch() method locates a page in the cache and returns a pointer to
  6614. ** an sqlite3_pcache_page object associated with that page, or a NULL pointer.
  6615. ** The pBuf element of the returned sqlite3_pcache_page object will be a
  6616. ** pointer to a buffer of szPage bytes used to store the content of a
  6617. ** single database page. The pExtra element of sqlite3_pcache_page will be
  6618. ** a pointer to the szExtra bytes of extra storage that SQLite has requested
  6619. ** for each entry in the page cache.
  6620. **
  6621. ** The page to be fetched is determined by the key. ^The minimum key value
  6622. ** is 1. After it has been retrieved using xFetch, the page is considered
  6623. ** to be "pinned".
  6624. **
  6625. ** If the requested page is already in the page cache, then the page cache
  6626. ** implementation must return a pointer to the page buffer with its content
  6627. ** intact. If the requested page is not already in the cache, then the
  6628. ** cache implementation should use the value of the createFlag
  6629. ** parameter to help it determined what action to take:
  6630. **
  6631. ** <table border=1 width=85% align=center>
  6632. ** <tr><th> createFlag <th> Behavior when page is not already in cache
  6633. ** <tr><td> 0 <td> Do not allocate a new page. Return NULL.
  6634. ** <tr><td> 1 <td> Allocate a new page if it easy and convenient to do so.
  6635. ** Otherwise return NULL.
  6636. ** <tr><td> 2 <td> Make every effort to allocate a new page. Only return
  6637. ** NULL if allocating a new page is effectively impossible.
  6638. ** </table>
  6639. **
  6640. ** ^(SQLite will normally invoke xFetch() with a createFlag of 0 or 1. SQLite
  6641. ** will only use a createFlag of 2 after a prior call with a createFlag of 1
  6642. ** failed.)^ In between the to xFetch() calls, SQLite may
  6643. ** attempt to unpin one or more cache pages by spilling the content of
  6644. ** pinned pages to disk and synching the operating system disk cache.
  6645. **
  6646. ** [[the xUnpin() page cache method]]
  6647. ** ^xUnpin() is called by SQLite with a pointer to a currently pinned page
  6648. ** as its second argument. If the third parameter, discard, is non-zero,
  6649. ** then the page must be evicted from the cache.
  6650. ** ^If the discard parameter is
  6651. ** zero, then the page may be discarded or retained at the discretion of
  6652. ** page cache implementation. ^The page cache implementation
  6653. ** may choose to evict unpinned pages at any time.
  6654. **
  6655. ** The cache must not perform any reference counting. A single
  6656. ** call to xUnpin() unpins the page regardless of the number of prior calls
  6657. ** to xFetch().
  6658. **
  6659. ** [[the xRekey() page cache methods]]
  6660. ** The xRekey() method is used to change the key value associated with the
  6661. ** page passed as the second argument. If the cache
  6662. ** previously contains an entry associated with newKey, it must be
  6663. ** discarded. ^Any prior cache entry associated with newKey is guaranteed not
  6664. ** to be pinned.
  6665. **
  6666. ** When SQLite calls the xTruncate() method, the cache must discard all
  6667. ** existing cache entries with page numbers (keys) greater than or equal
  6668. ** to the value of the iLimit parameter passed to xTruncate(). If any
  6669. ** of these pages are pinned, they are implicitly unpinned, meaning that
  6670. ** they can be safely discarded.
  6671. **
  6672. ** [[the xDestroy() page cache method]]
  6673. ** ^The xDestroy() method is used to delete a cache allocated by xCreate().
  6674. ** All resources associated with the specified cache should be freed. ^After
  6675. ** calling the xDestroy() method, SQLite considers the [sqlite3_pcache*]
  6676. ** handle invalid, and will not use it with any other sqlite3_pcache_methods2
  6677. ** functions.
  6678. **
  6679. ** [[the xShrink() page cache method]]
  6680. ** ^SQLite invokes the xShrink() method when it wants the page cache to
  6681. ** free up as much of heap memory as possible. The page cache implementation
  6682. ** is not obligated to free any memory, but well-behaved implementations should
  6683. ** do their best.
  6684. */
  6685. typedef struct sqlite3_pcache_methods2 sqlite3_pcache_methods2;
  6686. struct sqlite3_pcache_methods2 {
  6687. int iVersion;
  6688. void *pArg;
  6689. int (*xInit)(void*);
  6690. void (*xShutdown)(void*);
  6691. sqlite3_pcache *(*xCreate)(int szPage, int szExtra, int bPurgeable);
  6692. void (*xCachesize)(sqlite3_pcache*, int nCachesize);
  6693. int (*xPagecount)(sqlite3_pcache*);
  6694. sqlite3_pcache_page *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
  6695. void (*xUnpin)(sqlite3_pcache*, sqlite3_pcache_page*, int discard);
  6696. void (*xRekey)(sqlite3_pcache*, sqlite3_pcache_page*,
  6697. unsigned oldKey, unsigned newKey);
  6698. void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
  6699. void (*xDestroy)(sqlite3_pcache*);
  6700. void (*xShrink)(sqlite3_pcache*);
  6701. };
  6702. /*
  6703. ** This is the obsolete pcache_methods object that has now been replaced
  6704. ** by sqlite3_pcache_methods2. This object is not used by SQLite. It is
  6705. ** retained in the header file for backwards compatibility only.
  6706. */
  6707. typedef struct sqlite3_pcache_methods sqlite3_pcache_methods;
  6708. struct sqlite3_pcache_methods {
  6709. void *pArg;
  6710. int (*xInit)(void*);
  6711. void (*xShutdown)(void*);
  6712. sqlite3_pcache *(*xCreate)(int szPage, int bPurgeable);
  6713. void (*xCachesize)(sqlite3_pcache*, int nCachesize);
  6714. int (*xPagecount)(sqlite3_pcache*);
  6715. void *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
  6716. void (*xUnpin)(sqlite3_pcache*, void*, int discard);
  6717. void (*xRekey)(sqlite3_pcache*, void*, unsigned oldKey, unsigned newKey);
  6718. void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
  6719. void (*xDestroy)(sqlite3_pcache*);
  6720. };
  6721. /*
  6722. ** CAPI3REF: Online Backup Object
  6723. **
  6724. ** The sqlite3_backup object records state information about an ongoing
  6725. ** online backup operation. ^The sqlite3_backup object is created by
  6726. ** a call to [sqlite3_backup_init()] and is destroyed by a call to
  6727. ** [sqlite3_backup_finish()].
  6728. **
  6729. ** See Also: [Using the SQLite Online Backup API]
  6730. */
  6731. typedef struct sqlite3_backup sqlite3_backup;
  6732. /*
  6733. ** CAPI3REF: Online Backup API.
  6734. **
  6735. ** The backup API copies the content of one database into another.
  6736. ** It is useful either for creating backups of databases or
  6737. ** for copying in-memory databases to or from persistent files.
  6738. **
  6739. ** See Also: [Using the SQLite Online Backup API]
  6740. **
  6741. ** ^SQLite holds a write transaction open on the destination database file
  6742. ** for the duration of the backup operation.
  6743. ** ^The source database is read-locked only while it is being read;
  6744. ** it is not locked continuously for the entire backup operation.
  6745. ** ^Thus, the backup may be performed on a live source database without
  6746. ** preventing other database connections from
  6747. ** reading or writing to the source database while the backup is underway.
  6748. **
  6749. ** ^(To perform a backup operation:
  6750. ** <ol>
  6751. ** <li><b>sqlite3_backup_init()</b> is called once to initialize the
  6752. ** backup,
  6753. ** <li><b>sqlite3_backup_step()</b> is called one or more times to transfer
  6754. ** the data between the two databases, and finally
  6755. ** <li><b>sqlite3_backup_finish()</b> is called to release all resources
  6756. ** associated with the backup operation.
  6757. ** </ol>)^
  6758. ** There should be exactly one call to sqlite3_backup_finish() for each
  6759. ** successful call to sqlite3_backup_init().
  6760. **
  6761. ** [[sqlite3_backup_init()]] <b>sqlite3_backup_init()</b>
  6762. **
  6763. ** ^The D and N arguments to sqlite3_backup_init(D,N,S,M) are the
  6764. ** [database connection] associated with the destination database
  6765. ** and the database name, respectively.
  6766. ** ^The database name is "main" for the main database, "temp" for the
  6767. ** temporary database, or the name specified after the AS keyword in
  6768. ** an [ATTACH] statement for an attached database.
  6769. ** ^The S and M arguments passed to
  6770. ** sqlite3_backup_init(D,N,S,M) identify the [database connection]
  6771. ** and database name of the source database, respectively.
  6772. ** ^The source and destination [database connections] (parameters S and D)
  6773. ** must be different or else sqlite3_backup_init(D,N,S,M) will fail with
  6774. ** an error.
  6775. **
  6776. ** ^If an error occurs within sqlite3_backup_init(D,N,S,M), then NULL is
  6777. ** returned and an error code and error message are stored in the
  6778. ** destination [database connection] D.
  6779. ** ^The error code and message for the failed call to sqlite3_backup_init()
  6780. ** can be retrieved using the [sqlite3_errcode()], [sqlite3_errmsg()], and/or
  6781. ** [sqlite3_errmsg16()] functions.
  6782. ** ^A successful call to sqlite3_backup_init() returns a pointer to an
  6783. ** [sqlite3_backup] object.
  6784. ** ^The [sqlite3_backup] object may be used with the sqlite3_backup_step() and
  6785. ** sqlite3_backup_finish() functions to perform the specified backup
  6786. ** operation.
  6787. **
  6788. ** [[sqlite3_backup_step()]] <b>sqlite3_backup_step()</b>
  6789. **
  6790. ** ^Function sqlite3_backup_step(B,N) will copy up to N pages between
  6791. ** the source and destination databases specified by [sqlite3_backup] object B.
  6792. ** ^If N is negative, all remaining source pages are copied.
  6793. ** ^If sqlite3_backup_step(B,N) successfully copies N pages and there
  6794. ** are still more pages to be copied, then the function returns [SQLITE_OK].
  6795. ** ^If sqlite3_backup_step(B,N) successfully finishes copying all pages
  6796. ** from source to destination, then it returns [SQLITE_DONE].
  6797. ** ^If an error occurs while running sqlite3_backup_step(B,N),
  6798. ** then an [error code] is returned. ^As well as [SQLITE_OK] and
  6799. ** [SQLITE_DONE], a call to sqlite3_backup_step() may return [SQLITE_READONLY],
  6800. ** [SQLITE_NOMEM], [SQLITE_BUSY], [SQLITE_LOCKED], or an
  6801. ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX] extended error code.
  6802. **
  6803. ** ^(The sqlite3_backup_step() might return [SQLITE_READONLY] if
  6804. ** <ol>
  6805. ** <li> the destination database was opened read-only, or
  6806. ** <li> the destination database is using write-ahead-log journaling
  6807. ** and the destination and source page sizes differ, or
  6808. ** <li> the destination database is an in-memory database and the
  6809. ** destination and source page sizes differ.
  6810. ** </ol>)^
  6811. **
  6812. ** ^If sqlite3_backup_step() cannot obtain a required file-system lock, then
  6813. ** the [sqlite3_busy_handler | busy-handler function]
  6814. ** is invoked (if one is specified). ^If the
  6815. ** busy-handler returns non-zero before the lock is available, then
  6816. ** [SQLITE_BUSY] is returned to the caller. ^In this case the call to
  6817. ** sqlite3_backup_step() can be retried later. ^If the source
  6818. ** [database connection]
  6819. ** is being used to write to the source database when sqlite3_backup_step()
  6820. ** is called, then [SQLITE_LOCKED] is returned immediately. ^Again, in this
  6821. ** case the call to sqlite3_backup_step() can be retried later on. ^(If
  6822. ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX], [SQLITE_NOMEM], or
  6823. ** [SQLITE_READONLY] is returned, then
  6824. ** there is no point in retrying the call to sqlite3_backup_step(). These
  6825. ** errors are considered fatal.)^ The application must accept
  6826. ** that the backup operation has failed and pass the backup operation handle
  6827. ** to the sqlite3_backup_finish() to release associated resources.
  6828. **
  6829. ** ^The first call to sqlite3_backup_step() obtains an exclusive lock
  6830. ** on the destination file. ^The exclusive lock is not released until either
  6831. ** sqlite3_backup_finish() is called or the backup operation is complete
  6832. ** and sqlite3_backup_step() returns [SQLITE_DONE]. ^Every call to
  6833. ** sqlite3_backup_step() obtains a [shared lock] on the source database that
  6834. ** lasts for the duration of the sqlite3_backup_step() call.
  6835. ** ^Because the source database is not locked between calls to
  6836. ** sqlite3_backup_step(), the source database may be modified mid-way
  6837. ** through the backup process. ^If the source database is modified by an
  6838. ** external process or via a database connection other than the one being
  6839. ** used by the backup operation, then the backup will be automatically
  6840. ** restarted by the next call to sqlite3_backup_step(). ^If the source
  6841. ** database is modified by the using the same database connection as is used
  6842. ** by the backup operation, then the backup database is automatically
  6843. ** updated at the same time.
  6844. **
  6845. ** [[sqlite3_backup_finish()]] <b>sqlite3_backup_finish()</b>
  6846. **
  6847. ** When sqlite3_backup_step() has returned [SQLITE_DONE], or when the
  6848. ** application wishes to abandon the backup operation, the application
  6849. ** should destroy the [sqlite3_backup] by passing it to sqlite3_backup_finish().
  6850. ** ^The sqlite3_backup_finish() interfaces releases all
  6851. ** resources associated with the [sqlite3_backup] object.
  6852. ** ^If sqlite3_backup_step() has not yet returned [SQLITE_DONE], then any
  6853. ** active write-transaction on the destination database is rolled back.
  6854. ** The [sqlite3_backup] object is invalid
  6855. ** and may not be used following a call to sqlite3_backup_finish().
  6856. **
  6857. ** ^The value returned by sqlite3_backup_finish is [SQLITE_OK] if no
  6858. ** sqlite3_backup_step() errors occurred, regardless or whether or not
  6859. ** sqlite3_backup_step() completed.
  6860. ** ^If an out-of-memory condition or IO error occurred during any prior
  6861. ** sqlite3_backup_step() call on the same [sqlite3_backup] object, then
  6862. ** sqlite3_backup_finish() returns the corresponding [error code].
  6863. **
  6864. ** ^A return of [SQLITE_BUSY] or [SQLITE_LOCKED] from sqlite3_backup_step()
  6865. ** is not a permanent error and does not affect the return value of
  6866. ** sqlite3_backup_finish().
  6867. **
  6868. ** [[sqlite3_backup__remaining()]] [[sqlite3_backup_pagecount()]]
  6869. ** <b>sqlite3_backup_remaining() and sqlite3_backup_pagecount()</b>
  6870. **
  6871. ** ^Each call to sqlite3_backup_step() sets two values inside
  6872. ** the [sqlite3_backup] object: the number of pages still to be backed
  6873. ** up and the total number of pages in the source database file.
  6874. ** The sqlite3_backup_remaining() and sqlite3_backup_pagecount() interfaces
  6875. ** retrieve these two values, respectively.
  6876. **
  6877. ** ^The values returned by these functions are only updated by
  6878. ** sqlite3_backup_step(). ^If the source database is modified during a backup
  6879. ** operation, then the values are not updated to account for any extra
  6880. ** pages that need to be updated or the size of the source database file
  6881. ** changing.
  6882. **
  6883. ** <b>Concurrent Usage of Database Handles</b>
  6884. **
  6885. ** ^The source [database connection] may be used by the application for other
  6886. ** purposes while a backup operation is underway or being initialized.
  6887. ** ^If SQLite is compiled and configured to support threadsafe database
  6888. ** connections, then the source database connection may be used concurrently
  6889. ** from within other threads.
  6890. **
  6891. ** However, the application must guarantee that the destination
  6892. ** [database connection] is not passed to any other API (by any thread) after
  6893. ** sqlite3_backup_init() is called and before the corresponding call to
  6894. ** sqlite3_backup_finish(). SQLite does not currently check to see
  6895. ** if the application incorrectly accesses the destination [database connection]
  6896. ** and so no error code is reported, but the operations may malfunction
  6897. ** nevertheless. Use of the destination database connection while a
  6898. ** backup is in progress might also also cause a mutex deadlock.
  6899. **
  6900. ** If running in [shared cache mode], the application must
  6901. ** guarantee that the shared cache used by the destination database
  6902. ** is not accessed while the backup is running. In practice this means
  6903. ** that the application must guarantee that the disk file being
  6904. ** backed up to is not accessed by any connection within the process,
  6905. ** not just the specific connection that was passed to sqlite3_backup_init().
  6906. **
  6907. ** The [sqlite3_backup] object itself is partially threadsafe. Multiple
  6908. ** threads may safely make multiple concurrent calls to sqlite3_backup_step().
  6909. ** However, the sqlite3_backup_remaining() and sqlite3_backup_pagecount()
  6910. ** APIs are not strictly speaking threadsafe. If they are invoked at the
  6911. ** same time as another thread is invoking sqlite3_backup_step() it is
  6912. ** possible that they return invalid values.
  6913. */
  6914. SQLITE_API sqlite3_backup *sqlite3_backup_init(
  6915. sqlite3 *pDest, /* Destination database handle */
  6916. const char *zDestName, /* Destination database name */
  6917. sqlite3 *pSource, /* Source database handle */
  6918. const char *zSourceName /* Source database name */
  6919. );
  6920. SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage);
  6921. SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p);
  6922. SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p);
  6923. SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p);
  6924. /*
  6925. ** CAPI3REF: Unlock Notification
  6926. **
  6927. ** ^When running in shared-cache mode, a database operation may fail with
  6928. ** an [SQLITE_LOCKED] error if the required locks on the shared-cache or
  6929. ** individual tables within the shared-cache cannot be obtained. See
  6930. ** [SQLite Shared-Cache Mode] for a description of shared-cache locking.
  6931. ** ^This API may be used to register a callback that SQLite will invoke
  6932. ** when the connection currently holding the required lock relinquishes it.
  6933. ** ^This API is only available if the library was compiled with the
  6934. ** [SQLITE_ENABLE_UNLOCK_NOTIFY] C-preprocessor symbol defined.
  6935. **
  6936. ** See Also: [Using the SQLite Unlock Notification Feature].
  6937. **
  6938. ** ^Shared-cache locks are released when a database connection concludes
  6939. ** its current transaction, either by committing it or rolling it back.
  6940. **
  6941. ** ^When a connection (known as the blocked connection) fails to obtain a
  6942. ** shared-cache lock and SQLITE_LOCKED is returned to the caller, the
  6943. ** identity of the database connection (the blocking connection) that
  6944. ** has locked the required resource is stored internally. ^After an
  6945. ** application receives an SQLITE_LOCKED error, it may call the
  6946. ** sqlite3_unlock_notify() method with the blocked connection handle as
  6947. ** the first argument to register for a callback that will be invoked
  6948. ** when the blocking connections current transaction is concluded. ^The
  6949. ** callback is invoked from within the [sqlite3_step] or [sqlite3_close]
  6950. ** call that concludes the blocking connections transaction.
  6951. **
  6952. ** ^(If sqlite3_unlock_notify() is called in a multi-threaded application,
  6953. ** there is a chance that the blocking connection will have already
  6954. ** concluded its transaction by the time sqlite3_unlock_notify() is invoked.
  6955. ** If this happens, then the specified callback is invoked immediately,
  6956. ** from within the call to sqlite3_unlock_notify().)^
  6957. **
  6958. ** ^If the blocked connection is attempting to obtain a write-lock on a
  6959. ** shared-cache table, and more than one other connection currently holds
  6960. ** a read-lock on the same table, then SQLite arbitrarily selects one of
  6961. ** the other connections to use as the blocking connection.
  6962. **
  6963. ** ^(There may be at most one unlock-notify callback registered by a
  6964. ** blocked connection. If sqlite3_unlock_notify() is called when the
  6965. ** blocked connection already has a registered unlock-notify callback,
  6966. ** then the new callback replaces the old.)^ ^If sqlite3_unlock_notify() is
  6967. ** called with a NULL pointer as its second argument, then any existing
  6968. ** unlock-notify callback is canceled. ^The blocked connections
  6969. ** unlock-notify callback may also be canceled by closing the blocked
  6970. ** connection using [sqlite3_close()].
  6971. **
  6972. ** The unlock-notify callback is not reentrant. If an application invokes
  6973. ** any sqlite3_xxx API functions from within an unlock-notify callback, a
  6974. ** crash or deadlock may be the result.
  6975. **
  6976. ** ^Unless deadlock is detected (see below), sqlite3_unlock_notify() always
  6977. ** returns SQLITE_OK.
  6978. **
  6979. ** <b>Callback Invocation Details</b>
  6980. **
  6981. ** When an unlock-notify callback is registered, the application provides a
  6982. ** single void* pointer that is passed to the callback when it is invoked.
  6983. ** However, the signature of the callback function allows SQLite to pass
  6984. ** it an array of void* context pointers. The first argument passed to
  6985. ** an unlock-notify callback is a pointer to an array of void* pointers,
  6986. ** and the second is the number of entries in the array.
  6987. **
  6988. ** When a blocking connections transaction is concluded, there may be
  6989. ** more than one blocked connection that has registered for an unlock-notify
  6990. ** callback. ^If two or more such blocked connections have specified the
  6991. ** same callback function, then instead of invoking the callback function
  6992. ** multiple times, it is invoked once with the set of void* context pointers
  6993. ** specified by the blocked connections bundled together into an array.
  6994. ** This gives the application an opportunity to prioritize any actions
  6995. ** related to the set of unblocked database connections.
  6996. **
  6997. ** <b>Deadlock Detection</b>
  6998. **
  6999. ** Assuming that after registering for an unlock-notify callback a
  7000. ** database waits for the callback to be issued before taking any further
  7001. ** action (a reasonable assumption), then using this API may cause the
  7002. ** application to deadlock. For example, if connection X is waiting for
  7003. ** connection Y's transaction to be concluded, and similarly connection
  7004. ** Y is waiting on connection X's transaction, then neither connection
  7005. ** will proceed and the system may remain deadlocked indefinitely.
  7006. **
  7007. ** To avoid this scenario, the sqlite3_unlock_notify() performs deadlock
  7008. ** detection. ^If a given call to sqlite3_unlock_notify() would put the
  7009. ** system in a deadlocked state, then SQLITE_LOCKED is returned and no
  7010. ** unlock-notify callback is registered. The system is said to be in
  7011. ** a deadlocked state if connection A has registered for an unlock-notify
  7012. ** callback on the conclusion of connection B's transaction, and connection
  7013. ** B has itself registered for an unlock-notify callback when connection
  7014. ** A's transaction is concluded. ^Indirect deadlock is also detected, so
  7015. ** the system is also considered to be deadlocked if connection B has
  7016. ** registered for an unlock-notify callback on the conclusion of connection
  7017. ** C's transaction, where connection C is waiting on connection A. ^Any
  7018. ** number of levels of indirection are allowed.
  7019. **
  7020. ** <b>The "DROP TABLE" Exception</b>
  7021. **
  7022. ** When a call to [sqlite3_step()] returns SQLITE_LOCKED, it is almost
  7023. ** always appropriate to call sqlite3_unlock_notify(). There is however,
  7024. ** one exception. When executing a "DROP TABLE" or "DROP INDEX" statement,
  7025. ** SQLite checks if there are any currently executing SELECT statements
  7026. ** that belong to the same connection. If there are, SQLITE_LOCKED is
  7027. ** returned. In this case there is no "blocking connection", so invoking
  7028. ** sqlite3_unlock_notify() results in the unlock-notify callback being
  7029. ** invoked immediately. If the application then re-attempts the "DROP TABLE"
  7030. ** or "DROP INDEX" query, an infinite loop might be the result.
  7031. **
  7032. ** One way around this problem is to check the extended error code returned
  7033. ** by an sqlite3_step() call. ^(If there is a blocking connection, then the
  7034. ** extended error code is set to SQLITE_LOCKED_SHAREDCACHE. Otherwise, in
  7035. ** the special "DROP TABLE/INDEX" case, the extended error code is just
  7036. ** SQLITE_LOCKED.)^
  7037. */
  7038. SQLITE_API int sqlite3_unlock_notify(
  7039. sqlite3 *pBlocked, /* Waiting connection */
  7040. void (*xNotify)(void **apArg, int nArg), /* Callback function to invoke */
  7041. void *pNotifyArg /* Argument to pass to xNotify */
  7042. );
  7043. /*
  7044. ** CAPI3REF: String Comparison
  7045. **
  7046. ** ^The [sqlite3_stricmp()] and [sqlite3_strnicmp()] APIs allow applications
  7047. ** and extensions to compare the contents of two buffers containing UTF-8
  7048. ** strings in a case-independent fashion, using the same definition of "case
  7049. ** independence" that SQLite uses internally when comparing identifiers.
  7050. */
  7051. SQLITE_API int sqlite3_stricmp(const char *, const char *);
  7052. SQLITE_API int sqlite3_strnicmp(const char *, const char *, int);
  7053. /*
  7054. ** CAPI3REF: String Globbing
  7055. *
  7056. ** ^The [sqlite3_strglob(P,X)] interface returns zero if string X matches
  7057. ** the glob pattern P, and it returns non-zero if string X does not match
  7058. ** the glob pattern P. ^The definition of glob pattern matching used in
  7059. ** [sqlite3_strglob(P,X)] is the same as for the "X GLOB P" operator in the
  7060. ** SQL dialect used by SQLite. ^The sqlite3_strglob(P,X) function is case
  7061. ** sensitive.
  7062. **
  7063. ** Note that this routine returns zero on a match and non-zero if the strings
  7064. ** do not match, the same as [sqlite3_stricmp()] and [sqlite3_strnicmp()].
  7065. */
  7066. SQLITE_API int sqlite3_strglob(const char *zGlob, const char *zStr);
  7067. /*
  7068. ** CAPI3REF: Error Logging Interface
  7069. **
  7070. ** ^The [sqlite3_log()] interface writes a message into the [error log]
  7071. ** established by the [SQLITE_CONFIG_LOG] option to [sqlite3_config()].
  7072. ** ^If logging is enabled, the zFormat string and subsequent arguments are
  7073. ** used with [sqlite3_snprintf()] to generate the final output string.
  7074. **
  7075. ** The sqlite3_log() interface is intended for use by extensions such as
  7076. ** virtual tables, collating functions, and SQL functions. While there is
  7077. ** nothing to prevent an application from calling sqlite3_log(), doing so
  7078. ** is considered bad form.
  7079. **
  7080. ** The zFormat string must not be NULL.
  7081. **
  7082. ** To avoid deadlocks and other threading problems, the sqlite3_log() routine
  7083. ** will not use dynamically allocated memory. The log message is stored in
  7084. ** a fixed-length buffer on the stack. If the log message is longer than
  7085. ** a few hundred characters, it will be truncated to the length of the
  7086. ** buffer.
  7087. */
  7088. SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...);
  7089. /*
  7090. ** CAPI3REF: Write-Ahead Log Commit Hook
  7091. **
  7092. ** ^The [sqlite3_wal_hook()] function is used to register a callback that
  7093. ** will be invoked each time a database connection commits data to a
  7094. ** [write-ahead log] (i.e. whenever a transaction is committed in
  7095. ** [journal_mode | journal_mode=WAL mode]).
  7096. **
  7097. ** ^The callback is invoked by SQLite after the commit has taken place and
  7098. ** the associated write-lock on the database released, so the implementation
  7099. ** may read, write or [checkpoint] the database as required.
  7100. **
  7101. ** ^The first parameter passed to the callback function when it is invoked
  7102. ** is a copy of the third parameter passed to sqlite3_wal_hook() when
  7103. ** registering the callback. ^The second is a copy of the database handle.
  7104. ** ^The third parameter is the name of the database that was written to -
  7105. ** either "main" or the name of an [ATTACH]-ed database. ^The fourth parameter
  7106. ** is the number of pages currently in the write-ahead log file,
  7107. ** including those that were just committed.
  7108. **
  7109. ** The callback function should normally return [SQLITE_OK]. ^If an error
  7110. ** code is returned, that error will propagate back up through the
  7111. ** SQLite code base to cause the statement that provoked the callback
  7112. ** to report an error, though the commit will have still occurred. If the
  7113. ** callback returns [SQLITE_ROW] or [SQLITE_DONE], or if it returns a value
  7114. ** that does not correspond to any valid SQLite error code, the results
  7115. ** are undefined.
  7116. **
  7117. ** A single database handle may have at most a single write-ahead log callback
  7118. ** registered at one time. ^Calling [sqlite3_wal_hook()] replaces any
  7119. ** previously registered write-ahead log callback. ^Note that the
  7120. ** [sqlite3_wal_autocheckpoint()] interface and the
  7121. ** [wal_autocheckpoint pragma] both invoke [sqlite3_wal_hook()] and will
  7122. ** those overwrite any prior [sqlite3_wal_hook()] settings.
  7123. */
  7124. SQLITE_API void *sqlite3_wal_hook(
  7125. sqlite3*,
  7126. int(*)(void *,sqlite3*,const char*,int),
  7127. void*
  7128. );
  7129. /*
  7130. ** CAPI3REF: Configure an auto-checkpoint
  7131. **
  7132. ** ^The [sqlite3_wal_autocheckpoint(D,N)] is a wrapper around
  7133. ** [sqlite3_wal_hook()] that causes any database on [database connection] D
  7134. ** to automatically [checkpoint]
  7135. ** after committing a transaction if there are N or
  7136. ** more frames in the [write-ahead log] file. ^Passing zero or
  7137. ** a negative value as the nFrame parameter disables automatic
  7138. ** checkpoints entirely.
  7139. **
  7140. ** ^The callback registered by this function replaces any existing callback
  7141. ** registered using [sqlite3_wal_hook()]. ^Likewise, registering a callback
  7142. ** using [sqlite3_wal_hook()] disables the automatic checkpoint mechanism
  7143. ** configured by this function.
  7144. **
  7145. ** ^The [wal_autocheckpoint pragma] can be used to invoke this interface
  7146. ** from SQL.
  7147. **
  7148. ** ^Checkpoints initiated by this mechanism are
  7149. ** [sqlite3_wal_checkpoint_v2|PASSIVE].
  7150. **
  7151. ** ^Every new [database connection] defaults to having the auto-checkpoint
  7152. ** enabled with a threshold of 1000 or [SQLITE_DEFAULT_WAL_AUTOCHECKPOINT]
  7153. ** pages. The use of this interface
  7154. ** is only necessary if the default setting is found to be suboptimal
  7155. ** for a particular application.
  7156. */
  7157. SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int N);
  7158. /*
  7159. ** CAPI3REF: Checkpoint a database
  7160. **
  7161. ** ^The [sqlite3_wal_checkpoint(D,X)] interface causes database named X
  7162. ** on [database connection] D to be [checkpointed]. ^If X is NULL or an
  7163. ** empty string, then a checkpoint is run on all databases of
  7164. ** connection D. ^If the database connection D is not in
  7165. ** [WAL | write-ahead log mode] then this interface is a harmless no-op.
  7166. ** ^The [sqlite3_wal_checkpoint(D,X)] interface initiates a
  7167. ** [sqlite3_wal_checkpoint_v2|PASSIVE] checkpoint.
  7168. ** Use the [sqlite3_wal_checkpoint_v2()] interface to get a FULL
  7169. ** or RESET checkpoint.
  7170. **
  7171. ** ^The [wal_checkpoint pragma] can be used to invoke this interface
  7172. ** from SQL. ^The [sqlite3_wal_autocheckpoint()] interface and the
  7173. ** [wal_autocheckpoint pragma] can be used to cause this interface to be
  7174. ** run whenever the WAL reaches a certain size threshold.
  7175. **
  7176. ** See also: [sqlite3_wal_checkpoint_v2()]
  7177. */
  7178. SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb);
  7179. /*
  7180. ** CAPI3REF: Checkpoint a database
  7181. **
  7182. ** Run a checkpoint operation on WAL database zDb attached to database
  7183. ** handle db. The specific operation is determined by the value of the
  7184. ** eMode parameter:
  7185. **
  7186. ** <dl>
  7187. ** <dt>SQLITE_CHECKPOINT_PASSIVE<dd>
  7188. ** Checkpoint as many frames as possible without waiting for any database
  7189. ** readers or writers to finish. Sync the db file if all frames in the log
  7190. ** are checkpointed. This mode is the same as calling
  7191. ** sqlite3_wal_checkpoint(). The [sqlite3_busy_handler|busy-handler callback]
  7192. ** is never invoked.
  7193. **
  7194. ** <dt>SQLITE_CHECKPOINT_FULL<dd>
  7195. ** This mode blocks (it invokes the
  7196. ** [sqlite3_busy_handler|busy-handler callback]) until there is no
  7197. ** database writer and all readers are reading from the most recent database
  7198. ** snapshot. It then checkpoints all frames in the log file and syncs the
  7199. ** database file. This call blocks database writers while it is running,
  7200. ** but not database readers.
  7201. **
  7202. ** <dt>SQLITE_CHECKPOINT_RESTART<dd>
  7203. ** This mode works the same way as SQLITE_CHECKPOINT_FULL, except after
  7204. ** checkpointing the log file it blocks (calls the
  7205. ** [sqlite3_busy_handler|busy-handler callback])
  7206. ** until all readers are reading from the database file only. This ensures
  7207. ** that the next client to write to the database file restarts the log file
  7208. ** from the beginning. This call blocks database writers while it is running,
  7209. ** but not database readers.
  7210. ** </dl>
  7211. **
  7212. ** If pnLog is not NULL, then *pnLog is set to the total number of frames in
  7213. ** the log file before returning. If pnCkpt is not NULL, then *pnCkpt is set to
  7214. ** the total number of checkpointed frames (including any that were already
  7215. ** checkpointed when this function is called). *pnLog and *pnCkpt may be
  7216. ** populated even if sqlite3_wal_checkpoint_v2() returns other than SQLITE_OK.
  7217. ** If no values are available because of an error, they are both set to -1
  7218. ** before returning to communicate this to the caller.
  7219. **
  7220. ** All calls obtain an exclusive "checkpoint" lock on the database file. If
  7221. ** any other process is running a checkpoint operation at the same time, the
  7222. ** lock cannot be obtained and SQLITE_BUSY is returned. Even if there is a
  7223. ** busy-handler configured, it will not be invoked in this case.
  7224. **
  7225. ** The SQLITE_CHECKPOINT_FULL and RESTART modes also obtain the exclusive
  7226. ** "writer" lock on the database file. If the writer lock cannot be obtained
  7227. ** immediately, and a busy-handler is configured, it is invoked and the writer
  7228. ** lock retried until either the busy-handler returns 0 or the lock is
  7229. ** successfully obtained. The busy-handler is also invoked while waiting for
  7230. ** database readers as described above. If the busy-handler returns 0 before
  7231. ** the writer lock is obtained or while waiting for database readers, the
  7232. ** checkpoint operation proceeds from that point in the same way as
  7233. ** SQLITE_CHECKPOINT_PASSIVE - checkpointing as many frames as possible
  7234. ** without blocking any further. SQLITE_BUSY is returned in this case.
  7235. **
  7236. ** If parameter zDb is NULL or points to a zero length string, then the
  7237. ** specified operation is attempted on all WAL databases. In this case the
  7238. ** values written to output parameters *pnLog and *pnCkpt are undefined. If
  7239. ** an SQLITE_BUSY error is encountered when processing one or more of the
  7240. ** attached WAL databases, the operation is still attempted on any remaining
  7241. ** attached databases and SQLITE_BUSY is returned to the caller. If any other
  7242. ** error occurs while processing an attached database, processing is abandoned
  7243. ** and the error code returned to the caller immediately. If no error
  7244. ** (SQLITE_BUSY or otherwise) is encountered while processing the attached
  7245. ** databases, SQLITE_OK is returned.
  7246. **
  7247. ** If database zDb is the name of an attached database that is not in WAL
  7248. ** mode, SQLITE_OK is returned and both *pnLog and *pnCkpt set to -1. If
  7249. ** zDb is not NULL (or a zero length string) and is not the name of any
  7250. ** attached database, SQLITE_ERROR is returned to the caller.
  7251. */
  7252. SQLITE_API int sqlite3_wal_checkpoint_v2(
  7253. sqlite3 *db, /* Database handle */
  7254. const char *zDb, /* Name of attached database (or NULL) */
  7255. int eMode, /* SQLITE_CHECKPOINT_* value */
  7256. int *pnLog, /* OUT: Size of WAL log in frames */
  7257. int *pnCkpt /* OUT: Total number of frames checkpointed */
  7258. );
  7259. /*
  7260. ** CAPI3REF: Checkpoint operation parameters
  7261. **
  7262. ** These constants can be used as the 3rd parameter to
  7263. ** [sqlite3_wal_checkpoint_v2()]. See the [sqlite3_wal_checkpoint_v2()]
  7264. ** documentation for additional information about the meaning and use of
  7265. ** each of these values.
  7266. */
  7267. #define SQLITE_CHECKPOINT_PASSIVE 0
  7268. #define SQLITE_CHECKPOINT_FULL 1
  7269. #define SQLITE_CHECKPOINT_RESTART 2
  7270. /*
  7271. ** CAPI3REF: Virtual Table Interface Configuration
  7272. **
  7273. ** This function may be called by either the [xConnect] or [xCreate] method
  7274. ** of a [virtual table] implementation to configure
  7275. ** various facets of the virtual table interface.
  7276. **
  7277. ** If this interface is invoked outside the context of an xConnect or
  7278. ** xCreate virtual table method then the behavior is undefined.
  7279. **
  7280. ** At present, there is only one option that may be configured using
  7281. ** this function. (See [SQLITE_VTAB_CONSTRAINT_SUPPORT].) Further options
  7282. ** may be added in the future.
  7283. */
  7284. SQLITE_API int sqlite3_vtab_config(sqlite3*, int op, ...);
  7285. /*
  7286. ** CAPI3REF: Virtual Table Configuration Options
  7287. **
  7288. ** These macros define the various options to the
  7289. ** [sqlite3_vtab_config()] interface that [virtual table] implementations
  7290. ** can use to customize and optimize their behavior.
  7291. **
  7292. ** <dl>
  7293. ** <dt>SQLITE_VTAB_CONSTRAINT_SUPPORT
  7294. ** <dd>Calls of the form
  7295. ** [sqlite3_vtab_config](db,SQLITE_VTAB_CONSTRAINT_SUPPORT,X) are supported,
  7296. ** where X is an integer. If X is zero, then the [virtual table] whose
  7297. ** [xCreate] or [xConnect] method invoked [sqlite3_vtab_config()] does not
  7298. ** support constraints. In this configuration (which is the default) if
  7299. ** a call to the [xUpdate] method returns [SQLITE_CONSTRAINT], then the entire
  7300. ** statement is rolled back as if [ON CONFLICT | OR ABORT] had been
  7301. ** specified as part of the users SQL statement, regardless of the actual
  7302. ** ON CONFLICT mode specified.
  7303. **
  7304. ** If X is non-zero, then the virtual table implementation guarantees
  7305. ** that if [xUpdate] returns [SQLITE_CONSTRAINT], it will do so before
  7306. ** any modifications to internal or persistent data structures have been made.
  7307. ** If the [ON CONFLICT] mode is ABORT, FAIL, IGNORE or ROLLBACK, SQLite
  7308. ** is able to roll back a statement or database transaction, and abandon
  7309. ** or continue processing the current SQL statement as appropriate.
  7310. ** If the ON CONFLICT mode is REPLACE and the [xUpdate] method returns
  7311. ** [SQLITE_CONSTRAINT], SQLite handles this as if the ON CONFLICT mode
  7312. ** had been ABORT.
  7313. **
  7314. ** Virtual table implementations that are required to handle OR REPLACE
  7315. ** must do so within the [xUpdate] method. If a call to the
  7316. ** [sqlite3_vtab_on_conflict()] function indicates that the current ON
  7317. ** CONFLICT policy is REPLACE, the virtual table implementation should
  7318. ** silently replace the appropriate rows within the xUpdate callback and
  7319. ** return SQLITE_OK. Or, if this is not possible, it may return
  7320. ** SQLITE_CONSTRAINT, in which case SQLite falls back to OR ABORT
  7321. ** constraint handling.
  7322. ** </dl>
  7323. */
  7324. #define SQLITE_VTAB_CONSTRAINT_SUPPORT 1
  7325. /*
  7326. ** CAPI3REF: Determine The Virtual Table Conflict Policy
  7327. **
  7328. ** This function may only be called from within a call to the [xUpdate] method
  7329. ** of a [virtual table] implementation for an INSERT or UPDATE operation. ^The
  7330. ** value returned is one of [SQLITE_ROLLBACK], [SQLITE_IGNORE], [SQLITE_FAIL],
  7331. ** [SQLITE_ABORT], or [SQLITE_REPLACE], according to the [ON CONFLICT] mode
  7332. ** of the SQL statement that triggered the call to the [xUpdate] method of the
  7333. ** [virtual table].
  7334. */
  7335. SQLITE_API int sqlite3_vtab_on_conflict(sqlite3 *);
  7336. /*
  7337. ** CAPI3REF: Conflict resolution modes
  7338. ** KEYWORDS: {conflict resolution mode}
  7339. **
  7340. ** These constants are returned by [sqlite3_vtab_on_conflict()] to
  7341. ** inform a [virtual table] implementation what the [ON CONFLICT] mode
  7342. ** is for the SQL statement being evaluated.
  7343. **
  7344. ** Note that the [SQLITE_IGNORE] constant is also used as a potential
  7345. ** return value from the [sqlite3_set_authorizer()] callback and that
  7346. ** [SQLITE_ABORT] is also a [result code].
  7347. */
  7348. #define SQLITE_ROLLBACK 1
  7349. /* #define SQLITE_IGNORE 2 // Also used by sqlite3_authorizer() callback */
  7350. #define SQLITE_FAIL 3
  7351. /* #define SQLITE_ABORT 4 // Also an error code */
  7352. #define SQLITE_REPLACE 5
  7353. /*
  7354. ** Undo the hack that converts floating point types to integer for
  7355. ** builds on processors without floating point support.
  7356. */
  7357. #ifdef SQLITE_OMIT_FLOATING_POINT
  7358. # undef double
  7359. #endif
  7360. #if 0
  7361. } /* End of the 'extern "C"' block */
  7362. #endif
  7363. #endif /* _SQLITE3_H_ */
  7364. /*
  7365. ** 2010 August 30
  7366. **
  7367. ** The author disclaims copyright to this source code. In place of
  7368. ** a legal notice, here is a blessing:
  7369. **
  7370. ** May you do good and not evil.
  7371. ** May you find forgiveness for yourself and forgive others.
  7372. ** May you share freely, never taking more than you give.
  7373. **
  7374. *************************************************************************
  7375. */
  7376. #ifndef _SQLITE3RTREE_H_
  7377. #define _SQLITE3RTREE_H_
  7378. #if 0
  7379. extern "C" {
  7380. #endif
  7381. typedef struct sqlite3_rtree_geometry sqlite3_rtree_geometry;
  7382. typedef struct sqlite3_rtree_query_info sqlite3_rtree_query_info;
  7383. /* The double-precision datatype used by RTree depends on the
  7384. ** SQLITE_RTREE_INT_ONLY compile-time option.
  7385. */
  7386. #ifdef SQLITE_RTREE_INT_ONLY
  7387. typedef sqlite3_int64 sqlite3_rtree_dbl;
  7388. #else
  7389. typedef double sqlite3_rtree_dbl;
  7390. #endif
  7391. /*
  7392. ** Register a geometry callback named zGeom that can be used as part of an
  7393. ** R-Tree geometry query as follows:
  7394. **
  7395. ** SELECT ... FROM <rtree> WHERE <rtree col> MATCH $zGeom(... params ...)
  7396. */
  7397. SQLITE_API int sqlite3_rtree_geometry_callback(
  7398. sqlite3 *db,
  7399. const char *zGeom,
  7400. int (*xGeom)(sqlite3_rtree_geometry*, int, sqlite3_rtree_dbl*,int*),
  7401. void *pContext
  7402. );
  7403. /*
  7404. ** A pointer to a structure of the following type is passed as the first
  7405. ** argument to callbacks registered using rtree_geometry_callback().
  7406. */
  7407. struct sqlite3_rtree_geometry {
  7408. void *pContext; /* Copy of pContext passed to s_r_g_c() */
  7409. int nParam; /* Size of array aParam[] */
  7410. sqlite3_rtree_dbl *aParam; /* Parameters passed to SQL geom function */
  7411. void *pUser; /* Callback implementation user data */
  7412. void (*xDelUser)(void *); /* Called by SQLite to clean up pUser */
  7413. };
  7414. /*
  7415. ** Register a 2nd-generation geometry callback named zScore that can be
  7416. ** used as part of an R-Tree geometry query as follows:
  7417. **
  7418. ** SELECT ... FROM <rtree> WHERE <rtree col> MATCH $zQueryFunc(... params ...)
  7419. */
  7420. SQLITE_API int sqlite3_rtree_query_callback(
  7421. sqlite3 *db,
  7422. const char *zQueryFunc,
  7423. int (*xQueryFunc)(sqlite3_rtree_query_info*),
  7424. void *pContext,
  7425. void (*xDestructor)(void*)
  7426. );
  7427. /*
  7428. ** A pointer to a structure of the following type is passed as the
  7429. ** argument to scored geometry callback registered using
  7430. ** sqlite3_rtree_query_callback().
  7431. **
  7432. ** Note that the first 5 fields of this structure are identical to
  7433. ** sqlite3_rtree_geometry. This structure is a subclass of
  7434. ** sqlite3_rtree_geometry.
  7435. */
  7436. struct sqlite3_rtree_query_info {
  7437. void *pContext; /* pContext from when function registered */
  7438. int nParam; /* Number of function parameters */
  7439. sqlite3_rtree_dbl *aParam; /* value of function parameters */
  7440. void *pUser; /* callback can use this, if desired */
  7441. void (*xDelUser)(void*); /* function to free pUser */
  7442. sqlite3_rtree_dbl *aCoord; /* Coordinates of node or entry to check */
  7443. unsigned int *anQueue; /* Number of pending entries in the queue */
  7444. int nCoord; /* Number of coordinates */
  7445. int iLevel; /* Level of current node or entry */
  7446. int mxLevel; /* The largest iLevel value in the tree */
  7447. sqlite3_int64 iRowid; /* Rowid for current entry */
  7448. sqlite3_rtree_dbl rParentScore; /* Score of parent node */
  7449. int eParentWithin; /* Visibility of parent node */
  7450. int eWithin; /* OUT: Visiblity */
  7451. sqlite3_rtree_dbl rScore; /* OUT: Write the score here */
  7452. };
  7453. /*
  7454. ** Allowed values for sqlite3_rtree_query.eWithin and .eParentWithin.
  7455. */
  7456. #define NOT_WITHIN 0 /* Object completely outside of query region */
  7457. #define PARTLY_WITHIN 1 /* Object partially overlaps query region */
  7458. #define FULLY_WITHIN 2 /* Object fully contained within query region */
  7459. #if 0
  7460. } /* end of the 'extern "C"' block */
  7461. #endif
  7462. #endif /* ifndef _SQLITE3RTREE_H_ */
  7463. /************** End of sqlite3.h *********************************************/
  7464. /************** Continuing where we left off in sqliteInt.h ******************/
  7465. /*
  7466. ** Include the configuration header output by 'configure' if we're using the
  7467. ** autoconf-based build
  7468. */
  7469. #ifdef _HAVE_SQLITE_CONFIG_H
  7470. #include "config.h"
  7471. #endif
  7472. /************** Include sqliteLimit.h in the middle of sqliteInt.h ***********/
  7473. /************** Begin file sqliteLimit.h *************************************/
  7474. /*
  7475. ** 2007 May 7
  7476. **
  7477. ** The author disclaims copyright to this source code. In place of
  7478. ** a legal notice, here is a blessing:
  7479. **
  7480. ** May you do good and not evil.
  7481. ** May you find forgiveness for yourself and forgive others.
  7482. ** May you share freely, never taking more than you give.
  7483. **
  7484. *************************************************************************
  7485. **
  7486. ** This file defines various limits of what SQLite can process.
  7487. */
  7488. /*
  7489. ** The maximum length of a TEXT or BLOB in bytes. This also
  7490. ** limits the size of a row in a table or index.
  7491. **
  7492. ** The hard limit is the ability of a 32-bit signed integer
  7493. ** to count the size: 2^31-1 or 2147483647.
  7494. */
  7495. #ifndef SQLITE_MAX_LENGTH
  7496. # define SQLITE_MAX_LENGTH 1000000000
  7497. #endif
  7498. /*
  7499. ** This is the maximum number of
  7500. **
  7501. ** * Columns in a table
  7502. ** * Columns in an index
  7503. ** * Columns in a view
  7504. ** * Terms in the SET clause of an UPDATE statement
  7505. ** * Terms in the result set of a SELECT statement
  7506. ** * Terms in the GROUP BY or ORDER BY clauses of a SELECT statement.
  7507. ** * Terms in the VALUES clause of an INSERT statement
  7508. **
  7509. ** The hard upper limit here is 32676. Most database people will
  7510. ** tell you that in a well-normalized database, you usually should
  7511. ** not have more than a dozen or so columns in any table. And if
  7512. ** that is the case, there is no point in having more than a few
  7513. ** dozen values in any of the other situations described above.
  7514. */
  7515. #ifndef SQLITE_MAX_COLUMN
  7516. # define SQLITE_MAX_COLUMN 2000
  7517. #endif
  7518. /*
  7519. ** The maximum length of a single SQL statement in bytes.
  7520. **
  7521. ** It used to be the case that setting this value to zero would
  7522. ** turn the limit off. That is no longer true. It is not possible
  7523. ** to turn this limit off.
  7524. */
  7525. #ifndef SQLITE_MAX_SQL_LENGTH
  7526. # define SQLITE_MAX_SQL_LENGTH 1000000000
  7527. #endif
  7528. /*
  7529. ** The maximum depth of an expression tree. This is limited to
  7530. ** some extent by SQLITE_MAX_SQL_LENGTH. But sometime you might
  7531. ** want to place more severe limits on the complexity of an
  7532. ** expression.
  7533. **
  7534. ** A value of 0 used to mean that the limit was not enforced.
  7535. ** But that is no longer true. The limit is now strictly enforced
  7536. ** at all times.
  7537. */
  7538. #ifndef SQLITE_MAX_EXPR_DEPTH
  7539. # define SQLITE_MAX_EXPR_DEPTH 1000
  7540. #endif
  7541. /*
  7542. ** The maximum number of terms in a compound SELECT statement.
  7543. ** The code generator for compound SELECT statements does one
  7544. ** level of recursion for each term. A stack overflow can result
  7545. ** if the number of terms is too large. In practice, most SQL
  7546. ** never has more than 3 or 4 terms. Use a value of 0 to disable
  7547. ** any limit on the number of terms in a compount SELECT.
  7548. */
  7549. #ifndef SQLITE_MAX_COMPOUND_SELECT
  7550. # define SQLITE_MAX_COMPOUND_SELECT 500
  7551. #endif
  7552. /*
  7553. ** The maximum number of opcodes in a VDBE program.
  7554. ** Not currently enforced.
  7555. */
  7556. #ifndef SQLITE_MAX_VDBE_OP
  7557. # define SQLITE_MAX_VDBE_OP 25000
  7558. #endif
  7559. /*
  7560. ** The maximum number of arguments to an SQL function.
  7561. */
  7562. #ifndef SQLITE_MAX_FUNCTION_ARG
  7563. # define SQLITE_MAX_FUNCTION_ARG 127
  7564. #endif
  7565. /*
  7566. ** The maximum number of in-memory pages to use for the main database
  7567. ** table and for temporary tables. The SQLITE_DEFAULT_CACHE_SIZE
  7568. */
  7569. #ifndef SQLITE_DEFAULT_CACHE_SIZE
  7570. # define SQLITE_DEFAULT_CACHE_SIZE 2000
  7571. #endif
  7572. #ifndef SQLITE_DEFAULT_TEMP_CACHE_SIZE
  7573. # define SQLITE_DEFAULT_TEMP_CACHE_SIZE 500
  7574. #endif
  7575. /*
  7576. ** The default number of frames to accumulate in the log file before
  7577. ** checkpointing the database in WAL mode.
  7578. */
  7579. #ifndef SQLITE_DEFAULT_WAL_AUTOCHECKPOINT
  7580. # define SQLITE_DEFAULT_WAL_AUTOCHECKPOINT 1000
  7581. #endif
  7582. /*
  7583. ** The maximum number of attached databases. This must be between 0
  7584. ** and 62. The upper bound on 62 is because a 64-bit integer bitmap
  7585. ** is used internally to track attached databases.
  7586. */
  7587. #ifndef SQLITE_MAX_ATTACHED
  7588. # define SQLITE_MAX_ATTACHED 10
  7589. #endif
  7590. /*
  7591. ** The maximum value of a ?nnn wildcard that the parser will accept.
  7592. */
  7593. #ifndef SQLITE_MAX_VARIABLE_NUMBER
  7594. # define SQLITE_MAX_VARIABLE_NUMBER 999
  7595. #endif
  7596. /* Maximum page size. The upper bound on this value is 65536. This a limit
  7597. ** imposed by the use of 16-bit offsets within each page.
  7598. **
  7599. ** Earlier versions of SQLite allowed the user to change this value at
  7600. ** compile time. This is no longer permitted, on the grounds that it creates
  7601. ** a library that is technically incompatible with an SQLite library
  7602. ** compiled with a different limit. If a process operating on a database
  7603. ** with a page-size of 65536 bytes crashes, then an instance of SQLite
  7604. ** compiled with the default page-size limit will not be able to rollback
  7605. ** the aborted transaction. This could lead to database corruption.
  7606. */
  7607. #ifdef SQLITE_MAX_PAGE_SIZE
  7608. # undef SQLITE_MAX_PAGE_SIZE
  7609. #endif
  7610. #define SQLITE_MAX_PAGE_SIZE 65536
  7611. /*
  7612. ** The default size of a database page.
  7613. */
  7614. #ifndef SQLITE_DEFAULT_PAGE_SIZE
  7615. # define SQLITE_DEFAULT_PAGE_SIZE 1024
  7616. #endif
  7617. #if SQLITE_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
  7618. # undef SQLITE_DEFAULT_PAGE_SIZE
  7619. # define SQLITE_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
  7620. #endif
  7621. /*
  7622. ** Ordinarily, if no value is explicitly provided, SQLite creates databases
  7623. ** with page size SQLITE_DEFAULT_PAGE_SIZE. However, based on certain
  7624. ** device characteristics (sector-size and atomic write() support),
  7625. ** SQLite may choose a larger value. This constant is the maximum value
  7626. ** SQLite will choose on its own.
  7627. */
  7628. #ifndef SQLITE_MAX_DEFAULT_PAGE_SIZE
  7629. # define SQLITE_MAX_DEFAULT_PAGE_SIZE 8192
  7630. #endif
  7631. #if SQLITE_MAX_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
  7632. # undef SQLITE_MAX_DEFAULT_PAGE_SIZE
  7633. # define SQLITE_MAX_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
  7634. #endif
  7635. /*
  7636. ** Maximum number of pages in one database file.
  7637. **
  7638. ** This is really just the default value for the max_page_count pragma.
  7639. ** This value can be lowered (or raised) at run-time using that the
  7640. ** max_page_count macro.
  7641. */
  7642. #ifndef SQLITE_MAX_PAGE_COUNT
  7643. # define SQLITE_MAX_PAGE_COUNT 1073741823
  7644. #endif
  7645. /*
  7646. ** Maximum length (in bytes) of the pattern in a LIKE or GLOB
  7647. ** operator.
  7648. */
  7649. #ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
  7650. # define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
  7651. #endif
  7652. /*
  7653. ** Maximum depth of recursion for triggers.
  7654. **
  7655. ** A value of 1 means that a trigger program will not be able to itself
  7656. ** fire any triggers. A value of 0 means that no trigger programs at all
  7657. ** may be executed.
  7658. */
  7659. #ifndef SQLITE_MAX_TRIGGER_DEPTH
  7660. # define SQLITE_MAX_TRIGGER_DEPTH 1000
  7661. #endif
  7662. /************** End of sqliteLimit.h *****************************************/
  7663. /************** Continuing where we left off in sqliteInt.h ******************/
  7664. /* Disable nuisance warnings on Borland compilers */
  7665. #if defined(__BORLANDC__)
  7666. #pragma warn -rch /* unreachable code */
  7667. #pragma warn -ccc /* Condition is always true or false */
  7668. #pragma warn -aus /* Assigned value is never used */
  7669. #pragma warn -csu /* Comparing signed and unsigned */
  7670. #pragma warn -spa /* Suspicious pointer arithmetic */
  7671. #endif
  7672. /*
  7673. ** Include standard header files as necessary
  7674. */
  7675. #ifdef HAVE_STDINT_H
  7676. #include <stdint.h>
  7677. #endif
  7678. #ifdef HAVE_INTTYPES_H
  7679. #include <inttypes.h>
  7680. #endif
  7681. /*
  7682. ** The following macros are used to cast pointers to integers and
  7683. ** integers to pointers. The way you do this varies from one compiler
  7684. ** to the next, so we have developed the following set of #if statements
  7685. ** to generate appropriate macros for a wide range of compilers.
  7686. **
  7687. ** The correct "ANSI" way to do this is to use the intptr_t type.
  7688. ** Unfortunately, that typedef is not available on all compilers, or
  7689. ** if it is available, it requires an #include of specific headers
  7690. ** that vary from one machine to the next.
  7691. **
  7692. ** Ticket #3860: The llvm-gcc-4.2 compiler from Apple chokes on
  7693. ** the ((void*)&((char*)0)[X]) construct. But MSVC chokes on ((void*)(X)).
  7694. ** So we have to define the macros in different ways depending on the
  7695. ** compiler.
  7696. */
  7697. #if defined(__PTRDIFF_TYPE__) /* This case should work for GCC */
  7698. # define SQLITE_INT_TO_PTR(X) ((void*)(__PTRDIFF_TYPE__)(X))
  7699. # define SQLITE_PTR_TO_INT(X) ((int)(__PTRDIFF_TYPE__)(X))
  7700. #elif !defined(__GNUC__) /* Works for compilers other than LLVM */
  7701. # define SQLITE_INT_TO_PTR(X) ((void*)&((char*)0)[X])
  7702. # define SQLITE_PTR_TO_INT(X) ((int)(((char*)X)-(char*)0))
  7703. #elif defined(HAVE_STDINT_H) /* Use this case if we have ANSI headers */
  7704. # define SQLITE_INT_TO_PTR(X) ((void*)(intptr_t)(X))
  7705. # define SQLITE_PTR_TO_INT(X) ((int)(intptr_t)(X))
  7706. #else /* Generates a warning - but it always works */
  7707. # define SQLITE_INT_TO_PTR(X) ((void*)(X))
  7708. # define SQLITE_PTR_TO_INT(X) ((int)(X))
  7709. #endif
  7710. /*
  7711. ** A macro to hint to the compiler that a function should not be
  7712. ** inlined.
  7713. */
  7714. #if defined(__GNUC__)
  7715. # define SQLITE_NOINLINE __attribute__((noinline))
  7716. #elif defined(_MSC_VER) && _MSC_VER>=1310
  7717. # define SQLITE_NOINLINE __declspec(noinline)
  7718. #else
  7719. # define SQLITE_NOINLINE
  7720. #endif
  7721. /*
  7722. ** The SQLITE_THREADSAFE macro must be defined as 0, 1, or 2.
  7723. ** 0 means mutexes are permanently disable and the library is never
  7724. ** threadsafe. 1 means the library is serialized which is the highest
  7725. ** level of threadsafety. 2 means the library is multithreaded - multiple
  7726. ** threads can use SQLite as long as no two threads try to use the same
  7727. ** database connection at the same time.
  7728. **
  7729. ** Older versions of SQLite used an optional THREADSAFE macro.
  7730. ** We support that for legacy.
  7731. */
  7732. #if !defined(SQLITE_THREADSAFE)
  7733. # if defined(THREADSAFE)
  7734. # define SQLITE_THREADSAFE THREADSAFE
  7735. # else
  7736. # define SQLITE_THREADSAFE 1 /* IMP: R-07272-22309 */
  7737. # endif
  7738. #endif
  7739. /*
  7740. ** Powersafe overwrite is on by default. But can be turned off using
  7741. ** the -DSQLITE_POWERSAFE_OVERWRITE=0 command-line option.
  7742. */
  7743. #ifndef SQLITE_POWERSAFE_OVERWRITE
  7744. # define SQLITE_POWERSAFE_OVERWRITE 1
  7745. #endif
  7746. /*
  7747. ** The SQLITE_DEFAULT_MEMSTATUS macro must be defined as either 0 or 1.
  7748. ** It determines whether or not the features related to
  7749. ** SQLITE_CONFIG_MEMSTATUS are available by default or not. This value can
  7750. ** be overridden at runtime using the sqlite3_config() API.
  7751. */
  7752. #if !defined(SQLITE_DEFAULT_MEMSTATUS)
  7753. # define SQLITE_DEFAULT_MEMSTATUS 1
  7754. #endif
  7755. /*
  7756. ** Exactly one of the following macros must be defined in order to
  7757. ** specify which memory allocation subsystem to use.
  7758. **
  7759. ** SQLITE_SYSTEM_MALLOC // Use normal system malloc()
  7760. ** SQLITE_WIN32_MALLOC // Use Win32 native heap API
  7761. ** SQLITE_ZERO_MALLOC // Use a stub allocator that always fails
  7762. ** SQLITE_MEMDEBUG // Debugging version of system malloc()
  7763. **
  7764. ** On Windows, if the SQLITE_WIN32_MALLOC_VALIDATE macro is defined and the
  7765. ** assert() macro is enabled, each call into the Win32 native heap subsystem
  7766. ** will cause HeapValidate to be called. If heap validation should fail, an
  7767. ** assertion will be triggered.
  7768. **
  7769. ** If none of the above are defined, then set SQLITE_SYSTEM_MALLOC as
  7770. ** the default.
  7771. */
  7772. #if defined(SQLITE_SYSTEM_MALLOC) \
  7773. + defined(SQLITE_WIN32_MALLOC) \
  7774. + defined(SQLITE_ZERO_MALLOC) \
  7775. + defined(SQLITE_MEMDEBUG)>1
  7776. # error "Two or more of the following compile-time configuration options\
  7777. are defined but at most one is allowed:\
  7778. SQLITE_SYSTEM_MALLOC, SQLITE_WIN32_MALLOC, SQLITE_MEMDEBUG,\
  7779. SQLITE_ZERO_MALLOC"
  7780. #endif
  7781. #if defined(SQLITE_SYSTEM_MALLOC) \
  7782. + defined(SQLITE_WIN32_MALLOC) \
  7783. + defined(SQLITE_ZERO_MALLOC) \
  7784. + defined(SQLITE_MEMDEBUG)==0
  7785. # define SQLITE_SYSTEM_MALLOC 1
  7786. #endif
  7787. /*
  7788. ** If SQLITE_MALLOC_SOFT_LIMIT is not zero, then try to keep the
  7789. ** sizes of memory allocations below this value where possible.
  7790. */
  7791. #if !defined(SQLITE_MALLOC_SOFT_LIMIT)
  7792. # define SQLITE_MALLOC_SOFT_LIMIT 1024
  7793. #endif
  7794. /*
  7795. ** We need to define _XOPEN_SOURCE as follows in order to enable
  7796. ** recursive mutexes on most Unix systems and fchmod() on OpenBSD.
  7797. ** But _XOPEN_SOURCE define causes problems for Mac OS X, so omit
  7798. ** it.
  7799. */
  7800. #if !defined(_XOPEN_SOURCE) && !defined(__DARWIN__) && !defined(__APPLE__)
  7801. # define _XOPEN_SOURCE 600
  7802. #endif
  7803. /*
  7804. ** NDEBUG and SQLITE_DEBUG are opposites. It should always be true that
  7805. ** defined(NDEBUG)==!defined(SQLITE_DEBUG). If this is not currently true,
  7806. ** make it true by defining or undefining NDEBUG.
  7807. **
  7808. ** Setting NDEBUG makes the code smaller and faster by disabling the
  7809. ** assert() statements in the code. So we want the default action
  7810. ** to be for NDEBUG to be set and NDEBUG to be undefined only if SQLITE_DEBUG
  7811. ** is set. Thus NDEBUG becomes an opt-in rather than an opt-out
  7812. ** feature.
  7813. */
  7814. #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
  7815. # define NDEBUG 1
  7816. #endif
  7817. #if defined(NDEBUG) && defined(SQLITE_DEBUG)
  7818. # undef NDEBUG
  7819. #endif
  7820. /*
  7821. ** Enable SQLITE_ENABLE_EXPLAIN_COMMENTS if SQLITE_DEBUG is turned on.
  7822. */
  7823. #if !defined(SQLITE_ENABLE_EXPLAIN_COMMENTS) && defined(SQLITE_DEBUG)
  7824. # define SQLITE_ENABLE_EXPLAIN_COMMENTS 1
  7825. #endif
  7826. /*
  7827. ** The testcase() macro is used to aid in coverage testing. When
  7828. ** doing coverage testing, the condition inside the argument to
  7829. ** testcase() must be evaluated both true and false in order to
  7830. ** get full branch coverage. The testcase() macro is inserted
  7831. ** to help ensure adequate test coverage in places where simple
  7832. ** condition/decision coverage is inadequate. For example, testcase()
  7833. ** can be used to make sure boundary values are tested. For
  7834. ** bitmask tests, testcase() can be used to make sure each bit
  7835. ** is significant and used at least once. On switch statements
  7836. ** where multiple cases go to the same block of code, testcase()
  7837. ** can insure that all cases are evaluated.
  7838. **
  7839. */
  7840. #ifdef SQLITE_COVERAGE_TEST
  7841. SQLITE_PRIVATE void sqlite3Coverage(int);
  7842. # define testcase(X) if( X ){ sqlite3Coverage(__LINE__); }
  7843. #else
  7844. # define testcase(X)
  7845. #endif
  7846. /*
  7847. ** The TESTONLY macro is used to enclose variable declarations or
  7848. ** other bits of code that are needed to support the arguments
  7849. ** within testcase() and assert() macros.
  7850. */
  7851. #if !defined(NDEBUG) || defined(SQLITE_COVERAGE_TEST)
  7852. # define TESTONLY(X) X
  7853. #else
  7854. # define TESTONLY(X)
  7855. #endif
  7856. /*
  7857. ** Sometimes we need a small amount of code such as a variable initialization
  7858. ** to setup for a later assert() statement. We do not want this code to
  7859. ** appear when assert() is disabled. The following macro is therefore
  7860. ** used to contain that setup code. The "VVA" acronym stands for
  7861. ** "Verification, Validation, and Accreditation". In other words, the
  7862. ** code within VVA_ONLY() will only run during verification processes.
  7863. */
  7864. #ifndef NDEBUG
  7865. # define VVA_ONLY(X) X
  7866. #else
  7867. # define VVA_ONLY(X)
  7868. #endif
  7869. /*
  7870. ** The ALWAYS and NEVER macros surround boolean expressions which
  7871. ** are intended to always be true or false, respectively. Such
  7872. ** expressions could be omitted from the code completely. But they
  7873. ** are included in a few cases in order to enhance the resilience
  7874. ** of SQLite to unexpected behavior - to make the code "self-healing"
  7875. ** or "ductile" rather than being "brittle" and crashing at the first
  7876. ** hint of unplanned behavior.
  7877. **
  7878. ** In other words, ALWAYS and NEVER are added for defensive code.
  7879. **
  7880. ** When doing coverage testing ALWAYS and NEVER are hard-coded to
  7881. ** be true and false so that the unreachable code they specify will
  7882. ** not be counted as untested code.
  7883. */
  7884. #if defined(SQLITE_COVERAGE_TEST)
  7885. # define ALWAYS(X) (1)
  7886. # define NEVER(X) (0)
  7887. #elif !defined(NDEBUG)
  7888. # define ALWAYS(X) ((X)?1:(assert(0),0))
  7889. # define NEVER(X) ((X)?(assert(0),1):0)
  7890. #else
  7891. # define ALWAYS(X) (X)
  7892. # define NEVER(X) (X)
  7893. #endif
  7894. /*
  7895. ** Return true (non-zero) if the input is an integer that is too large
  7896. ** to fit in 32-bits. This macro is used inside of various testcase()
  7897. ** macros to verify that we have tested SQLite for large-file support.
  7898. */
  7899. #define IS_BIG_INT(X) (((X)&~(i64)0xffffffff)!=0)
  7900. /*
  7901. ** The macro unlikely() is a hint that surrounds a boolean
  7902. ** expression that is usually false. Macro likely() surrounds
  7903. ** a boolean expression that is usually true. These hints could,
  7904. ** in theory, be used by the compiler to generate better code, but
  7905. ** currently they are just comments for human readers.
  7906. */
  7907. #define likely(X) (X)
  7908. #define unlikely(X) (X)
  7909. /************** Include hash.h in the middle of sqliteInt.h ******************/
  7910. /************** Begin file hash.h ********************************************/
  7911. /*
  7912. ** 2001 September 22
  7913. **
  7914. ** The author disclaims copyright to this source code. In place of
  7915. ** a legal notice, here is a blessing:
  7916. **
  7917. ** May you do good and not evil.
  7918. ** May you find forgiveness for yourself and forgive others.
  7919. ** May you share freely, never taking more than you give.
  7920. **
  7921. *************************************************************************
  7922. ** This is the header file for the generic hash-table implementation
  7923. ** used in SQLite.
  7924. */
  7925. #ifndef _SQLITE_HASH_H_
  7926. #define _SQLITE_HASH_H_
  7927. /* Forward declarations of structures. */
  7928. typedef struct Hash Hash;
  7929. typedef struct HashElem HashElem;
  7930. /* A complete hash table is an instance of the following structure.
  7931. ** The internals of this structure are intended to be opaque -- client
  7932. ** code should not attempt to access or modify the fields of this structure
  7933. ** directly. Change this structure only by using the routines below.
  7934. ** However, some of the "procedures" and "functions" for modifying and
  7935. ** accessing this structure are really macros, so we can't really make
  7936. ** this structure opaque.
  7937. **
  7938. ** All elements of the hash table are on a single doubly-linked list.
  7939. ** Hash.first points to the head of this list.
  7940. **
  7941. ** There are Hash.htsize buckets. Each bucket points to a spot in
  7942. ** the global doubly-linked list. The contents of the bucket are the
  7943. ** element pointed to plus the next _ht.count-1 elements in the list.
  7944. **
  7945. ** Hash.htsize and Hash.ht may be zero. In that case lookup is done
  7946. ** by a linear search of the global list. For small tables, the
  7947. ** Hash.ht table is never allocated because if there are few elements
  7948. ** in the table, it is faster to do a linear search than to manage
  7949. ** the hash table.
  7950. */
  7951. struct Hash {
  7952. unsigned int htsize; /* Number of buckets in the hash table */
  7953. unsigned int count; /* Number of entries in this table */
  7954. HashElem *first; /* The first element of the array */
  7955. struct _ht { /* the hash table */
  7956. int count; /* Number of entries with this hash */
  7957. HashElem *chain; /* Pointer to first entry with this hash */
  7958. } *ht;
  7959. };
  7960. /* Each element in the hash table is an instance of the following
  7961. ** structure. All elements are stored on a single doubly-linked list.
  7962. **
  7963. ** Again, this structure is intended to be opaque, but it can't really
  7964. ** be opaque because it is used by macros.
  7965. */
  7966. struct HashElem {
  7967. HashElem *next, *prev; /* Next and previous elements in the table */
  7968. void *data; /* Data associated with this element */
  7969. const char *pKey; /* Key associated with this element */
  7970. };
  7971. /*
  7972. ** Access routines. To delete, insert a NULL pointer.
  7973. */
  7974. SQLITE_PRIVATE void sqlite3HashInit(Hash*);
  7975. SQLITE_PRIVATE void *sqlite3HashInsert(Hash*, const char *pKey, void *pData);
  7976. SQLITE_PRIVATE void *sqlite3HashFind(const Hash*, const char *pKey);
  7977. SQLITE_PRIVATE void sqlite3HashClear(Hash*);
  7978. /*
  7979. ** Macros for looping over all elements of a hash table. The idiom is
  7980. ** like this:
  7981. **
  7982. ** Hash h;
  7983. ** HashElem *p;
  7984. ** ...
  7985. ** for(p=sqliteHashFirst(&h); p; p=sqliteHashNext(p)){
  7986. ** SomeStructure *pData = sqliteHashData(p);
  7987. ** // do something with pData
  7988. ** }
  7989. */
  7990. #define sqliteHashFirst(H) ((H)->first)
  7991. #define sqliteHashNext(E) ((E)->next)
  7992. #define sqliteHashData(E) ((E)->data)
  7993. /* #define sqliteHashKey(E) ((E)->pKey) // NOT USED */
  7994. /* #define sqliteHashKeysize(E) ((E)->nKey) // NOT USED */
  7995. /*
  7996. ** Number of entries in a hash table
  7997. */
  7998. /* #define sqliteHashCount(H) ((H)->count) // NOT USED */
  7999. #endif /* _SQLITE_HASH_H_ */
  8000. /************** End of hash.h ************************************************/
  8001. /************** Continuing where we left off in sqliteInt.h ******************/
  8002. /************** Include parse.h in the middle of sqliteInt.h *****************/
  8003. /************** Begin file parse.h *******************************************/
  8004. #define TK_SEMI 1
  8005. #define TK_EXPLAIN 2
  8006. #define TK_QUERY 3
  8007. #define TK_PLAN 4
  8008. #define TK_BEGIN 5
  8009. #define TK_TRANSACTION 6
  8010. #define TK_DEFERRED 7
  8011. #define TK_IMMEDIATE 8
  8012. #define TK_EXCLUSIVE 9
  8013. #define TK_COMMIT 10
  8014. #define TK_END 11
  8015. #define TK_ROLLBACK 12
  8016. #define TK_SAVEPOINT 13
  8017. #define TK_RELEASE 14
  8018. #define TK_TO 15
  8019. #define TK_TABLE 16
  8020. #define TK_CREATE 17
  8021. #define TK_IF 18
  8022. #define TK_NOT 19
  8023. #define TK_EXISTS 20
  8024. #define TK_TEMP 21
  8025. #define TK_LP 22
  8026. #define TK_RP 23
  8027. #define TK_AS 24
  8028. #define TK_WITHOUT 25
  8029. #define TK_COMMA 26
  8030. #define TK_ID 27
  8031. #define TK_INDEXED 28
  8032. #define TK_ABORT 29
  8033. #define TK_ACTION 30
  8034. #define TK_AFTER 31
  8035. #define TK_ANALYZE 32
  8036. #define TK_ASC 33
  8037. #define TK_ATTACH 34
  8038. #define TK_BEFORE 35
  8039. #define TK_BY 36
  8040. #define TK_CASCADE 37
  8041. #define TK_CAST 38
  8042. #define TK_COLUMNKW 39
  8043. #define TK_CONFLICT 40
  8044. #define TK_DATABASE 41
  8045. #define TK_DESC 42
  8046. #define TK_DETACH 43
  8047. #define TK_EACH 44
  8048. #define TK_FAIL 45
  8049. #define TK_FOR 46
  8050. #define TK_IGNORE 47
  8051. #define TK_INITIALLY 48
  8052. #define TK_INSTEAD 49
  8053. #define TK_LIKE_KW 50
  8054. #define TK_MATCH 51
  8055. #define TK_NO 52
  8056. #define TK_KEY 53
  8057. #define TK_OF 54
  8058. #define TK_OFFSET 55
  8059. #define TK_PRAGMA 56
  8060. #define TK_RAISE 57
  8061. #define TK_RECURSIVE 58
  8062. #define TK_REPLACE 59
  8063. #define TK_RESTRICT 60
  8064. #define TK_ROW 61
  8065. #define TK_TRIGGER 62
  8066. #define TK_VACUUM 63
  8067. #define TK_VIEW 64
  8068. #define TK_VIRTUAL 65
  8069. #define TK_WITH 66
  8070. #define TK_REINDEX 67
  8071. #define TK_RENAME 68
  8072. #define TK_CTIME_KW 69
  8073. #define TK_ANY 70
  8074. #define TK_OR 71
  8075. #define TK_AND 72
  8076. #define TK_IS 73
  8077. #define TK_BETWEEN 74
  8078. #define TK_IN 75
  8079. #define TK_ISNULL 76
  8080. #define TK_NOTNULL 77
  8081. #define TK_NE 78
  8082. #define TK_EQ 79
  8083. #define TK_GT 80
  8084. #define TK_LE 81
  8085. #define TK_LT 82
  8086. #define TK_GE 83
  8087. #define TK_ESCAPE 84
  8088. #define TK_BITAND 85
  8089. #define TK_BITOR 86
  8090. #define TK_LSHIFT 87
  8091. #define TK_RSHIFT 88
  8092. #define TK_PLUS 89
  8093. #define TK_MINUS 90
  8094. #define TK_STAR 91
  8095. #define TK_SLASH 92
  8096. #define TK_REM 93
  8097. #define TK_CONCAT 94
  8098. #define TK_COLLATE 95
  8099. #define TK_BITNOT 96
  8100. #define TK_STRING 97
  8101. #define TK_JOIN_KW 98
  8102. #define TK_CONSTRAINT 99
  8103. #define TK_DEFAULT 100
  8104. #define TK_NULL 101
  8105. #define TK_PRIMARY 102
  8106. #define TK_UNIQUE 103
  8107. #define TK_CHECK 104
  8108. #define TK_REFERENCES 105
  8109. #define TK_AUTOINCR 106
  8110. #define TK_ON 107
  8111. #define TK_INSERT 108
  8112. #define TK_DELETE 109
  8113. #define TK_UPDATE 110
  8114. #define TK_SET 111
  8115. #define TK_DEFERRABLE 112
  8116. #define TK_FOREIGN 113
  8117. #define TK_DROP 114
  8118. #define TK_UNION 115
  8119. #define TK_ALL 116
  8120. #define TK_EXCEPT 117
  8121. #define TK_INTERSECT 118
  8122. #define TK_SELECT 119
  8123. #define TK_VALUES 120
  8124. #define TK_DISTINCT 121
  8125. #define TK_DOT 122
  8126. #define TK_FROM 123
  8127. #define TK_JOIN 124
  8128. #define TK_USING 125
  8129. #define TK_ORDER 126
  8130. #define TK_GROUP 127
  8131. #define TK_HAVING 128
  8132. #define TK_LIMIT 129
  8133. #define TK_WHERE 130
  8134. #define TK_INTO 131
  8135. #define TK_INTEGER 132
  8136. #define TK_FLOAT 133
  8137. #define TK_BLOB 134
  8138. #define TK_VARIABLE 135
  8139. #define TK_CASE 136
  8140. #define TK_WHEN 137
  8141. #define TK_THEN 138
  8142. #define TK_ELSE 139
  8143. #define TK_INDEX 140
  8144. #define TK_ALTER 141
  8145. #define TK_ADD 142
  8146. #define TK_TO_TEXT 143
  8147. #define TK_TO_BLOB 144
  8148. #define TK_TO_NUMERIC 145
  8149. #define TK_TO_INT 146
  8150. #define TK_TO_REAL 147
  8151. #define TK_ISNOT 148
  8152. #define TK_END_OF_FILE 149
  8153. #define TK_ILLEGAL 150
  8154. #define TK_SPACE 151
  8155. #define TK_UNCLOSED_STRING 152
  8156. #define TK_FUNCTION 153
  8157. #define TK_COLUMN 154
  8158. #define TK_AGG_FUNCTION 155
  8159. #define TK_AGG_COLUMN 156
  8160. #define TK_UMINUS 157
  8161. #define TK_UPLUS 158
  8162. #define TK_REGISTER 159
  8163. /************** End of parse.h ***********************************************/
  8164. /************** Continuing where we left off in sqliteInt.h ******************/
  8165. #include <stdio.h>
  8166. #include <stdlib.h>
  8167. #include <string.h>
  8168. #include <assert.h>
  8169. #include <stddef.h>
  8170. /*
  8171. ** If compiling for a processor that lacks floating point support,
  8172. ** substitute integer for floating-point
  8173. */
  8174. #ifdef SQLITE_OMIT_FLOATING_POINT
  8175. # define double sqlite_int64
  8176. # define float sqlite_int64
  8177. # define LONGDOUBLE_TYPE sqlite_int64
  8178. # ifndef SQLITE_BIG_DBL
  8179. # define SQLITE_BIG_DBL (((sqlite3_int64)1)<<50)
  8180. # endif
  8181. # define SQLITE_OMIT_DATETIME_FUNCS 1
  8182. # define SQLITE_OMIT_TRACE 1
  8183. # undef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
  8184. # undef SQLITE_HAVE_ISNAN
  8185. #endif
  8186. #ifndef SQLITE_BIG_DBL
  8187. # define SQLITE_BIG_DBL (1e99)
  8188. #endif
  8189. /*
  8190. ** OMIT_TEMPDB is set to 1 if SQLITE_OMIT_TEMPDB is defined, or 0
  8191. ** afterward. Having this macro allows us to cause the C compiler
  8192. ** to omit code used by TEMP tables without messy #ifndef statements.
  8193. */
  8194. #ifdef SQLITE_OMIT_TEMPDB
  8195. #define OMIT_TEMPDB 1
  8196. #else
  8197. #define OMIT_TEMPDB 0
  8198. #endif
  8199. /*
  8200. ** The "file format" number is an integer that is incremented whenever
  8201. ** the VDBE-level file format changes. The following macros define the
  8202. ** the default file format for new databases and the maximum file format
  8203. ** that the library can read.
  8204. */
  8205. #define SQLITE_MAX_FILE_FORMAT 4
  8206. #ifndef SQLITE_DEFAULT_FILE_FORMAT
  8207. # define SQLITE_DEFAULT_FILE_FORMAT 4
  8208. #endif
  8209. /*
  8210. ** Determine whether triggers are recursive by default. This can be
  8211. ** changed at run-time using a pragma.
  8212. */
  8213. #ifndef SQLITE_DEFAULT_RECURSIVE_TRIGGERS
  8214. # define SQLITE_DEFAULT_RECURSIVE_TRIGGERS 0
  8215. #endif
  8216. /*
  8217. ** Provide a default value for SQLITE_TEMP_STORE in case it is not specified
  8218. ** on the command-line
  8219. */
  8220. #ifndef SQLITE_TEMP_STORE
  8221. # define SQLITE_TEMP_STORE 1
  8222. # define SQLITE_TEMP_STORE_xc 1 /* Exclude from ctime.c */
  8223. #endif
  8224. /*
  8225. ** If no value has been provided for SQLITE_MAX_WORKER_THREADS, or if
  8226. ** SQLITE_TEMP_STORE is set to 3 (never use temporary files), set it
  8227. ** to zero.
  8228. */
  8229. #if SQLITE_TEMP_STORE==3 || SQLITE_THREADSAFE==0
  8230. # undef SQLITE_MAX_WORKER_THREADS
  8231. # define SQLITE_MAX_WORKER_THREADS 0
  8232. #endif
  8233. #ifndef SQLITE_MAX_WORKER_THREADS
  8234. # define SQLITE_MAX_WORKER_THREADS 8
  8235. #endif
  8236. #ifndef SQLITE_DEFAULT_WORKER_THREADS
  8237. # define SQLITE_DEFAULT_WORKER_THREADS 0
  8238. #endif
  8239. #if SQLITE_DEFAULT_WORKER_THREADS>SQLITE_MAX_WORKER_THREADS
  8240. # undef SQLITE_MAX_WORKER_THREADS
  8241. # define SQLITE_MAX_WORKER_THREADS SQLITE_DEFAULT_WORKER_THREADS
  8242. #endif
  8243. /*
  8244. ** GCC does not define the offsetof() macro so we'll have to do it
  8245. ** ourselves.
  8246. */
  8247. #ifndef offsetof
  8248. #define offsetof(STRUCTURE,FIELD) ((int)((char*)&((STRUCTURE*)0)->FIELD))
  8249. #endif
  8250. /*
  8251. ** Macros to compute minimum and maximum of two numbers.
  8252. */
  8253. #define MIN(A,B) ((A)<(B)?(A):(B))
  8254. #define MAX(A,B) ((A)>(B)?(A):(B))
  8255. /*
  8256. ** Swap two objects of type TYPE.
  8257. */
  8258. #define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
  8259. /*
  8260. ** Check to see if this machine uses EBCDIC. (Yes, believe it or
  8261. ** not, there are still machines out there that use EBCDIC.)
  8262. */
  8263. #if 'A' == '\301'
  8264. # define SQLITE_EBCDIC 1
  8265. #else
  8266. # define SQLITE_ASCII 1
  8267. #endif
  8268. /*
  8269. ** Integers of known sizes. These typedefs might change for architectures
  8270. ** where the sizes very. Preprocessor macros are available so that the
  8271. ** types can be conveniently redefined at compile-type. Like this:
  8272. **
  8273. ** cc '-DUINTPTR_TYPE=long long int' ...
  8274. */
  8275. #ifndef UINT32_TYPE
  8276. # ifdef HAVE_UINT32_T
  8277. # define UINT32_TYPE uint32_t
  8278. # else
  8279. # define UINT32_TYPE unsigned int
  8280. # endif
  8281. #endif
  8282. #ifndef UINT16_TYPE
  8283. # ifdef HAVE_UINT16_T
  8284. # define UINT16_TYPE uint16_t
  8285. # else
  8286. # define UINT16_TYPE unsigned short int
  8287. # endif
  8288. #endif
  8289. #ifndef INT16_TYPE
  8290. # ifdef HAVE_INT16_T
  8291. # define INT16_TYPE int16_t
  8292. # else
  8293. # define INT16_TYPE short int
  8294. # endif
  8295. #endif
  8296. #ifndef UINT8_TYPE
  8297. # ifdef HAVE_UINT8_T
  8298. # define UINT8_TYPE uint8_t
  8299. # else
  8300. # define UINT8_TYPE unsigned char
  8301. # endif
  8302. #endif
  8303. #ifndef INT8_TYPE
  8304. # ifdef HAVE_INT8_T
  8305. # define INT8_TYPE int8_t
  8306. # else
  8307. # define INT8_TYPE signed char
  8308. # endif
  8309. #endif
  8310. #ifndef LONGDOUBLE_TYPE
  8311. # define LONGDOUBLE_TYPE long double
  8312. #endif
  8313. typedef sqlite_int64 i64; /* 8-byte signed integer */
  8314. typedef sqlite_uint64 u64; /* 8-byte unsigned integer */
  8315. typedef UINT32_TYPE u32; /* 4-byte unsigned integer */
  8316. typedef UINT16_TYPE u16; /* 2-byte unsigned integer */
  8317. typedef INT16_TYPE i16; /* 2-byte signed integer */
  8318. typedef UINT8_TYPE u8; /* 1-byte unsigned integer */
  8319. typedef INT8_TYPE i8; /* 1-byte signed integer */
  8320. /*
  8321. ** SQLITE_MAX_U32 is a u64 constant that is the maximum u64 value
  8322. ** that can be stored in a u32 without loss of data. The value
  8323. ** is 0x00000000ffffffff. But because of quirks of some compilers, we
  8324. ** have to specify the value in the less intuitive manner shown:
  8325. */
  8326. #define SQLITE_MAX_U32 ((((u64)1)<<32)-1)
  8327. /*
  8328. ** The datatype used to store estimates of the number of rows in a
  8329. ** table or index. This is an unsigned integer type. For 99.9% of
  8330. ** the world, a 32-bit integer is sufficient. But a 64-bit integer
  8331. ** can be used at compile-time if desired.
  8332. */
  8333. #ifdef SQLITE_64BIT_STATS
  8334. typedef u64 tRowcnt; /* 64-bit only if requested at compile-time */
  8335. #else
  8336. typedef u32 tRowcnt; /* 32-bit is the default */
  8337. #endif
  8338. /*
  8339. ** Estimated quantities used for query planning are stored as 16-bit
  8340. ** logarithms. For quantity X, the value stored is 10*log2(X). This
  8341. ** gives a possible range of values of approximately 1.0e986 to 1e-986.
  8342. ** But the allowed values are "grainy". Not every value is representable.
  8343. ** For example, quantities 16 and 17 are both represented by a LogEst
  8344. ** of 40. However, since LogEst quantaties are suppose to be estimates,
  8345. ** not exact values, this imprecision is not a problem.
  8346. **
  8347. ** "LogEst" is short for "Logarithmic Estimate".
  8348. **
  8349. ** Examples:
  8350. ** 1 -> 0 20 -> 43 10000 -> 132
  8351. ** 2 -> 10 25 -> 46 25000 -> 146
  8352. ** 3 -> 16 100 -> 66 1000000 -> 199
  8353. ** 4 -> 20 1000 -> 99 1048576 -> 200
  8354. ** 10 -> 33 1024 -> 100 4294967296 -> 320
  8355. **
  8356. ** The LogEst can be negative to indicate fractional values.
  8357. ** Examples:
  8358. **
  8359. ** 0.5 -> -10 0.1 -> -33 0.0625 -> -40
  8360. */
  8361. typedef INT16_TYPE LogEst;
  8362. /*
  8363. ** Macros to determine whether the machine is big or little endian,
  8364. ** and whether or not that determination is run-time or compile-time.
  8365. **
  8366. ** For best performance, an attempt is made to guess at the byte-order
  8367. ** using C-preprocessor macros. If that is unsuccessful, or if
  8368. ** -DSQLITE_RUNTIME_BYTEORDER=1 is set, then byte-order is determined
  8369. ** at run-time.
  8370. */
  8371. #ifdef SQLITE_AMALGAMATION
  8372. SQLITE_PRIVATE const int sqlite3one = 1;
  8373. #else
  8374. SQLITE_PRIVATE const int sqlite3one;
  8375. #endif
  8376. #if (defined(i386) || defined(__i386__) || defined(_M_IX86) || \
  8377. defined(__x86_64) || defined(__x86_64__) || defined(_M_X64) || \
  8378. defined(_M_AMD64) || defined(_M_ARM) || defined(__x86) || \
  8379. defined(__arm__)) && !defined(SQLITE_RUNTIME_BYTEORDER)
  8380. # define SQLITE_BYTEORDER 1234
  8381. # define SQLITE_BIGENDIAN 0
  8382. # define SQLITE_LITTLEENDIAN 1
  8383. # define SQLITE_UTF16NATIVE SQLITE_UTF16LE
  8384. #endif
  8385. #if (defined(sparc) || defined(__ppc__)) \
  8386. && !defined(SQLITE_RUNTIME_BYTEORDER)
  8387. # define SQLITE_BYTEORDER 4321
  8388. # define SQLITE_BIGENDIAN 1
  8389. # define SQLITE_LITTLEENDIAN 0
  8390. # define SQLITE_UTF16NATIVE SQLITE_UTF16BE
  8391. #endif
  8392. #if !defined(SQLITE_BYTEORDER)
  8393. # define SQLITE_BYTEORDER 0 /* 0 means "unknown at compile-time" */
  8394. # define SQLITE_BIGENDIAN (*(char *)(&sqlite3one)==0)
  8395. # define SQLITE_LITTLEENDIAN (*(char *)(&sqlite3one)==1)
  8396. # define SQLITE_UTF16NATIVE (SQLITE_BIGENDIAN?SQLITE_UTF16BE:SQLITE_UTF16LE)
  8397. #endif
  8398. /*
  8399. ** Constants for the largest and smallest possible 64-bit signed integers.
  8400. ** These macros are designed to work correctly on both 32-bit and 64-bit
  8401. ** compilers.
  8402. */
  8403. #define LARGEST_INT64 (0xffffffff|(((i64)0x7fffffff)<<32))
  8404. #define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64)
  8405. /*
  8406. ** Round up a number to the next larger multiple of 8. This is used
  8407. ** to force 8-byte alignment on 64-bit architectures.
  8408. */
  8409. #define ROUND8(x) (((x)+7)&~7)
  8410. /*
  8411. ** Round down to the nearest multiple of 8
  8412. */
  8413. #define ROUNDDOWN8(x) ((x)&~7)
  8414. /*
  8415. ** Assert that the pointer X is aligned to an 8-byte boundary. This
  8416. ** macro is used only within assert() to verify that the code gets
  8417. ** all alignment restrictions correct.
  8418. **
  8419. ** Except, if SQLITE_4_BYTE_ALIGNED_MALLOC is defined, then the
  8420. ** underlying malloc() implementation might return us 4-byte aligned
  8421. ** pointers. In that case, only verify 4-byte alignment.
  8422. */
  8423. #ifdef SQLITE_4_BYTE_ALIGNED_MALLOC
  8424. # define EIGHT_BYTE_ALIGNMENT(X) ((((char*)(X) - (char*)0)&3)==0)
  8425. #else
  8426. # define EIGHT_BYTE_ALIGNMENT(X) ((((char*)(X) - (char*)0)&7)==0)
  8427. #endif
  8428. /*
  8429. ** Disable MMAP on platforms where it is known to not work
  8430. */
  8431. #if defined(__OpenBSD__) || defined(__QNXNTO__)
  8432. # undef SQLITE_MAX_MMAP_SIZE
  8433. # define SQLITE_MAX_MMAP_SIZE 0
  8434. #endif
  8435. /*
  8436. ** Default maximum size of memory used by memory-mapped I/O in the VFS
  8437. */
  8438. #ifdef __APPLE__
  8439. # include <TargetConditionals.h>
  8440. # if TARGET_OS_IPHONE
  8441. # undef SQLITE_MAX_MMAP_SIZE
  8442. # define SQLITE_MAX_MMAP_SIZE 0
  8443. # endif
  8444. #endif
  8445. #ifndef SQLITE_MAX_MMAP_SIZE
  8446. # if defined(__linux__) \
  8447. || defined(_WIN32) \
  8448. || (defined(__APPLE__) && defined(__MACH__)) \
  8449. || defined(__sun)
  8450. # define SQLITE_MAX_MMAP_SIZE 0x7fff0000 /* 2147418112 */
  8451. # else
  8452. # define SQLITE_MAX_MMAP_SIZE 0
  8453. # endif
  8454. # define SQLITE_MAX_MMAP_SIZE_xc 1 /* exclude from ctime.c */
  8455. #endif
  8456. /*
  8457. ** The default MMAP_SIZE is zero on all platforms. Or, even if a larger
  8458. ** default MMAP_SIZE is specified at compile-time, make sure that it does
  8459. ** not exceed the maximum mmap size.
  8460. */
  8461. #ifndef SQLITE_DEFAULT_MMAP_SIZE
  8462. # define SQLITE_DEFAULT_MMAP_SIZE 0
  8463. # define SQLITE_DEFAULT_MMAP_SIZE_xc 1 /* Exclude from ctime.c */
  8464. #endif
  8465. #if SQLITE_DEFAULT_MMAP_SIZE>SQLITE_MAX_MMAP_SIZE
  8466. # undef SQLITE_DEFAULT_MMAP_SIZE
  8467. # define SQLITE_DEFAULT_MMAP_SIZE SQLITE_MAX_MMAP_SIZE
  8468. #endif
  8469. /*
  8470. ** Only one of SQLITE_ENABLE_STAT3 or SQLITE_ENABLE_STAT4 can be defined.
  8471. ** Priority is given to SQLITE_ENABLE_STAT4. If either are defined, also
  8472. ** define SQLITE_ENABLE_STAT3_OR_STAT4
  8473. */
  8474. #ifdef SQLITE_ENABLE_STAT4
  8475. # undef SQLITE_ENABLE_STAT3
  8476. # define SQLITE_ENABLE_STAT3_OR_STAT4 1
  8477. #elif SQLITE_ENABLE_STAT3
  8478. # define SQLITE_ENABLE_STAT3_OR_STAT4 1
  8479. #elif SQLITE_ENABLE_STAT3_OR_STAT4
  8480. # undef SQLITE_ENABLE_STAT3_OR_STAT4
  8481. #endif
  8482. /*
  8483. ** SELECTTRACE_ENABLED will be either 1 or 0 depending on whether or not
  8484. ** the Select query generator tracing logic is turned on.
  8485. */
  8486. #if defined(SQLITE_DEBUG) || defined(SQLITE_ENABLE_SELECTTRACE)
  8487. # define SELECTTRACE_ENABLED 1
  8488. #else
  8489. # define SELECTTRACE_ENABLED 0
  8490. #endif
  8491. /*
  8492. ** An instance of the following structure is used to store the busy-handler
  8493. ** callback for a given sqlite handle.
  8494. **
  8495. ** The sqlite.busyHandler member of the sqlite struct contains the busy
  8496. ** callback for the database handle. Each pager opened via the sqlite
  8497. ** handle is passed a pointer to sqlite.busyHandler. The busy-handler
  8498. ** callback is currently invoked only from within pager.c.
  8499. */
  8500. typedef struct BusyHandler BusyHandler;
  8501. struct BusyHandler {
  8502. int (*xFunc)(void *,int); /* The busy callback */
  8503. void *pArg; /* First arg to busy callback */
  8504. int nBusy; /* Incremented with each busy call */
  8505. };
  8506. /*
  8507. ** Name of the master database table. The master database table
  8508. ** is a special table that holds the names and attributes of all
  8509. ** user tables and indices.
  8510. */
  8511. #define MASTER_NAME "sqlite_master"
  8512. #define TEMP_MASTER_NAME "sqlite_temp_master"
  8513. /*
  8514. ** The root-page of the master database table.
  8515. */
  8516. #define MASTER_ROOT 1
  8517. /*
  8518. ** The name of the schema table.
  8519. */
  8520. #define SCHEMA_TABLE(x) ((!OMIT_TEMPDB)&&(x==1)?TEMP_MASTER_NAME:MASTER_NAME)
  8521. /*
  8522. ** A convenience macro that returns the number of elements in
  8523. ** an array.
  8524. */
  8525. #define ArraySize(X) ((int)(sizeof(X)/sizeof(X[0])))
  8526. /*
  8527. ** Determine if the argument is a power of two
  8528. */
  8529. #define IsPowerOfTwo(X) (((X)&((X)-1))==0)
  8530. /*
  8531. ** The following value as a destructor means to use sqlite3DbFree().
  8532. ** The sqlite3DbFree() routine requires two parameters instead of the
  8533. ** one parameter that destructors normally want. So we have to introduce
  8534. ** this magic value that the code knows to handle differently. Any
  8535. ** pointer will work here as long as it is distinct from SQLITE_STATIC
  8536. ** and SQLITE_TRANSIENT.
  8537. */
  8538. #define SQLITE_DYNAMIC ((sqlite3_destructor_type)sqlite3MallocSize)
  8539. /*
  8540. ** When SQLITE_OMIT_WSD is defined, it means that the target platform does
  8541. ** not support Writable Static Data (WSD) such as global and static variables.
  8542. ** All variables must either be on the stack or dynamically allocated from
  8543. ** the heap. When WSD is unsupported, the variable declarations scattered
  8544. ** throughout the SQLite code must become constants instead. The SQLITE_WSD
  8545. ** macro is used for this purpose. And instead of referencing the variable
  8546. ** directly, we use its constant as a key to lookup the run-time allocated
  8547. ** buffer that holds real variable. The constant is also the initializer
  8548. ** for the run-time allocated buffer.
  8549. **
  8550. ** In the usual case where WSD is supported, the SQLITE_WSD and GLOBAL
  8551. ** macros become no-ops and have zero performance impact.
  8552. */
  8553. #ifdef SQLITE_OMIT_WSD
  8554. #define SQLITE_WSD const
  8555. #define GLOBAL(t,v) (*(t*)sqlite3_wsd_find((void*)&(v), sizeof(v)))
  8556. #define sqlite3GlobalConfig GLOBAL(struct Sqlite3Config, sqlite3Config)
  8557. SQLITE_API int sqlite3_wsd_init(int N, int J);
  8558. SQLITE_API void *sqlite3_wsd_find(void *K, int L);
  8559. #else
  8560. #define SQLITE_WSD
  8561. #define GLOBAL(t,v) v
  8562. #define sqlite3GlobalConfig sqlite3Config
  8563. #endif
  8564. /*
  8565. ** The following macros are used to suppress compiler warnings and to
  8566. ** make it clear to human readers when a function parameter is deliberately
  8567. ** left unused within the body of a function. This usually happens when
  8568. ** a function is called via a function pointer. For example the
  8569. ** implementation of an SQL aggregate step callback may not use the
  8570. ** parameter indicating the number of arguments passed to the aggregate,
  8571. ** if it knows that this is enforced elsewhere.
  8572. **
  8573. ** When a function parameter is not used at all within the body of a function,
  8574. ** it is generally named "NotUsed" or "NotUsed2" to make things even clearer.
  8575. ** However, these macros may also be used to suppress warnings related to
  8576. ** parameters that may or may not be used depending on compilation options.
  8577. ** For example those parameters only used in assert() statements. In these
  8578. ** cases the parameters are named as per the usual conventions.
  8579. */
  8580. #define UNUSED_PARAMETER(x) (void)(x)
  8581. #define UNUSED_PARAMETER2(x,y) UNUSED_PARAMETER(x),UNUSED_PARAMETER(y)
  8582. /*
  8583. ** Forward references to structures
  8584. */
  8585. typedef struct AggInfo AggInfo;
  8586. typedef struct AuthContext AuthContext;
  8587. typedef struct AutoincInfo AutoincInfo;
  8588. typedef struct Bitvec Bitvec;
  8589. typedef struct CollSeq CollSeq;
  8590. typedef struct Column Column;
  8591. typedef struct Db Db;
  8592. typedef struct Schema Schema;
  8593. typedef struct Expr Expr;
  8594. typedef struct ExprList ExprList;
  8595. typedef struct ExprSpan ExprSpan;
  8596. typedef struct FKey FKey;
  8597. typedef struct FuncDestructor FuncDestructor;
  8598. typedef struct FuncDef FuncDef;
  8599. typedef struct FuncDefHash FuncDefHash;
  8600. typedef struct IdList IdList;
  8601. typedef struct Index Index;
  8602. typedef struct IndexSample IndexSample;
  8603. typedef struct KeyClass KeyClass;
  8604. typedef struct KeyInfo KeyInfo;
  8605. typedef struct Lookaside Lookaside;
  8606. typedef struct LookasideSlot LookasideSlot;
  8607. typedef struct Module Module;
  8608. typedef struct NameContext NameContext;
  8609. typedef struct Parse Parse;
  8610. typedef struct PrintfArguments PrintfArguments;
  8611. typedef struct RowSet RowSet;
  8612. typedef struct Savepoint Savepoint;
  8613. typedef struct Select Select;
  8614. typedef struct SQLiteThread SQLiteThread;
  8615. typedef struct SelectDest SelectDest;
  8616. typedef struct SrcList SrcList;
  8617. typedef struct StrAccum StrAccum;
  8618. typedef struct Table Table;
  8619. typedef struct TableLock TableLock;
  8620. typedef struct Token Token;
  8621. typedef struct TreeView TreeView;
  8622. typedef struct Trigger Trigger;
  8623. typedef struct TriggerPrg TriggerPrg;
  8624. typedef struct TriggerStep TriggerStep;
  8625. typedef struct UnpackedRecord UnpackedRecord;
  8626. typedef struct VTable VTable;
  8627. typedef struct VtabCtx VtabCtx;
  8628. typedef struct Walker Walker;
  8629. typedef struct WhereInfo WhereInfo;
  8630. typedef struct With With;
  8631. /*
  8632. ** Defer sourcing vdbe.h and btree.h until after the "u8" and
  8633. ** "BusyHandler" typedefs. vdbe.h also requires a few of the opaque
  8634. ** pointer types (i.e. FuncDef) defined above.
  8635. */
  8636. /************** Include btree.h in the middle of sqliteInt.h *****************/
  8637. /************** Begin file btree.h *******************************************/
  8638. /*
  8639. ** 2001 September 15
  8640. **
  8641. ** The author disclaims copyright to this source code. In place of
  8642. ** a legal notice, here is a blessing:
  8643. **
  8644. ** May you do good and not evil.
  8645. ** May you find forgiveness for yourself and forgive others.
  8646. ** May you share freely, never taking more than you give.
  8647. **
  8648. *************************************************************************
  8649. ** This header file defines the interface that the sqlite B-Tree file
  8650. ** subsystem. See comments in the source code for a detailed description
  8651. ** of what each interface routine does.
  8652. */
  8653. #ifndef _BTREE_H_
  8654. #define _BTREE_H_
  8655. /* TODO: This definition is just included so other modules compile. It
  8656. ** needs to be revisited.
  8657. */
  8658. #define SQLITE_N_BTREE_META 10
  8659. /*
  8660. ** If defined as non-zero, auto-vacuum is enabled by default. Otherwise
  8661. ** it must be turned on for each database using "PRAGMA auto_vacuum = 1".
  8662. */
  8663. #ifndef SQLITE_DEFAULT_AUTOVACUUM
  8664. #define SQLITE_DEFAULT_AUTOVACUUM 0
  8665. #endif
  8666. #define BTREE_AUTOVACUUM_NONE 0 /* Do not do auto-vacuum */
  8667. #define BTREE_AUTOVACUUM_FULL 1 /* Do full auto-vacuum */
  8668. #define BTREE_AUTOVACUUM_INCR 2 /* Incremental vacuum */
  8669. /*
  8670. ** Forward declarations of structure
  8671. */
  8672. typedef struct Btree Btree;
  8673. typedef struct BtCursor BtCursor;
  8674. typedef struct BtShared BtShared;
  8675. SQLITE_PRIVATE int sqlite3BtreeOpen(
  8676. sqlite3_vfs *pVfs, /* VFS to use with this b-tree */
  8677. const char *zFilename, /* Name of database file to open */
  8678. sqlite3 *db, /* Associated database connection */
  8679. Btree **ppBtree, /* Return open Btree* here */
  8680. int flags, /* Flags */
  8681. int vfsFlags /* Flags passed through to VFS open */
  8682. );
  8683. /* The flags parameter to sqlite3BtreeOpen can be the bitwise or of the
  8684. ** following values.
  8685. **
  8686. ** NOTE: These values must match the corresponding PAGER_ values in
  8687. ** pager.h.
  8688. */
  8689. #define BTREE_OMIT_JOURNAL 1 /* Do not create or use a rollback journal */
  8690. #define BTREE_MEMORY 2 /* This is an in-memory DB */
  8691. #define BTREE_SINGLE 4 /* The file contains at most 1 b-tree */
  8692. #define BTREE_UNORDERED 8 /* Use of a hash implementation is OK */
  8693. SQLITE_PRIVATE int sqlite3BtreeClose(Btree*);
  8694. SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree*,int);
  8695. #if SQLITE_MAX_MMAP_SIZE>0
  8696. SQLITE_PRIVATE int sqlite3BtreeSetMmapLimit(Btree*,sqlite3_int64);
  8697. #endif
  8698. SQLITE_PRIVATE int sqlite3BtreeSetPagerFlags(Btree*,unsigned);
  8699. SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree*);
  8700. SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int nPagesize, int nReserve, int eFix);
  8701. SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree*);
  8702. SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree*,int);
  8703. SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree*);
  8704. SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree*,int);
  8705. SQLITE_PRIVATE int sqlite3BtreeGetReserve(Btree*);
  8706. #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_DEBUG)
  8707. SQLITE_PRIVATE int sqlite3BtreeGetReserveNoMutex(Btree *p);
  8708. #endif
  8709. SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *, int);
  8710. SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *);
  8711. SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree*,int);
  8712. SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree*, const char *zMaster);
  8713. SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree*, int);
  8714. SQLITE_PRIVATE int sqlite3BtreeCommit(Btree*);
  8715. SQLITE_PRIVATE int sqlite3BtreeRollback(Btree*,int);
  8716. SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree*,int);
  8717. SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree*, int*, int flags);
  8718. SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree*);
  8719. SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree*);
  8720. SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree*);
  8721. SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *, int, void(*)(void *));
  8722. SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *pBtree);
  8723. SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *pBtree, int iTab, u8 isWriteLock);
  8724. SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *, int, int);
  8725. SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *);
  8726. SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *);
  8727. SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *, Btree *);
  8728. SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *);
  8729. /* The flags parameter to sqlite3BtreeCreateTable can be the bitwise OR
  8730. ** of the flags shown below.
  8731. **
  8732. ** Every SQLite table must have either BTREE_INTKEY or BTREE_BLOBKEY set.
  8733. ** With BTREE_INTKEY, the table key is a 64-bit integer and arbitrary data
  8734. ** is stored in the leaves. (BTREE_INTKEY is used for SQL tables.) With
  8735. ** BTREE_BLOBKEY, the key is an arbitrary BLOB and no content is stored
  8736. ** anywhere - the key is the content. (BTREE_BLOBKEY is used for SQL
  8737. ** indices.)
  8738. */
  8739. #define BTREE_INTKEY 1 /* Table has only 64-bit signed integer keys */
  8740. #define BTREE_BLOBKEY 2 /* Table has keys only - no data */
  8741. SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree*, int, int*);
  8742. SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree*, int, int*);
  8743. SQLITE_PRIVATE int sqlite3BtreeClearTableOfCursor(BtCursor*);
  8744. SQLITE_PRIVATE void sqlite3BtreeTripAllCursors(Btree*, int);
  8745. SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *pBtree, int idx, u32 *pValue);
  8746. SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree*, int idx, u32 value);
  8747. SQLITE_PRIVATE int sqlite3BtreeNewDb(Btree *p);
  8748. /*
  8749. ** The second parameter to sqlite3BtreeGetMeta or sqlite3BtreeUpdateMeta
  8750. ** should be one of the following values. The integer values are assigned
  8751. ** to constants so that the offset of the corresponding field in an
  8752. ** SQLite database header may be found using the following formula:
  8753. **
  8754. ** offset = 36 + (idx * 4)
  8755. **
  8756. ** For example, the free-page-count field is located at byte offset 36 of
  8757. ** the database file header. The incr-vacuum-flag field is located at
  8758. ** byte offset 64 (== 36+4*7).
  8759. */
  8760. #define BTREE_FREE_PAGE_COUNT 0
  8761. #define BTREE_SCHEMA_VERSION 1
  8762. #define BTREE_FILE_FORMAT 2
  8763. #define BTREE_DEFAULT_CACHE_SIZE 3
  8764. #define BTREE_LARGEST_ROOT_PAGE 4
  8765. #define BTREE_TEXT_ENCODING 5
  8766. #define BTREE_USER_VERSION 6
  8767. #define BTREE_INCR_VACUUM 7
  8768. #define BTREE_APPLICATION_ID 8
  8769. /*
  8770. ** Values that may be OR'd together to form the second argument of an
  8771. ** sqlite3BtreeCursorHints() call.
  8772. */
  8773. #define BTREE_BULKLOAD 0x00000001
  8774. SQLITE_PRIVATE int sqlite3BtreeCursor(
  8775. Btree*, /* BTree containing table to open */
  8776. int iTable, /* Index of root page */
  8777. int wrFlag, /* 1 for writing. 0 for read-only */
  8778. struct KeyInfo*, /* First argument to compare function */
  8779. BtCursor *pCursor /* Space to write cursor structure */
  8780. );
  8781. SQLITE_PRIVATE int sqlite3BtreeCursorSize(void);
  8782. SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor*);
  8783. SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor*);
  8784. SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
  8785. BtCursor*,
  8786. UnpackedRecord *pUnKey,
  8787. i64 intKey,
  8788. int bias,
  8789. int *pRes
  8790. );
  8791. SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor*);
  8792. SQLITE_PRIVATE int sqlite3BtreeCursorRestore(BtCursor*, int*);
  8793. SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor*);
  8794. SQLITE_PRIVATE int sqlite3BtreeInsert(BtCursor*, const void *pKey, i64 nKey,
  8795. const void *pData, int nData,
  8796. int nZero, int bias, int seekResult);
  8797. SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor*, int *pRes);
  8798. SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor*, int *pRes);
  8799. SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor*, int *pRes);
  8800. SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor*);
  8801. SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor*, int *pRes);
  8802. SQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor*, i64 *pSize);
  8803. SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor*, u32 offset, u32 amt, void*);
  8804. SQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor*, u32 *pAmt);
  8805. SQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor*, u32 *pAmt);
  8806. SQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor*, u32 *pSize);
  8807. SQLITE_PRIVATE int sqlite3BtreeData(BtCursor*, u32 offset, u32 amt, void*);
  8808. SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(Btree*, int *aRoot, int nRoot, int, int*);
  8809. SQLITE_PRIVATE struct Pager *sqlite3BtreePager(Btree*);
  8810. SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor*, u32 offset, u32 amt, void*);
  8811. SQLITE_PRIVATE void sqlite3BtreeIncrblobCursor(BtCursor *);
  8812. SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *);
  8813. SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBt, int iVersion);
  8814. SQLITE_PRIVATE void sqlite3BtreeCursorHints(BtCursor *, unsigned int mask);
  8815. SQLITE_PRIVATE int sqlite3BtreeIsReadonly(Btree *pBt);
  8816. #ifndef NDEBUG
  8817. SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor*);
  8818. #endif
  8819. #ifndef SQLITE_OMIT_BTREECOUNT
  8820. SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *, i64 *);
  8821. #endif
  8822. #ifdef SQLITE_TEST
  8823. SQLITE_PRIVATE int sqlite3BtreeCursorInfo(BtCursor*, int*, int);
  8824. SQLITE_PRIVATE void sqlite3BtreeCursorList(Btree*);
  8825. #endif
  8826. #ifndef SQLITE_OMIT_WAL
  8827. SQLITE_PRIVATE int sqlite3BtreeCheckpoint(Btree*, int, int *, int *);
  8828. #endif
  8829. /*
  8830. ** If we are not using shared cache, then there is no need to
  8831. ** use mutexes to access the BtShared structures. So make the
  8832. ** Enter and Leave procedures no-ops.
  8833. */
  8834. #ifndef SQLITE_OMIT_SHARED_CACHE
  8835. SQLITE_PRIVATE void sqlite3BtreeEnter(Btree*);
  8836. SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3*);
  8837. #else
  8838. # define sqlite3BtreeEnter(X)
  8839. # define sqlite3BtreeEnterAll(X)
  8840. #endif
  8841. #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE
  8842. SQLITE_PRIVATE int sqlite3BtreeSharable(Btree*);
  8843. SQLITE_PRIVATE void sqlite3BtreeLeave(Btree*);
  8844. SQLITE_PRIVATE void sqlite3BtreeEnterCursor(BtCursor*);
  8845. SQLITE_PRIVATE void sqlite3BtreeLeaveCursor(BtCursor*);
  8846. SQLITE_PRIVATE void sqlite3BtreeLeaveAll(sqlite3*);
  8847. #ifndef NDEBUG
  8848. /* These routines are used inside assert() statements only. */
  8849. SQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree*);
  8850. SQLITE_PRIVATE int sqlite3BtreeHoldsAllMutexes(sqlite3*);
  8851. SQLITE_PRIVATE int sqlite3SchemaMutexHeld(sqlite3*,int,Schema*);
  8852. #endif
  8853. #else
  8854. # define sqlite3BtreeSharable(X) 0
  8855. # define sqlite3BtreeLeave(X)
  8856. # define sqlite3BtreeEnterCursor(X)
  8857. # define sqlite3BtreeLeaveCursor(X)
  8858. # define sqlite3BtreeLeaveAll(X)
  8859. # define sqlite3BtreeHoldsMutex(X) 1
  8860. # define sqlite3BtreeHoldsAllMutexes(X) 1
  8861. # define sqlite3SchemaMutexHeld(X,Y,Z) 1
  8862. #endif
  8863. #endif /* _BTREE_H_ */
  8864. /************** End of btree.h ***********************************************/
  8865. /************** Continuing where we left off in sqliteInt.h ******************/
  8866. /************** Include vdbe.h in the middle of sqliteInt.h ******************/
  8867. /************** Begin file vdbe.h ********************************************/
  8868. /*
  8869. ** 2001 September 15
  8870. **
  8871. ** The author disclaims copyright to this source code. In place of
  8872. ** a legal notice, here is a blessing:
  8873. **
  8874. ** May you do good and not evil.
  8875. ** May you find forgiveness for yourself and forgive others.
  8876. ** May you share freely, never taking more than you give.
  8877. **
  8878. *************************************************************************
  8879. ** Header file for the Virtual DataBase Engine (VDBE)
  8880. **
  8881. ** This header defines the interface to the virtual database engine
  8882. ** or VDBE. The VDBE implements an abstract machine that runs a
  8883. ** simple program to access and modify the underlying database.
  8884. */
  8885. #ifndef _SQLITE_VDBE_H_
  8886. #define _SQLITE_VDBE_H_
  8887. /* #include <stdio.h> */
  8888. /*
  8889. ** A single VDBE is an opaque structure named "Vdbe". Only routines
  8890. ** in the source file sqliteVdbe.c are allowed to see the insides
  8891. ** of this structure.
  8892. */
  8893. typedef struct Vdbe Vdbe;
  8894. /*
  8895. ** The names of the following types declared in vdbeInt.h are required
  8896. ** for the VdbeOp definition.
  8897. */
  8898. typedef struct Mem Mem;
  8899. typedef struct SubProgram SubProgram;
  8900. /*
  8901. ** A single instruction of the virtual machine has an opcode
  8902. ** and as many as three operands. The instruction is recorded
  8903. ** as an instance of the following structure:
  8904. */
  8905. struct VdbeOp {
  8906. u8 opcode; /* What operation to perform */
  8907. signed char p4type; /* One of the P4_xxx constants for p4 */
  8908. u8 opflags; /* Mask of the OPFLG_* flags in opcodes.h */
  8909. u8 p5; /* Fifth parameter is an unsigned character */
  8910. int p1; /* First operand */
  8911. int p2; /* Second parameter (often the jump destination) */
  8912. int p3; /* The third parameter */
  8913. union { /* fourth parameter */
  8914. int i; /* Integer value if p4type==P4_INT32 */
  8915. void *p; /* Generic pointer */
  8916. char *z; /* Pointer to data for string (char array) types */
  8917. i64 *pI64; /* Used when p4type is P4_INT64 */
  8918. double *pReal; /* Used when p4type is P4_REAL */
  8919. FuncDef *pFunc; /* Used when p4type is P4_FUNCDEF */
  8920. CollSeq *pColl; /* Used when p4type is P4_COLLSEQ */
  8921. Mem *pMem; /* Used when p4type is P4_MEM */
  8922. VTable *pVtab; /* Used when p4type is P4_VTAB */
  8923. KeyInfo *pKeyInfo; /* Used when p4type is P4_KEYINFO */
  8924. int *ai; /* Used when p4type is P4_INTARRAY */
  8925. SubProgram *pProgram; /* Used when p4type is P4_SUBPROGRAM */
  8926. int (*xAdvance)(BtCursor *, int *);
  8927. } p4;
  8928. #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  8929. char *zComment; /* Comment to improve readability */
  8930. #endif
  8931. #ifdef VDBE_PROFILE
  8932. u32 cnt; /* Number of times this instruction was executed */
  8933. u64 cycles; /* Total time spent executing this instruction */
  8934. #endif
  8935. #ifdef SQLITE_VDBE_COVERAGE
  8936. int iSrcLine; /* Source-code line that generated this opcode */
  8937. #endif
  8938. };
  8939. typedef struct VdbeOp VdbeOp;
  8940. /*
  8941. ** A sub-routine used to implement a trigger program.
  8942. */
  8943. struct SubProgram {
  8944. VdbeOp *aOp; /* Array of opcodes for sub-program */
  8945. int nOp; /* Elements in aOp[] */
  8946. int nMem; /* Number of memory cells required */
  8947. int nCsr; /* Number of cursors required */
  8948. int nOnce; /* Number of OP_Once instructions */
  8949. void *token; /* id that may be used to recursive triggers */
  8950. SubProgram *pNext; /* Next sub-program already visited */
  8951. };
  8952. /*
  8953. ** A smaller version of VdbeOp used for the VdbeAddOpList() function because
  8954. ** it takes up less space.
  8955. */
  8956. struct VdbeOpList {
  8957. u8 opcode; /* What operation to perform */
  8958. signed char p1; /* First operand */
  8959. signed char p2; /* Second parameter (often the jump destination) */
  8960. signed char p3; /* Third parameter */
  8961. };
  8962. typedef struct VdbeOpList VdbeOpList;
  8963. /*
  8964. ** Allowed values of VdbeOp.p4type
  8965. */
  8966. #define P4_NOTUSED 0 /* The P4 parameter is not used */
  8967. #define P4_DYNAMIC (-1) /* Pointer to a string obtained from sqliteMalloc() */
  8968. #define P4_STATIC (-2) /* Pointer to a static string */
  8969. #define P4_COLLSEQ (-4) /* P4 is a pointer to a CollSeq structure */
  8970. #define P4_FUNCDEF (-5) /* P4 is a pointer to a FuncDef structure */
  8971. #define P4_KEYINFO (-6) /* P4 is a pointer to a KeyInfo structure */
  8972. #define P4_MEM (-8) /* P4 is a pointer to a Mem* structure */
  8973. #define P4_TRANSIENT 0 /* P4 is a pointer to a transient string */
  8974. #define P4_VTAB (-10) /* P4 is a pointer to an sqlite3_vtab structure */
  8975. #define P4_MPRINTF (-11) /* P4 is a string obtained from sqlite3_mprintf() */
  8976. #define P4_REAL (-12) /* P4 is a 64-bit floating point value */
  8977. #define P4_INT64 (-13) /* P4 is a 64-bit signed integer */
  8978. #define P4_INT32 (-14) /* P4 is a 32-bit signed integer */
  8979. #define P4_INTARRAY (-15) /* P4 is a vector of 32-bit integers */
  8980. #define P4_SUBPROGRAM (-18) /* P4 is a pointer to a SubProgram structure */
  8981. #define P4_ADVANCE (-19) /* P4 is a pointer to BtreeNext() or BtreePrev() */
  8982. /* Error message codes for OP_Halt */
  8983. #define P5_ConstraintNotNull 1
  8984. #define P5_ConstraintUnique 2
  8985. #define P5_ConstraintCheck 3
  8986. #define P5_ConstraintFK 4
  8987. /*
  8988. ** The Vdbe.aColName array contains 5n Mem structures, where n is the
  8989. ** number of columns of data returned by the statement.
  8990. */
  8991. #define COLNAME_NAME 0
  8992. #define COLNAME_DECLTYPE 1
  8993. #define COLNAME_DATABASE 2
  8994. #define COLNAME_TABLE 3
  8995. #define COLNAME_COLUMN 4
  8996. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  8997. # define COLNAME_N 5 /* Number of COLNAME_xxx symbols */
  8998. #else
  8999. # ifdef SQLITE_OMIT_DECLTYPE
  9000. # define COLNAME_N 1 /* Store only the name */
  9001. # else
  9002. # define COLNAME_N 2 /* Store the name and decltype */
  9003. # endif
  9004. #endif
  9005. /*
  9006. ** The following macro converts a relative address in the p2 field
  9007. ** of a VdbeOp structure into a negative number so that
  9008. ** sqlite3VdbeAddOpList() knows that the address is relative. Calling
  9009. ** the macro again restores the address.
  9010. */
  9011. #define ADDR(X) (-1-(X))
  9012. /*
  9013. ** The makefile scans the vdbe.c source file and creates the "opcodes.h"
  9014. ** header file that defines a number for each opcode used by the VDBE.
  9015. */
  9016. /************** Include opcodes.h in the middle of vdbe.h ********************/
  9017. /************** Begin file opcodes.h *****************************************/
  9018. /* Automatically generated. Do not edit */
  9019. /* See the mkopcodeh.awk script for details */
  9020. #define OP_Function 1 /* synopsis: r[P3]=func(r[P2@P5]) */
  9021. #define OP_Savepoint 2
  9022. #define OP_AutoCommit 3
  9023. #define OP_Transaction 4
  9024. #define OP_SorterNext 5
  9025. #define OP_PrevIfOpen 6
  9026. #define OP_NextIfOpen 7
  9027. #define OP_Prev 8
  9028. #define OP_Next 9
  9029. #define OP_AggStep 10 /* synopsis: accum=r[P3] step(r[P2@P5]) */
  9030. #define OP_Checkpoint 11
  9031. #define OP_JournalMode 12
  9032. #define OP_Vacuum 13
  9033. #define OP_VFilter 14 /* synopsis: iplan=r[P3] zplan='P4' */
  9034. #define OP_VUpdate 15 /* synopsis: data=r[P3@P2] */
  9035. #define OP_Goto 16
  9036. #define OP_Gosub 17
  9037. #define OP_Return 18
  9038. #define OP_Not 19 /* same as TK_NOT, synopsis: r[P2]= !r[P1] */
  9039. #define OP_InitCoroutine 20
  9040. #define OP_EndCoroutine 21
  9041. #define OP_Yield 22
  9042. #define OP_HaltIfNull 23 /* synopsis: if r[P3]=null halt */
  9043. #define OP_Halt 24
  9044. #define OP_Integer 25 /* synopsis: r[P2]=P1 */
  9045. #define OP_Int64 26 /* synopsis: r[P2]=P4 */
  9046. #define OP_String 27 /* synopsis: r[P2]='P4' (len=P1) */
  9047. #define OP_Null 28 /* synopsis: r[P2..P3]=NULL */
  9048. #define OP_SoftNull 29 /* synopsis: r[P1]=NULL */
  9049. #define OP_Blob 30 /* synopsis: r[P2]=P4 (len=P1) */
  9050. #define OP_Variable 31 /* synopsis: r[P2]=parameter(P1,P4) */
  9051. #define OP_Move 32 /* synopsis: r[P2@P3]=r[P1@P3] */
  9052. #define OP_Copy 33 /* synopsis: r[P2@P3+1]=r[P1@P3+1] */
  9053. #define OP_SCopy 34 /* synopsis: r[P2]=r[P1] */
  9054. #define OP_ResultRow 35 /* synopsis: output=r[P1@P2] */
  9055. #define OP_CollSeq 36
  9056. #define OP_AddImm 37 /* synopsis: r[P1]=r[P1]+P2 */
  9057. #define OP_MustBeInt 38
  9058. #define OP_RealAffinity 39
  9059. #define OP_Cast 40 /* synopsis: affinity(r[P1]) */
  9060. #define OP_Permutation 41
  9061. #define OP_Compare 42 /* synopsis: r[P1@P3] <-> r[P2@P3] */
  9062. #define OP_Jump 43
  9063. #define OP_Once 44
  9064. #define OP_If 45
  9065. #define OP_IfNot 46
  9066. #define OP_Column 47 /* synopsis: r[P3]=PX */
  9067. #define OP_Affinity 48 /* synopsis: affinity(r[P1@P2]) */
  9068. #define OP_MakeRecord 49 /* synopsis: r[P3]=mkrec(r[P1@P2]) */
  9069. #define OP_Count 50 /* synopsis: r[P2]=count() */
  9070. #define OP_ReadCookie 51
  9071. #define OP_SetCookie 52
  9072. #define OP_ReopenIdx 53 /* synopsis: root=P2 iDb=P3 */
  9073. #define OP_OpenRead 54 /* synopsis: root=P2 iDb=P3 */
  9074. #define OP_OpenWrite 55 /* synopsis: root=P2 iDb=P3 */
  9075. #define OP_OpenAutoindex 56 /* synopsis: nColumn=P2 */
  9076. #define OP_OpenEphemeral 57 /* synopsis: nColumn=P2 */
  9077. #define OP_SorterOpen 58
  9078. #define OP_SequenceTest 59 /* synopsis: if( cursor[P1].ctr++ ) pc = P2 */
  9079. #define OP_OpenPseudo 60 /* synopsis: P3 columns in r[P2] */
  9080. #define OP_Close 61
  9081. #define OP_SeekLT 62 /* synopsis: key=r[P3@P4] */
  9082. #define OP_SeekLE 63 /* synopsis: key=r[P3@P4] */
  9083. #define OP_SeekGE 64 /* synopsis: key=r[P3@P4] */
  9084. #define OP_SeekGT 65 /* synopsis: key=r[P3@P4] */
  9085. #define OP_Seek 66 /* synopsis: intkey=r[P2] */
  9086. #define OP_NoConflict 67 /* synopsis: key=r[P3@P4] */
  9087. #define OP_NotFound 68 /* synopsis: key=r[P3@P4] */
  9088. #define OP_Found 69 /* synopsis: key=r[P3@P4] */
  9089. #define OP_NotExists 70 /* synopsis: intkey=r[P3] */
  9090. #define OP_Or 71 /* same as TK_OR, synopsis: r[P3]=(r[P1] || r[P2]) */
  9091. #define OP_And 72 /* same as TK_AND, synopsis: r[P3]=(r[P1] && r[P2]) */
  9092. #define OP_Sequence 73 /* synopsis: r[P2]=cursor[P1].ctr++ */
  9093. #define OP_NewRowid 74 /* synopsis: r[P2]=rowid */
  9094. #define OP_Insert 75 /* synopsis: intkey=r[P3] data=r[P2] */
  9095. #define OP_IsNull 76 /* same as TK_ISNULL, synopsis: if r[P1]==NULL goto P2 */
  9096. #define OP_NotNull 77 /* same as TK_NOTNULL, synopsis: if r[P1]!=NULL goto P2 */
  9097. #define OP_Ne 78 /* same as TK_NE, synopsis: if r[P1]!=r[P3] goto P2 */
  9098. #define OP_Eq 79 /* same as TK_EQ, synopsis: if r[P1]==r[P3] goto P2 */
  9099. #define OP_Gt 80 /* same as TK_GT, synopsis: if r[P1]>r[P3] goto P2 */
  9100. #define OP_Le 81 /* same as TK_LE, synopsis: if r[P1]<=r[P3] goto P2 */
  9101. #define OP_Lt 82 /* same as TK_LT, synopsis: if r[P1]<r[P3] goto P2 */
  9102. #define OP_Ge 83 /* same as TK_GE, synopsis: if r[P1]>=r[P3] goto P2 */
  9103. #define OP_InsertInt 84 /* synopsis: intkey=P3 data=r[P2] */
  9104. #define OP_BitAnd 85 /* same as TK_BITAND, synopsis: r[P3]=r[P1]&r[P2] */
  9105. #define OP_BitOr 86 /* same as TK_BITOR, synopsis: r[P3]=r[P1]|r[P2] */
  9106. #define OP_ShiftLeft 87 /* same as TK_LSHIFT, synopsis: r[P3]=r[P2]<<r[P1] */
  9107. #define OP_ShiftRight 88 /* same as TK_RSHIFT, synopsis: r[P3]=r[P2]>>r[P1] */
  9108. #define OP_Add 89 /* same as TK_PLUS, synopsis: r[P3]=r[P1]+r[P2] */
  9109. #define OP_Subtract 90 /* same as TK_MINUS, synopsis: r[P3]=r[P2]-r[P1] */
  9110. #define OP_Multiply 91 /* same as TK_STAR, synopsis: r[P3]=r[P1]*r[P2] */
  9111. #define OP_Divide 92 /* same as TK_SLASH, synopsis: r[P3]=r[P2]/r[P1] */
  9112. #define OP_Remainder 93 /* same as TK_REM, synopsis: r[P3]=r[P2]%r[P1] */
  9113. #define OP_Concat 94 /* same as TK_CONCAT, synopsis: r[P3]=r[P2]+r[P1] */
  9114. #define OP_Delete 95
  9115. #define OP_BitNot 96 /* same as TK_BITNOT, synopsis: r[P1]= ~r[P1] */
  9116. #define OP_String8 97 /* same as TK_STRING, synopsis: r[P2]='P4' */
  9117. #define OP_ResetCount 98
  9118. #define OP_SorterCompare 99 /* synopsis: if key(P1)!=trim(r[P3],P4) goto P2 */
  9119. #define OP_SorterData 100 /* synopsis: r[P2]=data */
  9120. #define OP_RowKey 101 /* synopsis: r[P2]=key */
  9121. #define OP_RowData 102 /* synopsis: r[P2]=data */
  9122. #define OP_Rowid 103 /* synopsis: r[P2]=rowid */
  9123. #define OP_NullRow 104
  9124. #define OP_Last 105
  9125. #define OP_SorterSort 106
  9126. #define OP_Sort 107
  9127. #define OP_Rewind 108
  9128. #define OP_SorterInsert 109
  9129. #define OP_IdxInsert 110 /* synopsis: key=r[P2] */
  9130. #define OP_IdxDelete 111 /* synopsis: key=r[P2@P3] */
  9131. #define OP_IdxRowid 112 /* synopsis: r[P2]=rowid */
  9132. #define OP_IdxLE 113 /* synopsis: key=r[P3@P4] */
  9133. #define OP_IdxGT 114 /* synopsis: key=r[P3@P4] */
  9134. #define OP_IdxLT 115 /* synopsis: key=r[P3@P4] */
  9135. #define OP_IdxGE 116 /* synopsis: key=r[P3@P4] */
  9136. #define OP_Destroy 117
  9137. #define OP_Clear 118
  9138. #define OP_ResetSorter 119
  9139. #define OP_CreateIndex 120 /* synopsis: r[P2]=root iDb=P1 */
  9140. #define OP_CreateTable 121 /* synopsis: r[P2]=root iDb=P1 */
  9141. #define OP_ParseSchema 122
  9142. #define OP_LoadAnalysis 123
  9143. #define OP_DropTable 124
  9144. #define OP_DropIndex 125
  9145. #define OP_DropTrigger 126
  9146. #define OP_IntegrityCk 127
  9147. #define OP_RowSetAdd 128 /* synopsis: rowset(P1)=r[P2] */
  9148. #define OP_RowSetRead 129 /* synopsis: r[P3]=rowset(P1) */
  9149. #define OP_RowSetTest 130 /* synopsis: if r[P3] in rowset(P1) goto P2 */
  9150. #define OP_Program 131
  9151. #define OP_Param 132
  9152. #define OP_Real 133 /* same as TK_FLOAT, synopsis: r[P2]=P4 */
  9153. #define OP_FkCounter 134 /* synopsis: fkctr[P1]+=P2 */
  9154. #define OP_FkIfZero 135 /* synopsis: if fkctr[P1]==0 goto P2 */
  9155. #define OP_MemMax 136 /* synopsis: r[P1]=max(r[P1],r[P2]) */
  9156. #define OP_IfPos 137 /* synopsis: if r[P1]>0 goto P2 */
  9157. #define OP_IfNeg 138 /* synopsis: r[P1]+=P3, if r[P1]<0 goto P2 */
  9158. #define OP_IfZero 139 /* synopsis: r[P1]+=P3, if r[P1]==0 goto P2 */
  9159. #define OP_AggFinal 140 /* synopsis: accum=r[P1] N=P2 */
  9160. #define OP_IncrVacuum 141
  9161. #define OP_Expire 142
  9162. #define OP_TableLock 143 /* synopsis: iDb=P1 root=P2 write=P3 */
  9163. #define OP_VBegin 144
  9164. #define OP_VCreate 145
  9165. #define OP_VDestroy 146
  9166. #define OP_VOpen 147
  9167. #define OP_VColumn 148 /* synopsis: r[P3]=vcolumn(P2) */
  9168. #define OP_VNext 149
  9169. #define OP_VRename 150
  9170. #define OP_Pagecount 151
  9171. #define OP_MaxPgcnt 152
  9172. #define OP_Init 153 /* synopsis: Start at P2 */
  9173. #define OP_Noop 154
  9174. #define OP_Explain 155
  9175. /* Properties such as "out2" or "jump" that are specified in
  9176. ** comments following the "case" for each opcode in the vdbe.c
  9177. ** are encoded into bitvectors as follows:
  9178. */
  9179. #define OPFLG_JUMP 0x0001 /* jump: P2 holds jmp target */
  9180. #define OPFLG_OUT2_PRERELEASE 0x0002 /* out2-prerelease: */
  9181. #define OPFLG_IN1 0x0004 /* in1: P1 is an input */
  9182. #define OPFLG_IN2 0x0008 /* in2: P2 is an input */
  9183. #define OPFLG_IN3 0x0010 /* in3: P3 is an input */
  9184. #define OPFLG_OUT2 0x0020 /* out2: P2 is an output */
  9185. #define OPFLG_OUT3 0x0040 /* out3: P3 is an output */
  9186. #define OPFLG_INITIALIZER {\
  9187. /* 0 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x01,\
  9188. /* 8 */ 0x01, 0x01, 0x00, 0x00, 0x02, 0x00, 0x01, 0x00,\
  9189. /* 16 */ 0x01, 0x01, 0x04, 0x24, 0x01, 0x04, 0x05, 0x10,\
  9190. /* 24 */ 0x00, 0x02, 0x02, 0x02, 0x02, 0x00, 0x02, 0x02,\
  9191. /* 32 */ 0x00, 0x00, 0x20, 0x00, 0x00, 0x04, 0x05, 0x04,\
  9192. /* 40 */ 0x04, 0x00, 0x00, 0x01, 0x01, 0x05, 0x05, 0x00,\
  9193. /* 48 */ 0x00, 0x00, 0x02, 0x02, 0x10, 0x00, 0x00, 0x00,\
  9194. /* 56 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x11, 0x11,\
  9195. /* 64 */ 0x11, 0x11, 0x08, 0x11, 0x11, 0x11, 0x11, 0x4c,\
  9196. /* 72 */ 0x4c, 0x02, 0x02, 0x00, 0x05, 0x05, 0x15, 0x15,\
  9197. /* 80 */ 0x15, 0x15, 0x15, 0x15, 0x00, 0x4c, 0x4c, 0x4c,\
  9198. /* 88 */ 0x4c, 0x4c, 0x4c, 0x4c, 0x4c, 0x4c, 0x4c, 0x00,\
  9199. /* 96 */ 0x24, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02,\
  9200. /* 104 */ 0x00, 0x01, 0x01, 0x01, 0x01, 0x08, 0x08, 0x00,\
  9201. /* 112 */ 0x02, 0x01, 0x01, 0x01, 0x01, 0x02, 0x00, 0x00,\
  9202. /* 120 */ 0x02, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
  9203. /* 128 */ 0x0c, 0x45, 0x15, 0x01, 0x02, 0x02, 0x00, 0x01,\
  9204. /* 136 */ 0x08, 0x05, 0x05, 0x05, 0x00, 0x01, 0x00, 0x00,\
  9205. /* 144 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x02,\
  9206. /* 152 */ 0x02, 0x01, 0x00, 0x00,}
  9207. /************** End of opcodes.h *********************************************/
  9208. /************** Continuing where we left off in vdbe.h ***********************/
  9209. /*
  9210. ** Prototypes for the VDBE interface. See comments on the implementation
  9211. ** for a description of what each of these routines does.
  9212. */
  9213. SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(Parse*);
  9214. SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe*,int);
  9215. SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe*,int,int);
  9216. SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe*,int,int,int);
  9217. SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe*,int,int,int,int);
  9218. SQLITE_PRIVATE int sqlite3VdbeAddOp4(Vdbe*,int,int,int,int,const char *zP4,int);
  9219. SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(Vdbe*,int,int,int,int,int);
  9220. SQLITE_PRIVATE int sqlite3VdbeAddOpList(Vdbe*, int nOp, VdbeOpList const *aOp, int iLineno);
  9221. SQLITE_PRIVATE void sqlite3VdbeAddParseSchemaOp(Vdbe*,int,char*);
  9222. SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe*, u32 addr, int P1);
  9223. SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe*, u32 addr, int P2);
  9224. SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe*, u32 addr, int P3);
  9225. SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe*, u8 P5);
  9226. SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe*, int addr);
  9227. SQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe*, int addr);
  9228. SQLITE_PRIVATE int sqlite3VdbeDeletePriorOpcode(Vdbe*, u8 op);
  9229. SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe*, int addr, const char *zP4, int N);
  9230. SQLITE_PRIVATE void sqlite3VdbeSetP4KeyInfo(Parse*, Index*);
  9231. SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe*, int);
  9232. SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe*, int);
  9233. SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe*);
  9234. SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe*);
  9235. SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe*);
  9236. SQLITE_PRIVATE void sqlite3VdbeClearObject(sqlite3*,Vdbe*);
  9237. SQLITE_PRIVATE void sqlite3VdbeMakeReady(Vdbe*,Parse*);
  9238. SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe*);
  9239. SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe*, int);
  9240. SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe*);
  9241. #ifdef SQLITE_DEBUG
  9242. SQLITE_PRIVATE int sqlite3VdbeAssertMayAbort(Vdbe *, int);
  9243. #endif
  9244. SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe*);
  9245. SQLITE_PRIVATE void sqlite3VdbeRewind(Vdbe*);
  9246. SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe*);
  9247. SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe*,int);
  9248. SQLITE_PRIVATE int sqlite3VdbeSetColName(Vdbe*, int, int, const char *, void(*)(void*));
  9249. SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe*);
  9250. SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe*);
  9251. SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe*, const char *z, int n, int);
  9252. SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe*,Vdbe*);
  9253. SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe*, int*, int*);
  9254. SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetBoundValue(Vdbe*, int, u8);
  9255. SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe*, int);
  9256. #ifndef SQLITE_OMIT_TRACE
  9257. SQLITE_PRIVATE char *sqlite3VdbeExpandSql(Vdbe*, const char*);
  9258. #endif
  9259. SQLITE_PRIVATE int sqlite3MemCompare(const Mem*, const Mem*, const CollSeq*);
  9260. SQLITE_PRIVATE void sqlite3VdbeRecordUnpack(KeyInfo*,int,const void*,UnpackedRecord*);
  9261. SQLITE_PRIVATE int sqlite3VdbeRecordCompare(int,const void*,UnpackedRecord*);
  9262. SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(KeyInfo *, char *, int, char **);
  9263. typedef int (*RecordCompare)(int,const void*,UnpackedRecord*);
  9264. SQLITE_PRIVATE RecordCompare sqlite3VdbeFindCompare(UnpackedRecord*);
  9265. #ifndef SQLITE_OMIT_TRIGGER
  9266. SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *, SubProgram *);
  9267. #endif
  9268. /* Use SQLITE_ENABLE_COMMENTS to enable generation of extra comments on
  9269. ** each VDBE opcode.
  9270. **
  9271. ** Use the SQLITE_ENABLE_MODULE_COMMENTS macro to see some extra no-op
  9272. ** comments in VDBE programs that show key decision points in the code
  9273. ** generator.
  9274. */
  9275. #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  9276. SQLITE_PRIVATE void sqlite3VdbeComment(Vdbe*, const char*, ...);
  9277. # define VdbeComment(X) sqlite3VdbeComment X
  9278. SQLITE_PRIVATE void sqlite3VdbeNoopComment(Vdbe*, const char*, ...);
  9279. # define VdbeNoopComment(X) sqlite3VdbeNoopComment X
  9280. # ifdef SQLITE_ENABLE_MODULE_COMMENTS
  9281. # define VdbeModuleComment(X) sqlite3VdbeNoopComment X
  9282. # else
  9283. # define VdbeModuleComment(X)
  9284. # endif
  9285. #else
  9286. # define VdbeComment(X)
  9287. # define VdbeNoopComment(X)
  9288. # define VdbeModuleComment(X)
  9289. #endif
  9290. /*
  9291. ** The VdbeCoverage macros are used to set a coverage testing point
  9292. ** for VDBE branch instructions. The coverage testing points are line
  9293. ** numbers in the sqlite3.c source file. VDBE branch coverage testing
  9294. ** only works with an amalagmation build. That's ok since a VDBE branch
  9295. ** coverage build designed for testing the test suite only. No application
  9296. ** should ever ship with VDBE branch coverage measuring turned on.
  9297. **
  9298. ** VdbeCoverage(v) // Mark the previously coded instruction
  9299. ** // as a branch
  9300. **
  9301. ** VdbeCoverageIf(v, conditional) // Mark previous if conditional true
  9302. **
  9303. ** VdbeCoverageAlwaysTaken(v) // Previous branch is always taken
  9304. **
  9305. ** VdbeCoverageNeverTaken(v) // Previous branch is never taken
  9306. **
  9307. ** Every VDBE branch operation must be tagged with one of the macros above.
  9308. ** If not, then when "make test" is run with -DSQLITE_VDBE_COVERAGE and
  9309. ** -DSQLITE_DEBUG then an ALWAYS() will fail in the vdbeTakeBranch()
  9310. ** routine in vdbe.c, alerting the developer to the missed tag.
  9311. */
  9312. #ifdef SQLITE_VDBE_COVERAGE
  9313. SQLITE_PRIVATE void sqlite3VdbeSetLineNumber(Vdbe*,int);
  9314. # define VdbeCoverage(v) sqlite3VdbeSetLineNumber(v,__LINE__)
  9315. # define VdbeCoverageIf(v,x) if(x)sqlite3VdbeSetLineNumber(v,__LINE__)
  9316. # define VdbeCoverageAlwaysTaken(v) sqlite3VdbeSetLineNumber(v,2);
  9317. # define VdbeCoverageNeverTaken(v) sqlite3VdbeSetLineNumber(v,1);
  9318. # define VDBE_OFFSET_LINENO(x) (__LINE__+x)
  9319. #else
  9320. # define VdbeCoverage(v)
  9321. # define VdbeCoverageIf(v,x)
  9322. # define VdbeCoverageAlwaysTaken(v)
  9323. # define VdbeCoverageNeverTaken(v)
  9324. # define VDBE_OFFSET_LINENO(x) 0
  9325. #endif
  9326. #endif
  9327. /************** End of vdbe.h ************************************************/
  9328. /************** Continuing where we left off in sqliteInt.h ******************/
  9329. /************** Include pager.h in the middle of sqliteInt.h *****************/
  9330. /************** Begin file pager.h *******************************************/
  9331. /*
  9332. ** 2001 September 15
  9333. **
  9334. ** The author disclaims copyright to this source code. In place of
  9335. ** a legal notice, here is a blessing:
  9336. **
  9337. ** May you do good and not evil.
  9338. ** May you find forgiveness for yourself and forgive others.
  9339. ** May you share freely, never taking more than you give.
  9340. **
  9341. *************************************************************************
  9342. ** This header file defines the interface that the sqlite page cache
  9343. ** subsystem. The page cache subsystem reads and writes a file a page
  9344. ** at a time and provides a journal for rollback.
  9345. */
  9346. #ifndef _PAGER_H_
  9347. #define _PAGER_H_
  9348. /*
  9349. ** Default maximum size for persistent journal files. A negative
  9350. ** value means no limit. This value may be overridden using the
  9351. ** sqlite3PagerJournalSizeLimit() API. See also "PRAGMA journal_size_limit".
  9352. */
  9353. #ifndef SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT
  9354. #define SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT -1
  9355. #endif
  9356. /*
  9357. ** The type used to represent a page number. The first page in a file
  9358. ** is called page 1. 0 is used to represent "not a page".
  9359. */
  9360. typedef u32 Pgno;
  9361. /*
  9362. ** Each open file is managed by a separate instance of the "Pager" structure.
  9363. */
  9364. typedef struct Pager Pager;
  9365. /*
  9366. ** Handle type for pages.
  9367. */
  9368. typedef struct PgHdr DbPage;
  9369. /*
  9370. ** Page number PAGER_MJ_PGNO is never used in an SQLite database (it is
  9371. ** reserved for working around a windows/posix incompatibility). It is
  9372. ** used in the journal to signify that the remainder of the journal file
  9373. ** is devoted to storing a master journal name - there are no more pages to
  9374. ** roll back. See comments for function writeMasterJournal() in pager.c
  9375. ** for details.
  9376. */
  9377. #define PAGER_MJ_PGNO(x) ((Pgno)((PENDING_BYTE/((x)->pageSize))+1))
  9378. /*
  9379. ** Allowed values for the flags parameter to sqlite3PagerOpen().
  9380. **
  9381. ** NOTE: These values must match the corresponding BTREE_ values in btree.h.
  9382. */
  9383. #define PAGER_OMIT_JOURNAL 0x0001 /* Do not use a rollback journal */
  9384. #define PAGER_MEMORY 0x0002 /* In-memory database */
  9385. /*
  9386. ** Valid values for the second argument to sqlite3PagerLockingMode().
  9387. */
  9388. #define PAGER_LOCKINGMODE_QUERY -1
  9389. #define PAGER_LOCKINGMODE_NORMAL 0
  9390. #define PAGER_LOCKINGMODE_EXCLUSIVE 1
  9391. /*
  9392. ** Numeric constants that encode the journalmode.
  9393. */
  9394. #define PAGER_JOURNALMODE_QUERY (-1) /* Query the value of journalmode */
  9395. #define PAGER_JOURNALMODE_DELETE 0 /* Commit by deleting journal file */
  9396. #define PAGER_JOURNALMODE_PERSIST 1 /* Commit by zeroing journal header */
  9397. #define PAGER_JOURNALMODE_OFF 2 /* Journal omitted. */
  9398. #define PAGER_JOURNALMODE_TRUNCATE 3 /* Commit by truncating journal */
  9399. #define PAGER_JOURNALMODE_MEMORY 4 /* In-memory journal file */
  9400. #define PAGER_JOURNALMODE_WAL 5 /* Use write-ahead logging */
  9401. /*
  9402. ** Flags that make up the mask passed to sqlite3PagerAcquire().
  9403. */
  9404. #define PAGER_GET_NOCONTENT 0x01 /* Do not load data from disk */
  9405. #define PAGER_GET_READONLY 0x02 /* Read-only page is acceptable */
  9406. /*
  9407. ** Flags for sqlite3PagerSetFlags()
  9408. */
  9409. #define PAGER_SYNCHRONOUS_OFF 0x01 /* PRAGMA synchronous=OFF */
  9410. #define PAGER_SYNCHRONOUS_NORMAL 0x02 /* PRAGMA synchronous=NORMAL */
  9411. #define PAGER_SYNCHRONOUS_FULL 0x03 /* PRAGMA synchronous=FULL */
  9412. #define PAGER_SYNCHRONOUS_MASK 0x03 /* Mask for three values above */
  9413. #define PAGER_FULLFSYNC 0x04 /* PRAGMA fullfsync=ON */
  9414. #define PAGER_CKPT_FULLFSYNC 0x08 /* PRAGMA checkpoint_fullfsync=ON */
  9415. #define PAGER_CACHESPILL 0x10 /* PRAGMA cache_spill=ON */
  9416. #define PAGER_FLAGS_MASK 0x1c /* All above except SYNCHRONOUS */
  9417. /*
  9418. ** The remainder of this file contains the declarations of the functions
  9419. ** that make up the Pager sub-system API. See source code comments for
  9420. ** a detailed description of each routine.
  9421. */
  9422. /* Open and close a Pager connection. */
  9423. SQLITE_PRIVATE int sqlite3PagerOpen(
  9424. sqlite3_vfs*,
  9425. Pager **ppPager,
  9426. const char*,
  9427. int,
  9428. int,
  9429. int,
  9430. void(*)(DbPage*)
  9431. );
  9432. SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager);
  9433. SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager*, int, unsigned char*);
  9434. /* Functions used to configure a Pager object. */
  9435. SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(Pager*, int(*)(void *), void *);
  9436. SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager*, u32*, int);
  9437. SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager*, int);
  9438. SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager*, int);
  9439. SQLITE_PRIVATE void sqlite3PagerSetMmapLimit(Pager *, sqlite3_int64);
  9440. SQLITE_PRIVATE void sqlite3PagerShrink(Pager*);
  9441. SQLITE_PRIVATE void sqlite3PagerSetFlags(Pager*,unsigned);
  9442. SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *, int);
  9443. SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *, int);
  9444. SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager*);
  9445. SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager*);
  9446. SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *, i64);
  9447. SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager*);
  9448. /* Functions used to obtain and release page references. */
  9449. SQLITE_PRIVATE int sqlite3PagerAcquire(Pager *pPager, Pgno pgno, DbPage **ppPage, int clrFlag);
  9450. #define sqlite3PagerGet(A,B,C) sqlite3PagerAcquire(A,B,C,0)
  9451. SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno);
  9452. SQLITE_PRIVATE void sqlite3PagerRef(DbPage*);
  9453. SQLITE_PRIVATE void sqlite3PagerUnref(DbPage*);
  9454. SQLITE_PRIVATE void sqlite3PagerUnrefNotNull(DbPage*);
  9455. /* Operations on page references. */
  9456. SQLITE_PRIVATE int sqlite3PagerWrite(DbPage*);
  9457. SQLITE_PRIVATE void sqlite3PagerDontWrite(DbPage*);
  9458. SQLITE_PRIVATE int sqlite3PagerMovepage(Pager*,DbPage*,Pgno,int);
  9459. SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage*);
  9460. SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *);
  9461. SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *);
  9462. /* Functions used to manage pager transactions and savepoints. */
  9463. SQLITE_PRIVATE void sqlite3PagerPagecount(Pager*, int*);
  9464. SQLITE_PRIVATE int sqlite3PagerBegin(Pager*, int exFlag, int);
  9465. SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(Pager*,const char *zMaster, int);
  9466. SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager*);
  9467. SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager, const char *zMaster);
  9468. SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager*);
  9469. SQLITE_PRIVATE int sqlite3PagerRollback(Pager*);
  9470. SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int n);
  9471. SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint);
  9472. SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager);
  9473. #ifndef SQLITE_OMIT_WAL
  9474. SQLITE_PRIVATE int sqlite3PagerCheckpoint(Pager *pPager, int, int*, int*);
  9475. SQLITE_PRIVATE int sqlite3PagerWalSupported(Pager *pPager);
  9476. SQLITE_PRIVATE int sqlite3PagerWalCallback(Pager *pPager);
  9477. SQLITE_PRIVATE int sqlite3PagerOpenWal(Pager *pPager, int *pisOpen);
  9478. SQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager);
  9479. #endif
  9480. #ifdef SQLITE_ENABLE_ZIPVFS
  9481. SQLITE_PRIVATE int sqlite3PagerWalFramesize(Pager *pPager);
  9482. #endif
  9483. /* Functions used to query pager state and configuration. */
  9484. SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager*);
  9485. SQLITE_PRIVATE int sqlite3PagerRefcount(Pager*);
  9486. SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager*);
  9487. SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager*, int);
  9488. SQLITE_PRIVATE const sqlite3_vfs *sqlite3PagerVfs(Pager*);
  9489. SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager*);
  9490. SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager*);
  9491. SQLITE_PRIVATE int sqlite3PagerNosync(Pager*);
  9492. SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager*);
  9493. SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager*);
  9494. SQLITE_PRIVATE void sqlite3PagerCacheStat(Pager *, int, int, int *);
  9495. SQLITE_PRIVATE void sqlite3PagerClearCache(Pager *);
  9496. SQLITE_PRIVATE int sqlite3SectorSize(sqlite3_file *);
  9497. /* Functions used to truncate the database file. */
  9498. SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager*,Pgno);
  9499. SQLITE_PRIVATE void sqlite3PagerRekey(DbPage*, Pgno, u16);
  9500. #if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_WAL)
  9501. SQLITE_PRIVATE void *sqlite3PagerCodec(DbPage *);
  9502. #endif
  9503. /* Functions to support testing and debugging. */
  9504. #if !defined(NDEBUG) || defined(SQLITE_TEST)
  9505. SQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage*);
  9506. SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage*);
  9507. #endif
  9508. #ifdef SQLITE_TEST
  9509. SQLITE_PRIVATE int *sqlite3PagerStats(Pager*);
  9510. SQLITE_PRIVATE void sqlite3PagerRefdump(Pager*);
  9511. void disable_simulated_io_errors(void);
  9512. void enable_simulated_io_errors(void);
  9513. #else
  9514. # define disable_simulated_io_errors()
  9515. # define enable_simulated_io_errors()
  9516. #endif
  9517. #endif /* _PAGER_H_ */
  9518. /************** End of pager.h ***********************************************/
  9519. /************** Continuing where we left off in sqliteInt.h ******************/
  9520. /************** Include pcache.h in the middle of sqliteInt.h ****************/
  9521. /************** Begin file pcache.h ******************************************/
  9522. /*
  9523. ** 2008 August 05
  9524. **
  9525. ** The author disclaims copyright to this source code. In place of
  9526. ** a legal notice, here is a blessing:
  9527. **
  9528. ** May you do good and not evil.
  9529. ** May you find forgiveness for yourself and forgive others.
  9530. ** May you share freely, never taking more than you give.
  9531. **
  9532. *************************************************************************
  9533. ** This header file defines the interface that the sqlite page cache
  9534. ** subsystem.
  9535. */
  9536. #ifndef _PCACHE_H_
  9537. typedef struct PgHdr PgHdr;
  9538. typedef struct PCache PCache;
  9539. /*
  9540. ** Every page in the cache is controlled by an instance of the following
  9541. ** structure.
  9542. */
  9543. struct PgHdr {
  9544. sqlite3_pcache_page *pPage; /* Pcache object page handle */
  9545. void *pData; /* Page data */
  9546. void *pExtra; /* Extra content */
  9547. PgHdr *pDirty; /* Transient list of dirty pages */
  9548. Pager *pPager; /* The pager this page is part of */
  9549. Pgno pgno; /* Page number for this page */
  9550. #ifdef SQLITE_CHECK_PAGES
  9551. u32 pageHash; /* Hash of page content */
  9552. #endif
  9553. u16 flags; /* PGHDR flags defined below */
  9554. /**********************************************************************
  9555. ** Elements above are public. All that follows is private to pcache.c
  9556. ** and should not be accessed by other modules.
  9557. */
  9558. i16 nRef; /* Number of users of this page */
  9559. PCache *pCache; /* Cache that owns this page */
  9560. PgHdr *pDirtyNext; /* Next element in list of dirty pages */
  9561. PgHdr *pDirtyPrev; /* Previous element in list of dirty pages */
  9562. };
  9563. /* Bit values for PgHdr.flags */
  9564. #define PGHDR_DIRTY 0x002 /* Page has changed */
  9565. #define PGHDR_NEED_SYNC 0x004 /* Fsync the rollback journal before
  9566. ** writing this page to the database */
  9567. #define PGHDR_NEED_READ 0x008 /* Content is unread */
  9568. #define PGHDR_REUSE_UNLIKELY 0x010 /* A hint that reuse is unlikely */
  9569. #define PGHDR_DONT_WRITE 0x020 /* Do not write content to disk */
  9570. #define PGHDR_MMAP 0x040 /* This is an mmap page object */
  9571. /* Initialize and shutdown the page cache subsystem */
  9572. SQLITE_PRIVATE int sqlite3PcacheInitialize(void);
  9573. SQLITE_PRIVATE void sqlite3PcacheShutdown(void);
  9574. /* Page cache buffer management:
  9575. ** These routines implement SQLITE_CONFIG_PAGECACHE.
  9576. */
  9577. SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *, int sz, int n);
  9578. /* Create a new pager cache.
  9579. ** Under memory stress, invoke xStress to try to make pages clean.
  9580. ** Only clean and unpinned pages can be reclaimed.
  9581. */
  9582. SQLITE_PRIVATE int sqlite3PcacheOpen(
  9583. int szPage, /* Size of every page */
  9584. int szExtra, /* Extra space associated with each page */
  9585. int bPurgeable, /* True if pages are on backing store */
  9586. int (*xStress)(void*, PgHdr*), /* Call to try to make pages clean */
  9587. void *pStress, /* Argument to xStress */
  9588. PCache *pToInit /* Preallocated space for the PCache */
  9589. );
  9590. /* Modify the page-size after the cache has been created. */
  9591. SQLITE_PRIVATE int sqlite3PcacheSetPageSize(PCache *, int);
  9592. /* Return the size in bytes of a PCache object. Used to preallocate
  9593. ** storage space.
  9594. */
  9595. SQLITE_PRIVATE int sqlite3PcacheSize(void);
  9596. /* One release per successful fetch. Page is pinned until released.
  9597. ** Reference counted.
  9598. */
  9599. SQLITE_PRIVATE sqlite3_pcache_page *sqlite3PcacheFetch(PCache*, Pgno, int createFlag);
  9600. SQLITE_PRIVATE int sqlite3PcacheFetchStress(PCache*, Pgno, sqlite3_pcache_page**);
  9601. SQLITE_PRIVATE PgHdr *sqlite3PcacheFetchFinish(PCache*, Pgno, sqlite3_pcache_page *pPage);
  9602. SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr*);
  9603. SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr*); /* Remove page from cache */
  9604. SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr*); /* Make sure page is marked dirty */
  9605. SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr*); /* Mark a single page as clean */
  9606. SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache*); /* Mark all dirty list pages as clean */
  9607. /* Change a page number. Used by incr-vacuum. */
  9608. SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr*, Pgno);
  9609. /* Remove all pages with pgno>x. Reset the cache if x==0 */
  9610. SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache*, Pgno x);
  9611. /* Get a list of all dirty pages in the cache, sorted by page number */
  9612. SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache*);
  9613. /* Reset and close the cache object */
  9614. SQLITE_PRIVATE void sqlite3PcacheClose(PCache*);
  9615. /* Clear flags from pages of the page cache */
  9616. SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *);
  9617. /* Discard the contents of the cache */
  9618. SQLITE_PRIVATE void sqlite3PcacheClear(PCache*);
  9619. /* Return the total number of outstanding page references */
  9620. SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache*);
  9621. /* Increment the reference count of an existing page */
  9622. SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr*);
  9623. SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr*);
  9624. /* Return the total number of pages stored in the cache */
  9625. SQLITE_PRIVATE int sqlite3PcachePagecount(PCache*);
  9626. #if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
  9627. /* Iterate through all dirty pages currently stored in the cache. This
  9628. ** interface is only available if SQLITE_CHECK_PAGES is defined when the
  9629. ** library is built.
  9630. */
  9631. SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *));
  9632. #endif
  9633. /* Set and get the suggested cache-size for the specified pager-cache.
  9634. **
  9635. ** If no global maximum is configured, then the system attempts to limit
  9636. ** the total number of pages cached by purgeable pager-caches to the sum
  9637. ** of the suggested cache-sizes.
  9638. */
  9639. SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *, int);
  9640. #ifdef SQLITE_TEST
  9641. SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *);
  9642. #endif
  9643. /* Free up as much memory as possible from the page cache */
  9644. SQLITE_PRIVATE void sqlite3PcacheShrink(PCache*);
  9645. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  9646. /* Try to return memory used by the pcache module to the main memory heap */
  9647. SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int);
  9648. #endif
  9649. #ifdef SQLITE_TEST
  9650. SQLITE_PRIVATE void sqlite3PcacheStats(int*,int*,int*,int*);
  9651. #endif
  9652. SQLITE_PRIVATE void sqlite3PCacheSetDefault(void);
  9653. #endif /* _PCACHE_H_ */
  9654. /************** End of pcache.h **********************************************/
  9655. /************** Continuing where we left off in sqliteInt.h ******************/
  9656. /************** Include os.h in the middle of sqliteInt.h ********************/
  9657. /************** Begin file os.h **********************************************/
  9658. /*
  9659. ** 2001 September 16
  9660. **
  9661. ** The author disclaims copyright to this source code. In place of
  9662. ** a legal notice, here is a blessing:
  9663. **
  9664. ** May you do good and not evil.
  9665. ** May you find forgiveness for yourself and forgive others.
  9666. ** May you share freely, never taking more than you give.
  9667. **
  9668. ******************************************************************************
  9669. **
  9670. ** This header file (together with is companion C source-code file
  9671. ** "os.c") attempt to abstract the underlying operating system so that
  9672. ** the SQLite library will work on both POSIX and windows systems.
  9673. **
  9674. ** This header file is #include-ed by sqliteInt.h and thus ends up
  9675. ** being included by every source file.
  9676. */
  9677. #ifndef _SQLITE_OS_H_
  9678. #define _SQLITE_OS_H_
  9679. /*
  9680. ** Attempt to automatically detect the operating system and setup the
  9681. ** necessary pre-processor macros for it.
  9682. */
  9683. /************** Include os_setup.h in the middle of os.h *********************/
  9684. /************** Begin file os_setup.h ****************************************/
  9685. /*
  9686. ** 2013 November 25
  9687. **
  9688. ** The author disclaims copyright to this source code. In place of
  9689. ** a legal notice, here is a blessing:
  9690. **
  9691. ** May you do good and not evil.
  9692. ** May you find forgiveness for yourself and forgive others.
  9693. ** May you share freely, never taking more than you give.
  9694. **
  9695. ******************************************************************************
  9696. **
  9697. ** This file contains pre-processor directives related to operating system
  9698. ** detection and/or setup.
  9699. */
  9700. #ifndef _OS_SETUP_H_
  9701. #define _OS_SETUP_H_
  9702. /*
  9703. ** Figure out if we are dealing with Unix, Windows, or some other operating
  9704. ** system.
  9705. **
  9706. ** After the following block of preprocess macros, all of SQLITE_OS_UNIX,
  9707. ** SQLITE_OS_WIN, and SQLITE_OS_OTHER will defined to either 1 or 0. One of
  9708. ** the three will be 1. The other two will be 0.
  9709. */
  9710. #if defined(SQLITE_OS_OTHER)
  9711. # if SQLITE_OS_OTHER==1
  9712. # undef SQLITE_OS_UNIX
  9713. # define SQLITE_OS_UNIX 0
  9714. # undef SQLITE_OS_WIN
  9715. # define SQLITE_OS_WIN 0
  9716. # else
  9717. # undef SQLITE_OS_OTHER
  9718. # endif
  9719. #endif
  9720. #if !defined(SQLITE_OS_UNIX) && !defined(SQLITE_OS_OTHER)
  9721. # define SQLITE_OS_OTHER 0
  9722. # ifndef SQLITE_OS_WIN
  9723. # if defined(_WIN32) || defined(WIN32) || defined(__CYGWIN__) || \
  9724. defined(__MINGW32__) || defined(__BORLANDC__)
  9725. # define SQLITE_OS_WIN 1
  9726. # define SQLITE_OS_UNIX 0
  9727. # else
  9728. # define SQLITE_OS_WIN 0
  9729. # define SQLITE_OS_UNIX 1
  9730. # endif
  9731. # else
  9732. # define SQLITE_OS_UNIX 0
  9733. # endif
  9734. #else
  9735. # ifndef SQLITE_OS_WIN
  9736. # define SQLITE_OS_WIN 0
  9737. # endif
  9738. #endif
  9739. #endif /* _OS_SETUP_H_ */
  9740. /************** End of os_setup.h ********************************************/
  9741. /************** Continuing where we left off in os.h *************************/
  9742. /* If the SET_FULLSYNC macro is not defined above, then make it
  9743. ** a no-op
  9744. */
  9745. #ifndef SET_FULLSYNC
  9746. # define SET_FULLSYNC(x,y)
  9747. #endif
  9748. /*
  9749. ** The default size of a disk sector
  9750. */
  9751. #ifndef SQLITE_DEFAULT_SECTOR_SIZE
  9752. # define SQLITE_DEFAULT_SECTOR_SIZE 4096
  9753. #endif
  9754. /*
  9755. ** Temporary files are named starting with this prefix followed by 16 random
  9756. ** alphanumeric characters, and no file extension. They are stored in the
  9757. ** OS's standard temporary file directory, and are deleted prior to exit.
  9758. ** If sqlite is being embedded in another program, you may wish to change the
  9759. ** prefix to reflect your program's name, so that if your program exits
  9760. ** prematurely, old temporary files can be easily identified. This can be done
  9761. ** using -DSQLITE_TEMP_FILE_PREFIX=myprefix_ on the compiler command line.
  9762. **
  9763. ** 2006-10-31: The default prefix used to be "sqlite_". But then
  9764. ** Mcafee started using SQLite in their anti-virus product and it
  9765. ** started putting files with the "sqlite" name in the c:/temp folder.
  9766. ** This annoyed many windows users. Those users would then do a
  9767. ** Google search for "sqlite", find the telephone numbers of the
  9768. ** developers and call to wake them up at night and complain.
  9769. ** For this reason, the default name prefix is changed to be "sqlite"
  9770. ** spelled backwards. So the temp files are still identified, but
  9771. ** anybody smart enough to figure out the code is also likely smart
  9772. ** enough to know that calling the developer will not help get rid
  9773. ** of the file.
  9774. */
  9775. #ifndef SQLITE_TEMP_FILE_PREFIX
  9776. # define SQLITE_TEMP_FILE_PREFIX "etilqs_"
  9777. #endif
  9778. /*
  9779. ** The following values may be passed as the second argument to
  9780. ** sqlite3OsLock(). The various locks exhibit the following semantics:
  9781. **
  9782. ** SHARED: Any number of processes may hold a SHARED lock simultaneously.
  9783. ** RESERVED: A single process may hold a RESERVED lock on a file at
  9784. ** any time. Other processes may hold and obtain new SHARED locks.
  9785. ** PENDING: A single process may hold a PENDING lock on a file at
  9786. ** any one time. Existing SHARED locks may persist, but no new
  9787. ** SHARED locks may be obtained by other processes.
  9788. ** EXCLUSIVE: An EXCLUSIVE lock precludes all other locks.
  9789. **
  9790. ** PENDING_LOCK may not be passed directly to sqlite3OsLock(). Instead, a
  9791. ** process that requests an EXCLUSIVE lock may actually obtain a PENDING
  9792. ** lock. This can be upgraded to an EXCLUSIVE lock by a subsequent call to
  9793. ** sqlite3OsLock().
  9794. */
  9795. #define NO_LOCK 0
  9796. #define SHARED_LOCK 1
  9797. #define RESERVED_LOCK 2
  9798. #define PENDING_LOCK 3
  9799. #define EXCLUSIVE_LOCK 4
  9800. /*
  9801. ** File Locking Notes: (Mostly about windows but also some info for Unix)
  9802. **
  9803. ** We cannot use LockFileEx() or UnlockFileEx() on Win95/98/ME because
  9804. ** those functions are not available. So we use only LockFile() and
  9805. ** UnlockFile().
  9806. **
  9807. ** LockFile() prevents not just writing but also reading by other processes.
  9808. ** A SHARED_LOCK is obtained by locking a single randomly-chosen
  9809. ** byte out of a specific range of bytes. The lock byte is obtained at
  9810. ** random so two separate readers can probably access the file at the
  9811. ** same time, unless they are unlucky and choose the same lock byte.
  9812. ** An EXCLUSIVE_LOCK is obtained by locking all bytes in the range.
  9813. ** There can only be one writer. A RESERVED_LOCK is obtained by locking
  9814. ** a single byte of the file that is designated as the reserved lock byte.
  9815. ** A PENDING_LOCK is obtained by locking a designated byte different from
  9816. ** the RESERVED_LOCK byte.
  9817. **
  9818. ** On WinNT/2K/XP systems, LockFileEx() and UnlockFileEx() are available,
  9819. ** which means we can use reader/writer locks. When reader/writer locks
  9820. ** are used, the lock is placed on the same range of bytes that is used
  9821. ** for probabilistic locking in Win95/98/ME. Hence, the locking scheme
  9822. ** will support two or more Win95 readers or two or more WinNT readers.
  9823. ** But a single Win95 reader will lock out all WinNT readers and a single
  9824. ** WinNT reader will lock out all other Win95 readers.
  9825. **
  9826. ** The following #defines specify the range of bytes used for locking.
  9827. ** SHARED_SIZE is the number of bytes available in the pool from which
  9828. ** a random byte is selected for a shared lock. The pool of bytes for
  9829. ** shared locks begins at SHARED_FIRST.
  9830. **
  9831. ** The same locking strategy and
  9832. ** byte ranges are used for Unix. This leaves open the possibility of having
  9833. ** clients on win95, winNT, and unix all talking to the same shared file
  9834. ** and all locking correctly. To do so would require that samba (or whatever
  9835. ** tool is being used for file sharing) implements locks correctly between
  9836. ** windows and unix. I'm guessing that isn't likely to happen, but by
  9837. ** using the same locking range we are at least open to the possibility.
  9838. **
  9839. ** Locking in windows is manditory. For this reason, we cannot store
  9840. ** actual data in the bytes used for locking. The pager never allocates
  9841. ** the pages involved in locking therefore. SHARED_SIZE is selected so
  9842. ** that all locks will fit on a single page even at the minimum page size.
  9843. ** PENDING_BYTE defines the beginning of the locks. By default PENDING_BYTE
  9844. ** is set high so that we don't have to allocate an unused page except
  9845. ** for very large databases. But one should test the page skipping logic
  9846. ** by setting PENDING_BYTE low and running the entire regression suite.
  9847. **
  9848. ** Changing the value of PENDING_BYTE results in a subtly incompatible
  9849. ** file format. Depending on how it is changed, you might not notice
  9850. ** the incompatibility right away, even running a full regression test.
  9851. ** The default location of PENDING_BYTE is the first byte past the
  9852. ** 1GB boundary.
  9853. **
  9854. */
  9855. #ifdef SQLITE_OMIT_WSD
  9856. # define PENDING_BYTE (0x40000000)
  9857. #else
  9858. # define PENDING_BYTE sqlite3PendingByte
  9859. #endif
  9860. #define RESERVED_BYTE (PENDING_BYTE+1)
  9861. #define SHARED_FIRST (PENDING_BYTE+2)
  9862. #define SHARED_SIZE 510
  9863. /*
  9864. ** Wrapper around OS specific sqlite3_os_init() function.
  9865. */
  9866. SQLITE_PRIVATE int sqlite3OsInit(void);
  9867. /*
  9868. ** Functions for accessing sqlite3_file methods
  9869. */
  9870. SQLITE_PRIVATE int sqlite3OsClose(sqlite3_file*);
  9871. SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file*, void*, int amt, i64 offset);
  9872. SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file*, const void*, int amt, i64 offset);
  9873. SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file*, i64 size);
  9874. SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file*, int);
  9875. SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file*, i64 *pSize);
  9876. SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file*, int);
  9877. SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file*, int);
  9878. SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut);
  9879. SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file*,int,void*);
  9880. SQLITE_PRIVATE void sqlite3OsFileControlHint(sqlite3_file*,int,void*);
  9881. #define SQLITE_FCNTL_DB_UNCHANGED 0xca093fa0
  9882. SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id);
  9883. SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id);
  9884. SQLITE_PRIVATE int sqlite3OsShmMap(sqlite3_file *,int,int,int,void volatile **);
  9885. SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int, int, int);
  9886. SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id);
  9887. SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int);
  9888. SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64, int, void **);
  9889. SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *, i64, void *);
  9890. /*
  9891. ** Functions for accessing sqlite3_vfs methods
  9892. */
  9893. SQLITE_PRIVATE int sqlite3OsOpen(sqlite3_vfs *, const char *, sqlite3_file*, int, int *);
  9894. SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *, const char *, int);
  9895. SQLITE_PRIVATE int sqlite3OsAccess(sqlite3_vfs *, const char *, int, int *pResOut);
  9896. SQLITE_PRIVATE int sqlite3OsFullPathname(sqlite3_vfs *, const char *, int, char *);
  9897. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  9898. SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *, const char *);
  9899. SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *, int, char *);
  9900. SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *, void *, const char *))(void);
  9901. SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *, void *);
  9902. #endif /* SQLITE_OMIT_LOAD_EXTENSION */
  9903. SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *, int, char *);
  9904. SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *, int);
  9905. SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *, sqlite3_int64*);
  9906. /*
  9907. ** Convenience functions for opening and closing files using
  9908. ** sqlite3_malloc() to obtain space for the file-handle structure.
  9909. */
  9910. SQLITE_PRIVATE int sqlite3OsOpenMalloc(sqlite3_vfs *, const char *, sqlite3_file **, int,int*);
  9911. SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *);
  9912. #endif /* _SQLITE_OS_H_ */
  9913. /************** End of os.h **************************************************/
  9914. /************** Continuing where we left off in sqliteInt.h ******************/
  9915. /************** Include mutex.h in the middle of sqliteInt.h *****************/
  9916. /************** Begin file mutex.h *******************************************/
  9917. /*
  9918. ** 2007 August 28
  9919. **
  9920. ** The author disclaims copyright to this source code. In place of
  9921. ** a legal notice, here is a blessing:
  9922. **
  9923. ** May you do good and not evil.
  9924. ** May you find forgiveness for yourself and forgive others.
  9925. ** May you share freely, never taking more than you give.
  9926. **
  9927. *************************************************************************
  9928. **
  9929. ** This file contains the common header for all mutex implementations.
  9930. ** The sqliteInt.h header #includes this file so that it is available
  9931. ** to all source files. We break it out in an effort to keep the code
  9932. ** better organized.
  9933. **
  9934. ** NOTE: source files should *not* #include this header file directly.
  9935. ** Source files should #include the sqliteInt.h file and let that file
  9936. ** include this one indirectly.
  9937. */
  9938. /*
  9939. ** Figure out what version of the code to use. The choices are
  9940. **
  9941. ** SQLITE_MUTEX_OMIT No mutex logic. Not even stubs. The
  9942. ** mutexes implementation cannot be overridden
  9943. ** at start-time.
  9944. **
  9945. ** SQLITE_MUTEX_NOOP For single-threaded applications. No
  9946. ** mutual exclusion is provided. But this
  9947. ** implementation can be overridden at
  9948. ** start-time.
  9949. **
  9950. ** SQLITE_MUTEX_PTHREADS For multi-threaded applications on Unix.
  9951. **
  9952. ** SQLITE_MUTEX_W32 For multi-threaded applications on Win32.
  9953. */
  9954. #if !SQLITE_THREADSAFE
  9955. # define SQLITE_MUTEX_OMIT
  9956. #endif
  9957. #if SQLITE_THREADSAFE && !defined(SQLITE_MUTEX_NOOP)
  9958. # if SQLITE_OS_UNIX
  9959. # define SQLITE_MUTEX_PTHREADS
  9960. # elif SQLITE_OS_WIN
  9961. # define SQLITE_MUTEX_W32
  9962. # else
  9963. # define SQLITE_MUTEX_NOOP
  9964. # endif
  9965. #endif
  9966. #ifdef SQLITE_MUTEX_OMIT
  9967. /*
  9968. ** If this is a no-op implementation, implement everything as macros.
  9969. */
  9970. #define sqlite3_mutex_alloc(X) ((sqlite3_mutex*)8)
  9971. #define sqlite3_mutex_free(X)
  9972. #define sqlite3_mutex_enter(X)
  9973. #define sqlite3_mutex_try(X) SQLITE_OK
  9974. #define sqlite3_mutex_leave(X)
  9975. #define sqlite3_mutex_held(X) ((void)(X),1)
  9976. #define sqlite3_mutex_notheld(X) ((void)(X),1)
  9977. #define sqlite3MutexAlloc(X) ((sqlite3_mutex*)8)
  9978. #define sqlite3MutexInit() SQLITE_OK
  9979. #define sqlite3MutexEnd()
  9980. #define MUTEX_LOGIC(X)
  9981. #else
  9982. #define MUTEX_LOGIC(X) X
  9983. #endif /* defined(SQLITE_MUTEX_OMIT) */
  9984. /************** End of mutex.h ***********************************************/
  9985. /************** Continuing where we left off in sqliteInt.h ******************/
  9986. /*
  9987. ** Each database file to be accessed by the system is an instance
  9988. ** of the following structure. There are normally two of these structures
  9989. ** in the sqlite.aDb[] array. aDb[0] is the main database file and
  9990. ** aDb[1] is the database file used to hold temporary tables. Additional
  9991. ** databases may be attached.
  9992. */
  9993. struct Db {
  9994. char *zName; /* Name of this database */
  9995. Btree *pBt; /* The B*Tree structure for this database file */
  9996. u8 safety_level; /* How aggressive at syncing data to disk */
  9997. Schema *pSchema; /* Pointer to database schema (possibly shared) */
  9998. };
  9999. /*
  10000. ** An instance of the following structure stores a database schema.
  10001. **
  10002. ** Most Schema objects are associated with a Btree. The exception is
  10003. ** the Schema for the TEMP databaes (sqlite3.aDb[1]) which is free-standing.
  10004. ** In shared cache mode, a single Schema object can be shared by multiple
  10005. ** Btrees that refer to the same underlying BtShared object.
  10006. **
  10007. ** Schema objects are automatically deallocated when the last Btree that
  10008. ** references them is destroyed. The TEMP Schema is manually freed by
  10009. ** sqlite3_close().
  10010. *
  10011. ** A thread must be holding a mutex on the corresponding Btree in order
  10012. ** to access Schema content. This implies that the thread must also be
  10013. ** holding a mutex on the sqlite3 connection pointer that owns the Btree.
  10014. ** For a TEMP Schema, only the connection mutex is required.
  10015. */
  10016. struct Schema {
  10017. int schema_cookie; /* Database schema version number for this file */
  10018. int iGeneration; /* Generation counter. Incremented with each change */
  10019. Hash tblHash; /* All tables indexed by name */
  10020. Hash idxHash; /* All (named) indices indexed by name */
  10021. Hash trigHash; /* All triggers indexed by name */
  10022. Hash fkeyHash; /* All foreign keys by referenced table name */
  10023. Table *pSeqTab; /* The sqlite_sequence table used by AUTOINCREMENT */
  10024. u8 file_format; /* Schema format version for this file */
  10025. u8 enc; /* Text encoding used by this database */
  10026. u16 schemaFlags; /* Flags associated with this schema */
  10027. int cache_size; /* Number of pages to use in the cache */
  10028. };
  10029. /*
  10030. ** These macros can be used to test, set, or clear bits in the
  10031. ** Db.pSchema->flags field.
  10032. */
  10033. #define DbHasProperty(D,I,P) (((D)->aDb[I].pSchema->schemaFlags&(P))==(P))
  10034. #define DbHasAnyProperty(D,I,P) (((D)->aDb[I].pSchema->schemaFlags&(P))!=0)
  10035. #define DbSetProperty(D,I,P) (D)->aDb[I].pSchema->schemaFlags|=(P)
  10036. #define DbClearProperty(D,I,P) (D)->aDb[I].pSchema->schemaFlags&=~(P)
  10037. /*
  10038. ** Allowed values for the DB.pSchema->flags field.
  10039. **
  10040. ** The DB_SchemaLoaded flag is set after the database schema has been
  10041. ** read into internal hash tables.
  10042. **
  10043. ** DB_UnresetViews means that one or more views have column names that
  10044. ** have been filled out. If the schema changes, these column names might
  10045. ** changes and so the view will need to be reset.
  10046. */
  10047. #define DB_SchemaLoaded 0x0001 /* The schema has been loaded */
  10048. #define DB_UnresetViews 0x0002 /* Some views have defined column names */
  10049. #define DB_Empty 0x0004 /* The file is empty (length 0 bytes) */
  10050. /*
  10051. ** The number of different kinds of things that can be limited
  10052. ** using the sqlite3_limit() interface.
  10053. */
  10054. #define SQLITE_N_LIMIT (SQLITE_LIMIT_WORKER_THREADS+1)
  10055. /*
  10056. ** Lookaside malloc is a set of fixed-size buffers that can be used
  10057. ** to satisfy small transient memory allocation requests for objects
  10058. ** associated with a particular database connection. The use of
  10059. ** lookaside malloc provides a significant performance enhancement
  10060. ** (approx 10%) by avoiding numerous malloc/free requests while parsing
  10061. ** SQL statements.
  10062. **
  10063. ** The Lookaside structure holds configuration information about the
  10064. ** lookaside malloc subsystem. Each available memory allocation in
  10065. ** the lookaside subsystem is stored on a linked list of LookasideSlot
  10066. ** objects.
  10067. **
  10068. ** Lookaside allocations are only allowed for objects that are associated
  10069. ** with a particular database connection. Hence, schema information cannot
  10070. ** be stored in lookaside because in shared cache mode the schema information
  10071. ** is shared by multiple database connections. Therefore, while parsing
  10072. ** schema information, the Lookaside.bEnabled flag is cleared so that
  10073. ** lookaside allocations are not used to construct the schema objects.
  10074. */
  10075. struct Lookaside {
  10076. u16 sz; /* Size of each buffer in bytes */
  10077. u8 bEnabled; /* False to disable new lookaside allocations */
  10078. u8 bMalloced; /* True if pStart obtained from sqlite3_malloc() */
  10079. int nOut; /* Number of buffers currently checked out */
  10080. int mxOut; /* Highwater mark for nOut */
  10081. int anStat[3]; /* 0: hits. 1: size misses. 2: full misses */
  10082. LookasideSlot *pFree; /* List of available buffers */
  10083. void *pStart; /* First byte of available memory space */
  10084. void *pEnd; /* First byte past end of available space */
  10085. };
  10086. struct LookasideSlot {
  10087. LookasideSlot *pNext; /* Next buffer in the list of free buffers */
  10088. };
  10089. /*
  10090. ** A hash table for function definitions.
  10091. **
  10092. ** Hash each FuncDef structure into one of the FuncDefHash.a[] slots.
  10093. ** Collisions are on the FuncDef.pHash chain.
  10094. */
  10095. struct FuncDefHash {
  10096. FuncDef *a[23]; /* Hash table for functions */
  10097. };
  10098. #ifdef SQLITE_USER_AUTHENTICATION
  10099. /*
  10100. ** Information held in the "sqlite3" database connection object and used
  10101. ** to manage user authentication.
  10102. */
  10103. typedef struct sqlite3_userauth sqlite3_userauth;
  10104. struct sqlite3_userauth {
  10105. u8 authLevel; /* Current authentication level */
  10106. int nAuthPW; /* Size of the zAuthPW in bytes */
  10107. char *zAuthPW; /* Password used to authenticate */
  10108. char *zAuthUser; /* User name used to authenticate */
  10109. };
  10110. /* Allowed values for sqlite3_userauth.authLevel */
  10111. #define UAUTH_Unknown 0 /* Authentication not yet checked */
  10112. #define UAUTH_Fail 1 /* User authentication failed */
  10113. #define UAUTH_User 2 /* Authenticated as a normal user */
  10114. #define UAUTH_Admin 3 /* Authenticated as an administrator */
  10115. /* Functions used only by user authorization logic */
  10116. SQLITE_PRIVATE int sqlite3UserAuthTable(const char*);
  10117. SQLITE_PRIVATE int sqlite3UserAuthCheckLogin(sqlite3*,const char*,u8*);
  10118. SQLITE_PRIVATE void sqlite3UserAuthInit(sqlite3*);
  10119. SQLITE_PRIVATE void sqlite3CryptFunc(sqlite3_context*,int,sqlite3_value**);
  10120. #endif /* SQLITE_USER_AUTHENTICATION */
  10121. /*
  10122. ** typedef for the authorization callback function.
  10123. */
  10124. #ifdef SQLITE_USER_AUTHENTICATION
  10125. typedef int (*sqlite3_xauth)(void*,int,const char*,const char*,const char*,
  10126. const char*, const char*);
  10127. #else
  10128. typedef int (*sqlite3_xauth)(void*,int,const char*,const char*,const char*,
  10129. const char*);
  10130. #endif
  10131. /*
  10132. ** Each database connection is an instance of the following structure.
  10133. */
  10134. struct sqlite3 {
  10135. sqlite3_vfs *pVfs; /* OS Interface */
  10136. struct Vdbe *pVdbe; /* List of active virtual machines */
  10137. CollSeq *pDfltColl; /* The default collating sequence (BINARY) */
  10138. sqlite3_mutex *mutex; /* Connection mutex */
  10139. Db *aDb; /* All backends */
  10140. int nDb; /* Number of backends currently in use */
  10141. int flags; /* Miscellaneous flags. See below */
  10142. i64 lastRowid; /* ROWID of most recent insert (see above) */
  10143. i64 szMmap; /* Default mmap_size setting */
  10144. unsigned int openFlags; /* Flags passed to sqlite3_vfs.xOpen() */
  10145. int errCode; /* Most recent error code (SQLITE_*) */
  10146. int errMask; /* & result codes with this before returning */
  10147. u16 dbOptFlags; /* Flags to enable/disable optimizations */
  10148. u8 autoCommit; /* The auto-commit flag. */
  10149. u8 temp_store; /* 1: file 2: memory 0: default */
  10150. u8 mallocFailed; /* True if we have seen a malloc failure */
  10151. u8 dfltLockMode; /* Default locking-mode for attached dbs */
  10152. signed char nextAutovac; /* Autovac setting after VACUUM if >=0 */
  10153. u8 suppressErr; /* Do not issue error messages if true */
  10154. u8 vtabOnConflict; /* Value to return for s3_vtab_on_conflict() */
  10155. u8 isTransactionSavepoint; /* True if the outermost savepoint is a TS */
  10156. int nextPagesize; /* Pagesize after VACUUM if >0 */
  10157. u32 magic; /* Magic number for detect library misuse */
  10158. int nChange; /* Value returned by sqlite3_changes() */
  10159. int nTotalChange; /* Value returned by sqlite3_total_changes() */
  10160. int aLimit[SQLITE_N_LIMIT]; /* Limits */
  10161. int nMaxSorterMmap; /* Maximum size of regions mapped by sorter */
  10162. struct sqlite3InitInfo { /* Information used during initialization */
  10163. int newTnum; /* Rootpage of table being initialized */
  10164. u8 iDb; /* Which db file is being initialized */
  10165. u8 busy; /* TRUE if currently initializing */
  10166. u8 orphanTrigger; /* Last statement is orphaned TEMP trigger */
  10167. } init;
  10168. int nVdbeActive; /* Number of VDBEs currently running */
  10169. int nVdbeRead; /* Number of active VDBEs that read or write */
  10170. int nVdbeWrite; /* Number of active VDBEs that read and write */
  10171. int nVdbeExec; /* Number of nested calls to VdbeExec() */
  10172. int nExtension; /* Number of loaded extensions */
  10173. void **aExtension; /* Array of shared library handles */
  10174. void (*xTrace)(void*,const char*); /* Trace function */
  10175. void *pTraceArg; /* Argument to the trace function */
  10176. void (*xProfile)(void*,const char*,u64); /* Profiling function */
  10177. void *pProfileArg; /* Argument to profile function */
  10178. void *pCommitArg; /* Argument to xCommitCallback() */
  10179. int (*xCommitCallback)(void*); /* Invoked at every commit. */
  10180. void *pRollbackArg; /* Argument to xRollbackCallback() */
  10181. void (*xRollbackCallback)(void*); /* Invoked at every commit. */
  10182. void *pUpdateArg;
  10183. void (*xUpdateCallback)(void*,int, const char*,const char*,sqlite_int64);
  10184. #ifndef SQLITE_OMIT_WAL
  10185. int (*xWalCallback)(void *, sqlite3 *, const char *, int);
  10186. void *pWalArg;
  10187. #endif
  10188. void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*);
  10189. void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*);
  10190. void *pCollNeededArg;
  10191. sqlite3_value *pErr; /* Most recent error message */
  10192. union {
  10193. volatile int isInterrupted; /* True if sqlite3_interrupt has been called */
  10194. double notUsed1; /* Spacer */
  10195. } u1;
  10196. Lookaside lookaside; /* Lookaside malloc configuration */
  10197. #ifndef SQLITE_OMIT_AUTHORIZATION
  10198. sqlite3_xauth xAuth; /* Access authorization function */
  10199. void *pAuthArg; /* 1st argument to the access auth function */
  10200. #endif
  10201. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  10202. int (*xProgress)(void *); /* The progress callback */
  10203. void *pProgressArg; /* Argument to the progress callback */
  10204. unsigned nProgressOps; /* Number of opcodes for progress callback */
  10205. #endif
  10206. #ifndef SQLITE_OMIT_VIRTUALTABLE
  10207. int nVTrans; /* Allocated size of aVTrans */
  10208. Hash aModule; /* populated by sqlite3_create_module() */
  10209. VtabCtx *pVtabCtx; /* Context for active vtab connect/create */
  10210. VTable **aVTrans; /* Virtual tables with open transactions */
  10211. VTable *pDisconnect; /* Disconnect these in next sqlite3_prepare() */
  10212. #endif
  10213. FuncDefHash aFunc; /* Hash table of connection functions */
  10214. Hash aCollSeq; /* All collating sequences */
  10215. BusyHandler busyHandler; /* Busy callback */
  10216. Db aDbStatic[2]; /* Static space for the 2 default backends */
  10217. Savepoint *pSavepoint; /* List of active savepoints */
  10218. int busyTimeout; /* Busy handler timeout, in msec */
  10219. int nSavepoint; /* Number of non-transaction savepoints */
  10220. int nStatement; /* Number of nested statement-transactions */
  10221. i64 nDeferredCons; /* Net deferred constraints this transaction. */
  10222. i64 nDeferredImmCons; /* Net deferred immediate constraints */
  10223. int *pnBytesFreed; /* If not NULL, increment this in DbFree() */
  10224. #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
  10225. /* The following variables are all protected by the STATIC_MASTER
  10226. ** mutex, not by sqlite3.mutex. They are used by code in notify.c.
  10227. **
  10228. ** When X.pUnlockConnection==Y, that means that X is waiting for Y to
  10229. ** unlock so that it can proceed.
  10230. **
  10231. ** When X.pBlockingConnection==Y, that means that something that X tried
  10232. ** tried to do recently failed with an SQLITE_LOCKED error due to locks
  10233. ** held by Y.
  10234. */
  10235. sqlite3 *pBlockingConnection; /* Connection that caused SQLITE_LOCKED */
  10236. sqlite3 *pUnlockConnection; /* Connection to watch for unlock */
  10237. void *pUnlockArg; /* Argument to xUnlockNotify */
  10238. void (*xUnlockNotify)(void **, int); /* Unlock notify callback */
  10239. sqlite3 *pNextBlocked; /* Next in list of all blocked connections */
  10240. #endif
  10241. #ifdef SQLITE_USER_AUTHENTICATION
  10242. sqlite3_userauth auth; /* User authentication information */
  10243. #endif
  10244. };
  10245. /*
  10246. ** A macro to discover the encoding of a database.
  10247. */
  10248. #define ENC(db) ((db)->aDb[0].pSchema->enc)
  10249. /*
  10250. ** Possible values for the sqlite3.flags.
  10251. */
  10252. #define SQLITE_VdbeTrace 0x00000001 /* True to trace VDBE execution */
  10253. #define SQLITE_InternChanges 0x00000002 /* Uncommitted Hash table changes */
  10254. #define SQLITE_FullFSync 0x00000004 /* Use full fsync on the backend */
  10255. #define SQLITE_CkptFullFSync 0x00000008 /* Use full fsync for checkpoint */
  10256. #define SQLITE_CacheSpill 0x00000010 /* OK to spill pager cache */
  10257. #define SQLITE_FullColNames 0x00000020 /* Show full column names on SELECT */
  10258. #define SQLITE_ShortColNames 0x00000040 /* Show short columns names */
  10259. #define SQLITE_CountRows 0x00000080 /* Count rows changed by INSERT, */
  10260. /* DELETE, or UPDATE and return */
  10261. /* the count using a callback. */
  10262. #define SQLITE_NullCallback 0x00000100 /* Invoke the callback once if the */
  10263. /* result set is empty */
  10264. #define SQLITE_SqlTrace 0x00000200 /* Debug print SQL as it executes */
  10265. #define SQLITE_VdbeListing 0x00000400 /* Debug listings of VDBE programs */
  10266. #define SQLITE_WriteSchema 0x00000800 /* OK to update SQLITE_MASTER */
  10267. #define SQLITE_VdbeAddopTrace 0x00001000 /* Trace sqlite3VdbeAddOp() calls */
  10268. #define SQLITE_IgnoreChecks 0x00002000 /* Do not enforce check constraints */
  10269. #define SQLITE_ReadUncommitted 0x0004000 /* For shared-cache mode */
  10270. #define SQLITE_LegacyFileFmt 0x00008000 /* Create new databases in format 1 */
  10271. #define SQLITE_RecoveryMode 0x00010000 /* Ignore schema errors */
  10272. #define SQLITE_ReverseOrder 0x00020000 /* Reverse unordered SELECTs */
  10273. #define SQLITE_RecTriggers 0x00040000 /* Enable recursive triggers */
  10274. #define SQLITE_ForeignKeys 0x00080000 /* Enforce foreign key constraints */
  10275. #define SQLITE_AutoIndex 0x00100000 /* Enable automatic indexes */
  10276. #define SQLITE_PreferBuiltin 0x00200000 /* Preference to built-in funcs */
  10277. #define SQLITE_LoadExtension 0x00400000 /* Enable load_extension */
  10278. #define SQLITE_EnableTrigger 0x00800000 /* True to enable triggers */
  10279. #define SQLITE_DeferFKs 0x01000000 /* Defer all FK constraints */
  10280. #define SQLITE_QueryOnly 0x02000000 /* Disable database changes */
  10281. #define SQLITE_VdbeEQP 0x04000000 /* Debug EXPLAIN QUERY PLAN */
  10282. /*
  10283. ** Bits of the sqlite3.dbOptFlags field that are used by the
  10284. ** sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS,...) interface to
  10285. ** selectively disable various optimizations.
  10286. */
  10287. #define SQLITE_QueryFlattener 0x0001 /* Query flattening */
  10288. #define SQLITE_ColumnCache 0x0002 /* Column cache */
  10289. #define SQLITE_GroupByOrder 0x0004 /* GROUPBY cover of ORDERBY */
  10290. #define SQLITE_FactorOutConst 0x0008 /* Constant factoring */
  10291. /* not used 0x0010 // Was: SQLITE_IdxRealAsInt */
  10292. #define SQLITE_DistinctOpt 0x0020 /* DISTINCT using indexes */
  10293. #define SQLITE_CoverIdxScan 0x0040 /* Covering index scans */
  10294. #define SQLITE_OrderByIdxJoin 0x0080 /* ORDER BY of joins via index */
  10295. #define SQLITE_SubqCoroutine 0x0100 /* Evaluate subqueries as coroutines */
  10296. #define SQLITE_Transitive 0x0200 /* Transitive constraints */
  10297. #define SQLITE_OmitNoopJoin 0x0400 /* Omit unused tables in joins */
  10298. #define SQLITE_Stat34 0x0800 /* Use STAT3 or STAT4 data */
  10299. #define SQLITE_AllOpts 0xffff /* All optimizations */
  10300. /*
  10301. ** Macros for testing whether or not optimizations are enabled or disabled.
  10302. */
  10303. #ifndef SQLITE_OMIT_BUILTIN_TEST
  10304. #define OptimizationDisabled(db, mask) (((db)->dbOptFlags&(mask))!=0)
  10305. #define OptimizationEnabled(db, mask) (((db)->dbOptFlags&(mask))==0)
  10306. #else
  10307. #define OptimizationDisabled(db, mask) 0
  10308. #define OptimizationEnabled(db, mask) 1
  10309. #endif
  10310. /*
  10311. ** Return true if it OK to factor constant expressions into the initialization
  10312. ** code. The argument is a Parse object for the code generator.
  10313. */
  10314. #define ConstFactorOk(P) ((P)->okConstFactor)
  10315. /*
  10316. ** Possible values for the sqlite.magic field.
  10317. ** The numbers are obtained at random and have no special meaning, other
  10318. ** than being distinct from one another.
  10319. */
  10320. #define SQLITE_MAGIC_OPEN 0xa029a697 /* Database is open */
  10321. #define SQLITE_MAGIC_CLOSED 0x9f3c2d33 /* Database is closed */
  10322. #define SQLITE_MAGIC_SICK 0x4b771290 /* Error and awaiting close */
  10323. #define SQLITE_MAGIC_BUSY 0xf03b7906 /* Database currently in use */
  10324. #define SQLITE_MAGIC_ERROR 0xb5357930 /* An SQLITE_MISUSE error occurred */
  10325. #define SQLITE_MAGIC_ZOMBIE 0x64cffc7f /* Close with last statement close */
  10326. /*
  10327. ** Each SQL function is defined by an instance of the following
  10328. ** structure. A pointer to this structure is stored in the sqlite.aFunc
  10329. ** hash table. When multiple functions have the same name, the hash table
  10330. ** points to a linked list of these structures.
  10331. */
  10332. struct FuncDef {
  10333. i16 nArg; /* Number of arguments. -1 means unlimited */
  10334. u16 funcFlags; /* Some combination of SQLITE_FUNC_* */
  10335. void *pUserData; /* User data parameter */
  10336. FuncDef *pNext; /* Next function with same name */
  10337. void (*xFunc)(sqlite3_context*,int,sqlite3_value**); /* Regular function */
  10338. void (*xStep)(sqlite3_context*,int,sqlite3_value**); /* Aggregate step */
  10339. void (*xFinalize)(sqlite3_context*); /* Aggregate finalizer */
  10340. char *zName; /* SQL name of the function. */
  10341. FuncDef *pHash; /* Next with a different name but the same hash */
  10342. FuncDestructor *pDestructor; /* Reference counted destructor function */
  10343. };
  10344. /*
  10345. ** This structure encapsulates a user-function destructor callback (as
  10346. ** configured using create_function_v2()) and a reference counter. When
  10347. ** create_function_v2() is called to create a function with a destructor,
  10348. ** a single object of this type is allocated. FuncDestructor.nRef is set to
  10349. ** the number of FuncDef objects created (either 1 or 3, depending on whether
  10350. ** or not the specified encoding is SQLITE_ANY). The FuncDef.pDestructor
  10351. ** member of each of the new FuncDef objects is set to point to the allocated
  10352. ** FuncDestructor.
  10353. **
  10354. ** Thereafter, when one of the FuncDef objects is deleted, the reference
  10355. ** count on this object is decremented. When it reaches 0, the destructor
  10356. ** is invoked and the FuncDestructor structure freed.
  10357. */
  10358. struct FuncDestructor {
  10359. int nRef;
  10360. void (*xDestroy)(void *);
  10361. void *pUserData;
  10362. };
  10363. /*
  10364. ** Possible values for FuncDef.flags. Note that the _LENGTH and _TYPEOF
  10365. ** values must correspond to OPFLAG_LENGTHARG and OPFLAG_TYPEOFARG. There
  10366. ** are assert() statements in the code to verify this.
  10367. */
  10368. #define SQLITE_FUNC_ENCMASK 0x003 /* SQLITE_UTF8, SQLITE_UTF16BE or UTF16LE */
  10369. #define SQLITE_FUNC_LIKE 0x004 /* Candidate for the LIKE optimization */
  10370. #define SQLITE_FUNC_CASE 0x008 /* Case-sensitive LIKE-type function */
  10371. #define SQLITE_FUNC_EPHEM 0x010 /* Ephemeral. Delete with VDBE */
  10372. #define SQLITE_FUNC_NEEDCOLL 0x020 /* sqlite3GetFuncCollSeq() might be called */
  10373. #define SQLITE_FUNC_LENGTH 0x040 /* Built-in length() function */
  10374. #define SQLITE_FUNC_TYPEOF 0x080 /* Built-in typeof() function */
  10375. #define SQLITE_FUNC_COUNT 0x100 /* Built-in count(*) aggregate */
  10376. #define SQLITE_FUNC_COALESCE 0x200 /* Built-in coalesce() or ifnull() */
  10377. #define SQLITE_FUNC_UNLIKELY 0x400 /* Built-in unlikely() function */
  10378. #define SQLITE_FUNC_CONSTANT 0x800 /* Constant inputs give a constant output */
  10379. #define SQLITE_FUNC_MINMAX 0x1000 /* True for min() and max() aggregates */
  10380. /*
  10381. ** The following three macros, FUNCTION(), LIKEFUNC() and AGGREGATE() are
  10382. ** used to create the initializers for the FuncDef structures.
  10383. **
  10384. ** FUNCTION(zName, nArg, iArg, bNC, xFunc)
  10385. ** Used to create a scalar function definition of a function zName
  10386. ** implemented by C function xFunc that accepts nArg arguments. The
  10387. ** value passed as iArg is cast to a (void*) and made available
  10388. ** as the user-data (sqlite3_user_data()) for the function. If
  10389. ** argument bNC is true, then the SQLITE_FUNC_NEEDCOLL flag is set.
  10390. **
  10391. ** VFUNCTION(zName, nArg, iArg, bNC, xFunc)
  10392. ** Like FUNCTION except it omits the SQLITE_FUNC_CONSTANT flag.
  10393. **
  10394. ** AGGREGATE(zName, nArg, iArg, bNC, xStep, xFinal)
  10395. ** Used to create an aggregate function definition implemented by
  10396. ** the C functions xStep and xFinal. The first four parameters
  10397. ** are interpreted in the same way as the first 4 parameters to
  10398. ** FUNCTION().
  10399. **
  10400. ** LIKEFUNC(zName, nArg, pArg, flags)
  10401. ** Used to create a scalar function definition of a function zName
  10402. ** that accepts nArg arguments and is implemented by a call to C
  10403. ** function likeFunc. Argument pArg is cast to a (void *) and made
  10404. ** available as the function user-data (sqlite3_user_data()). The
  10405. ** FuncDef.flags variable is set to the value passed as the flags
  10406. ** parameter.
  10407. */
  10408. #define FUNCTION(zName, nArg, iArg, bNC, xFunc) \
  10409. {nArg, SQLITE_FUNC_CONSTANT|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
  10410. SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, #zName, 0, 0}
  10411. #define VFUNCTION(zName, nArg, iArg, bNC, xFunc) \
  10412. {nArg, SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
  10413. SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, #zName, 0, 0}
  10414. #define FUNCTION2(zName, nArg, iArg, bNC, xFunc, extraFlags) \
  10415. {nArg,SQLITE_FUNC_CONSTANT|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL)|extraFlags,\
  10416. SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, #zName, 0, 0}
  10417. #define STR_FUNCTION(zName, nArg, pArg, bNC, xFunc) \
  10418. {nArg, SQLITE_FUNC_CONSTANT|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
  10419. pArg, 0, xFunc, 0, 0, #zName, 0, 0}
  10420. #define LIKEFUNC(zName, nArg, arg, flags) \
  10421. {nArg, SQLITE_FUNC_CONSTANT|SQLITE_UTF8|flags, \
  10422. (void *)arg, 0, likeFunc, 0, 0, #zName, 0, 0}
  10423. #define AGGREGATE(zName, nArg, arg, nc, xStep, xFinal) \
  10424. {nArg, SQLITE_UTF8|(nc*SQLITE_FUNC_NEEDCOLL), \
  10425. SQLITE_INT_TO_PTR(arg), 0, 0, xStep,xFinal,#zName,0,0}
  10426. #define AGGREGATE2(zName, nArg, arg, nc, xStep, xFinal, extraFlags) \
  10427. {nArg, SQLITE_UTF8|(nc*SQLITE_FUNC_NEEDCOLL)|extraFlags, \
  10428. SQLITE_INT_TO_PTR(arg), 0, 0, xStep,xFinal,#zName,0,0}
  10429. /*
  10430. ** All current savepoints are stored in a linked list starting at
  10431. ** sqlite3.pSavepoint. The first element in the list is the most recently
  10432. ** opened savepoint. Savepoints are added to the list by the vdbe
  10433. ** OP_Savepoint instruction.
  10434. */
  10435. struct Savepoint {
  10436. char *zName; /* Savepoint name (nul-terminated) */
  10437. i64 nDeferredCons; /* Number of deferred fk violations */
  10438. i64 nDeferredImmCons; /* Number of deferred imm fk. */
  10439. Savepoint *pNext; /* Parent savepoint (if any) */
  10440. };
  10441. /*
  10442. ** The following are used as the second parameter to sqlite3Savepoint(),
  10443. ** and as the P1 argument to the OP_Savepoint instruction.
  10444. */
  10445. #define SAVEPOINT_BEGIN 0
  10446. #define SAVEPOINT_RELEASE 1
  10447. #define SAVEPOINT_ROLLBACK 2
  10448. /*
  10449. ** Each SQLite module (virtual table definition) is defined by an
  10450. ** instance of the following structure, stored in the sqlite3.aModule
  10451. ** hash table.
  10452. */
  10453. struct Module {
  10454. const sqlite3_module *pModule; /* Callback pointers */
  10455. const char *zName; /* Name passed to create_module() */
  10456. void *pAux; /* pAux passed to create_module() */
  10457. void (*xDestroy)(void *); /* Module destructor function */
  10458. };
  10459. /*
  10460. ** information about each column of an SQL table is held in an instance
  10461. ** of this structure.
  10462. */
  10463. struct Column {
  10464. char *zName; /* Name of this column */
  10465. Expr *pDflt; /* Default value of this column */
  10466. char *zDflt; /* Original text of the default value */
  10467. char *zType; /* Data type for this column */
  10468. char *zColl; /* Collating sequence. If NULL, use the default */
  10469. u8 notNull; /* An OE_ code for handling a NOT NULL constraint */
  10470. char affinity; /* One of the SQLITE_AFF_... values */
  10471. u8 szEst; /* Estimated size of this column. INT==1 */
  10472. u8 colFlags; /* Boolean properties. See COLFLAG_ defines below */
  10473. };
  10474. /* Allowed values for Column.colFlags:
  10475. */
  10476. #define COLFLAG_PRIMKEY 0x0001 /* Column is part of the primary key */
  10477. #define COLFLAG_HIDDEN 0x0002 /* A hidden column in a virtual table */
  10478. /*
  10479. ** A "Collating Sequence" is defined by an instance of the following
  10480. ** structure. Conceptually, a collating sequence consists of a name and
  10481. ** a comparison routine that defines the order of that sequence.
  10482. **
  10483. ** If CollSeq.xCmp is NULL, it means that the
  10484. ** collating sequence is undefined. Indices built on an undefined
  10485. ** collating sequence may not be read or written.
  10486. */
  10487. struct CollSeq {
  10488. char *zName; /* Name of the collating sequence, UTF-8 encoded */
  10489. u8 enc; /* Text encoding handled by xCmp() */
  10490. void *pUser; /* First argument to xCmp() */
  10491. int (*xCmp)(void*,int, const void*, int, const void*);
  10492. void (*xDel)(void*); /* Destructor for pUser */
  10493. };
  10494. /*
  10495. ** A sort order can be either ASC or DESC.
  10496. */
  10497. #define SQLITE_SO_ASC 0 /* Sort in ascending order */
  10498. #define SQLITE_SO_DESC 1 /* Sort in ascending order */
  10499. /*
  10500. ** Column affinity types.
  10501. **
  10502. ** These used to have mnemonic name like 'i' for SQLITE_AFF_INTEGER and
  10503. ** 't' for SQLITE_AFF_TEXT. But we can save a little space and improve
  10504. ** the speed a little by numbering the values consecutively.
  10505. **
  10506. ** But rather than start with 0 or 1, we begin with 'A'. That way,
  10507. ** when multiple affinity types are concatenated into a string and
  10508. ** used as the P4 operand, they will be more readable.
  10509. **
  10510. ** Note also that the numeric types are grouped together so that testing
  10511. ** for a numeric type is a single comparison. And the NONE type is first.
  10512. */
  10513. #define SQLITE_AFF_NONE 'A'
  10514. #define SQLITE_AFF_TEXT 'B'
  10515. #define SQLITE_AFF_NUMERIC 'C'
  10516. #define SQLITE_AFF_INTEGER 'D'
  10517. #define SQLITE_AFF_REAL 'E'
  10518. #define sqlite3IsNumericAffinity(X) ((X)>=SQLITE_AFF_NUMERIC)
  10519. /*
  10520. ** The SQLITE_AFF_MASK values masks off the significant bits of an
  10521. ** affinity value.
  10522. */
  10523. #define SQLITE_AFF_MASK 0x47
  10524. /*
  10525. ** Additional bit values that can be ORed with an affinity without
  10526. ** changing the affinity.
  10527. **
  10528. ** The SQLITE_NOTNULL flag is a combination of NULLEQ and JUMPIFNULL.
  10529. ** It causes an assert() to fire if either operand to a comparison
  10530. ** operator is NULL. It is added to certain comparison operators to
  10531. ** prove that the operands are always NOT NULL.
  10532. */
  10533. #define SQLITE_JUMPIFNULL 0x10 /* jumps if either operand is NULL */
  10534. #define SQLITE_STOREP2 0x20 /* Store result in reg[P2] rather than jump */
  10535. #define SQLITE_NULLEQ 0x80 /* NULL=NULL */
  10536. #define SQLITE_NOTNULL 0x90 /* Assert that operands are never NULL */
  10537. /*
  10538. ** An object of this type is created for each virtual table present in
  10539. ** the database schema.
  10540. **
  10541. ** If the database schema is shared, then there is one instance of this
  10542. ** structure for each database connection (sqlite3*) that uses the shared
  10543. ** schema. This is because each database connection requires its own unique
  10544. ** instance of the sqlite3_vtab* handle used to access the virtual table
  10545. ** implementation. sqlite3_vtab* handles can not be shared between
  10546. ** database connections, even when the rest of the in-memory database
  10547. ** schema is shared, as the implementation often stores the database
  10548. ** connection handle passed to it via the xConnect() or xCreate() method
  10549. ** during initialization internally. This database connection handle may
  10550. ** then be used by the virtual table implementation to access real tables
  10551. ** within the database. So that they appear as part of the callers
  10552. ** transaction, these accesses need to be made via the same database
  10553. ** connection as that used to execute SQL operations on the virtual table.
  10554. **
  10555. ** All VTable objects that correspond to a single table in a shared
  10556. ** database schema are initially stored in a linked-list pointed to by
  10557. ** the Table.pVTable member variable of the corresponding Table object.
  10558. ** When an sqlite3_prepare() operation is required to access the virtual
  10559. ** table, it searches the list for the VTable that corresponds to the
  10560. ** database connection doing the preparing so as to use the correct
  10561. ** sqlite3_vtab* handle in the compiled query.
  10562. **
  10563. ** When an in-memory Table object is deleted (for example when the
  10564. ** schema is being reloaded for some reason), the VTable objects are not
  10565. ** deleted and the sqlite3_vtab* handles are not xDisconnect()ed
  10566. ** immediately. Instead, they are moved from the Table.pVTable list to
  10567. ** another linked list headed by the sqlite3.pDisconnect member of the
  10568. ** corresponding sqlite3 structure. They are then deleted/xDisconnected
  10569. ** next time a statement is prepared using said sqlite3*. This is done
  10570. ** to avoid deadlock issues involving multiple sqlite3.mutex mutexes.
  10571. ** Refer to comments above function sqlite3VtabUnlockList() for an
  10572. ** explanation as to why it is safe to add an entry to an sqlite3.pDisconnect
  10573. ** list without holding the corresponding sqlite3.mutex mutex.
  10574. **
  10575. ** The memory for objects of this type is always allocated by
  10576. ** sqlite3DbMalloc(), using the connection handle stored in VTable.db as
  10577. ** the first argument.
  10578. */
  10579. struct VTable {
  10580. sqlite3 *db; /* Database connection associated with this table */
  10581. Module *pMod; /* Pointer to module implementation */
  10582. sqlite3_vtab *pVtab; /* Pointer to vtab instance */
  10583. int nRef; /* Number of pointers to this structure */
  10584. u8 bConstraint; /* True if constraints are supported */
  10585. int iSavepoint; /* Depth of the SAVEPOINT stack */
  10586. VTable *pNext; /* Next in linked list (see above) */
  10587. };
  10588. /*
  10589. ** Each SQL table is represented in memory by an instance of the
  10590. ** following structure.
  10591. **
  10592. ** Table.zName is the name of the table. The case of the original
  10593. ** CREATE TABLE statement is stored, but case is not significant for
  10594. ** comparisons.
  10595. **
  10596. ** Table.nCol is the number of columns in this table. Table.aCol is a
  10597. ** pointer to an array of Column structures, one for each column.
  10598. **
  10599. ** If the table has an INTEGER PRIMARY KEY, then Table.iPKey is the index of
  10600. ** the column that is that key. Otherwise Table.iPKey is negative. Note
  10601. ** that the datatype of the PRIMARY KEY must be INTEGER for this field to
  10602. ** be set. An INTEGER PRIMARY KEY is used as the rowid for each row of
  10603. ** the table. If a table has no INTEGER PRIMARY KEY, then a random rowid
  10604. ** is generated for each row of the table. TF_HasPrimaryKey is set if
  10605. ** the table has any PRIMARY KEY, INTEGER or otherwise.
  10606. **
  10607. ** Table.tnum is the page number for the root BTree page of the table in the
  10608. ** database file. If Table.iDb is the index of the database table backend
  10609. ** in sqlite.aDb[]. 0 is for the main database and 1 is for the file that
  10610. ** holds temporary tables and indices. If TF_Ephemeral is set
  10611. ** then the table is stored in a file that is automatically deleted
  10612. ** when the VDBE cursor to the table is closed. In this case Table.tnum
  10613. ** refers VDBE cursor number that holds the table open, not to the root
  10614. ** page number. Transient tables are used to hold the results of a
  10615. ** sub-query that appears instead of a real table name in the FROM clause
  10616. ** of a SELECT statement.
  10617. */
  10618. struct Table {
  10619. char *zName; /* Name of the table or view */
  10620. Column *aCol; /* Information about each column */
  10621. Index *pIndex; /* List of SQL indexes on this table. */
  10622. Select *pSelect; /* NULL for tables. Points to definition if a view. */
  10623. FKey *pFKey; /* Linked list of all foreign keys in this table */
  10624. char *zColAff; /* String defining the affinity of each column */
  10625. #ifndef SQLITE_OMIT_CHECK
  10626. ExprList *pCheck; /* All CHECK constraints */
  10627. #endif
  10628. LogEst nRowLogEst; /* Estimated rows in table - from sqlite_stat1 table */
  10629. int tnum; /* Root BTree node for this table (see note above) */
  10630. i16 iPKey; /* If not negative, use aCol[iPKey] as the primary key */
  10631. i16 nCol; /* Number of columns in this table */
  10632. u16 nRef; /* Number of pointers to this Table */
  10633. LogEst szTabRow; /* Estimated size of each table row in bytes */
  10634. #ifdef SQLITE_ENABLE_COSTMULT
  10635. LogEst costMult; /* Cost multiplier for using this table */
  10636. #endif
  10637. u8 tabFlags; /* Mask of TF_* values */
  10638. u8 keyConf; /* What to do in case of uniqueness conflict on iPKey */
  10639. #ifndef SQLITE_OMIT_ALTERTABLE
  10640. int addColOffset; /* Offset in CREATE TABLE stmt to add a new column */
  10641. #endif
  10642. #ifndef SQLITE_OMIT_VIRTUALTABLE
  10643. int nModuleArg; /* Number of arguments to the module */
  10644. char **azModuleArg; /* Text of all module args. [0] is module name */
  10645. VTable *pVTable; /* List of VTable objects. */
  10646. #endif
  10647. Trigger *pTrigger; /* List of triggers stored in pSchema */
  10648. Schema *pSchema; /* Schema that contains this table */
  10649. Table *pNextZombie; /* Next on the Parse.pZombieTab list */
  10650. };
  10651. /*
  10652. ** Allowed values for Table.tabFlags.
  10653. */
  10654. #define TF_Readonly 0x01 /* Read-only system table */
  10655. #define TF_Ephemeral 0x02 /* An ephemeral table */
  10656. #define TF_HasPrimaryKey 0x04 /* Table has a primary key */
  10657. #define TF_Autoincrement 0x08 /* Integer primary key is autoincrement */
  10658. #define TF_Virtual 0x10 /* Is a virtual table */
  10659. #define TF_WithoutRowid 0x20 /* No rowid used. PRIMARY KEY is the key */
  10660. /*
  10661. ** Test to see whether or not a table is a virtual table. This is
  10662. ** done as a macro so that it will be optimized out when virtual
  10663. ** table support is omitted from the build.
  10664. */
  10665. #ifndef SQLITE_OMIT_VIRTUALTABLE
  10666. # define IsVirtual(X) (((X)->tabFlags & TF_Virtual)!=0)
  10667. # define IsHiddenColumn(X) (((X)->colFlags & COLFLAG_HIDDEN)!=0)
  10668. #else
  10669. # define IsVirtual(X) 0
  10670. # define IsHiddenColumn(X) 0
  10671. #endif
  10672. /* Does the table have a rowid */
  10673. #define HasRowid(X) (((X)->tabFlags & TF_WithoutRowid)==0)
  10674. /*
  10675. ** Each foreign key constraint is an instance of the following structure.
  10676. **
  10677. ** A foreign key is associated with two tables. The "from" table is
  10678. ** the table that contains the REFERENCES clause that creates the foreign
  10679. ** key. The "to" table is the table that is named in the REFERENCES clause.
  10680. ** Consider this example:
  10681. **
  10682. ** CREATE TABLE ex1(
  10683. ** a INTEGER PRIMARY KEY,
  10684. ** b INTEGER CONSTRAINT fk1 REFERENCES ex2(x)
  10685. ** );
  10686. **
  10687. ** For foreign key "fk1", the from-table is "ex1" and the to-table is "ex2".
  10688. ** Equivalent names:
  10689. **
  10690. ** from-table == child-table
  10691. ** to-table == parent-table
  10692. **
  10693. ** Each REFERENCES clause generates an instance of the following structure
  10694. ** which is attached to the from-table. The to-table need not exist when
  10695. ** the from-table is created. The existence of the to-table is not checked.
  10696. **
  10697. ** The list of all parents for child Table X is held at X.pFKey.
  10698. **
  10699. ** A list of all children for a table named Z (which might not even exist)
  10700. ** is held in Schema.fkeyHash with a hash key of Z.
  10701. */
  10702. struct FKey {
  10703. Table *pFrom; /* Table containing the REFERENCES clause (aka: Child) */
  10704. FKey *pNextFrom; /* Next FKey with the same in pFrom. Next parent of pFrom */
  10705. char *zTo; /* Name of table that the key points to (aka: Parent) */
  10706. FKey *pNextTo; /* Next with the same zTo. Next child of zTo. */
  10707. FKey *pPrevTo; /* Previous with the same zTo */
  10708. int nCol; /* Number of columns in this key */
  10709. /* EV: R-30323-21917 */
  10710. u8 isDeferred; /* True if constraint checking is deferred till COMMIT */
  10711. u8 aAction[2]; /* ON DELETE and ON UPDATE actions, respectively */
  10712. Trigger *apTrigger[2];/* Triggers for aAction[] actions */
  10713. struct sColMap { /* Mapping of columns in pFrom to columns in zTo */
  10714. int iFrom; /* Index of column in pFrom */
  10715. char *zCol; /* Name of column in zTo. If NULL use PRIMARY KEY */
  10716. } aCol[1]; /* One entry for each of nCol columns */
  10717. };
  10718. /*
  10719. ** SQLite supports many different ways to resolve a constraint
  10720. ** error. ROLLBACK processing means that a constraint violation
  10721. ** causes the operation in process to fail and for the current transaction
  10722. ** to be rolled back. ABORT processing means the operation in process
  10723. ** fails and any prior changes from that one operation are backed out,
  10724. ** but the transaction is not rolled back. FAIL processing means that
  10725. ** the operation in progress stops and returns an error code. But prior
  10726. ** changes due to the same operation are not backed out and no rollback
  10727. ** occurs. IGNORE means that the particular row that caused the constraint
  10728. ** error is not inserted or updated. Processing continues and no error
  10729. ** is returned. REPLACE means that preexisting database rows that caused
  10730. ** a UNIQUE constraint violation are removed so that the new insert or
  10731. ** update can proceed. Processing continues and no error is reported.
  10732. **
  10733. ** RESTRICT, SETNULL, and CASCADE actions apply only to foreign keys.
  10734. ** RESTRICT is the same as ABORT for IMMEDIATE foreign keys and the
  10735. ** same as ROLLBACK for DEFERRED keys. SETNULL means that the foreign
  10736. ** key is set to NULL. CASCADE means that a DELETE or UPDATE of the
  10737. ** referenced table row is propagated into the row that holds the
  10738. ** foreign key.
  10739. **
  10740. ** The following symbolic values are used to record which type
  10741. ** of action to take.
  10742. */
  10743. #define OE_None 0 /* There is no constraint to check */
  10744. #define OE_Rollback 1 /* Fail the operation and rollback the transaction */
  10745. #define OE_Abort 2 /* Back out changes but do no rollback transaction */
  10746. #define OE_Fail 3 /* Stop the operation but leave all prior changes */
  10747. #define OE_Ignore 4 /* Ignore the error. Do not do the INSERT or UPDATE */
  10748. #define OE_Replace 5 /* Delete existing record, then do INSERT or UPDATE */
  10749. #define OE_Restrict 6 /* OE_Abort for IMMEDIATE, OE_Rollback for DEFERRED */
  10750. #define OE_SetNull 7 /* Set the foreign key value to NULL */
  10751. #define OE_SetDflt 8 /* Set the foreign key value to its default */
  10752. #define OE_Cascade 9 /* Cascade the changes */
  10753. #define OE_Default 10 /* Do whatever the default action is */
  10754. /*
  10755. ** An instance of the following structure is passed as the first
  10756. ** argument to sqlite3VdbeKeyCompare and is used to control the
  10757. ** comparison of the two index keys.
  10758. **
  10759. ** Note that aSortOrder[] and aColl[] have nField+1 slots. There
  10760. ** are nField slots for the columns of an index then one extra slot
  10761. ** for the rowid at the end.
  10762. */
  10763. struct KeyInfo {
  10764. u32 nRef; /* Number of references to this KeyInfo object */
  10765. u8 enc; /* Text encoding - one of the SQLITE_UTF* values */
  10766. u16 nField; /* Number of key columns in the index */
  10767. u16 nXField; /* Number of columns beyond the key columns */
  10768. sqlite3 *db; /* The database connection */
  10769. u8 *aSortOrder; /* Sort order for each column. */
  10770. CollSeq *aColl[1]; /* Collating sequence for each term of the key */
  10771. };
  10772. /*
  10773. ** An instance of the following structure holds information about a
  10774. ** single index record that has already been parsed out into individual
  10775. ** values.
  10776. **
  10777. ** A record is an object that contains one or more fields of data.
  10778. ** Records are used to store the content of a table row and to store
  10779. ** the key of an index. A blob encoding of a record is created by
  10780. ** the OP_MakeRecord opcode of the VDBE and is disassembled by the
  10781. ** OP_Column opcode.
  10782. **
  10783. ** This structure holds a record that has already been disassembled
  10784. ** into its constituent fields.
  10785. **
  10786. ** The r1 and r2 member variables are only used by the optimized comparison
  10787. ** functions vdbeRecordCompareInt() and vdbeRecordCompareString().
  10788. */
  10789. struct UnpackedRecord {
  10790. KeyInfo *pKeyInfo; /* Collation and sort-order information */
  10791. u16 nField; /* Number of entries in apMem[] */
  10792. i8 default_rc; /* Comparison result if keys are equal */
  10793. u8 errCode; /* Error detected by xRecordCompare (CORRUPT or NOMEM) */
  10794. Mem *aMem; /* Values */
  10795. int r1; /* Value to return if (lhs > rhs) */
  10796. int r2; /* Value to return if (rhs < lhs) */
  10797. };
  10798. /*
  10799. ** Each SQL index is represented in memory by an
  10800. ** instance of the following structure.
  10801. **
  10802. ** The columns of the table that are to be indexed are described
  10803. ** by the aiColumn[] field of this structure. For example, suppose
  10804. ** we have the following table and index:
  10805. **
  10806. ** CREATE TABLE Ex1(c1 int, c2 int, c3 text);
  10807. ** CREATE INDEX Ex2 ON Ex1(c3,c1);
  10808. **
  10809. ** In the Table structure describing Ex1, nCol==3 because there are
  10810. ** three columns in the table. In the Index structure describing
  10811. ** Ex2, nColumn==2 since 2 of the 3 columns of Ex1 are indexed.
  10812. ** The value of aiColumn is {2, 0}. aiColumn[0]==2 because the
  10813. ** first column to be indexed (c3) has an index of 2 in Ex1.aCol[].
  10814. ** The second column to be indexed (c1) has an index of 0 in
  10815. ** Ex1.aCol[], hence Ex2.aiColumn[1]==0.
  10816. **
  10817. ** The Index.onError field determines whether or not the indexed columns
  10818. ** must be unique and what to do if they are not. When Index.onError=OE_None,
  10819. ** it means this is not a unique index. Otherwise it is a unique index
  10820. ** and the value of Index.onError indicate the which conflict resolution
  10821. ** algorithm to employ whenever an attempt is made to insert a non-unique
  10822. ** element.
  10823. */
  10824. struct Index {
  10825. char *zName; /* Name of this index */
  10826. i16 *aiColumn; /* Which columns are used by this index. 1st is 0 */
  10827. LogEst *aiRowLogEst; /* From ANALYZE: Est. rows selected by each column */
  10828. Table *pTable; /* The SQL table being indexed */
  10829. char *zColAff; /* String defining the affinity of each column */
  10830. Index *pNext; /* The next index associated with the same table */
  10831. Schema *pSchema; /* Schema containing this index */
  10832. u8 *aSortOrder; /* for each column: True==DESC, False==ASC */
  10833. char **azColl; /* Array of collation sequence names for index */
  10834. Expr *pPartIdxWhere; /* WHERE clause for partial indices */
  10835. KeyInfo *pKeyInfo; /* A KeyInfo object suitable for this index */
  10836. int tnum; /* DB Page containing root of this index */
  10837. LogEst szIdxRow; /* Estimated average row size in bytes */
  10838. u16 nKeyCol; /* Number of columns forming the key */
  10839. u16 nColumn; /* Number of columns stored in the index */
  10840. u8 onError; /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
  10841. unsigned idxType:2; /* 1==UNIQUE, 2==PRIMARY KEY, 0==CREATE INDEX */
  10842. unsigned bUnordered:1; /* Use this index for == or IN queries only */
  10843. unsigned uniqNotNull:1; /* True if UNIQUE and NOT NULL for all columns */
  10844. unsigned isResized:1; /* True if resizeIndexObject() has been called */
  10845. unsigned isCovering:1; /* True if this is a covering index */
  10846. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  10847. int nSample; /* Number of elements in aSample[] */
  10848. int nSampleCol; /* Size of IndexSample.anEq[] and so on */
  10849. tRowcnt *aAvgEq; /* Average nEq values for keys not in aSample */
  10850. IndexSample *aSample; /* Samples of the left-most key */
  10851. tRowcnt *aiRowEst; /* Non-logarithmic stat1 data for this index */
  10852. tRowcnt nRowEst0; /* Non-logarithmic number of rows in the index */
  10853. #endif
  10854. };
  10855. /*
  10856. ** Allowed values for Index.idxType
  10857. */
  10858. #define SQLITE_IDXTYPE_APPDEF 0 /* Created using CREATE INDEX */
  10859. #define SQLITE_IDXTYPE_UNIQUE 1 /* Implements a UNIQUE constraint */
  10860. #define SQLITE_IDXTYPE_PRIMARYKEY 2 /* Is the PRIMARY KEY for the table */
  10861. /* Return true if index X is a PRIMARY KEY index */
  10862. #define IsPrimaryKeyIndex(X) ((X)->idxType==SQLITE_IDXTYPE_PRIMARYKEY)
  10863. /* Return true if index X is a UNIQUE index */
  10864. #define IsUniqueIndex(X) ((X)->onError!=OE_None)
  10865. /*
  10866. ** Each sample stored in the sqlite_stat3 table is represented in memory
  10867. ** using a structure of this type. See documentation at the top of the
  10868. ** analyze.c source file for additional information.
  10869. */
  10870. struct IndexSample {
  10871. void *p; /* Pointer to sampled record */
  10872. int n; /* Size of record in bytes */
  10873. tRowcnt *anEq; /* Est. number of rows where the key equals this sample */
  10874. tRowcnt *anLt; /* Est. number of rows where key is less than this sample */
  10875. tRowcnt *anDLt; /* Est. number of distinct keys less than this sample */
  10876. };
  10877. /*
  10878. ** Each token coming out of the lexer is an instance of
  10879. ** this structure. Tokens are also used as part of an expression.
  10880. **
  10881. ** Note if Token.z==0 then Token.dyn and Token.n are undefined and
  10882. ** may contain random values. Do not make any assumptions about Token.dyn
  10883. ** and Token.n when Token.z==0.
  10884. */
  10885. struct Token {
  10886. const char *z; /* Text of the token. Not NULL-terminated! */
  10887. unsigned int n; /* Number of characters in this token */
  10888. };
  10889. /*
  10890. ** An instance of this structure contains information needed to generate
  10891. ** code for a SELECT that contains aggregate functions.
  10892. **
  10893. ** If Expr.op==TK_AGG_COLUMN or TK_AGG_FUNCTION then Expr.pAggInfo is a
  10894. ** pointer to this structure. The Expr.iColumn field is the index in
  10895. ** AggInfo.aCol[] or AggInfo.aFunc[] of information needed to generate
  10896. ** code for that node.
  10897. **
  10898. ** AggInfo.pGroupBy and AggInfo.aFunc.pExpr point to fields within the
  10899. ** original Select structure that describes the SELECT statement. These
  10900. ** fields do not need to be freed when deallocating the AggInfo structure.
  10901. */
  10902. struct AggInfo {
  10903. u8 directMode; /* Direct rendering mode means take data directly
  10904. ** from source tables rather than from accumulators */
  10905. u8 useSortingIdx; /* In direct mode, reference the sorting index rather
  10906. ** than the source table */
  10907. int sortingIdx; /* Cursor number of the sorting index */
  10908. int sortingIdxPTab; /* Cursor number of pseudo-table */
  10909. int nSortingColumn; /* Number of columns in the sorting index */
  10910. int mnReg, mxReg; /* Range of registers allocated for aCol and aFunc */
  10911. ExprList *pGroupBy; /* The group by clause */
  10912. struct AggInfo_col { /* For each column used in source tables */
  10913. Table *pTab; /* Source table */
  10914. int iTable; /* Cursor number of the source table */
  10915. int iColumn; /* Column number within the source table */
  10916. int iSorterColumn; /* Column number in the sorting index */
  10917. int iMem; /* Memory location that acts as accumulator */
  10918. Expr *pExpr; /* The original expression */
  10919. } *aCol;
  10920. int nColumn; /* Number of used entries in aCol[] */
  10921. int nAccumulator; /* Number of columns that show through to the output.
  10922. ** Additional columns are used only as parameters to
  10923. ** aggregate functions */
  10924. struct AggInfo_func { /* For each aggregate function */
  10925. Expr *pExpr; /* Expression encoding the function */
  10926. FuncDef *pFunc; /* The aggregate function implementation */
  10927. int iMem; /* Memory location that acts as accumulator */
  10928. int iDistinct; /* Ephemeral table used to enforce DISTINCT */
  10929. } *aFunc;
  10930. int nFunc; /* Number of entries in aFunc[] */
  10931. };
  10932. /*
  10933. ** The datatype ynVar is a signed integer, either 16-bit or 32-bit.
  10934. ** Usually it is 16-bits. But if SQLITE_MAX_VARIABLE_NUMBER is greater
  10935. ** than 32767 we have to make it 32-bit. 16-bit is preferred because
  10936. ** it uses less memory in the Expr object, which is a big memory user
  10937. ** in systems with lots of prepared statements. And few applications
  10938. ** need more than about 10 or 20 variables. But some extreme users want
  10939. ** to have prepared statements with over 32767 variables, and for them
  10940. ** the option is available (at compile-time).
  10941. */
  10942. #if SQLITE_MAX_VARIABLE_NUMBER<=32767
  10943. typedef i16 ynVar;
  10944. #else
  10945. typedef int ynVar;
  10946. #endif
  10947. /*
  10948. ** Each node of an expression in the parse tree is an instance
  10949. ** of this structure.
  10950. **
  10951. ** Expr.op is the opcode. The integer parser token codes are reused
  10952. ** as opcodes here. For example, the parser defines TK_GE to be an integer
  10953. ** code representing the ">=" operator. This same integer code is reused
  10954. ** to represent the greater-than-or-equal-to operator in the expression
  10955. ** tree.
  10956. **
  10957. ** If the expression is an SQL literal (TK_INTEGER, TK_FLOAT, TK_BLOB,
  10958. ** or TK_STRING), then Expr.token contains the text of the SQL literal. If
  10959. ** the expression is a variable (TK_VARIABLE), then Expr.token contains the
  10960. ** variable name. Finally, if the expression is an SQL function (TK_FUNCTION),
  10961. ** then Expr.token contains the name of the function.
  10962. **
  10963. ** Expr.pRight and Expr.pLeft are the left and right subexpressions of a
  10964. ** binary operator. Either or both may be NULL.
  10965. **
  10966. ** Expr.x.pList is a list of arguments if the expression is an SQL function,
  10967. ** a CASE expression or an IN expression of the form "<lhs> IN (<y>, <z>...)".
  10968. ** Expr.x.pSelect is used if the expression is a sub-select or an expression of
  10969. ** the form "<lhs> IN (SELECT ...)". If the EP_xIsSelect bit is set in the
  10970. ** Expr.flags mask, then Expr.x.pSelect is valid. Otherwise, Expr.x.pList is
  10971. ** valid.
  10972. **
  10973. ** An expression of the form ID or ID.ID refers to a column in a table.
  10974. ** For such expressions, Expr.op is set to TK_COLUMN and Expr.iTable is
  10975. ** the integer cursor number of a VDBE cursor pointing to that table and
  10976. ** Expr.iColumn is the column number for the specific column. If the
  10977. ** expression is used as a result in an aggregate SELECT, then the
  10978. ** value is also stored in the Expr.iAgg column in the aggregate so that
  10979. ** it can be accessed after all aggregates are computed.
  10980. **
  10981. ** If the expression is an unbound variable marker (a question mark
  10982. ** character '?' in the original SQL) then the Expr.iTable holds the index
  10983. ** number for that variable.
  10984. **
  10985. ** If the expression is a subquery then Expr.iColumn holds an integer
  10986. ** register number containing the result of the subquery. If the
  10987. ** subquery gives a constant result, then iTable is -1. If the subquery
  10988. ** gives a different answer at different times during statement processing
  10989. ** then iTable is the address of a subroutine that computes the subquery.
  10990. **
  10991. ** If the Expr is of type OP_Column, and the table it is selecting from
  10992. ** is a disk table or the "old.*" pseudo-table, then pTab points to the
  10993. ** corresponding table definition.
  10994. **
  10995. ** ALLOCATION NOTES:
  10996. **
  10997. ** Expr objects can use a lot of memory space in database schema. To
  10998. ** help reduce memory requirements, sometimes an Expr object will be
  10999. ** truncated. And to reduce the number of memory allocations, sometimes
  11000. ** two or more Expr objects will be stored in a single memory allocation,
  11001. ** together with Expr.zToken strings.
  11002. **
  11003. ** If the EP_Reduced and EP_TokenOnly flags are set when
  11004. ** an Expr object is truncated. When EP_Reduced is set, then all
  11005. ** the child Expr objects in the Expr.pLeft and Expr.pRight subtrees
  11006. ** are contained within the same memory allocation. Note, however, that
  11007. ** the subtrees in Expr.x.pList or Expr.x.pSelect are always separately
  11008. ** allocated, regardless of whether or not EP_Reduced is set.
  11009. */
  11010. struct Expr {
  11011. u8 op; /* Operation performed by this node */
  11012. char affinity; /* The affinity of the column or 0 if not a column */
  11013. u32 flags; /* Various flags. EP_* See below */
  11014. union {
  11015. char *zToken; /* Token value. Zero terminated and dequoted */
  11016. int iValue; /* Non-negative integer value if EP_IntValue */
  11017. } u;
  11018. /* If the EP_TokenOnly flag is set in the Expr.flags mask, then no
  11019. ** space is allocated for the fields below this point. An attempt to
  11020. ** access them will result in a segfault or malfunction.
  11021. *********************************************************************/
  11022. Expr *pLeft; /* Left subnode */
  11023. Expr *pRight; /* Right subnode */
  11024. union {
  11025. ExprList *pList; /* op = IN, EXISTS, SELECT, CASE, FUNCTION, BETWEEN */
  11026. Select *pSelect; /* EP_xIsSelect and op = IN, EXISTS, SELECT */
  11027. } x;
  11028. /* If the EP_Reduced flag is set in the Expr.flags mask, then no
  11029. ** space is allocated for the fields below this point. An attempt to
  11030. ** access them will result in a segfault or malfunction.
  11031. *********************************************************************/
  11032. #if SQLITE_MAX_EXPR_DEPTH>0
  11033. int nHeight; /* Height of the tree headed by this node */
  11034. #endif
  11035. int iTable; /* TK_COLUMN: cursor number of table holding column
  11036. ** TK_REGISTER: register number
  11037. ** TK_TRIGGER: 1 -> new, 0 -> old
  11038. ** EP_Unlikely: 134217728 times likelihood */
  11039. ynVar iColumn; /* TK_COLUMN: column index. -1 for rowid.
  11040. ** TK_VARIABLE: variable number (always >= 1). */
  11041. i16 iAgg; /* Which entry in pAggInfo->aCol[] or ->aFunc[] */
  11042. i16 iRightJoinTable; /* If EP_FromJoin, the right table of the join */
  11043. u8 op2; /* TK_REGISTER: original value of Expr.op
  11044. ** TK_COLUMN: the value of p5 for OP_Column
  11045. ** TK_AGG_FUNCTION: nesting depth */
  11046. AggInfo *pAggInfo; /* Used by TK_AGG_COLUMN and TK_AGG_FUNCTION */
  11047. Table *pTab; /* Table for TK_COLUMN expressions. */
  11048. };
  11049. /*
  11050. ** The following are the meanings of bits in the Expr.flags field.
  11051. */
  11052. #define EP_FromJoin 0x000001 /* Originated in ON or USING clause of a join */
  11053. #define EP_Agg 0x000002 /* Contains one or more aggregate functions */
  11054. #define EP_Resolved 0x000004 /* IDs have been resolved to COLUMNs */
  11055. #define EP_Error 0x000008 /* Expression contains one or more errors */
  11056. #define EP_Distinct 0x000010 /* Aggregate function with DISTINCT keyword */
  11057. #define EP_VarSelect 0x000020 /* pSelect is correlated, not constant */
  11058. #define EP_DblQuoted 0x000040 /* token.z was originally in "..." */
  11059. #define EP_InfixFunc 0x000080 /* True for an infix function: LIKE, GLOB, etc */
  11060. #define EP_Collate 0x000100 /* Tree contains a TK_COLLATE operator */
  11061. #define EP_Generic 0x000200 /* Ignore COLLATE or affinity on this tree */
  11062. #define EP_IntValue 0x000400 /* Integer value contained in u.iValue */
  11063. #define EP_xIsSelect 0x000800 /* x.pSelect is valid (otherwise x.pList is) */
  11064. #define EP_Skip 0x001000 /* COLLATE, AS, or UNLIKELY */
  11065. #define EP_Reduced 0x002000 /* Expr struct EXPR_REDUCEDSIZE bytes only */
  11066. #define EP_TokenOnly 0x004000 /* Expr struct EXPR_TOKENONLYSIZE bytes only */
  11067. #define EP_Static 0x008000 /* Held in memory not obtained from malloc() */
  11068. #define EP_MemToken 0x010000 /* Need to sqlite3DbFree() Expr.zToken */
  11069. #define EP_NoReduce 0x020000 /* Cannot EXPRDUP_REDUCE this Expr */
  11070. #define EP_Unlikely 0x040000 /* unlikely() or likelihood() function */
  11071. #define EP_Constant 0x080000 /* Node is a constant */
  11072. /*
  11073. ** These macros can be used to test, set, or clear bits in the
  11074. ** Expr.flags field.
  11075. */
  11076. #define ExprHasProperty(E,P) (((E)->flags&(P))!=0)
  11077. #define ExprHasAllProperty(E,P) (((E)->flags&(P))==(P))
  11078. #define ExprSetProperty(E,P) (E)->flags|=(P)
  11079. #define ExprClearProperty(E,P) (E)->flags&=~(P)
  11080. /* The ExprSetVVAProperty() macro is used for Verification, Validation,
  11081. ** and Accreditation only. It works like ExprSetProperty() during VVA
  11082. ** processes but is a no-op for delivery.
  11083. */
  11084. #ifdef SQLITE_DEBUG
  11085. # define ExprSetVVAProperty(E,P) (E)->flags|=(P)
  11086. #else
  11087. # define ExprSetVVAProperty(E,P)
  11088. #endif
  11089. /*
  11090. ** Macros to determine the number of bytes required by a normal Expr
  11091. ** struct, an Expr struct with the EP_Reduced flag set in Expr.flags
  11092. ** and an Expr struct with the EP_TokenOnly flag set.
  11093. */
  11094. #define EXPR_FULLSIZE sizeof(Expr) /* Full size */
  11095. #define EXPR_REDUCEDSIZE offsetof(Expr,iTable) /* Common features */
  11096. #define EXPR_TOKENONLYSIZE offsetof(Expr,pLeft) /* Fewer features */
  11097. /*
  11098. ** Flags passed to the sqlite3ExprDup() function. See the header comment
  11099. ** above sqlite3ExprDup() for details.
  11100. */
  11101. #define EXPRDUP_REDUCE 0x0001 /* Used reduced-size Expr nodes */
  11102. /*
  11103. ** A list of expressions. Each expression may optionally have a
  11104. ** name. An expr/name combination can be used in several ways, such
  11105. ** as the list of "expr AS ID" fields following a "SELECT" or in the
  11106. ** list of "ID = expr" items in an UPDATE. A list of expressions can
  11107. ** also be used as the argument to a function, in which case the a.zName
  11108. ** field is not used.
  11109. **
  11110. ** By default the Expr.zSpan field holds a human-readable description of
  11111. ** the expression that is used in the generation of error messages and
  11112. ** column labels. In this case, Expr.zSpan is typically the text of a
  11113. ** column expression as it exists in a SELECT statement. However, if
  11114. ** the bSpanIsTab flag is set, then zSpan is overloaded to mean the name
  11115. ** of the result column in the form: DATABASE.TABLE.COLUMN. This later
  11116. ** form is used for name resolution with nested FROM clauses.
  11117. */
  11118. struct ExprList {
  11119. int nExpr; /* Number of expressions on the list */
  11120. struct ExprList_item { /* For each expression in the list */
  11121. Expr *pExpr; /* The list of expressions */
  11122. char *zName; /* Token associated with this expression */
  11123. char *zSpan; /* Original text of the expression */
  11124. u8 sortOrder; /* 1 for DESC or 0 for ASC */
  11125. unsigned done :1; /* A flag to indicate when processing is finished */
  11126. unsigned bSpanIsTab :1; /* zSpan holds DB.TABLE.COLUMN */
  11127. unsigned reusable :1; /* Constant expression is reusable */
  11128. union {
  11129. struct {
  11130. u16 iOrderByCol; /* For ORDER BY, column number in result set */
  11131. u16 iAlias; /* Index into Parse.aAlias[] for zName */
  11132. } x;
  11133. int iConstExprReg; /* Register in which Expr value is cached */
  11134. } u;
  11135. } *a; /* Alloc a power of two greater or equal to nExpr */
  11136. };
  11137. /*
  11138. ** An instance of this structure is used by the parser to record both
  11139. ** the parse tree for an expression and the span of input text for an
  11140. ** expression.
  11141. */
  11142. struct ExprSpan {
  11143. Expr *pExpr; /* The expression parse tree */
  11144. const char *zStart; /* First character of input text */
  11145. const char *zEnd; /* One character past the end of input text */
  11146. };
  11147. /*
  11148. ** An instance of this structure can hold a simple list of identifiers,
  11149. ** such as the list "a,b,c" in the following statements:
  11150. **
  11151. ** INSERT INTO t(a,b,c) VALUES ...;
  11152. ** CREATE INDEX idx ON t(a,b,c);
  11153. ** CREATE TRIGGER trig BEFORE UPDATE ON t(a,b,c) ...;
  11154. **
  11155. ** The IdList.a.idx field is used when the IdList represents the list of
  11156. ** column names after a table name in an INSERT statement. In the statement
  11157. **
  11158. ** INSERT INTO t(a,b,c) ...
  11159. **
  11160. ** If "a" is the k-th column of table "t", then IdList.a[0].idx==k.
  11161. */
  11162. struct IdList {
  11163. struct IdList_item {
  11164. char *zName; /* Name of the identifier */
  11165. int idx; /* Index in some Table.aCol[] of a column named zName */
  11166. } *a;
  11167. int nId; /* Number of identifiers on the list */
  11168. };
  11169. /*
  11170. ** The bitmask datatype defined below is used for various optimizations.
  11171. **
  11172. ** Changing this from a 64-bit to a 32-bit type limits the number of
  11173. ** tables in a join to 32 instead of 64. But it also reduces the size
  11174. ** of the library by 738 bytes on ix86.
  11175. */
  11176. typedef u64 Bitmask;
  11177. /*
  11178. ** The number of bits in a Bitmask. "BMS" means "BitMask Size".
  11179. */
  11180. #define BMS ((int)(sizeof(Bitmask)*8))
  11181. /*
  11182. ** A bit in a Bitmask
  11183. */
  11184. #define MASKBIT(n) (((Bitmask)1)<<(n))
  11185. #define MASKBIT32(n) (((unsigned int)1)<<(n))
  11186. /*
  11187. ** The following structure describes the FROM clause of a SELECT statement.
  11188. ** Each table or subquery in the FROM clause is a separate element of
  11189. ** the SrcList.a[] array.
  11190. **
  11191. ** With the addition of multiple database support, the following structure
  11192. ** can also be used to describe a particular table such as the table that
  11193. ** is modified by an INSERT, DELETE, or UPDATE statement. In standard SQL,
  11194. ** such a table must be a simple name: ID. But in SQLite, the table can
  11195. ** now be identified by a database name, a dot, then the table name: ID.ID.
  11196. **
  11197. ** The jointype starts out showing the join type between the current table
  11198. ** and the next table on the list. The parser builds the list this way.
  11199. ** But sqlite3SrcListShiftJoinType() later shifts the jointypes so that each
  11200. ** jointype expresses the join between the table and the previous table.
  11201. **
  11202. ** In the colUsed field, the high-order bit (bit 63) is set if the table
  11203. ** contains more than 63 columns and the 64-th or later column is used.
  11204. */
  11205. struct SrcList {
  11206. int nSrc; /* Number of tables or subqueries in the FROM clause */
  11207. u32 nAlloc; /* Number of entries allocated in a[] below */
  11208. struct SrcList_item {
  11209. Schema *pSchema; /* Schema to which this item is fixed */
  11210. char *zDatabase; /* Name of database holding this table */
  11211. char *zName; /* Name of the table */
  11212. char *zAlias; /* The "B" part of a "A AS B" phrase. zName is the "A" */
  11213. Table *pTab; /* An SQL table corresponding to zName */
  11214. Select *pSelect; /* A SELECT statement used in place of a table name */
  11215. int addrFillSub; /* Address of subroutine to manifest a subquery */
  11216. int regReturn; /* Register holding return address of addrFillSub */
  11217. int regResult; /* Registers holding results of a co-routine */
  11218. u8 jointype; /* Type of join between this able and the previous */
  11219. unsigned notIndexed :1; /* True if there is a NOT INDEXED clause */
  11220. unsigned isCorrelated :1; /* True if sub-query is correlated */
  11221. unsigned viaCoroutine :1; /* Implemented as a co-routine */
  11222. unsigned isRecursive :1; /* True for recursive reference in WITH */
  11223. #ifndef SQLITE_OMIT_EXPLAIN
  11224. u8 iSelectId; /* If pSelect!=0, the id of the sub-select in EQP */
  11225. #endif
  11226. int iCursor; /* The VDBE cursor number used to access this table */
  11227. Expr *pOn; /* The ON clause of a join */
  11228. IdList *pUsing; /* The USING clause of a join */
  11229. Bitmask colUsed; /* Bit N (1<<N) set if column N of pTab is used */
  11230. char *zIndex; /* Identifier from "INDEXED BY <zIndex>" clause */
  11231. Index *pIndex; /* Index structure corresponding to zIndex, if any */
  11232. } a[1]; /* One entry for each identifier on the list */
  11233. };
  11234. /*
  11235. ** Permitted values of the SrcList.a.jointype field
  11236. */
  11237. #define JT_INNER 0x0001 /* Any kind of inner or cross join */
  11238. #define JT_CROSS 0x0002 /* Explicit use of the CROSS keyword */
  11239. #define JT_NATURAL 0x0004 /* True for a "natural" join */
  11240. #define JT_LEFT 0x0008 /* Left outer join */
  11241. #define JT_RIGHT 0x0010 /* Right outer join */
  11242. #define JT_OUTER 0x0020 /* The "OUTER" keyword is present */
  11243. #define JT_ERROR 0x0040 /* unknown or unsupported join type */
  11244. /*
  11245. ** Flags appropriate for the wctrlFlags parameter of sqlite3WhereBegin()
  11246. ** and the WhereInfo.wctrlFlags member.
  11247. */
  11248. #define WHERE_ORDERBY_NORMAL 0x0000 /* No-op */
  11249. #define WHERE_ORDERBY_MIN 0x0001 /* ORDER BY processing for min() func */
  11250. #define WHERE_ORDERBY_MAX 0x0002 /* ORDER BY processing for max() func */
  11251. #define WHERE_ONEPASS_DESIRED 0x0004 /* Want to do one-pass UPDATE/DELETE */
  11252. #define WHERE_DUPLICATES_OK 0x0008 /* Ok to return a row more than once */
  11253. #define WHERE_OMIT_OPEN_CLOSE 0x0010 /* Table cursors are already open */
  11254. #define WHERE_FORCE_TABLE 0x0020 /* Do not use an index-only search */
  11255. #define WHERE_ONETABLE_ONLY 0x0040 /* Only code the 1st table in pTabList */
  11256. /* 0x0080 // not currently used */
  11257. #define WHERE_GROUPBY 0x0100 /* pOrderBy is really a GROUP BY */
  11258. #define WHERE_DISTINCTBY 0x0200 /* pOrderby is really a DISTINCT clause */
  11259. #define WHERE_WANT_DISTINCT 0x0400 /* All output needs to be distinct */
  11260. #define WHERE_SORTBYGROUP 0x0800 /* Support sqlite3WhereIsSorted() */
  11261. #define WHERE_REOPEN_IDX 0x1000 /* Try to use OP_ReopenIdx */
  11262. /* Allowed return values from sqlite3WhereIsDistinct()
  11263. */
  11264. #define WHERE_DISTINCT_NOOP 0 /* DISTINCT keyword not used */
  11265. #define WHERE_DISTINCT_UNIQUE 1 /* No duplicates */
  11266. #define WHERE_DISTINCT_ORDERED 2 /* All duplicates are adjacent */
  11267. #define WHERE_DISTINCT_UNORDERED 3 /* Duplicates are scattered */
  11268. /*
  11269. ** A NameContext defines a context in which to resolve table and column
  11270. ** names. The context consists of a list of tables (the pSrcList) field and
  11271. ** a list of named expression (pEList). The named expression list may
  11272. ** be NULL. The pSrc corresponds to the FROM clause of a SELECT or
  11273. ** to the table being operated on by INSERT, UPDATE, or DELETE. The
  11274. ** pEList corresponds to the result set of a SELECT and is NULL for
  11275. ** other statements.
  11276. **
  11277. ** NameContexts can be nested. When resolving names, the inner-most
  11278. ** context is searched first. If no match is found, the next outer
  11279. ** context is checked. If there is still no match, the next context
  11280. ** is checked. This process continues until either a match is found
  11281. ** or all contexts are check. When a match is found, the nRef member of
  11282. ** the context containing the match is incremented.
  11283. **
  11284. ** Each subquery gets a new NameContext. The pNext field points to the
  11285. ** NameContext in the parent query. Thus the process of scanning the
  11286. ** NameContext list corresponds to searching through successively outer
  11287. ** subqueries looking for a match.
  11288. */
  11289. struct NameContext {
  11290. Parse *pParse; /* The parser */
  11291. SrcList *pSrcList; /* One or more tables used to resolve names */
  11292. ExprList *pEList; /* Optional list of result-set columns */
  11293. AggInfo *pAggInfo; /* Information about aggregates at this level */
  11294. NameContext *pNext; /* Next outer name context. NULL for outermost */
  11295. int nRef; /* Number of names resolved by this context */
  11296. int nErr; /* Number of errors encountered while resolving names */
  11297. u16 ncFlags; /* Zero or more NC_* flags defined below */
  11298. };
  11299. /*
  11300. ** Allowed values for the NameContext, ncFlags field.
  11301. **
  11302. ** Note: NC_MinMaxAgg must have the same value as SF_MinMaxAgg and
  11303. ** SQLITE_FUNC_MINMAX.
  11304. **
  11305. */
  11306. #define NC_AllowAgg 0x0001 /* Aggregate functions are allowed here */
  11307. #define NC_HasAgg 0x0002 /* One or more aggregate functions seen */
  11308. #define NC_IsCheck 0x0004 /* True if resolving names in a CHECK constraint */
  11309. #define NC_InAggFunc 0x0008 /* True if analyzing arguments to an agg func */
  11310. #define NC_PartIdx 0x0010 /* True if resolving a partial index WHERE */
  11311. #define NC_MinMaxAgg 0x1000 /* min/max aggregates seen. See note above */
  11312. /*
  11313. ** An instance of the following structure contains all information
  11314. ** needed to generate code for a single SELECT statement.
  11315. **
  11316. ** nLimit is set to -1 if there is no LIMIT clause. nOffset is set to 0.
  11317. ** If there is a LIMIT clause, the parser sets nLimit to the value of the
  11318. ** limit and nOffset to the value of the offset (or 0 if there is not
  11319. ** offset). But later on, nLimit and nOffset become the memory locations
  11320. ** in the VDBE that record the limit and offset counters.
  11321. **
  11322. ** addrOpenEphm[] entries contain the address of OP_OpenEphemeral opcodes.
  11323. ** These addresses must be stored so that we can go back and fill in
  11324. ** the P4_KEYINFO and P2 parameters later. Neither the KeyInfo nor
  11325. ** the number of columns in P2 can be computed at the same time
  11326. ** as the OP_OpenEphm instruction is coded because not
  11327. ** enough information about the compound query is known at that point.
  11328. ** The KeyInfo for addrOpenTran[0] and [1] contains collating sequences
  11329. ** for the result set. The KeyInfo for addrOpenEphm[2] contains collating
  11330. ** sequences for the ORDER BY clause.
  11331. */
  11332. struct Select {
  11333. ExprList *pEList; /* The fields of the result */
  11334. u8 op; /* One of: TK_UNION TK_ALL TK_INTERSECT TK_EXCEPT */
  11335. u16 selFlags; /* Various SF_* values */
  11336. int iLimit, iOffset; /* Memory registers holding LIMIT & OFFSET counters */
  11337. #if SELECTTRACE_ENABLED
  11338. char zSelName[12]; /* Symbolic name of this SELECT use for debugging */
  11339. #endif
  11340. int addrOpenEphm[2]; /* OP_OpenEphem opcodes related to this select */
  11341. u64 nSelectRow; /* Estimated number of result rows */
  11342. SrcList *pSrc; /* The FROM clause */
  11343. Expr *pWhere; /* The WHERE clause */
  11344. ExprList *pGroupBy; /* The GROUP BY clause */
  11345. Expr *pHaving; /* The HAVING clause */
  11346. ExprList *pOrderBy; /* The ORDER BY clause */
  11347. Select *pPrior; /* Prior select in a compound select statement */
  11348. Select *pNext; /* Next select to the left in a compound */
  11349. Expr *pLimit; /* LIMIT expression. NULL means not used. */
  11350. Expr *pOffset; /* OFFSET expression. NULL means not used. */
  11351. With *pWith; /* WITH clause attached to this select. Or NULL. */
  11352. };
  11353. /*
  11354. ** Allowed values for Select.selFlags. The "SF" prefix stands for
  11355. ** "Select Flag".
  11356. */
  11357. #define SF_Distinct 0x0001 /* Output should be DISTINCT */
  11358. #define SF_Resolved 0x0002 /* Identifiers have been resolved */
  11359. #define SF_Aggregate 0x0004 /* Contains aggregate functions */
  11360. #define SF_UsesEphemeral 0x0008 /* Uses the OpenEphemeral opcode */
  11361. #define SF_Expanded 0x0010 /* sqlite3SelectExpand() called on this */
  11362. #define SF_HasTypeInfo 0x0020 /* FROM subqueries have Table metadata */
  11363. #define SF_Compound 0x0040 /* Part of a compound query */
  11364. #define SF_Values 0x0080 /* Synthesized from VALUES clause */
  11365. /* 0x0100 NOT USED */
  11366. #define SF_NestedFrom 0x0200 /* Part of a parenthesized FROM clause */
  11367. #define SF_MaybeConvert 0x0400 /* Need convertCompoundSelectToSubquery() */
  11368. #define SF_Recursive 0x0800 /* The recursive part of a recursive CTE */
  11369. #define SF_MinMaxAgg 0x1000 /* Aggregate containing min() or max() */
  11370. /*
  11371. ** The results of a SELECT can be distributed in several ways, as defined
  11372. ** by one of the following macros. The "SRT" prefix means "SELECT Result
  11373. ** Type".
  11374. **
  11375. ** SRT_Union Store results as a key in a temporary index
  11376. ** identified by pDest->iSDParm.
  11377. **
  11378. ** SRT_Except Remove results from the temporary index pDest->iSDParm.
  11379. **
  11380. ** SRT_Exists Store a 1 in memory cell pDest->iSDParm if the result
  11381. ** set is not empty.
  11382. **
  11383. ** SRT_Discard Throw the results away. This is used by SELECT
  11384. ** statements within triggers whose only purpose is
  11385. ** the side-effects of functions.
  11386. **
  11387. ** All of the above are free to ignore their ORDER BY clause. Those that
  11388. ** follow must honor the ORDER BY clause.
  11389. **
  11390. ** SRT_Output Generate a row of output (using the OP_ResultRow
  11391. ** opcode) for each row in the result set.
  11392. **
  11393. ** SRT_Mem Only valid if the result is a single column.
  11394. ** Store the first column of the first result row
  11395. ** in register pDest->iSDParm then abandon the rest
  11396. ** of the query. This destination implies "LIMIT 1".
  11397. **
  11398. ** SRT_Set The result must be a single column. Store each
  11399. ** row of result as the key in table pDest->iSDParm.
  11400. ** Apply the affinity pDest->affSdst before storing
  11401. ** results. Used to implement "IN (SELECT ...)".
  11402. **
  11403. ** SRT_EphemTab Create an temporary table pDest->iSDParm and store
  11404. ** the result there. The cursor is left open after
  11405. ** returning. This is like SRT_Table except that
  11406. ** this destination uses OP_OpenEphemeral to create
  11407. ** the table first.
  11408. **
  11409. ** SRT_Coroutine Generate a co-routine that returns a new row of
  11410. ** results each time it is invoked. The entry point
  11411. ** of the co-routine is stored in register pDest->iSDParm
  11412. ** and the result row is stored in pDest->nDest registers
  11413. ** starting with pDest->iSdst.
  11414. **
  11415. ** SRT_Table Store results in temporary table pDest->iSDParm.
  11416. ** SRT_Fifo This is like SRT_EphemTab except that the table
  11417. ** is assumed to already be open. SRT_Fifo has
  11418. ** the additional property of being able to ignore
  11419. ** the ORDER BY clause.
  11420. **
  11421. ** SRT_DistFifo Store results in a temporary table pDest->iSDParm.
  11422. ** But also use temporary table pDest->iSDParm+1 as
  11423. ** a record of all prior results and ignore any duplicate
  11424. ** rows. Name means: "Distinct Fifo".
  11425. **
  11426. ** SRT_Queue Store results in priority queue pDest->iSDParm (really
  11427. ** an index). Append a sequence number so that all entries
  11428. ** are distinct.
  11429. **
  11430. ** SRT_DistQueue Store results in priority queue pDest->iSDParm only if
  11431. ** the same record has never been stored before. The
  11432. ** index at pDest->iSDParm+1 hold all prior stores.
  11433. */
  11434. #define SRT_Union 1 /* Store result as keys in an index */
  11435. #define SRT_Except 2 /* Remove result from a UNION index */
  11436. #define SRT_Exists 3 /* Store 1 if the result is not empty */
  11437. #define SRT_Discard 4 /* Do not save the results anywhere */
  11438. #define SRT_Fifo 5 /* Store result as data with an automatic rowid */
  11439. #define SRT_DistFifo 6 /* Like SRT_Fifo, but unique results only */
  11440. #define SRT_Queue 7 /* Store result in an queue */
  11441. #define SRT_DistQueue 8 /* Like SRT_Queue, but unique results only */
  11442. /* The ORDER BY clause is ignored for all of the above */
  11443. #define IgnorableOrderby(X) ((X->eDest)<=SRT_DistQueue)
  11444. #define SRT_Output 9 /* Output each row of result */
  11445. #define SRT_Mem 10 /* Store result in a memory cell */
  11446. #define SRT_Set 11 /* Store results as keys in an index */
  11447. #define SRT_EphemTab 12 /* Create transient tab and store like SRT_Table */
  11448. #define SRT_Coroutine 13 /* Generate a single row of result */
  11449. #define SRT_Table 14 /* Store result as data with an automatic rowid */
  11450. /*
  11451. ** An instance of this object describes where to put of the results of
  11452. ** a SELECT statement.
  11453. */
  11454. struct SelectDest {
  11455. u8 eDest; /* How to dispose of the results. On of SRT_* above. */
  11456. char affSdst; /* Affinity used when eDest==SRT_Set */
  11457. int iSDParm; /* A parameter used by the eDest disposal method */
  11458. int iSdst; /* Base register where results are written */
  11459. int nSdst; /* Number of registers allocated */
  11460. ExprList *pOrderBy; /* Key columns for SRT_Queue and SRT_DistQueue */
  11461. };
  11462. /*
  11463. ** During code generation of statements that do inserts into AUTOINCREMENT
  11464. ** tables, the following information is attached to the Table.u.autoInc.p
  11465. ** pointer of each autoincrement table to record some side information that
  11466. ** the code generator needs. We have to keep per-table autoincrement
  11467. ** information in case inserts are down within triggers. Triggers do not
  11468. ** normally coordinate their activities, but we do need to coordinate the
  11469. ** loading and saving of autoincrement information.
  11470. */
  11471. struct AutoincInfo {
  11472. AutoincInfo *pNext; /* Next info block in a list of them all */
  11473. Table *pTab; /* Table this info block refers to */
  11474. int iDb; /* Index in sqlite3.aDb[] of database holding pTab */
  11475. int regCtr; /* Memory register holding the rowid counter */
  11476. };
  11477. /*
  11478. ** Size of the column cache
  11479. */
  11480. #ifndef SQLITE_N_COLCACHE
  11481. # define SQLITE_N_COLCACHE 10
  11482. #endif
  11483. /*
  11484. ** At least one instance of the following structure is created for each
  11485. ** trigger that may be fired while parsing an INSERT, UPDATE or DELETE
  11486. ** statement. All such objects are stored in the linked list headed at
  11487. ** Parse.pTriggerPrg and deleted once statement compilation has been
  11488. ** completed.
  11489. **
  11490. ** A Vdbe sub-program that implements the body and WHEN clause of trigger
  11491. ** TriggerPrg.pTrigger, assuming a default ON CONFLICT clause of
  11492. ** TriggerPrg.orconf, is stored in the TriggerPrg.pProgram variable.
  11493. ** The Parse.pTriggerPrg list never contains two entries with the same
  11494. ** values for both pTrigger and orconf.
  11495. **
  11496. ** The TriggerPrg.aColmask[0] variable is set to a mask of old.* columns
  11497. ** accessed (or set to 0 for triggers fired as a result of INSERT
  11498. ** statements). Similarly, the TriggerPrg.aColmask[1] variable is set to
  11499. ** a mask of new.* columns used by the program.
  11500. */
  11501. struct TriggerPrg {
  11502. Trigger *pTrigger; /* Trigger this program was coded from */
  11503. TriggerPrg *pNext; /* Next entry in Parse.pTriggerPrg list */
  11504. SubProgram *pProgram; /* Program implementing pTrigger/orconf */
  11505. int orconf; /* Default ON CONFLICT policy */
  11506. u32 aColmask[2]; /* Masks of old.*, new.* columns accessed */
  11507. };
  11508. /*
  11509. ** The yDbMask datatype for the bitmask of all attached databases.
  11510. */
  11511. #if SQLITE_MAX_ATTACHED>30
  11512. typedef unsigned char yDbMask[(SQLITE_MAX_ATTACHED+9)/8];
  11513. # define DbMaskTest(M,I) (((M)[(I)/8]&(1<<((I)&7)))!=0)
  11514. # define DbMaskZero(M) memset((M),0,sizeof(M))
  11515. # define DbMaskSet(M,I) (M)[(I)/8]|=(1<<((I)&7))
  11516. # define DbMaskAllZero(M) sqlite3DbMaskAllZero(M)
  11517. # define DbMaskNonZero(M) (sqlite3DbMaskAllZero(M)==0)
  11518. #else
  11519. typedef unsigned int yDbMask;
  11520. # define DbMaskTest(M,I) (((M)&(((yDbMask)1)<<(I)))!=0)
  11521. # define DbMaskZero(M) (M)=0
  11522. # define DbMaskSet(M,I) (M)|=(((yDbMask)1)<<(I))
  11523. # define DbMaskAllZero(M) (M)==0
  11524. # define DbMaskNonZero(M) (M)!=0
  11525. #endif
  11526. /*
  11527. ** An SQL parser context. A copy of this structure is passed through
  11528. ** the parser and down into all the parser action routine in order to
  11529. ** carry around information that is global to the entire parse.
  11530. **
  11531. ** The structure is divided into two parts. When the parser and code
  11532. ** generate call themselves recursively, the first part of the structure
  11533. ** is constant but the second part is reset at the beginning and end of
  11534. ** each recursion.
  11535. **
  11536. ** The nTableLock and aTableLock variables are only used if the shared-cache
  11537. ** feature is enabled (if sqlite3Tsd()->useSharedData is true). They are
  11538. ** used to store the set of table-locks required by the statement being
  11539. ** compiled. Function sqlite3TableLock() is used to add entries to the
  11540. ** list.
  11541. */
  11542. struct Parse {
  11543. sqlite3 *db; /* The main database structure */
  11544. char *zErrMsg; /* An error message */
  11545. Vdbe *pVdbe; /* An engine for executing database bytecode */
  11546. int rc; /* Return code from execution */
  11547. u8 colNamesSet; /* TRUE after OP_ColumnName has been issued to pVdbe */
  11548. u8 checkSchema; /* Causes schema cookie check after an error */
  11549. u8 nested; /* Number of nested calls to the parser/code generator */
  11550. u8 nTempReg; /* Number of temporary registers in aTempReg[] */
  11551. u8 isMultiWrite; /* True if statement may modify/insert multiple rows */
  11552. u8 mayAbort; /* True if statement may throw an ABORT exception */
  11553. u8 hasCompound; /* Need to invoke convertCompoundSelectToSubquery() */
  11554. u8 okConstFactor; /* OK to factor out constants */
  11555. int aTempReg[8]; /* Holding area for temporary registers */
  11556. int nRangeReg; /* Size of the temporary register block */
  11557. int iRangeReg; /* First register in temporary register block */
  11558. int nErr; /* Number of errors seen */
  11559. int nTab; /* Number of previously allocated VDBE cursors */
  11560. int nMem; /* Number of memory cells used so far */
  11561. int nSet; /* Number of sets used so far */
  11562. int nOnce; /* Number of OP_Once instructions so far */
  11563. int nOpAlloc; /* Number of slots allocated for Vdbe.aOp[] */
  11564. int iFixedOp; /* Never back out opcodes iFixedOp-1 or earlier */
  11565. int ckBase; /* Base register of data during check constraints */
  11566. int iPartIdxTab; /* Table corresponding to a partial index */
  11567. int iCacheLevel; /* ColCache valid when aColCache[].iLevel<=iCacheLevel */
  11568. int iCacheCnt; /* Counter used to generate aColCache[].lru values */
  11569. int nLabel; /* Number of labels used */
  11570. int *aLabel; /* Space to hold the labels */
  11571. struct yColCache {
  11572. int iTable; /* Table cursor number */
  11573. i16 iColumn; /* Table column number */
  11574. u8 tempReg; /* iReg is a temp register that needs to be freed */
  11575. int iLevel; /* Nesting level */
  11576. int iReg; /* Reg with value of this column. 0 means none. */
  11577. int lru; /* Least recently used entry has the smallest value */
  11578. } aColCache[SQLITE_N_COLCACHE]; /* One for each column cache entry */
  11579. ExprList *pConstExpr;/* Constant expressions */
  11580. Token constraintName;/* Name of the constraint currently being parsed */
  11581. yDbMask writeMask; /* Start a write transaction on these databases */
  11582. yDbMask cookieMask; /* Bitmask of schema verified databases */
  11583. int cookieValue[SQLITE_MAX_ATTACHED+2]; /* Values of cookies to verify */
  11584. int regRowid; /* Register holding rowid of CREATE TABLE entry */
  11585. int regRoot; /* Register holding root page number for new objects */
  11586. int nMaxArg; /* Max args passed to user function by sub-program */
  11587. #if SELECTTRACE_ENABLED
  11588. int nSelect; /* Number of SELECT statements seen */
  11589. int nSelectIndent; /* How far to indent SELECTTRACE() output */
  11590. #endif
  11591. #ifndef SQLITE_OMIT_SHARED_CACHE
  11592. int nTableLock; /* Number of locks in aTableLock */
  11593. TableLock *aTableLock; /* Required table locks for shared-cache mode */
  11594. #endif
  11595. AutoincInfo *pAinc; /* Information about AUTOINCREMENT counters */
  11596. /* Information used while coding trigger programs. */
  11597. Parse *pToplevel; /* Parse structure for main program (or NULL) */
  11598. Table *pTriggerTab; /* Table triggers are being coded for */
  11599. int addrCrTab; /* Address of OP_CreateTable opcode on CREATE TABLE */
  11600. int addrSkipPK; /* Address of instruction to skip PRIMARY KEY index */
  11601. u32 nQueryLoop; /* Est number of iterations of a query (10*log2(N)) */
  11602. u32 oldmask; /* Mask of old.* columns referenced */
  11603. u32 newmask; /* Mask of new.* columns referenced */
  11604. u8 eTriggerOp; /* TK_UPDATE, TK_INSERT or TK_DELETE */
  11605. u8 eOrconf; /* Default ON CONFLICT policy for trigger steps */
  11606. u8 disableTriggers; /* True to disable triggers */
  11607. /************************************************************************
  11608. ** Above is constant between recursions. Below is reset before and after
  11609. ** each recursion. The boundary between these two regions is determined
  11610. ** using offsetof(Parse,nVar) so the nVar field must be the first field
  11611. ** in the recursive region.
  11612. ************************************************************************/
  11613. int nVar; /* Number of '?' variables seen in the SQL so far */
  11614. int nzVar; /* Number of available slots in azVar[] */
  11615. u8 iPkSortOrder; /* ASC or DESC for INTEGER PRIMARY KEY */
  11616. u8 bFreeWith; /* True if pWith should be freed with parser */
  11617. u8 explain; /* True if the EXPLAIN flag is found on the query */
  11618. #ifndef SQLITE_OMIT_VIRTUALTABLE
  11619. u8 declareVtab; /* True if inside sqlite3_declare_vtab() */
  11620. int nVtabLock; /* Number of virtual tables to lock */
  11621. #endif
  11622. int nAlias; /* Number of aliased result set columns */
  11623. int nHeight; /* Expression tree height of current sub-select */
  11624. #ifndef SQLITE_OMIT_EXPLAIN
  11625. int iSelectId; /* ID of current select for EXPLAIN output */
  11626. int iNextSelectId; /* Next available select ID for EXPLAIN output */
  11627. #endif
  11628. char **azVar; /* Pointers to names of parameters */
  11629. Vdbe *pReprepare; /* VM being reprepared (sqlite3Reprepare()) */
  11630. const char *zTail; /* All SQL text past the last semicolon parsed */
  11631. Table *pNewTable; /* A table being constructed by CREATE TABLE */
  11632. Trigger *pNewTrigger; /* Trigger under construct by a CREATE TRIGGER */
  11633. const char *zAuthContext; /* The 6th parameter to db->xAuth callbacks */
  11634. Token sNameToken; /* Token with unqualified schema object name */
  11635. Token sLastToken; /* The last token parsed */
  11636. #ifndef SQLITE_OMIT_VIRTUALTABLE
  11637. Token sArg; /* Complete text of a module argument */
  11638. Table **apVtabLock; /* Pointer to virtual tables needing locking */
  11639. #endif
  11640. Table *pZombieTab; /* List of Table objects to delete after code gen */
  11641. TriggerPrg *pTriggerPrg; /* Linked list of coded triggers */
  11642. With *pWith; /* Current WITH clause, or NULL */
  11643. };
  11644. /*
  11645. ** Return true if currently inside an sqlite3_declare_vtab() call.
  11646. */
  11647. #ifdef SQLITE_OMIT_VIRTUALTABLE
  11648. #define IN_DECLARE_VTAB 0
  11649. #else
  11650. #define IN_DECLARE_VTAB (pParse->declareVtab)
  11651. #endif
  11652. /*
  11653. ** An instance of the following structure can be declared on a stack and used
  11654. ** to save the Parse.zAuthContext value so that it can be restored later.
  11655. */
  11656. struct AuthContext {
  11657. const char *zAuthContext; /* Put saved Parse.zAuthContext here */
  11658. Parse *pParse; /* The Parse structure */
  11659. };
  11660. /*
  11661. ** Bitfield flags for P5 value in various opcodes.
  11662. */
  11663. #define OPFLAG_NCHANGE 0x01 /* Set to update db->nChange */
  11664. #define OPFLAG_EPHEM 0x01 /* OP_Column: Ephemeral output is ok */
  11665. #define OPFLAG_LASTROWID 0x02 /* Set to update db->lastRowid */
  11666. #define OPFLAG_ISUPDATE 0x04 /* This OP_Insert is an sql UPDATE */
  11667. #define OPFLAG_APPEND 0x08 /* This is likely to be an append */
  11668. #define OPFLAG_USESEEKRESULT 0x10 /* Try to avoid a seek in BtreeInsert() */
  11669. #define OPFLAG_LENGTHARG 0x40 /* OP_Column only used for length() */
  11670. #define OPFLAG_TYPEOFARG 0x80 /* OP_Column only used for typeof() */
  11671. #define OPFLAG_BULKCSR 0x01 /* OP_Open** used to open bulk cursor */
  11672. #define OPFLAG_P2ISREG 0x02 /* P2 to OP_Open** is a register number */
  11673. #define OPFLAG_PERMUTE 0x01 /* OP_Compare: use the permutation */
  11674. /*
  11675. * Each trigger present in the database schema is stored as an instance of
  11676. * struct Trigger.
  11677. *
  11678. * Pointers to instances of struct Trigger are stored in two ways.
  11679. * 1. In the "trigHash" hash table (part of the sqlite3* that represents the
  11680. * database). This allows Trigger structures to be retrieved by name.
  11681. * 2. All triggers associated with a single table form a linked list, using the
  11682. * pNext member of struct Trigger. A pointer to the first element of the
  11683. * linked list is stored as the "pTrigger" member of the associated
  11684. * struct Table.
  11685. *
  11686. * The "step_list" member points to the first element of a linked list
  11687. * containing the SQL statements specified as the trigger program.
  11688. */
  11689. struct Trigger {
  11690. char *zName; /* The name of the trigger */
  11691. char *table; /* The table or view to which the trigger applies */
  11692. u8 op; /* One of TK_DELETE, TK_UPDATE, TK_INSERT */
  11693. u8 tr_tm; /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
  11694. Expr *pWhen; /* The WHEN clause of the expression (may be NULL) */
  11695. IdList *pColumns; /* If this is an UPDATE OF <column-list> trigger,
  11696. the <column-list> is stored here */
  11697. Schema *pSchema; /* Schema containing the trigger */
  11698. Schema *pTabSchema; /* Schema containing the table */
  11699. TriggerStep *step_list; /* Link list of trigger program steps */
  11700. Trigger *pNext; /* Next trigger associated with the table */
  11701. };
  11702. /*
  11703. ** A trigger is either a BEFORE or an AFTER trigger. The following constants
  11704. ** determine which.
  11705. **
  11706. ** If there are multiple triggers, you might of some BEFORE and some AFTER.
  11707. ** In that cases, the constants below can be ORed together.
  11708. */
  11709. #define TRIGGER_BEFORE 1
  11710. #define TRIGGER_AFTER 2
  11711. /*
  11712. * An instance of struct TriggerStep is used to store a single SQL statement
  11713. * that is a part of a trigger-program.
  11714. *
  11715. * Instances of struct TriggerStep are stored in a singly linked list (linked
  11716. * using the "pNext" member) referenced by the "step_list" member of the
  11717. * associated struct Trigger instance. The first element of the linked list is
  11718. * the first step of the trigger-program.
  11719. *
  11720. * The "op" member indicates whether this is a "DELETE", "INSERT", "UPDATE" or
  11721. * "SELECT" statement. The meanings of the other members is determined by the
  11722. * value of "op" as follows:
  11723. *
  11724. * (op == TK_INSERT)
  11725. * orconf -> stores the ON CONFLICT algorithm
  11726. * pSelect -> If this is an INSERT INTO ... SELECT ... statement, then
  11727. * this stores a pointer to the SELECT statement. Otherwise NULL.
  11728. * target -> A token holding the quoted name of the table to insert into.
  11729. * pExprList -> If this is an INSERT INTO ... VALUES ... statement, then
  11730. * this stores values to be inserted. Otherwise NULL.
  11731. * pIdList -> If this is an INSERT INTO ... (<column-names>) VALUES ...
  11732. * statement, then this stores the column-names to be
  11733. * inserted into.
  11734. *
  11735. * (op == TK_DELETE)
  11736. * target -> A token holding the quoted name of the table to delete from.
  11737. * pWhere -> The WHERE clause of the DELETE statement if one is specified.
  11738. * Otherwise NULL.
  11739. *
  11740. * (op == TK_UPDATE)
  11741. * target -> A token holding the quoted name of the table to update rows of.
  11742. * pWhere -> The WHERE clause of the UPDATE statement if one is specified.
  11743. * Otherwise NULL.
  11744. * pExprList -> A list of the columns to update and the expressions to update
  11745. * them to. See sqlite3Update() documentation of "pChanges"
  11746. * argument.
  11747. *
  11748. */
  11749. struct TriggerStep {
  11750. u8 op; /* One of TK_DELETE, TK_UPDATE, TK_INSERT, TK_SELECT */
  11751. u8 orconf; /* OE_Rollback etc. */
  11752. Trigger *pTrig; /* The trigger that this step is a part of */
  11753. Select *pSelect; /* SELECT statment or RHS of INSERT INTO .. SELECT ... */
  11754. Token target; /* Target table for DELETE, UPDATE, INSERT */
  11755. Expr *pWhere; /* The WHERE clause for DELETE or UPDATE steps */
  11756. ExprList *pExprList; /* SET clause for UPDATE. */
  11757. IdList *pIdList; /* Column names for INSERT */
  11758. TriggerStep *pNext; /* Next in the link-list */
  11759. TriggerStep *pLast; /* Last element in link-list. Valid for 1st elem only */
  11760. };
  11761. /*
  11762. ** The following structure contains information used by the sqliteFix...
  11763. ** routines as they walk the parse tree to make database references
  11764. ** explicit.
  11765. */
  11766. typedef struct DbFixer DbFixer;
  11767. struct DbFixer {
  11768. Parse *pParse; /* The parsing context. Error messages written here */
  11769. Schema *pSchema; /* Fix items to this schema */
  11770. int bVarOnly; /* Check for variable references only */
  11771. const char *zDb; /* Make sure all objects are contained in this database */
  11772. const char *zType; /* Type of the container - used for error messages */
  11773. const Token *pName; /* Name of the container - used for error messages */
  11774. };
  11775. /*
  11776. ** An objected used to accumulate the text of a string where we
  11777. ** do not necessarily know how big the string will be in the end.
  11778. */
  11779. struct StrAccum {
  11780. sqlite3 *db; /* Optional database for lookaside. Can be NULL */
  11781. char *zBase; /* A base allocation. Not from malloc. */
  11782. char *zText; /* The string collected so far */
  11783. int nChar; /* Length of the string so far */
  11784. int nAlloc; /* Amount of space allocated in zText */
  11785. int mxAlloc; /* Maximum allowed string length */
  11786. u8 useMalloc; /* 0: none, 1: sqlite3DbMalloc, 2: sqlite3_malloc */
  11787. u8 accError; /* STRACCUM_NOMEM or STRACCUM_TOOBIG */
  11788. };
  11789. #define STRACCUM_NOMEM 1
  11790. #define STRACCUM_TOOBIG 2
  11791. /*
  11792. ** A pointer to this structure is used to communicate information
  11793. ** from sqlite3Init and OP_ParseSchema into the sqlite3InitCallback.
  11794. */
  11795. typedef struct {
  11796. sqlite3 *db; /* The database being initialized */
  11797. char **pzErrMsg; /* Error message stored here */
  11798. int iDb; /* 0 for main database. 1 for TEMP, 2.. for ATTACHed */
  11799. int rc; /* Result code stored here */
  11800. } InitData;
  11801. /*
  11802. ** Structure containing global configuration data for the SQLite library.
  11803. **
  11804. ** This structure also contains some state information.
  11805. */
  11806. struct Sqlite3Config {
  11807. int bMemstat; /* True to enable memory status */
  11808. int bCoreMutex; /* True to enable core mutexing */
  11809. int bFullMutex; /* True to enable full mutexing */
  11810. int bOpenUri; /* True to interpret filenames as URIs */
  11811. int bUseCis; /* Use covering indices for full-scans */
  11812. int mxStrlen; /* Maximum string length */
  11813. int neverCorrupt; /* Database is always well-formed */
  11814. int szLookaside; /* Default lookaside buffer size */
  11815. int nLookaside; /* Default lookaside buffer count */
  11816. sqlite3_mem_methods m; /* Low-level memory allocation interface */
  11817. sqlite3_mutex_methods mutex; /* Low-level mutex interface */
  11818. sqlite3_pcache_methods2 pcache2; /* Low-level page-cache interface */
  11819. void *pHeap; /* Heap storage space */
  11820. int nHeap; /* Size of pHeap[] */
  11821. int mnReq, mxReq; /* Min and max heap requests sizes */
  11822. sqlite3_int64 szMmap; /* mmap() space per open file */
  11823. sqlite3_int64 mxMmap; /* Maximum value for szMmap */
  11824. void *pScratch; /* Scratch memory */
  11825. int szScratch; /* Size of each scratch buffer */
  11826. int nScratch; /* Number of scratch buffers */
  11827. void *pPage; /* Page cache memory */
  11828. int szPage; /* Size of each page in pPage[] */
  11829. int nPage; /* Number of pages in pPage[] */
  11830. int mxParserStack; /* maximum depth of the parser stack */
  11831. int sharedCacheEnabled; /* true if shared-cache mode enabled */
  11832. /* The above might be initialized to non-zero. The following need to always
  11833. ** initially be zero, however. */
  11834. int isInit; /* True after initialization has finished */
  11835. int inProgress; /* True while initialization in progress */
  11836. int isMutexInit; /* True after mutexes are initialized */
  11837. int isMallocInit; /* True after malloc is initialized */
  11838. int isPCacheInit; /* True after malloc is initialized */
  11839. int nRefInitMutex; /* Number of users of pInitMutex */
  11840. sqlite3_mutex *pInitMutex; /* Mutex used by sqlite3_initialize() */
  11841. void (*xLog)(void*,int,const char*); /* Function for logging */
  11842. void *pLogArg; /* First argument to xLog() */
  11843. #ifdef SQLITE_ENABLE_SQLLOG
  11844. void(*xSqllog)(void*,sqlite3*,const char*, int);
  11845. void *pSqllogArg;
  11846. #endif
  11847. #ifdef SQLITE_VDBE_COVERAGE
  11848. /* The following callback (if not NULL) is invoked on every VDBE branch
  11849. ** operation. Set the callback using SQLITE_TESTCTRL_VDBE_COVERAGE.
  11850. */
  11851. void (*xVdbeBranch)(void*,int iSrcLine,u8 eThis,u8 eMx); /* Callback */
  11852. void *pVdbeBranchArg; /* 1st argument */
  11853. #endif
  11854. #ifndef SQLITE_OMIT_BUILTIN_TEST
  11855. int (*xTestCallback)(int); /* Invoked by sqlite3FaultSim() */
  11856. #endif
  11857. int bLocaltimeFault; /* True to fail localtime() calls */
  11858. };
  11859. /*
  11860. ** This macro is used inside of assert() statements to indicate that
  11861. ** the assert is only valid on a well-formed database. Instead of:
  11862. **
  11863. ** assert( X );
  11864. **
  11865. ** One writes:
  11866. **
  11867. ** assert( X || CORRUPT_DB );
  11868. **
  11869. ** CORRUPT_DB is true during normal operation. CORRUPT_DB does not indicate
  11870. ** that the database is definitely corrupt, only that it might be corrupt.
  11871. ** For most test cases, CORRUPT_DB is set to false using a special
  11872. ** sqlite3_test_control(). This enables assert() statements to prove
  11873. ** things that are always true for well-formed databases.
  11874. */
  11875. #define CORRUPT_DB (sqlite3Config.neverCorrupt==0)
  11876. /*
  11877. ** Context pointer passed down through the tree-walk.
  11878. */
  11879. struct Walker {
  11880. int (*xExprCallback)(Walker*, Expr*); /* Callback for expressions */
  11881. int (*xSelectCallback)(Walker*,Select*); /* Callback for SELECTs */
  11882. void (*xSelectCallback2)(Walker*,Select*);/* Second callback for SELECTs */
  11883. Parse *pParse; /* Parser context. */
  11884. int walkerDepth; /* Number of subqueries */
  11885. u8 eCode; /* A small processing code */
  11886. union { /* Extra data for callback */
  11887. NameContext *pNC; /* Naming context */
  11888. int n; /* A counter */
  11889. int iCur; /* A cursor number */
  11890. SrcList *pSrcList; /* FROM clause */
  11891. struct SrcCount *pSrcCount; /* Counting column references */
  11892. } u;
  11893. };
  11894. /* Forward declarations */
  11895. SQLITE_PRIVATE int sqlite3WalkExpr(Walker*, Expr*);
  11896. SQLITE_PRIVATE int sqlite3WalkExprList(Walker*, ExprList*);
  11897. SQLITE_PRIVATE int sqlite3WalkSelect(Walker*, Select*);
  11898. SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker*, Select*);
  11899. SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker*, Select*);
  11900. /*
  11901. ** Return code from the parse-tree walking primitives and their
  11902. ** callbacks.
  11903. */
  11904. #define WRC_Continue 0 /* Continue down into children */
  11905. #define WRC_Prune 1 /* Omit children but continue walking siblings */
  11906. #define WRC_Abort 2 /* Abandon the tree walk */
  11907. /*
  11908. ** An instance of this structure represents a set of one or more CTEs
  11909. ** (common table expressions) created by a single WITH clause.
  11910. */
  11911. struct With {
  11912. int nCte; /* Number of CTEs in the WITH clause */
  11913. With *pOuter; /* Containing WITH clause, or NULL */
  11914. struct Cte { /* For each CTE in the WITH clause.... */
  11915. char *zName; /* Name of this CTE */
  11916. ExprList *pCols; /* List of explicit column names, or NULL */
  11917. Select *pSelect; /* The definition of this CTE */
  11918. const char *zErr; /* Error message for circular references */
  11919. } a[1];
  11920. };
  11921. #ifdef SQLITE_DEBUG
  11922. /*
  11923. ** An instance of the TreeView object is used for printing the content of
  11924. ** data structures on sqlite3DebugPrintf() using a tree-like view.
  11925. */
  11926. struct TreeView {
  11927. int iLevel; /* Which level of the tree we are on */
  11928. u8 bLine[100]; /* Draw vertical in column i if bLine[i] is true */
  11929. };
  11930. #endif /* SQLITE_DEBUG */
  11931. /*
  11932. ** Assuming zIn points to the first byte of a UTF-8 character,
  11933. ** advance zIn to point to the first byte of the next UTF-8 character.
  11934. */
  11935. #define SQLITE_SKIP_UTF8(zIn) { \
  11936. if( (*(zIn++))>=0xc0 ){ \
  11937. while( (*zIn & 0xc0)==0x80 ){ zIn++; } \
  11938. } \
  11939. }
  11940. /*
  11941. ** The SQLITE_*_BKPT macros are substitutes for the error codes with
  11942. ** the same name but without the _BKPT suffix. These macros invoke
  11943. ** routines that report the line-number on which the error originated
  11944. ** using sqlite3_log(). The routines also provide a convenient place
  11945. ** to set a debugger breakpoint.
  11946. */
  11947. SQLITE_PRIVATE int sqlite3CorruptError(int);
  11948. SQLITE_PRIVATE int sqlite3MisuseError(int);
  11949. SQLITE_PRIVATE int sqlite3CantopenError(int);
  11950. #define SQLITE_CORRUPT_BKPT sqlite3CorruptError(__LINE__)
  11951. #define SQLITE_MISUSE_BKPT sqlite3MisuseError(__LINE__)
  11952. #define SQLITE_CANTOPEN_BKPT sqlite3CantopenError(__LINE__)
  11953. /*
  11954. ** FTS4 is really an extension for FTS3. It is enabled using the
  11955. ** SQLITE_ENABLE_FTS3 macro. But to avoid confusion we also call
  11956. ** the SQLITE_ENABLE_FTS4 macro to serve as an alias for SQLITE_ENABLE_FTS3.
  11957. */
  11958. #if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3)
  11959. # define SQLITE_ENABLE_FTS3
  11960. #endif
  11961. /*
  11962. ** The ctype.h header is needed for non-ASCII systems. It is also
  11963. ** needed by FTS3 when FTS3 is included in the amalgamation.
  11964. */
  11965. #if !defined(SQLITE_ASCII) || \
  11966. (defined(SQLITE_ENABLE_FTS3) && defined(SQLITE_AMALGAMATION))
  11967. # include <ctype.h>
  11968. #endif
  11969. /*
  11970. ** The following macros mimic the standard library functions toupper(),
  11971. ** isspace(), isalnum(), isdigit() and isxdigit(), respectively. The
  11972. ** sqlite versions only work for ASCII characters, regardless of locale.
  11973. */
  11974. #ifdef SQLITE_ASCII
  11975. # define sqlite3Toupper(x) ((x)&~(sqlite3CtypeMap[(unsigned char)(x)]&0x20))
  11976. # define sqlite3Isspace(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x01)
  11977. # define sqlite3Isalnum(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x06)
  11978. # define sqlite3Isalpha(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x02)
  11979. # define sqlite3Isdigit(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x04)
  11980. # define sqlite3Isxdigit(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x08)
  11981. # define sqlite3Tolower(x) (sqlite3UpperToLower[(unsigned char)(x)])
  11982. #else
  11983. # define sqlite3Toupper(x) toupper((unsigned char)(x))
  11984. # define sqlite3Isspace(x) isspace((unsigned char)(x))
  11985. # define sqlite3Isalnum(x) isalnum((unsigned char)(x))
  11986. # define sqlite3Isalpha(x) isalpha((unsigned char)(x))
  11987. # define sqlite3Isdigit(x) isdigit((unsigned char)(x))
  11988. # define sqlite3Isxdigit(x) isxdigit((unsigned char)(x))
  11989. # define sqlite3Tolower(x) tolower((unsigned char)(x))
  11990. #endif
  11991. SQLITE_PRIVATE int sqlite3IsIdChar(u8);
  11992. /*
  11993. ** Internal function prototypes
  11994. */
  11995. #define sqlite3StrICmp sqlite3_stricmp
  11996. SQLITE_PRIVATE int sqlite3Strlen30(const char*);
  11997. #define sqlite3StrNICmp sqlite3_strnicmp
  11998. SQLITE_PRIVATE int sqlite3MallocInit(void);
  11999. SQLITE_PRIVATE void sqlite3MallocEnd(void);
  12000. SQLITE_PRIVATE void *sqlite3Malloc(u64);
  12001. SQLITE_PRIVATE void *sqlite3MallocZero(u64);
  12002. SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3*, u64);
  12003. SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3*, u64);
  12004. SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3*,const char*);
  12005. SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3*,const char*, u64);
  12006. SQLITE_PRIVATE void *sqlite3Realloc(void*, u64);
  12007. SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *, void *, u64);
  12008. SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *, void *, u64);
  12009. SQLITE_PRIVATE void sqlite3DbFree(sqlite3*, void*);
  12010. SQLITE_PRIVATE int sqlite3MallocSize(void*);
  12011. SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3*, void*);
  12012. SQLITE_PRIVATE void *sqlite3ScratchMalloc(int);
  12013. SQLITE_PRIVATE void sqlite3ScratchFree(void*);
  12014. SQLITE_PRIVATE void *sqlite3PageMalloc(int);
  12015. SQLITE_PRIVATE void sqlite3PageFree(void*);
  12016. SQLITE_PRIVATE void sqlite3MemSetDefault(void);
  12017. SQLITE_PRIVATE void sqlite3BenignMallocHooks(void (*)(void), void (*)(void));
  12018. SQLITE_PRIVATE int sqlite3HeapNearlyFull(void);
  12019. /*
  12020. ** On systems with ample stack space and that support alloca(), make
  12021. ** use of alloca() to obtain space for large automatic objects. By default,
  12022. ** obtain space from malloc().
  12023. **
  12024. ** The alloca() routine never returns NULL. This will cause code paths
  12025. ** that deal with sqlite3StackAlloc() failures to be unreachable.
  12026. */
  12027. #ifdef SQLITE_USE_ALLOCA
  12028. # define sqlite3StackAllocRaw(D,N) alloca(N)
  12029. # define sqlite3StackAllocZero(D,N) memset(alloca(N), 0, N)
  12030. # define sqlite3StackFree(D,P)
  12031. #else
  12032. # define sqlite3StackAllocRaw(D,N) sqlite3DbMallocRaw(D,N)
  12033. # define sqlite3StackAllocZero(D,N) sqlite3DbMallocZero(D,N)
  12034. # define sqlite3StackFree(D,P) sqlite3DbFree(D,P)
  12035. #endif
  12036. #ifdef SQLITE_ENABLE_MEMSYS3
  12037. SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void);
  12038. #endif
  12039. #ifdef SQLITE_ENABLE_MEMSYS5
  12040. SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void);
  12041. #endif
  12042. #ifndef SQLITE_MUTEX_OMIT
  12043. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void);
  12044. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void);
  12045. SQLITE_PRIVATE sqlite3_mutex *sqlite3MutexAlloc(int);
  12046. SQLITE_PRIVATE int sqlite3MutexInit(void);
  12047. SQLITE_PRIVATE int sqlite3MutexEnd(void);
  12048. #endif
  12049. SQLITE_PRIVATE int sqlite3StatusValue(int);
  12050. SQLITE_PRIVATE void sqlite3StatusAdd(int, int);
  12051. SQLITE_PRIVATE void sqlite3StatusSet(int, int);
  12052. #ifndef SQLITE_OMIT_FLOATING_POINT
  12053. SQLITE_PRIVATE int sqlite3IsNaN(double);
  12054. #else
  12055. # define sqlite3IsNaN(X) 0
  12056. #endif
  12057. /*
  12058. ** An instance of the following structure holds information about SQL
  12059. ** functions arguments that are the parameters to the printf() function.
  12060. */
  12061. struct PrintfArguments {
  12062. int nArg; /* Total number of arguments */
  12063. int nUsed; /* Number of arguments used so far */
  12064. sqlite3_value **apArg; /* The argument values */
  12065. };
  12066. #define SQLITE_PRINTF_INTERNAL 0x01
  12067. #define SQLITE_PRINTF_SQLFUNC 0x02
  12068. SQLITE_PRIVATE void sqlite3VXPrintf(StrAccum*, u32, const char*, va_list);
  12069. SQLITE_PRIVATE void sqlite3XPrintf(StrAccum*, u32, const char*, ...);
  12070. SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3*,const char*, ...);
  12071. SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3*,const char*, va_list);
  12072. SQLITE_PRIVATE char *sqlite3MAppendf(sqlite3*,char*,const char*,...);
  12073. #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
  12074. SQLITE_PRIVATE void sqlite3DebugPrintf(const char*, ...);
  12075. #endif
  12076. #if defined(SQLITE_TEST)
  12077. SQLITE_PRIVATE void *sqlite3TestTextToPtr(const char*);
  12078. #endif
  12079. #if defined(SQLITE_DEBUG)
  12080. SQLITE_PRIVATE TreeView *sqlite3TreeViewPush(TreeView*,u8);
  12081. SQLITE_PRIVATE void sqlite3TreeViewPop(TreeView*);
  12082. SQLITE_PRIVATE void sqlite3TreeViewLine(TreeView*, const char*, ...);
  12083. SQLITE_PRIVATE void sqlite3TreeViewItem(TreeView*, const char*, u8);
  12084. SQLITE_PRIVATE void sqlite3TreeViewExpr(TreeView*, const Expr*, u8);
  12085. SQLITE_PRIVATE void sqlite3TreeViewExprList(TreeView*, const ExprList*, u8, const char*);
  12086. SQLITE_PRIVATE void sqlite3TreeViewSelect(TreeView*, const Select*, u8);
  12087. #endif
  12088. SQLITE_PRIVATE void sqlite3SetString(char **, sqlite3*, const char*, ...);
  12089. SQLITE_PRIVATE void sqlite3ErrorMsg(Parse*, const char*, ...);
  12090. SQLITE_PRIVATE int sqlite3Dequote(char*);
  12091. SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char*, int);
  12092. SQLITE_PRIVATE int sqlite3RunParser(Parse*, const char*, char **);
  12093. SQLITE_PRIVATE void sqlite3FinishCoding(Parse*);
  12094. SQLITE_PRIVATE int sqlite3GetTempReg(Parse*);
  12095. SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse*,int);
  12096. SQLITE_PRIVATE int sqlite3GetTempRange(Parse*,int);
  12097. SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse*,int,int);
  12098. SQLITE_PRIVATE void sqlite3ClearTempRegCache(Parse*);
  12099. SQLITE_PRIVATE Expr *sqlite3ExprAlloc(sqlite3*,int,const Token*,int);
  12100. SQLITE_PRIVATE Expr *sqlite3Expr(sqlite3*,int,const char*);
  12101. SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(sqlite3*,Expr*,Expr*,Expr*);
  12102. SQLITE_PRIVATE Expr *sqlite3PExpr(Parse*, int, Expr*, Expr*, const Token*);
  12103. SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3*,Expr*, Expr*);
  12104. SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse*,ExprList*, Token*);
  12105. SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse*, Expr*);
  12106. SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3*, Expr*);
  12107. SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(Parse*,ExprList*,Expr*);
  12108. SQLITE_PRIVATE void sqlite3ExprListSetName(Parse*,ExprList*,Token*,int);
  12109. SQLITE_PRIVATE void sqlite3ExprListSetSpan(Parse*,ExprList*,ExprSpan*);
  12110. SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3*, ExprList*);
  12111. SQLITE_PRIVATE int sqlite3Init(sqlite3*, char**);
  12112. SQLITE_PRIVATE int sqlite3InitCallback(void*, int, char**, char**);
  12113. SQLITE_PRIVATE void sqlite3Pragma(Parse*,Token*,Token*,Token*,int);
  12114. SQLITE_PRIVATE void sqlite3ResetAllSchemasOfConnection(sqlite3*);
  12115. SQLITE_PRIVATE void sqlite3ResetOneSchema(sqlite3*,int);
  12116. SQLITE_PRIVATE void sqlite3CollapseDatabaseArray(sqlite3*);
  12117. SQLITE_PRIVATE void sqlite3BeginParse(Parse*,int);
  12118. SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3*);
  12119. SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse*,Select*);
  12120. SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *, int);
  12121. SQLITE_PRIVATE Index *sqlite3PrimaryKeyIndex(Table*);
  12122. SQLITE_PRIVATE i16 sqlite3ColumnOfIndex(Index*, i16);
  12123. SQLITE_PRIVATE void sqlite3StartTable(Parse*,Token*,Token*,int,int,int,int);
  12124. SQLITE_PRIVATE void sqlite3AddColumn(Parse*,Token*);
  12125. SQLITE_PRIVATE void sqlite3AddNotNull(Parse*, int);
  12126. SQLITE_PRIVATE void sqlite3AddPrimaryKey(Parse*, ExprList*, int, int, int);
  12127. SQLITE_PRIVATE void sqlite3AddCheckConstraint(Parse*, Expr*);
  12128. SQLITE_PRIVATE void sqlite3AddColumnType(Parse*,Token*);
  12129. SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse*,ExprSpan*);
  12130. SQLITE_PRIVATE void sqlite3AddCollateType(Parse*, Token*);
  12131. SQLITE_PRIVATE void sqlite3EndTable(Parse*,Token*,Token*,u8,Select*);
  12132. SQLITE_PRIVATE int sqlite3ParseUri(const char*,const char*,unsigned int*,
  12133. sqlite3_vfs**,char**,char **);
  12134. SQLITE_PRIVATE Btree *sqlite3DbNameToBtree(sqlite3*,const char*);
  12135. SQLITE_PRIVATE int sqlite3CodeOnce(Parse *);
  12136. #ifdef SQLITE_OMIT_BUILTIN_TEST
  12137. # define sqlite3FaultSim(X) SQLITE_OK
  12138. #else
  12139. SQLITE_PRIVATE int sqlite3FaultSim(int);
  12140. #endif
  12141. SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32);
  12142. SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec*, u32);
  12143. SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec*, u32);
  12144. SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec*, u32, void*);
  12145. SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec*);
  12146. SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec*);
  12147. SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int,int*);
  12148. SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3*, void*, unsigned int);
  12149. SQLITE_PRIVATE void sqlite3RowSetClear(RowSet*);
  12150. SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet*, i64);
  12151. SQLITE_PRIVATE int sqlite3RowSetTest(RowSet*, int iBatch, i64);
  12152. SQLITE_PRIVATE int sqlite3RowSetNext(RowSet*, i64*);
  12153. SQLITE_PRIVATE void sqlite3CreateView(Parse*,Token*,Token*,Token*,Select*,int,int);
  12154. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
  12155. SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse*,Table*);
  12156. #else
  12157. # define sqlite3ViewGetColumnNames(A,B) 0
  12158. #endif
  12159. #if SQLITE_MAX_ATTACHED>30
  12160. SQLITE_PRIVATE int sqlite3DbMaskAllZero(yDbMask);
  12161. #endif
  12162. SQLITE_PRIVATE void sqlite3DropTable(Parse*, SrcList*, int, int);
  12163. SQLITE_PRIVATE void sqlite3CodeDropTable(Parse*, Table*, int, int);
  12164. SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3*, Table*);
  12165. #ifndef SQLITE_OMIT_AUTOINCREMENT
  12166. SQLITE_PRIVATE void sqlite3AutoincrementBegin(Parse *pParse);
  12167. SQLITE_PRIVATE void sqlite3AutoincrementEnd(Parse *pParse);
  12168. #else
  12169. # define sqlite3AutoincrementBegin(X)
  12170. # define sqlite3AutoincrementEnd(X)
  12171. #endif
  12172. SQLITE_PRIVATE void sqlite3Insert(Parse*, SrcList*, Select*, IdList*, int);
  12173. SQLITE_PRIVATE void *sqlite3ArrayAllocate(sqlite3*,void*,int,int*,int*);
  12174. SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3*, IdList*, Token*);
  12175. SQLITE_PRIVATE int sqlite3IdListIndex(IdList*,const char*);
  12176. SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(sqlite3*, SrcList*, int, int);
  12177. SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(sqlite3*, SrcList*, Token*, Token*);
  12178. SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(Parse*, SrcList*, Token*, Token*,
  12179. Token*, Select*, Expr*, IdList*);
  12180. SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *, SrcList *, Token *);
  12181. SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *, struct SrcList_item *);
  12182. SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList*);
  12183. SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse*, SrcList*);
  12184. SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3*, IdList*);
  12185. SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3*, SrcList*);
  12186. SQLITE_PRIVATE Index *sqlite3AllocateIndexObject(sqlite3*,i16,int,char**);
  12187. SQLITE_PRIVATE Index *sqlite3CreateIndex(Parse*,Token*,Token*,SrcList*,ExprList*,int,Token*,
  12188. Expr*, int, int);
  12189. SQLITE_PRIVATE void sqlite3DropIndex(Parse*, SrcList*, int);
  12190. SQLITE_PRIVATE int sqlite3Select(Parse*, Select*, SelectDest*);
  12191. SQLITE_PRIVATE Select *sqlite3SelectNew(Parse*,ExprList*,SrcList*,Expr*,ExprList*,
  12192. Expr*,ExprList*,u16,Expr*,Expr*);
  12193. SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3*, Select*);
  12194. SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse*, SrcList*);
  12195. SQLITE_PRIVATE int sqlite3IsReadOnly(Parse*, Table*, int);
  12196. SQLITE_PRIVATE void sqlite3OpenTable(Parse*, int iCur, int iDb, Table*, int);
  12197. #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
  12198. SQLITE_PRIVATE Expr *sqlite3LimitWhere(Parse*,SrcList*,Expr*,ExprList*,Expr*,Expr*,char*);
  12199. #endif
  12200. SQLITE_PRIVATE void sqlite3DeleteFrom(Parse*, SrcList*, Expr*);
  12201. SQLITE_PRIVATE void sqlite3Update(Parse*, SrcList*, ExprList*, Expr*, int);
  12202. SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(Parse*,SrcList*,Expr*,ExprList*,ExprList*,u16,int);
  12203. SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo*);
  12204. SQLITE_PRIVATE u64 sqlite3WhereOutputRowCount(WhereInfo*);
  12205. SQLITE_PRIVATE int sqlite3WhereIsDistinct(WhereInfo*);
  12206. SQLITE_PRIVATE int sqlite3WhereIsOrdered(WhereInfo*);
  12207. SQLITE_PRIVATE int sqlite3WhereIsSorted(WhereInfo*);
  12208. SQLITE_PRIVATE int sqlite3WhereContinueLabel(WhereInfo*);
  12209. SQLITE_PRIVATE int sqlite3WhereBreakLabel(WhereInfo*);
  12210. SQLITE_PRIVATE int sqlite3WhereOkOnePass(WhereInfo*, int*);
  12211. SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(Parse*, Table*, int, int, int, u8);
  12212. SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(Vdbe*, Table*, int, int, int);
  12213. SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse*, int, int, int);
  12214. SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse*, int, int, int);
  12215. SQLITE_PRIVATE void sqlite3ExprCachePush(Parse*);
  12216. SQLITE_PRIVATE void sqlite3ExprCachePop(Parse*);
  12217. SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse*, int, int);
  12218. SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse*);
  12219. SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse*, int, int);
  12220. SQLITE_PRIVATE void sqlite3ExprCode(Parse*, Expr*, int);
  12221. SQLITE_PRIVATE void sqlite3ExprCodeFactorable(Parse*, Expr*, int);
  12222. SQLITE_PRIVATE void sqlite3ExprCodeAtInit(Parse*, Expr*, int, u8);
  12223. SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse*, Expr*, int*);
  12224. SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse*, Expr*, int);
  12225. SQLITE_PRIVATE void sqlite3ExprCodeAndCache(Parse*, Expr*, int);
  12226. SQLITE_PRIVATE int sqlite3ExprCodeExprList(Parse*, ExprList*, int, u8);
  12227. #define SQLITE_ECEL_DUP 0x01 /* Deep, not shallow copies */
  12228. #define SQLITE_ECEL_FACTOR 0x02 /* Factor out constant terms */
  12229. SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse*, Expr*, int, int);
  12230. SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse*, Expr*, int, int);
  12231. SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3*,const char*, const char*);
  12232. SQLITE_PRIVATE Table *sqlite3LocateTable(Parse*,int isView,const char*, const char*);
  12233. SQLITE_PRIVATE Table *sqlite3LocateTableItem(Parse*,int isView,struct SrcList_item *);
  12234. SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3*,const char*, const char*);
  12235. SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3*,int,const char*);
  12236. SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3*,int,const char*);
  12237. SQLITE_PRIVATE void sqlite3Vacuum(Parse*);
  12238. SQLITE_PRIVATE int sqlite3RunVacuum(char**, sqlite3*);
  12239. SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3*, Token*);
  12240. SQLITE_PRIVATE int sqlite3ExprCompare(Expr*, Expr*, int);
  12241. SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList*, ExprList*, int);
  12242. SQLITE_PRIVATE int sqlite3ExprImpliesExpr(Expr*, Expr*, int);
  12243. SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext*, Expr*);
  12244. SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext*,ExprList*);
  12245. SQLITE_PRIVATE int sqlite3FunctionUsesThisSrc(Expr*, SrcList*);
  12246. SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse*);
  12247. SQLITE_PRIVATE void sqlite3PrngSaveState(void);
  12248. SQLITE_PRIVATE void sqlite3PrngRestoreState(void);
  12249. SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3*,int);
  12250. SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse*, int);
  12251. SQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse*, const char *zDb);
  12252. SQLITE_PRIVATE void sqlite3BeginTransaction(Parse*, int);
  12253. SQLITE_PRIVATE void sqlite3CommitTransaction(Parse*);
  12254. SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse*);
  12255. SQLITE_PRIVATE void sqlite3Savepoint(Parse*, int, Token*);
  12256. SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *);
  12257. SQLITE_PRIVATE void sqlite3LeaveMutexAndCloseZombie(sqlite3*);
  12258. SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr*);
  12259. SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr*);
  12260. SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr*, u8);
  12261. SQLITE_PRIVATE int sqlite3ExprIsTableConstant(Expr*,int);
  12262. SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr*, int*);
  12263. SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr*);
  12264. SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr*, char);
  12265. SQLITE_PRIVATE int sqlite3IsRowid(const char*);
  12266. SQLITE_PRIVATE void sqlite3GenerateRowDelete(Parse*,Table*,Trigger*,int,int,int,i16,u8,u8,u8);
  12267. SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(Parse*, Table*, int, int, int*);
  12268. SQLITE_PRIVATE int sqlite3GenerateIndexKey(Parse*, Index*, int, int, int, int*,Index*,int);
  12269. SQLITE_PRIVATE void sqlite3ResolvePartIdxLabel(Parse*,int);
  12270. SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(Parse*,Table*,int*,int,int,int,int,
  12271. u8,u8,int,int*);
  12272. SQLITE_PRIVATE void sqlite3CompleteInsertion(Parse*,Table*,int,int,int,int*,int,int,int);
  12273. SQLITE_PRIVATE int sqlite3OpenTableAndIndices(Parse*, Table*, int, int, u8*, int*, int*);
  12274. SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse*, int, int);
  12275. SQLITE_PRIVATE void sqlite3MultiWrite(Parse*);
  12276. SQLITE_PRIVATE void sqlite3MayAbort(Parse*);
  12277. SQLITE_PRIVATE void sqlite3HaltConstraint(Parse*, int, int, char*, i8, u8);
  12278. SQLITE_PRIVATE void sqlite3UniqueConstraint(Parse*, int, Index*);
  12279. SQLITE_PRIVATE void sqlite3RowidConstraint(Parse*, int, Table*);
  12280. SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3*,Expr*,int);
  12281. SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3*,ExprList*,int);
  12282. SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3*,SrcList*,int);
  12283. SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3*,IdList*);
  12284. SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3*,Select*,int);
  12285. #if SELECTTRACE_ENABLED
  12286. SQLITE_PRIVATE void sqlite3SelectSetName(Select*,const char*);
  12287. #else
  12288. # define sqlite3SelectSetName(A,B)
  12289. #endif
  12290. SQLITE_PRIVATE void sqlite3FuncDefInsert(FuncDefHash*, FuncDef*);
  12291. SQLITE_PRIVATE FuncDef *sqlite3FindFunction(sqlite3*,const char*,int,int,u8,u8);
  12292. SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(sqlite3*);
  12293. SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void);
  12294. SQLITE_PRIVATE void sqlite3RegisterGlobalFunctions(void);
  12295. SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3*);
  12296. SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3*);
  12297. SQLITE_PRIVATE void sqlite3ChangeCookie(Parse*, int);
  12298. #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
  12299. SQLITE_PRIVATE void sqlite3MaterializeView(Parse*, Table*, Expr*, int);
  12300. #endif
  12301. #ifndef SQLITE_OMIT_TRIGGER
  12302. SQLITE_PRIVATE void sqlite3BeginTrigger(Parse*, Token*,Token*,int,int,IdList*,SrcList*,
  12303. Expr*,int, int);
  12304. SQLITE_PRIVATE void sqlite3FinishTrigger(Parse*, TriggerStep*, Token*);
  12305. SQLITE_PRIVATE void sqlite3DropTrigger(Parse*, SrcList*, int);
  12306. SQLITE_PRIVATE void sqlite3DropTriggerPtr(Parse*, Trigger*);
  12307. SQLITE_PRIVATE Trigger *sqlite3TriggersExist(Parse *, Table*, int, ExprList*, int *pMask);
  12308. SQLITE_PRIVATE Trigger *sqlite3TriggerList(Parse *, Table *);
  12309. SQLITE_PRIVATE void sqlite3CodeRowTrigger(Parse*, Trigger *, int, ExprList*, int, Table *,
  12310. int, int, int);
  12311. SQLITE_PRIVATE void sqlite3CodeRowTriggerDirect(Parse *, Trigger *, Table *, int, int, int);
  12312. void sqliteViewTriggers(Parse*, Table*, Expr*, int, ExprList*);
  12313. SQLITE_PRIVATE void sqlite3DeleteTriggerStep(sqlite3*, TriggerStep*);
  12314. SQLITE_PRIVATE TriggerStep *sqlite3TriggerSelectStep(sqlite3*,Select*);
  12315. SQLITE_PRIVATE TriggerStep *sqlite3TriggerInsertStep(sqlite3*,Token*, IdList*,
  12316. Select*,u8);
  12317. SQLITE_PRIVATE TriggerStep *sqlite3TriggerUpdateStep(sqlite3*,Token*,ExprList*, Expr*, u8);
  12318. SQLITE_PRIVATE TriggerStep *sqlite3TriggerDeleteStep(sqlite3*,Token*, Expr*);
  12319. SQLITE_PRIVATE void sqlite3DeleteTrigger(sqlite3*, Trigger*);
  12320. SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTrigger(sqlite3*,int,const char*);
  12321. SQLITE_PRIVATE u32 sqlite3TriggerColmask(Parse*,Trigger*,ExprList*,int,int,Table*,int);
  12322. # define sqlite3ParseToplevel(p) ((p)->pToplevel ? (p)->pToplevel : (p))
  12323. #else
  12324. # define sqlite3TriggersExist(B,C,D,E,F) 0
  12325. # define sqlite3DeleteTrigger(A,B)
  12326. # define sqlite3DropTriggerPtr(A,B)
  12327. # define sqlite3UnlinkAndDeleteTrigger(A,B,C)
  12328. # define sqlite3CodeRowTrigger(A,B,C,D,E,F,G,H,I)
  12329. # define sqlite3CodeRowTriggerDirect(A,B,C,D,E,F)
  12330. # define sqlite3TriggerList(X, Y) 0
  12331. # define sqlite3ParseToplevel(p) p
  12332. # define sqlite3TriggerColmask(A,B,C,D,E,F,G) 0
  12333. #endif
  12334. SQLITE_PRIVATE int sqlite3JoinType(Parse*, Token*, Token*, Token*);
  12335. SQLITE_PRIVATE void sqlite3CreateForeignKey(Parse*, ExprList*, Token*, ExprList*, int);
  12336. SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse*, int);
  12337. #ifndef SQLITE_OMIT_AUTHORIZATION
  12338. SQLITE_PRIVATE void sqlite3AuthRead(Parse*,Expr*,Schema*,SrcList*);
  12339. SQLITE_PRIVATE int sqlite3AuthCheck(Parse*,int, const char*, const char*, const char*);
  12340. SQLITE_PRIVATE void sqlite3AuthContextPush(Parse*, AuthContext*, const char*);
  12341. SQLITE_PRIVATE void sqlite3AuthContextPop(AuthContext*);
  12342. SQLITE_PRIVATE int sqlite3AuthReadCol(Parse*, const char *, const char *, int);
  12343. #else
  12344. # define sqlite3AuthRead(a,b,c,d)
  12345. # define sqlite3AuthCheck(a,b,c,d,e) SQLITE_OK
  12346. # define sqlite3AuthContextPush(a,b,c)
  12347. # define sqlite3AuthContextPop(a) ((void)(a))
  12348. #endif
  12349. SQLITE_PRIVATE void sqlite3Attach(Parse*, Expr*, Expr*, Expr*);
  12350. SQLITE_PRIVATE void sqlite3Detach(Parse*, Expr*);
  12351. SQLITE_PRIVATE void sqlite3FixInit(DbFixer*, Parse*, int, const char*, const Token*);
  12352. SQLITE_PRIVATE int sqlite3FixSrcList(DbFixer*, SrcList*);
  12353. SQLITE_PRIVATE int sqlite3FixSelect(DbFixer*, Select*);
  12354. SQLITE_PRIVATE int sqlite3FixExpr(DbFixer*, Expr*);
  12355. SQLITE_PRIVATE int sqlite3FixExprList(DbFixer*, ExprList*);
  12356. SQLITE_PRIVATE int sqlite3FixTriggerStep(DbFixer*, TriggerStep*);
  12357. SQLITE_PRIVATE int sqlite3AtoF(const char *z, double*, int, u8);
  12358. SQLITE_PRIVATE int sqlite3GetInt32(const char *, int*);
  12359. SQLITE_PRIVATE int sqlite3Atoi(const char*);
  12360. SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *pData, int nChar);
  12361. SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *pData, int nByte);
  12362. SQLITE_PRIVATE u32 sqlite3Utf8Read(const u8**);
  12363. SQLITE_PRIVATE LogEst sqlite3LogEst(u64);
  12364. SQLITE_PRIVATE LogEst sqlite3LogEstAdd(LogEst,LogEst);
  12365. #ifndef SQLITE_OMIT_VIRTUALTABLE
  12366. SQLITE_PRIVATE LogEst sqlite3LogEstFromDouble(double);
  12367. #endif
  12368. SQLITE_PRIVATE u64 sqlite3LogEstToInt(LogEst);
  12369. /*
  12370. ** Routines to read and write variable-length integers. These used to
  12371. ** be defined locally, but now we use the varint routines in the util.c
  12372. ** file.
  12373. */
  12374. SQLITE_PRIVATE int sqlite3PutVarint(unsigned char*, u64);
  12375. SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *, u64 *);
  12376. SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *, u32 *);
  12377. SQLITE_PRIVATE int sqlite3VarintLen(u64 v);
  12378. /*
  12379. ** The common case is for a varint to be a single byte. They following
  12380. ** macros handle the common case without a procedure call, but then call
  12381. ** the procedure for larger varints.
  12382. */
  12383. #define getVarint32(A,B) \
  12384. (u8)((*(A)<(u8)0x80)?((B)=(u32)*(A)),1:sqlite3GetVarint32((A),(u32 *)&(B)))
  12385. #define putVarint32(A,B) \
  12386. (u8)(((u32)(B)<(u32)0x80)?(*(A)=(unsigned char)(B)),1:\
  12387. sqlite3PutVarint((A),(B)))
  12388. #define getVarint sqlite3GetVarint
  12389. #define putVarint sqlite3PutVarint
  12390. SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(Vdbe *, Index *);
  12391. SQLITE_PRIVATE void sqlite3TableAffinity(Vdbe*, Table*, int);
  12392. SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2);
  12393. SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity);
  12394. SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr);
  12395. SQLITE_PRIVATE int sqlite3Atoi64(const char*, i64*, int, u8);
  12396. SQLITE_PRIVATE int sqlite3DecOrHexToI64(const char*, i64*);
  12397. SQLITE_PRIVATE void sqlite3ErrorWithMsg(sqlite3*, int, const char*,...);
  12398. SQLITE_PRIVATE void sqlite3Error(sqlite3*,int);
  12399. SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3*, const char *z, int n);
  12400. SQLITE_PRIVATE u8 sqlite3HexToInt(int h);
  12401. SQLITE_PRIVATE int sqlite3TwoPartName(Parse *, Token *, Token *, Token **);
  12402. #if defined(SQLITE_TEST)
  12403. SQLITE_PRIVATE const char *sqlite3ErrName(int);
  12404. #endif
  12405. SQLITE_PRIVATE const char *sqlite3ErrStr(int);
  12406. SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse);
  12407. SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(sqlite3*,u8 enc, const char*,int);
  12408. SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char*zName);
  12409. SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr);
  12410. SQLITE_PRIVATE Expr *sqlite3ExprAddCollateToken(Parse *pParse, Expr*, const Token*);
  12411. SQLITE_PRIVATE Expr *sqlite3ExprAddCollateString(Parse*,Expr*,const char*);
  12412. SQLITE_PRIVATE Expr *sqlite3ExprSkipCollate(Expr*);
  12413. SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *, CollSeq *);
  12414. SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *, const char *);
  12415. SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *, int);
  12416. SQLITE_PRIVATE int sqlite3AddInt64(i64*,i64);
  12417. SQLITE_PRIVATE int sqlite3SubInt64(i64*,i64);
  12418. SQLITE_PRIVATE int sqlite3MulInt64(i64*,i64);
  12419. SQLITE_PRIVATE int sqlite3AbsInt32(int);
  12420. #ifdef SQLITE_ENABLE_8_3_NAMES
  12421. SQLITE_PRIVATE void sqlite3FileSuffix3(const char*, char*);
  12422. #else
  12423. # define sqlite3FileSuffix3(X,Y)
  12424. #endif
  12425. SQLITE_PRIVATE u8 sqlite3GetBoolean(const char *z,u8);
  12426. SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value*, u8);
  12427. SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value*, u8);
  12428. SQLITE_PRIVATE void sqlite3ValueSetStr(sqlite3_value*, int, const void *,u8,
  12429. void(*)(void*));
  12430. SQLITE_PRIVATE void sqlite3ValueSetNull(sqlite3_value*);
  12431. SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value*);
  12432. SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *);
  12433. SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *, const void*, int, u8);
  12434. SQLITE_PRIVATE int sqlite3ValueFromExpr(sqlite3 *, Expr *, u8, u8, sqlite3_value **);
  12435. SQLITE_PRIVATE void sqlite3ValueApplyAffinity(sqlite3_value *, u8, u8);
  12436. #ifndef SQLITE_AMALGAMATION
  12437. SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[];
  12438. SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[];
  12439. SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[];
  12440. SQLITE_PRIVATE const Token sqlite3IntTokens[];
  12441. SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config;
  12442. SQLITE_PRIVATE SQLITE_WSD FuncDefHash sqlite3GlobalFunctions;
  12443. #ifndef SQLITE_OMIT_WSD
  12444. SQLITE_PRIVATE int sqlite3PendingByte;
  12445. #endif
  12446. #endif
  12447. SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3*, int, int, int);
  12448. SQLITE_PRIVATE void sqlite3Reindex(Parse*, Token*, Token*);
  12449. SQLITE_PRIVATE void sqlite3AlterFunctions(void);
  12450. SQLITE_PRIVATE void sqlite3AlterRenameTable(Parse*, SrcList*, Token*);
  12451. SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *, int *);
  12452. SQLITE_PRIVATE void sqlite3NestedParse(Parse*, const char*, ...);
  12453. SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3*);
  12454. SQLITE_PRIVATE int sqlite3CodeSubselect(Parse *, Expr *, int, int);
  12455. SQLITE_PRIVATE void sqlite3SelectPrep(Parse*, Select*, NameContext*);
  12456. SQLITE_PRIVATE int sqlite3MatchSpanName(const char*, const char*, const char*, const char*);
  12457. SQLITE_PRIVATE int sqlite3ResolveExprNames(NameContext*, Expr*);
  12458. SQLITE_PRIVATE void sqlite3ResolveSelectNames(Parse*, Select*, NameContext*);
  12459. SQLITE_PRIVATE void sqlite3ResolveSelfReference(Parse*,Table*,int,Expr*,ExprList*);
  12460. SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(Parse*, Select*, ExprList*, const char*);
  12461. SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *, Table *, int, int);
  12462. SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *, Token *);
  12463. SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *, SrcList *);
  12464. SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(Parse*, u8, CollSeq *, const char*);
  12465. SQLITE_PRIVATE char sqlite3AffinityType(const char*, u8*);
  12466. SQLITE_PRIVATE void sqlite3Analyze(Parse*, Token*, Token*);
  12467. SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler*);
  12468. SQLITE_PRIVATE int sqlite3FindDb(sqlite3*, Token*);
  12469. SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *, const char *);
  12470. SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3*,int iDB);
  12471. SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3*,Index*);
  12472. SQLITE_PRIVATE void sqlite3DefaultRowEst(Index*);
  12473. SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3*, int);
  12474. SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3*,Expr*,int*,char*);
  12475. SQLITE_PRIVATE void sqlite3MinimumFileFormat(Parse*, int, int);
  12476. SQLITE_PRIVATE void sqlite3SchemaClear(void *);
  12477. SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *, Btree *);
  12478. SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *);
  12479. SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoAlloc(sqlite3*,int,int);
  12480. SQLITE_PRIVATE void sqlite3KeyInfoUnref(KeyInfo*);
  12481. SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoRef(KeyInfo*);
  12482. SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoOfIndex(Parse*, Index*);
  12483. #ifdef SQLITE_DEBUG
  12484. SQLITE_PRIVATE int sqlite3KeyInfoIsWriteable(KeyInfo*);
  12485. #endif
  12486. SQLITE_PRIVATE int sqlite3CreateFunc(sqlite3 *, const char *, int, int, void *,
  12487. void (*)(sqlite3_context*,int,sqlite3_value **),
  12488. void (*)(sqlite3_context*,int,sqlite3_value **), void (*)(sqlite3_context*),
  12489. FuncDestructor *pDestructor
  12490. );
  12491. SQLITE_PRIVATE int sqlite3ApiExit(sqlite3 *db, int);
  12492. SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *);
  12493. SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum*, char*, int, int);
  12494. SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum*,const char*,int);
  12495. SQLITE_PRIVATE void sqlite3StrAccumAppendAll(StrAccum*,const char*);
  12496. SQLITE_PRIVATE void sqlite3AppendSpace(StrAccum*,int);
  12497. SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum*);
  12498. SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum*);
  12499. SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest*,int,int);
  12500. SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *, SrcList *, int, int);
  12501. SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *);
  12502. SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *, Pgno, const u8 *);
  12503. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  12504. SQLITE_PRIVATE void sqlite3AnalyzeFunctions(void);
  12505. SQLITE_PRIVATE int sqlite3Stat4ProbeSetValue(Parse*,Index*,UnpackedRecord**,Expr*,u8,int,int*);
  12506. SQLITE_PRIVATE int sqlite3Stat4ValueFromExpr(Parse*, Expr*, u8, sqlite3_value**);
  12507. SQLITE_PRIVATE void sqlite3Stat4ProbeFree(UnpackedRecord*);
  12508. SQLITE_PRIVATE int sqlite3Stat4Column(sqlite3*, const void*, int, int, sqlite3_value**);
  12509. #endif
  12510. /*
  12511. ** The interface to the LEMON-generated parser
  12512. */
  12513. SQLITE_PRIVATE void *sqlite3ParserAlloc(void*(*)(u64));
  12514. SQLITE_PRIVATE void sqlite3ParserFree(void*, void(*)(void*));
  12515. SQLITE_PRIVATE void sqlite3Parser(void*, int, Token, Parse*);
  12516. #ifdef YYTRACKMAXSTACKDEPTH
  12517. SQLITE_PRIVATE int sqlite3ParserStackPeak(void*);
  12518. #endif
  12519. SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3*);
  12520. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  12521. SQLITE_PRIVATE void sqlite3CloseExtensions(sqlite3*);
  12522. #else
  12523. # define sqlite3CloseExtensions(X)
  12524. #endif
  12525. #ifndef SQLITE_OMIT_SHARED_CACHE
  12526. SQLITE_PRIVATE void sqlite3TableLock(Parse *, int, int, u8, const char *);
  12527. #else
  12528. #define sqlite3TableLock(v,w,x,y,z)
  12529. #endif
  12530. #ifdef SQLITE_TEST
  12531. SQLITE_PRIVATE int sqlite3Utf8To8(unsigned char*);
  12532. #endif
  12533. #ifdef SQLITE_OMIT_VIRTUALTABLE
  12534. # define sqlite3VtabClear(Y)
  12535. # define sqlite3VtabSync(X,Y) SQLITE_OK
  12536. # define sqlite3VtabRollback(X)
  12537. # define sqlite3VtabCommit(X)
  12538. # define sqlite3VtabInSync(db) 0
  12539. # define sqlite3VtabLock(X)
  12540. # define sqlite3VtabUnlock(X)
  12541. # define sqlite3VtabUnlockList(X)
  12542. # define sqlite3VtabSavepoint(X, Y, Z) SQLITE_OK
  12543. # define sqlite3GetVTable(X,Y) ((VTable*)0)
  12544. #else
  12545. SQLITE_PRIVATE void sqlite3VtabClear(sqlite3 *db, Table*);
  12546. SQLITE_PRIVATE void sqlite3VtabDisconnect(sqlite3 *db, Table *p);
  12547. SQLITE_PRIVATE int sqlite3VtabSync(sqlite3 *db, Vdbe*);
  12548. SQLITE_PRIVATE int sqlite3VtabRollback(sqlite3 *db);
  12549. SQLITE_PRIVATE int sqlite3VtabCommit(sqlite3 *db);
  12550. SQLITE_PRIVATE void sqlite3VtabLock(VTable *);
  12551. SQLITE_PRIVATE void sqlite3VtabUnlock(VTable *);
  12552. SQLITE_PRIVATE void sqlite3VtabUnlockList(sqlite3*);
  12553. SQLITE_PRIVATE int sqlite3VtabSavepoint(sqlite3 *, int, int);
  12554. SQLITE_PRIVATE void sqlite3VtabImportErrmsg(Vdbe*, sqlite3_vtab*);
  12555. SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3*, Table*);
  12556. # define sqlite3VtabInSync(db) ((db)->nVTrans>0 && (db)->aVTrans==0)
  12557. #endif
  12558. SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse*,Table*);
  12559. SQLITE_PRIVATE void sqlite3VtabBeginParse(Parse*, Token*, Token*, Token*, int);
  12560. SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse*, Token*);
  12561. SQLITE_PRIVATE void sqlite3VtabArgInit(Parse*);
  12562. SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse*, Token*);
  12563. SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3*, int, const char *, char **);
  12564. SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse*, Table*);
  12565. SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3*, int, const char *);
  12566. SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *, VTable *);
  12567. SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(sqlite3 *,FuncDef*, int nArg, Expr*);
  12568. SQLITE_PRIVATE void sqlite3InvalidFunction(sqlite3_context*,int,sqlite3_value**);
  12569. SQLITE_PRIVATE sqlite3_int64 sqlite3StmtCurrentTime(sqlite3_context*);
  12570. SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe*, const char*, int);
  12571. SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *, sqlite3_stmt *);
  12572. SQLITE_PRIVATE void sqlite3ParserReset(Parse*);
  12573. SQLITE_PRIVATE int sqlite3Reprepare(Vdbe*);
  12574. SQLITE_PRIVATE void sqlite3ExprListCheckLength(Parse*, ExprList*, const char*);
  12575. SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(Parse *, Expr *, Expr *);
  12576. SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3*);
  12577. SQLITE_PRIVATE const char *sqlite3JournalModename(int);
  12578. #ifndef SQLITE_OMIT_WAL
  12579. SQLITE_PRIVATE int sqlite3Checkpoint(sqlite3*, int, int, int*, int*);
  12580. SQLITE_PRIVATE int sqlite3WalDefaultHook(void*,sqlite3*,const char*,int);
  12581. #endif
  12582. #ifndef SQLITE_OMIT_CTE
  12583. SQLITE_PRIVATE With *sqlite3WithAdd(Parse*,With*,Token*,ExprList*,Select*);
  12584. SQLITE_PRIVATE void sqlite3WithDelete(sqlite3*,With*);
  12585. SQLITE_PRIVATE void sqlite3WithPush(Parse*, With*, u8);
  12586. #else
  12587. #define sqlite3WithPush(x,y,z)
  12588. #define sqlite3WithDelete(x,y)
  12589. #endif
  12590. /* Declarations for functions in fkey.c. All of these are replaced by
  12591. ** no-op macros if OMIT_FOREIGN_KEY is defined. In this case no foreign
  12592. ** key functionality is available. If OMIT_TRIGGER is defined but
  12593. ** OMIT_FOREIGN_KEY is not, only some of the functions are no-oped. In
  12594. ** this case foreign keys are parsed, but no other functionality is
  12595. ** provided (enforcement of FK constraints requires the triggers sub-system).
  12596. */
  12597. #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
  12598. SQLITE_PRIVATE void sqlite3FkCheck(Parse*, Table*, int, int, int*, int);
  12599. SQLITE_PRIVATE void sqlite3FkDropTable(Parse*, SrcList *, Table*);
  12600. SQLITE_PRIVATE void sqlite3FkActions(Parse*, Table*, ExprList*, int, int*, int);
  12601. SQLITE_PRIVATE int sqlite3FkRequired(Parse*, Table*, int*, int);
  12602. SQLITE_PRIVATE u32 sqlite3FkOldmask(Parse*, Table*);
  12603. SQLITE_PRIVATE FKey *sqlite3FkReferences(Table *);
  12604. #else
  12605. #define sqlite3FkActions(a,b,c,d,e,f)
  12606. #define sqlite3FkCheck(a,b,c,d,e,f)
  12607. #define sqlite3FkDropTable(a,b,c)
  12608. #define sqlite3FkOldmask(a,b) 0
  12609. #define sqlite3FkRequired(a,b,c,d) 0
  12610. #endif
  12611. #ifndef SQLITE_OMIT_FOREIGN_KEY
  12612. SQLITE_PRIVATE void sqlite3FkDelete(sqlite3 *, Table*);
  12613. SQLITE_PRIVATE int sqlite3FkLocateIndex(Parse*,Table*,FKey*,Index**,int**);
  12614. #else
  12615. #define sqlite3FkDelete(a,b)
  12616. #define sqlite3FkLocateIndex(a,b,c,d,e)
  12617. #endif
  12618. /*
  12619. ** Available fault injectors. Should be numbered beginning with 0.
  12620. */
  12621. #define SQLITE_FAULTINJECTOR_MALLOC 0
  12622. #define SQLITE_FAULTINJECTOR_COUNT 1
  12623. /*
  12624. ** The interface to the code in fault.c used for identifying "benign"
  12625. ** malloc failures. This is only present if SQLITE_OMIT_BUILTIN_TEST
  12626. ** is not defined.
  12627. */
  12628. #ifndef SQLITE_OMIT_BUILTIN_TEST
  12629. SQLITE_PRIVATE void sqlite3BeginBenignMalloc(void);
  12630. SQLITE_PRIVATE void sqlite3EndBenignMalloc(void);
  12631. #else
  12632. #define sqlite3BeginBenignMalloc()
  12633. #define sqlite3EndBenignMalloc()
  12634. #endif
  12635. /*
  12636. ** Allowed return values from sqlite3FindInIndex()
  12637. */
  12638. #define IN_INDEX_ROWID 1 /* Search the rowid of the table */
  12639. #define IN_INDEX_EPH 2 /* Search an ephemeral b-tree */
  12640. #define IN_INDEX_INDEX_ASC 3 /* Existing index ASCENDING */
  12641. #define IN_INDEX_INDEX_DESC 4 /* Existing index DESCENDING */
  12642. #define IN_INDEX_NOOP 5 /* No table available. Use comparisons */
  12643. /*
  12644. ** Allowed flags for the 3rd parameter to sqlite3FindInIndex().
  12645. */
  12646. #define IN_INDEX_NOOP_OK 0x0001 /* OK to return IN_INDEX_NOOP */
  12647. #define IN_INDEX_MEMBERSHIP 0x0002 /* IN operator used for membership test */
  12648. #define IN_INDEX_LOOP 0x0004 /* IN operator used as a loop */
  12649. SQLITE_PRIVATE int sqlite3FindInIndex(Parse *, Expr *, u32, int*);
  12650. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  12651. SQLITE_PRIVATE int sqlite3JournalOpen(sqlite3_vfs *, const char *, sqlite3_file *, int, int);
  12652. SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *);
  12653. SQLITE_PRIVATE int sqlite3JournalCreate(sqlite3_file *);
  12654. SQLITE_PRIVATE int sqlite3JournalExists(sqlite3_file *p);
  12655. #else
  12656. #define sqlite3JournalSize(pVfs) ((pVfs)->szOsFile)
  12657. #define sqlite3JournalExists(p) 1
  12658. #endif
  12659. SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *);
  12660. SQLITE_PRIVATE int sqlite3MemJournalSize(void);
  12661. SQLITE_PRIVATE int sqlite3IsMemJournal(sqlite3_file *);
  12662. #if SQLITE_MAX_EXPR_DEPTH>0
  12663. SQLITE_PRIVATE void sqlite3ExprSetHeight(Parse *pParse, Expr *p);
  12664. SQLITE_PRIVATE int sqlite3SelectExprHeight(Select *);
  12665. SQLITE_PRIVATE int sqlite3ExprCheckHeight(Parse*, int);
  12666. #else
  12667. #define sqlite3ExprSetHeight(x,y)
  12668. #define sqlite3SelectExprHeight(x) 0
  12669. #define sqlite3ExprCheckHeight(x,y)
  12670. #endif
  12671. SQLITE_PRIVATE u32 sqlite3Get4byte(const u8*);
  12672. SQLITE_PRIVATE void sqlite3Put4byte(u8*, u32);
  12673. #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
  12674. SQLITE_PRIVATE void sqlite3ConnectionBlocked(sqlite3 *, sqlite3 *);
  12675. SQLITE_PRIVATE void sqlite3ConnectionUnlocked(sqlite3 *db);
  12676. SQLITE_PRIVATE void sqlite3ConnectionClosed(sqlite3 *db);
  12677. #else
  12678. #define sqlite3ConnectionBlocked(x,y)
  12679. #define sqlite3ConnectionUnlocked(x)
  12680. #define sqlite3ConnectionClosed(x)
  12681. #endif
  12682. #ifdef SQLITE_DEBUG
  12683. SQLITE_PRIVATE void sqlite3ParserTrace(FILE*, char *);
  12684. #endif
  12685. /*
  12686. ** If the SQLITE_ENABLE IOTRACE exists then the global variable
  12687. ** sqlite3IoTrace is a pointer to a printf-like routine used to
  12688. ** print I/O tracing messages.
  12689. */
  12690. #ifdef SQLITE_ENABLE_IOTRACE
  12691. # define IOTRACE(A) if( sqlite3IoTrace ){ sqlite3IoTrace A; }
  12692. SQLITE_PRIVATE void sqlite3VdbeIOTraceSql(Vdbe*);
  12693. SQLITE_PRIVATE void (*sqlite3IoTrace)(const char*,...);
  12694. #else
  12695. # define IOTRACE(A)
  12696. # define sqlite3VdbeIOTraceSql(X)
  12697. #endif
  12698. /*
  12699. ** These routines are available for the mem2.c debugging memory allocator
  12700. ** only. They are used to verify that different "types" of memory
  12701. ** allocations are properly tracked by the system.
  12702. **
  12703. ** sqlite3MemdebugSetType() sets the "type" of an allocation to one of
  12704. ** the MEMTYPE_* macros defined below. The type must be a bitmask with
  12705. ** a single bit set.
  12706. **
  12707. ** sqlite3MemdebugHasType() returns true if any of the bits in its second
  12708. ** argument match the type set by the previous sqlite3MemdebugSetType().
  12709. ** sqlite3MemdebugHasType() is intended for use inside assert() statements.
  12710. **
  12711. ** sqlite3MemdebugNoType() returns true if none of the bits in its second
  12712. ** argument match the type set by the previous sqlite3MemdebugSetType().
  12713. **
  12714. ** Perhaps the most important point is the difference between MEMTYPE_HEAP
  12715. ** and MEMTYPE_LOOKASIDE. If an allocation is MEMTYPE_LOOKASIDE, that means
  12716. ** it might have been allocated by lookaside, except the allocation was
  12717. ** too large or lookaside was already full. It is important to verify
  12718. ** that allocations that might have been satisfied by lookaside are not
  12719. ** passed back to non-lookaside free() routines. Asserts such as the
  12720. ** example above are placed on the non-lookaside free() routines to verify
  12721. ** this constraint.
  12722. **
  12723. ** All of this is no-op for a production build. It only comes into
  12724. ** play when the SQLITE_MEMDEBUG compile-time option is used.
  12725. */
  12726. #ifdef SQLITE_MEMDEBUG
  12727. SQLITE_PRIVATE void sqlite3MemdebugSetType(void*,u8);
  12728. SQLITE_PRIVATE int sqlite3MemdebugHasType(void*,u8);
  12729. SQLITE_PRIVATE int sqlite3MemdebugNoType(void*,u8);
  12730. #else
  12731. # define sqlite3MemdebugSetType(X,Y) /* no-op */
  12732. # define sqlite3MemdebugHasType(X,Y) 1
  12733. # define sqlite3MemdebugNoType(X,Y) 1
  12734. #endif
  12735. #define MEMTYPE_HEAP 0x01 /* General heap allocations */
  12736. #define MEMTYPE_LOOKASIDE 0x02 /* Heap that might have been lookaside */
  12737. #define MEMTYPE_SCRATCH 0x04 /* Scratch allocations */
  12738. #define MEMTYPE_PCACHE 0x08 /* Page cache allocations */
  12739. /*
  12740. ** Threading interface
  12741. */
  12742. #if SQLITE_MAX_WORKER_THREADS>0
  12743. SQLITE_PRIVATE int sqlite3ThreadCreate(SQLiteThread**,void*(*)(void*),void*);
  12744. SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread*, void**);
  12745. #endif
  12746. #endif /* _SQLITEINT_H_ */
  12747. /************** End of sqliteInt.h *******************************************/
  12748. /************** Begin file global.c ******************************************/
  12749. /*
  12750. ** 2008 June 13
  12751. **
  12752. ** The author disclaims copyright to this source code. In place of
  12753. ** a legal notice, here is a blessing:
  12754. **
  12755. ** May you do good and not evil.
  12756. ** May you find forgiveness for yourself and forgive others.
  12757. ** May you share freely, never taking more than you give.
  12758. **
  12759. *************************************************************************
  12760. **
  12761. ** This file contains definitions of global variables and constants.
  12762. */
  12763. /* An array to map all upper-case characters into their corresponding
  12764. ** lower-case character.
  12765. **
  12766. ** SQLite only considers US-ASCII (or EBCDIC) characters. We do not
  12767. ** handle case conversions for the UTF character set since the tables
  12768. ** involved are nearly as big or bigger than SQLite itself.
  12769. */
  12770. SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[] = {
  12771. #ifdef SQLITE_ASCII
  12772. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17,
  12773. 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
  12774. 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
  12775. 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 97, 98, 99,100,101,102,103,
  12776. 104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,
  12777. 122, 91, 92, 93, 94, 95, 96, 97, 98, 99,100,101,102,103,104,105,106,107,
  12778. 108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,
  12779. 126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
  12780. 144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,
  12781. 162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,
  12782. 180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,
  12783. 198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,
  12784. 216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,
  12785. 234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,
  12786. 252,253,254,255
  12787. #endif
  12788. #ifdef SQLITE_EBCDIC
  12789. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, /* 0x */
  12790. 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, /* 1x */
  12791. 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, /* 2x */
  12792. 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, /* 3x */
  12793. 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, /* 4x */
  12794. 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, /* 5x */
  12795. 96, 97, 66, 67, 68, 69, 70, 71, 72, 73,106,107,108,109,110,111, /* 6x */
  12796. 112, 81, 82, 83, 84, 85, 86, 87, 88, 89,122,123,124,125,126,127, /* 7x */
  12797. 128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143, /* 8x */
  12798. 144,145,146,147,148,149,150,151,152,153,154,155,156,157,156,159, /* 9x */
  12799. 160,161,162,163,164,165,166,167,168,169,170,171,140,141,142,175, /* Ax */
  12800. 176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191, /* Bx */
  12801. 192,129,130,131,132,133,134,135,136,137,202,203,204,205,206,207, /* Cx */
  12802. 208,145,146,147,148,149,150,151,152,153,218,219,220,221,222,223, /* Dx */
  12803. 224,225,162,163,164,165,166,167,168,169,232,203,204,205,206,207, /* Ex */
  12804. 239,240,241,242,243,244,245,246,247,248,249,219,220,221,222,255, /* Fx */
  12805. #endif
  12806. };
  12807. /*
  12808. ** The following 256 byte lookup table is used to support SQLites built-in
  12809. ** equivalents to the following standard library functions:
  12810. **
  12811. ** isspace() 0x01
  12812. ** isalpha() 0x02
  12813. ** isdigit() 0x04
  12814. ** isalnum() 0x06
  12815. ** isxdigit() 0x08
  12816. ** toupper() 0x20
  12817. ** SQLite identifier character 0x40
  12818. **
  12819. ** Bit 0x20 is set if the mapped character requires translation to upper
  12820. ** case. i.e. if the character is a lower-case ASCII character.
  12821. ** If x is a lower-case ASCII character, then its upper-case equivalent
  12822. ** is (x - 0x20). Therefore toupper() can be implemented as:
  12823. **
  12824. ** (x & ~(map[x]&0x20))
  12825. **
  12826. ** Standard function tolower() is implemented using the sqlite3UpperToLower[]
  12827. ** array. tolower() is used more often than toupper() by SQLite.
  12828. **
  12829. ** Bit 0x40 is set if the character non-alphanumeric and can be used in an
  12830. ** SQLite identifier. Identifiers are alphanumerics, "_", "$", and any
  12831. ** non-ASCII UTF character. Hence the test for whether or not a character is
  12832. ** part of an identifier is 0x46.
  12833. **
  12834. ** SQLite's versions are identical to the standard versions assuming a
  12835. ** locale of "C". They are implemented as macros in sqliteInt.h.
  12836. */
  12837. #ifdef SQLITE_ASCII
  12838. SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[256] = {
  12839. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 00..07 ........ */
  12840. 0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, /* 08..0f ........ */
  12841. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 10..17 ........ */
  12842. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 18..1f ........ */
  12843. 0x01, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, /* 20..27 !"#$%&' */
  12844. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 28..2f ()*+,-./ */
  12845. 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, /* 30..37 01234567 */
  12846. 0x0c, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 38..3f 89:;<=>? */
  12847. 0x00, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x02, /* 40..47 @ABCDEFG */
  12848. 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, /* 48..4f HIJKLMNO */
  12849. 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, /* 50..57 PQRSTUVW */
  12850. 0x02, 0x02, 0x02, 0x00, 0x00, 0x00, 0x00, 0x40, /* 58..5f XYZ[\]^_ */
  12851. 0x00, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x22, /* 60..67 `abcdefg */
  12852. 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, /* 68..6f hijklmno */
  12853. 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, /* 70..77 pqrstuvw */
  12854. 0x22, 0x22, 0x22, 0x00, 0x00, 0x00, 0x00, 0x00, /* 78..7f xyz{|}~. */
  12855. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 80..87 ........ */
  12856. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 88..8f ........ */
  12857. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 90..97 ........ */
  12858. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 98..9f ........ */
  12859. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* a0..a7 ........ */
  12860. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* a8..af ........ */
  12861. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* b0..b7 ........ */
  12862. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* b8..bf ........ */
  12863. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* c0..c7 ........ */
  12864. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* c8..cf ........ */
  12865. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* d0..d7 ........ */
  12866. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* d8..df ........ */
  12867. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* e0..e7 ........ */
  12868. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* e8..ef ........ */
  12869. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* f0..f7 ........ */
  12870. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40 /* f8..ff ........ */
  12871. };
  12872. #endif
  12873. /* EVIDENCE-OF: R-02982-34736 In order to maintain full backwards
  12874. ** compatibility for legacy applications, the URI filename capability is
  12875. ** disabled by default.
  12876. **
  12877. ** EVIDENCE-OF: R-38799-08373 URI filenames can be enabled or disabled
  12878. ** using the SQLITE_USE_URI=1 or SQLITE_USE_URI=0 compile-time options.
  12879. */
  12880. #ifndef SQLITE_USE_URI
  12881. # define SQLITE_USE_URI 0
  12882. #endif
  12883. #ifndef SQLITE_ALLOW_COVERING_INDEX_SCAN
  12884. # define SQLITE_ALLOW_COVERING_INDEX_SCAN 1
  12885. #endif
  12886. /*
  12887. ** The following singleton contains the global configuration for
  12888. ** the SQLite library.
  12889. */
  12890. SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config = {
  12891. SQLITE_DEFAULT_MEMSTATUS, /* bMemstat */
  12892. 1, /* bCoreMutex */
  12893. SQLITE_THREADSAFE==1, /* bFullMutex */
  12894. SQLITE_USE_URI, /* bOpenUri */
  12895. SQLITE_ALLOW_COVERING_INDEX_SCAN, /* bUseCis */
  12896. 0x7ffffffe, /* mxStrlen */
  12897. 0, /* neverCorrupt */
  12898. 128, /* szLookaside */
  12899. 500, /* nLookaside */
  12900. {0,0,0,0,0,0,0,0}, /* m */
  12901. {0,0,0,0,0,0,0,0,0}, /* mutex */
  12902. {0,0,0,0,0,0,0,0,0,0,0,0,0},/* pcache2 */
  12903. (void*)0, /* pHeap */
  12904. 0, /* nHeap */
  12905. 0, 0, /* mnHeap, mxHeap */
  12906. SQLITE_DEFAULT_MMAP_SIZE, /* szMmap */
  12907. SQLITE_MAX_MMAP_SIZE, /* mxMmap */
  12908. (void*)0, /* pScratch */
  12909. 0, /* szScratch */
  12910. 0, /* nScratch */
  12911. (void*)0, /* pPage */
  12912. 0, /* szPage */
  12913. 0, /* nPage */
  12914. 0, /* mxParserStack */
  12915. 0, /* sharedCacheEnabled */
  12916. /* All the rest should always be initialized to zero */
  12917. 0, /* isInit */
  12918. 0, /* inProgress */
  12919. 0, /* isMutexInit */
  12920. 0, /* isMallocInit */
  12921. 0, /* isPCacheInit */
  12922. 0, /* nRefInitMutex */
  12923. 0, /* pInitMutex */
  12924. 0, /* xLog */
  12925. 0, /* pLogArg */
  12926. #ifdef SQLITE_ENABLE_SQLLOG
  12927. 0, /* xSqllog */
  12928. 0, /* pSqllogArg */
  12929. #endif
  12930. #ifdef SQLITE_VDBE_COVERAGE
  12931. 0, /* xVdbeBranch */
  12932. 0, /* pVbeBranchArg */
  12933. #endif
  12934. #ifndef SQLITE_OMIT_BUILTIN_TEST
  12935. 0, /* xTestCallback */
  12936. #endif
  12937. 0 /* bLocaltimeFault */
  12938. };
  12939. /*
  12940. ** Hash table for global functions - functions common to all
  12941. ** database connections. After initialization, this table is
  12942. ** read-only.
  12943. */
  12944. SQLITE_PRIVATE SQLITE_WSD FuncDefHash sqlite3GlobalFunctions;
  12945. /*
  12946. ** Constant tokens for values 0 and 1.
  12947. */
  12948. SQLITE_PRIVATE const Token sqlite3IntTokens[] = {
  12949. { "0", 1 },
  12950. { "1", 1 }
  12951. };
  12952. /*
  12953. ** The value of the "pending" byte must be 0x40000000 (1 byte past the
  12954. ** 1-gibabyte boundary) in a compatible database. SQLite never uses
  12955. ** the database page that contains the pending byte. It never attempts
  12956. ** to read or write that page. The pending byte page is set assign
  12957. ** for use by the VFS layers as space for managing file locks.
  12958. **
  12959. ** During testing, it is often desirable to move the pending byte to
  12960. ** a different position in the file. This allows code that has to
  12961. ** deal with the pending byte to run on files that are much smaller
  12962. ** than 1 GiB. The sqlite3_test_control() interface can be used to
  12963. ** move the pending byte.
  12964. **
  12965. ** IMPORTANT: Changing the pending byte to any value other than
  12966. ** 0x40000000 results in an incompatible database file format!
  12967. ** Changing the pending byte during operating results in undefined
  12968. ** and dileterious behavior.
  12969. */
  12970. #ifndef SQLITE_OMIT_WSD
  12971. SQLITE_PRIVATE int sqlite3PendingByte = 0x40000000;
  12972. #endif
  12973. /*
  12974. ** Properties of opcodes. The OPFLG_INITIALIZER macro is
  12975. ** created by mkopcodeh.awk during compilation. Data is obtained
  12976. ** from the comments following the "case OP_xxxx:" statements in
  12977. ** the vdbe.c file.
  12978. */
  12979. SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[] = OPFLG_INITIALIZER;
  12980. /************** End of global.c **********************************************/
  12981. /************** Begin file ctime.c *******************************************/
  12982. /*
  12983. ** 2010 February 23
  12984. **
  12985. ** The author disclaims copyright to this source code. In place of
  12986. ** a legal notice, here is a blessing:
  12987. **
  12988. ** May you do good and not evil.
  12989. ** May you find forgiveness for yourself and forgive others.
  12990. ** May you share freely, never taking more than you give.
  12991. **
  12992. *************************************************************************
  12993. **
  12994. ** This file implements routines used to report what compile-time options
  12995. ** SQLite was built with.
  12996. */
  12997. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  12998. /*
  12999. ** An array of names of all compile-time options. This array should
  13000. ** be sorted A-Z.
  13001. **
  13002. ** This array looks large, but in a typical installation actually uses
  13003. ** only a handful of compile-time options, so most times this array is usually
  13004. ** rather short and uses little memory space.
  13005. */
  13006. static const char * const azCompileOpt[] = {
  13007. /* These macros are provided to "stringify" the value of the define
  13008. ** for those options in which the value is meaningful. */
  13009. #define CTIMEOPT_VAL_(opt) #opt
  13010. #define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt)
  13011. #ifdef SQLITE_32BIT_ROWID
  13012. "32BIT_ROWID",
  13013. #endif
  13014. #ifdef SQLITE_4_BYTE_ALIGNED_MALLOC
  13015. "4_BYTE_ALIGNED_MALLOC",
  13016. #endif
  13017. #ifdef SQLITE_CASE_SENSITIVE_LIKE
  13018. "CASE_SENSITIVE_LIKE",
  13019. #endif
  13020. #ifdef SQLITE_CHECK_PAGES
  13021. "CHECK_PAGES",
  13022. #endif
  13023. #ifdef SQLITE_COVERAGE_TEST
  13024. "COVERAGE_TEST",
  13025. #endif
  13026. #ifdef SQLITE_DEBUG
  13027. "DEBUG",
  13028. #endif
  13029. #ifdef SQLITE_DEFAULT_LOCKING_MODE
  13030. "DEFAULT_LOCKING_MODE=" CTIMEOPT_VAL(SQLITE_DEFAULT_LOCKING_MODE),
  13031. #endif
  13032. #if defined(SQLITE_DEFAULT_MMAP_SIZE) && !defined(SQLITE_DEFAULT_MMAP_SIZE_xc)
  13033. "DEFAULT_MMAP_SIZE=" CTIMEOPT_VAL(SQLITE_DEFAULT_MMAP_SIZE),
  13034. #endif
  13035. #ifdef SQLITE_DISABLE_DIRSYNC
  13036. "DISABLE_DIRSYNC",
  13037. #endif
  13038. #ifdef SQLITE_DISABLE_LFS
  13039. "DISABLE_LFS",
  13040. #endif
  13041. #ifdef SQLITE_ENABLE_API_ARMOR
  13042. "ENABLE_API_ARMOR",
  13043. #endif
  13044. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  13045. "ENABLE_ATOMIC_WRITE",
  13046. #endif
  13047. #ifdef SQLITE_ENABLE_CEROD
  13048. "ENABLE_CEROD",
  13049. #endif
  13050. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  13051. "ENABLE_COLUMN_METADATA",
  13052. #endif
  13053. #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
  13054. "ENABLE_EXPENSIVE_ASSERT",
  13055. #endif
  13056. #ifdef SQLITE_ENABLE_FTS1
  13057. "ENABLE_FTS1",
  13058. #endif
  13059. #ifdef SQLITE_ENABLE_FTS2
  13060. "ENABLE_FTS2",
  13061. #endif
  13062. #ifdef SQLITE_ENABLE_FTS3
  13063. "ENABLE_FTS3",
  13064. #endif
  13065. #ifdef SQLITE_ENABLE_FTS3_PARENTHESIS
  13066. "ENABLE_FTS3_PARENTHESIS",
  13067. #endif
  13068. #ifdef SQLITE_ENABLE_FTS4
  13069. "ENABLE_FTS4",
  13070. #endif
  13071. #ifdef SQLITE_ENABLE_ICU
  13072. "ENABLE_ICU",
  13073. #endif
  13074. #ifdef SQLITE_ENABLE_IOTRACE
  13075. "ENABLE_IOTRACE",
  13076. #endif
  13077. #ifdef SQLITE_ENABLE_LOAD_EXTENSION
  13078. "ENABLE_LOAD_EXTENSION",
  13079. #endif
  13080. #ifdef SQLITE_ENABLE_LOCKING_STYLE
  13081. "ENABLE_LOCKING_STYLE=" CTIMEOPT_VAL(SQLITE_ENABLE_LOCKING_STYLE),
  13082. #endif
  13083. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  13084. "ENABLE_MEMORY_MANAGEMENT",
  13085. #endif
  13086. #ifdef SQLITE_ENABLE_MEMSYS3
  13087. "ENABLE_MEMSYS3",
  13088. #endif
  13089. #ifdef SQLITE_ENABLE_MEMSYS5
  13090. "ENABLE_MEMSYS5",
  13091. #endif
  13092. #ifdef SQLITE_ENABLE_OVERSIZE_CELL_CHECK
  13093. "ENABLE_OVERSIZE_CELL_CHECK",
  13094. #endif
  13095. #ifdef SQLITE_ENABLE_RTREE
  13096. "ENABLE_RTREE",
  13097. #endif
  13098. #if defined(SQLITE_ENABLE_STAT4)
  13099. "ENABLE_STAT4",
  13100. #elif defined(SQLITE_ENABLE_STAT3)
  13101. "ENABLE_STAT3",
  13102. #endif
  13103. #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
  13104. "ENABLE_UNLOCK_NOTIFY",
  13105. #endif
  13106. #ifdef SQLITE_ENABLE_UPDATE_DELETE_LIMIT
  13107. "ENABLE_UPDATE_DELETE_LIMIT",
  13108. #endif
  13109. #ifdef SQLITE_HAS_CODEC
  13110. "HAS_CODEC",
  13111. #endif
  13112. #ifdef SQLITE_HAVE_ISNAN
  13113. "HAVE_ISNAN",
  13114. #endif
  13115. #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
  13116. "HOMEGROWN_RECURSIVE_MUTEX",
  13117. #endif
  13118. #ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
  13119. "IGNORE_AFP_LOCK_ERRORS",
  13120. #endif
  13121. #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
  13122. "IGNORE_FLOCK_LOCK_ERRORS",
  13123. #endif
  13124. #ifdef SQLITE_INT64_TYPE
  13125. "INT64_TYPE",
  13126. #endif
  13127. #ifdef SQLITE_LOCK_TRACE
  13128. "LOCK_TRACE",
  13129. #endif
  13130. #if defined(SQLITE_MAX_MMAP_SIZE) && !defined(SQLITE_MAX_MMAP_SIZE_xc)
  13131. "MAX_MMAP_SIZE=" CTIMEOPT_VAL(SQLITE_MAX_MMAP_SIZE),
  13132. #endif
  13133. #ifdef SQLITE_MAX_SCHEMA_RETRY
  13134. "MAX_SCHEMA_RETRY=" CTIMEOPT_VAL(SQLITE_MAX_SCHEMA_RETRY),
  13135. #endif
  13136. #ifdef SQLITE_MEMDEBUG
  13137. "MEMDEBUG",
  13138. #endif
  13139. #ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
  13140. "MIXED_ENDIAN_64BIT_FLOAT",
  13141. #endif
  13142. #ifdef SQLITE_NO_SYNC
  13143. "NO_SYNC",
  13144. #endif
  13145. #ifdef SQLITE_OMIT_ALTERTABLE
  13146. "OMIT_ALTERTABLE",
  13147. #endif
  13148. #ifdef SQLITE_OMIT_ANALYZE
  13149. "OMIT_ANALYZE",
  13150. #endif
  13151. #ifdef SQLITE_OMIT_ATTACH
  13152. "OMIT_ATTACH",
  13153. #endif
  13154. #ifdef SQLITE_OMIT_AUTHORIZATION
  13155. "OMIT_AUTHORIZATION",
  13156. #endif
  13157. #ifdef SQLITE_OMIT_AUTOINCREMENT
  13158. "OMIT_AUTOINCREMENT",
  13159. #endif
  13160. #ifdef SQLITE_OMIT_AUTOINIT
  13161. "OMIT_AUTOINIT",
  13162. #endif
  13163. #ifdef SQLITE_OMIT_AUTOMATIC_INDEX
  13164. "OMIT_AUTOMATIC_INDEX",
  13165. #endif
  13166. #ifdef SQLITE_OMIT_AUTORESET
  13167. "OMIT_AUTORESET",
  13168. #endif
  13169. #ifdef SQLITE_OMIT_AUTOVACUUM
  13170. "OMIT_AUTOVACUUM",
  13171. #endif
  13172. #ifdef SQLITE_OMIT_BETWEEN_OPTIMIZATION
  13173. "OMIT_BETWEEN_OPTIMIZATION",
  13174. #endif
  13175. #ifdef SQLITE_OMIT_BLOB_LITERAL
  13176. "OMIT_BLOB_LITERAL",
  13177. #endif
  13178. #ifdef SQLITE_OMIT_BTREECOUNT
  13179. "OMIT_BTREECOUNT",
  13180. #endif
  13181. #ifdef SQLITE_OMIT_BUILTIN_TEST
  13182. "OMIT_BUILTIN_TEST",
  13183. #endif
  13184. #ifdef SQLITE_OMIT_CAST
  13185. "OMIT_CAST",
  13186. #endif
  13187. #ifdef SQLITE_OMIT_CHECK
  13188. "OMIT_CHECK",
  13189. #endif
  13190. #ifdef SQLITE_OMIT_COMPLETE
  13191. "OMIT_COMPLETE",
  13192. #endif
  13193. #ifdef SQLITE_OMIT_COMPOUND_SELECT
  13194. "OMIT_COMPOUND_SELECT",
  13195. #endif
  13196. #ifdef SQLITE_OMIT_CTE
  13197. "OMIT_CTE",
  13198. #endif
  13199. #ifdef SQLITE_OMIT_DATETIME_FUNCS
  13200. "OMIT_DATETIME_FUNCS",
  13201. #endif
  13202. #ifdef SQLITE_OMIT_DECLTYPE
  13203. "OMIT_DECLTYPE",
  13204. #endif
  13205. #ifdef SQLITE_OMIT_DEPRECATED
  13206. "OMIT_DEPRECATED",
  13207. #endif
  13208. #ifdef SQLITE_OMIT_DISKIO
  13209. "OMIT_DISKIO",
  13210. #endif
  13211. #ifdef SQLITE_OMIT_EXPLAIN
  13212. "OMIT_EXPLAIN",
  13213. #endif
  13214. #ifdef SQLITE_OMIT_FLAG_PRAGMAS
  13215. "OMIT_FLAG_PRAGMAS",
  13216. #endif
  13217. #ifdef SQLITE_OMIT_FLOATING_POINT
  13218. "OMIT_FLOATING_POINT",
  13219. #endif
  13220. #ifdef SQLITE_OMIT_FOREIGN_KEY
  13221. "OMIT_FOREIGN_KEY",
  13222. #endif
  13223. #ifdef SQLITE_OMIT_GET_TABLE
  13224. "OMIT_GET_TABLE",
  13225. #endif
  13226. #ifdef SQLITE_OMIT_INCRBLOB
  13227. "OMIT_INCRBLOB",
  13228. #endif
  13229. #ifdef SQLITE_OMIT_INTEGRITY_CHECK
  13230. "OMIT_INTEGRITY_CHECK",
  13231. #endif
  13232. #ifdef SQLITE_OMIT_LIKE_OPTIMIZATION
  13233. "OMIT_LIKE_OPTIMIZATION",
  13234. #endif
  13235. #ifdef SQLITE_OMIT_LOAD_EXTENSION
  13236. "OMIT_LOAD_EXTENSION",
  13237. #endif
  13238. #ifdef SQLITE_OMIT_LOCALTIME
  13239. "OMIT_LOCALTIME",
  13240. #endif
  13241. #ifdef SQLITE_OMIT_LOOKASIDE
  13242. "OMIT_LOOKASIDE",
  13243. #endif
  13244. #ifdef SQLITE_OMIT_MEMORYDB
  13245. "OMIT_MEMORYDB",
  13246. #endif
  13247. #ifdef SQLITE_OMIT_OR_OPTIMIZATION
  13248. "OMIT_OR_OPTIMIZATION",
  13249. #endif
  13250. #ifdef SQLITE_OMIT_PAGER_PRAGMAS
  13251. "OMIT_PAGER_PRAGMAS",
  13252. #endif
  13253. #ifdef SQLITE_OMIT_PRAGMA
  13254. "OMIT_PRAGMA",
  13255. #endif
  13256. #ifdef SQLITE_OMIT_PROGRESS_CALLBACK
  13257. "OMIT_PROGRESS_CALLBACK",
  13258. #endif
  13259. #ifdef SQLITE_OMIT_QUICKBALANCE
  13260. "OMIT_QUICKBALANCE",
  13261. #endif
  13262. #ifdef SQLITE_OMIT_REINDEX
  13263. "OMIT_REINDEX",
  13264. #endif
  13265. #ifdef SQLITE_OMIT_SCHEMA_PRAGMAS
  13266. "OMIT_SCHEMA_PRAGMAS",
  13267. #endif
  13268. #ifdef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
  13269. "OMIT_SCHEMA_VERSION_PRAGMAS",
  13270. #endif
  13271. #ifdef SQLITE_OMIT_SHARED_CACHE
  13272. "OMIT_SHARED_CACHE",
  13273. #endif
  13274. #ifdef SQLITE_OMIT_SUBQUERY
  13275. "OMIT_SUBQUERY",
  13276. #endif
  13277. #ifdef SQLITE_OMIT_TCL_VARIABLE
  13278. "OMIT_TCL_VARIABLE",
  13279. #endif
  13280. #ifdef SQLITE_OMIT_TEMPDB
  13281. "OMIT_TEMPDB",
  13282. #endif
  13283. #ifdef SQLITE_OMIT_TRACE
  13284. "OMIT_TRACE",
  13285. #endif
  13286. #ifdef SQLITE_OMIT_TRIGGER
  13287. "OMIT_TRIGGER",
  13288. #endif
  13289. #ifdef SQLITE_OMIT_TRUNCATE_OPTIMIZATION
  13290. "OMIT_TRUNCATE_OPTIMIZATION",
  13291. #endif
  13292. #ifdef SQLITE_OMIT_UTF16
  13293. "OMIT_UTF16",
  13294. #endif
  13295. #ifdef SQLITE_OMIT_VACUUM
  13296. "OMIT_VACUUM",
  13297. #endif
  13298. #ifdef SQLITE_OMIT_VIEW
  13299. "OMIT_VIEW",
  13300. #endif
  13301. #ifdef SQLITE_OMIT_VIRTUALTABLE
  13302. "OMIT_VIRTUALTABLE",
  13303. #endif
  13304. #ifdef SQLITE_OMIT_WAL
  13305. "OMIT_WAL",
  13306. #endif
  13307. #ifdef SQLITE_OMIT_WSD
  13308. "OMIT_WSD",
  13309. #endif
  13310. #ifdef SQLITE_OMIT_XFER_OPT
  13311. "OMIT_XFER_OPT",
  13312. #endif
  13313. #ifdef SQLITE_PERFORMANCE_TRACE
  13314. "PERFORMANCE_TRACE",
  13315. #endif
  13316. #ifdef SQLITE_PROXY_DEBUG
  13317. "PROXY_DEBUG",
  13318. #endif
  13319. #ifdef SQLITE_RTREE_INT_ONLY
  13320. "RTREE_INT_ONLY",
  13321. #endif
  13322. #ifdef SQLITE_SECURE_DELETE
  13323. "SECURE_DELETE",
  13324. #endif
  13325. #ifdef SQLITE_SMALL_STACK
  13326. "SMALL_STACK",
  13327. #endif
  13328. #ifdef SQLITE_SOUNDEX
  13329. "SOUNDEX",
  13330. #endif
  13331. #ifdef SQLITE_SYSTEM_MALLOC
  13332. "SYSTEM_MALLOC",
  13333. #endif
  13334. #ifdef SQLITE_TCL
  13335. "TCL",
  13336. #endif
  13337. #if defined(SQLITE_TEMP_STORE) && !defined(SQLITE_TEMP_STORE_xc)
  13338. "TEMP_STORE=" CTIMEOPT_VAL(SQLITE_TEMP_STORE),
  13339. #endif
  13340. #ifdef SQLITE_TEST
  13341. "TEST",
  13342. #endif
  13343. #if defined(SQLITE_THREADSAFE)
  13344. "THREADSAFE=" CTIMEOPT_VAL(SQLITE_THREADSAFE),
  13345. #endif
  13346. #ifdef SQLITE_USE_ALLOCA
  13347. "USE_ALLOCA",
  13348. #endif
  13349. #ifdef SQLITE_USER_AUTHENTICATION
  13350. "USER_AUTHENTICATION",
  13351. #endif
  13352. #ifdef SQLITE_WIN32_MALLOC
  13353. "WIN32_MALLOC",
  13354. #endif
  13355. #ifdef SQLITE_ZERO_MALLOC
  13356. "ZERO_MALLOC"
  13357. #endif
  13358. };
  13359. /*
  13360. ** Given the name of a compile-time option, return true if that option
  13361. ** was used and false if not.
  13362. **
  13363. ** The name can optionally begin with "SQLITE_" but the "SQLITE_" prefix
  13364. ** is not required for a match.
  13365. */
  13366. SQLITE_API int sqlite3_compileoption_used(const char *zOptName){
  13367. int i, n;
  13368. #ifdef SQLITE_ENABLE_API_ARMOR
  13369. if( zOptName==0 ){
  13370. (void)SQLITE_MISUSE_BKPT;
  13371. return 0;
  13372. }
  13373. #endif
  13374. if( sqlite3StrNICmp(zOptName, "SQLITE_", 7)==0 ) zOptName += 7;
  13375. n = sqlite3Strlen30(zOptName);
  13376. /* Since ArraySize(azCompileOpt) is normally in single digits, a
  13377. ** linear search is adequate. No need for a binary search. */
  13378. for(i=0; i<ArraySize(azCompileOpt); i++){
  13379. if( sqlite3StrNICmp(zOptName, azCompileOpt[i], n)==0
  13380. && sqlite3IsIdChar((unsigned char)azCompileOpt[i][n])==0
  13381. ){
  13382. return 1;
  13383. }
  13384. }
  13385. return 0;
  13386. }
  13387. /*
  13388. ** Return the N-th compile-time option string. If N is out of range,
  13389. ** return a NULL pointer.
  13390. */
  13391. SQLITE_API const char *sqlite3_compileoption_get(int N){
  13392. if( N>=0 && N<ArraySize(azCompileOpt) ){
  13393. return azCompileOpt[N];
  13394. }
  13395. return 0;
  13396. }
  13397. #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
  13398. /************** End of ctime.c ***********************************************/
  13399. /************** Begin file status.c ******************************************/
  13400. /*
  13401. ** 2008 June 18
  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. **
  13412. ** This module implements the sqlite3_status() interface and related
  13413. ** functionality.
  13414. */
  13415. /************** Include vdbeInt.h in the middle of status.c ******************/
  13416. /************** Begin file vdbeInt.h *****************************************/
  13417. /*
  13418. ** 2003 September 6
  13419. **
  13420. ** The author disclaims copyright to this source code. In place of
  13421. ** a legal notice, here is a blessing:
  13422. **
  13423. ** May you do good and not evil.
  13424. ** May you find forgiveness for yourself and forgive others.
  13425. ** May you share freely, never taking more than you give.
  13426. **
  13427. *************************************************************************
  13428. ** This is the header file for information that is private to the
  13429. ** VDBE. This information used to all be at the top of the single
  13430. ** source code file "vdbe.c". When that file became too big (over
  13431. ** 6000 lines long) it was split up into several smaller files and
  13432. ** this header information was factored out.
  13433. */
  13434. #ifndef _VDBEINT_H_
  13435. #define _VDBEINT_H_
  13436. /*
  13437. ** The maximum number of times that a statement will try to reparse
  13438. ** itself before giving up and returning SQLITE_SCHEMA.
  13439. */
  13440. #ifndef SQLITE_MAX_SCHEMA_RETRY
  13441. # define SQLITE_MAX_SCHEMA_RETRY 50
  13442. #endif
  13443. /*
  13444. ** SQL is translated into a sequence of instructions to be
  13445. ** executed by a virtual machine. Each instruction is an instance
  13446. ** of the following structure.
  13447. */
  13448. typedef struct VdbeOp Op;
  13449. /*
  13450. ** Boolean values
  13451. */
  13452. typedef unsigned Bool;
  13453. /* Opaque type used by code in vdbesort.c */
  13454. typedef struct VdbeSorter VdbeSorter;
  13455. /* Opaque type used by the explainer */
  13456. typedef struct Explain Explain;
  13457. /* Elements of the linked list at Vdbe.pAuxData */
  13458. typedef struct AuxData AuxData;
  13459. /*
  13460. ** A cursor is a pointer into a single BTree within a database file.
  13461. ** The cursor can seek to a BTree entry with a particular key, or
  13462. ** loop over all entries of the Btree. You can also insert new BTree
  13463. ** entries or retrieve the key or data from the entry that the cursor
  13464. ** is currently pointing to.
  13465. **
  13466. ** Cursors can also point to virtual tables, sorters, or "pseudo-tables".
  13467. ** A pseudo-table is a single-row table implemented by registers.
  13468. **
  13469. ** Every cursor that the virtual machine has open is represented by an
  13470. ** instance of the following structure.
  13471. */
  13472. struct VdbeCursor {
  13473. BtCursor *pCursor; /* The cursor structure of the backend */
  13474. Btree *pBt; /* Separate file holding temporary table */
  13475. KeyInfo *pKeyInfo; /* Info about index keys needed by index cursors */
  13476. int seekResult; /* Result of previous sqlite3BtreeMoveto() */
  13477. int pseudoTableReg; /* Register holding pseudotable content. */
  13478. i16 nField; /* Number of fields in the header */
  13479. u16 nHdrParsed; /* Number of header fields parsed so far */
  13480. #ifdef SQLITE_DEBUG
  13481. u8 seekOp; /* Most recent seek operation on this cursor */
  13482. #endif
  13483. i8 iDb; /* Index of cursor database in db->aDb[] (or -1) */
  13484. u8 nullRow; /* True if pointing to a row with no data */
  13485. u8 deferredMoveto; /* A call to sqlite3BtreeMoveto() is needed */
  13486. Bool isEphemeral:1; /* True for an ephemeral table */
  13487. Bool useRandomRowid:1;/* Generate new record numbers semi-randomly */
  13488. Bool isTable:1; /* True if a table requiring integer keys */
  13489. Bool isOrdered:1; /* True if the underlying table is BTREE_UNORDERED */
  13490. Pgno pgnoRoot; /* Root page of the open btree cursor */
  13491. sqlite3_vtab_cursor *pVtabCursor; /* The cursor for a virtual table */
  13492. i64 seqCount; /* Sequence counter */
  13493. i64 movetoTarget; /* Argument to the deferred sqlite3BtreeMoveto() */
  13494. VdbeSorter *pSorter; /* Sorter object for OP_SorterOpen cursors */
  13495. /* Cached information about the header for the data record that the
  13496. ** cursor is currently pointing to. Only valid if cacheStatus matches
  13497. ** Vdbe.cacheCtr. Vdbe.cacheCtr will never take on the value of
  13498. ** CACHE_STALE and so setting cacheStatus=CACHE_STALE guarantees that
  13499. ** the cache is out of date.
  13500. **
  13501. ** aRow might point to (ephemeral) data for the current row, or it might
  13502. ** be NULL.
  13503. */
  13504. u32 cacheStatus; /* Cache is valid if this matches Vdbe.cacheCtr */
  13505. u32 payloadSize; /* Total number of bytes in the record */
  13506. u32 szRow; /* Byte available in aRow */
  13507. u32 iHdrOffset; /* Offset to next unparsed byte of the header */
  13508. const u8 *aRow; /* Data for the current row, if all on one page */
  13509. u32 *aOffset; /* Pointer to aType[nField] */
  13510. u32 aType[1]; /* Type values for all entries in the record */
  13511. /* 2*nField extra array elements allocated for aType[], beyond the one
  13512. ** static element declared in the structure. nField total array slots for
  13513. ** aType[] and nField+1 array slots for aOffset[] */
  13514. };
  13515. typedef struct VdbeCursor VdbeCursor;
  13516. /*
  13517. ** When a sub-program is executed (OP_Program), a structure of this type
  13518. ** is allocated to store the current value of the program counter, as
  13519. ** well as the current memory cell array and various other frame specific
  13520. ** values stored in the Vdbe struct. When the sub-program is finished,
  13521. ** these values are copied back to the Vdbe from the VdbeFrame structure,
  13522. ** restoring the state of the VM to as it was before the sub-program
  13523. ** began executing.
  13524. **
  13525. ** The memory for a VdbeFrame object is allocated and managed by a memory
  13526. ** cell in the parent (calling) frame. When the memory cell is deleted or
  13527. ** overwritten, the VdbeFrame object is not freed immediately. Instead, it
  13528. ** is linked into the Vdbe.pDelFrame list. The contents of the Vdbe.pDelFrame
  13529. ** list is deleted when the VM is reset in VdbeHalt(). The reason for doing
  13530. ** this instead of deleting the VdbeFrame immediately is to avoid recursive
  13531. ** calls to sqlite3VdbeMemRelease() when the memory cells belonging to the
  13532. ** child frame are released.
  13533. **
  13534. ** The currently executing frame is stored in Vdbe.pFrame. Vdbe.pFrame is
  13535. ** set to NULL if the currently executing frame is the main program.
  13536. */
  13537. typedef struct VdbeFrame VdbeFrame;
  13538. struct VdbeFrame {
  13539. Vdbe *v; /* VM this frame belongs to */
  13540. VdbeFrame *pParent; /* Parent of this frame, or NULL if parent is main */
  13541. Op *aOp; /* Program instructions for parent frame */
  13542. Mem *aMem; /* Array of memory cells for parent frame */
  13543. u8 *aOnceFlag; /* Array of OP_Once flags for parent frame */
  13544. VdbeCursor **apCsr; /* Array of Vdbe cursors for parent frame */
  13545. void *token; /* Copy of SubProgram.token */
  13546. i64 lastRowid; /* Last insert rowid (sqlite3.lastRowid) */
  13547. int nCursor; /* Number of entries in apCsr */
  13548. int pc; /* Program Counter in parent (calling) frame */
  13549. int nOp; /* Size of aOp array */
  13550. int nMem; /* Number of entries in aMem */
  13551. int nOnceFlag; /* Number of entries in aOnceFlag */
  13552. int nChildMem; /* Number of memory cells for child frame */
  13553. int nChildCsr; /* Number of cursors for child frame */
  13554. int nChange; /* Statement changes (Vdbe.nChanges) */
  13555. };
  13556. #define VdbeFrameMem(p) ((Mem *)&((u8 *)p)[ROUND8(sizeof(VdbeFrame))])
  13557. /*
  13558. ** A value for VdbeCursor.cacheValid that means the cache is always invalid.
  13559. */
  13560. #define CACHE_STALE 0
  13561. /*
  13562. ** Internally, the vdbe manipulates nearly all SQL values as Mem
  13563. ** structures. Each Mem struct may cache multiple representations (string,
  13564. ** integer etc.) of the same value.
  13565. */
  13566. struct Mem {
  13567. union MemValue {
  13568. double r; /* Real value used when MEM_Real is set in flags */
  13569. i64 i; /* Integer value used when MEM_Int is set in flags */
  13570. int nZero; /* Used when bit MEM_Zero is set in flags */
  13571. FuncDef *pDef; /* Used only when flags==MEM_Agg */
  13572. RowSet *pRowSet; /* Used only when flags==MEM_RowSet */
  13573. VdbeFrame *pFrame; /* Used when flags==MEM_Frame */
  13574. } u;
  13575. u16 flags; /* Some combination of MEM_Null, MEM_Str, MEM_Dyn, etc. */
  13576. u8 enc; /* SQLITE_UTF8, SQLITE_UTF16BE, SQLITE_UTF16LE */
  13577. int n; /* Number of characters in string value, excluding '\0' */
  13578. char *z; /* String or BLOB value */
  13579. /* ShallowCopy only needs to copy the information above */
  13580. char *zMalloc; /* Space to hold MEM_Str or MEM_Blob if szMalloc>0 */
  13581. int szMalloc; /* Size of the zMalloc allocation */
  13582. u32 uTemp; /* Transient storage for serial_type in OP_MakeRecord */
  13583. sqlite3 *db; /* The associated database connection */
  13584. void (*xDel)(void*);/* Destructor for Mem.z - only valid if MEM_Dyn */
  13585. #ifdef SQLITE_DEBUG
  13586. Mem *pScopyFrom; /* This Mem is a shallow copy of pScopyFrom */
  13587. void *pFiller; /* So that sizeof(Mem) is a multiple of 8 */
  13588. #endif
  13589. };
  13590. /* One or more of the following flags are set to indicate the validOK
  13591. ** representations of the value stored in the Mem struct.
  13592. **
  13593. ** If the MEM_Null flag is set, then the value is an SQL NULL value.
  13594. ** No other flags may be set in this case.
  13595. **
  13596. ** If the MEM_Str flag is set then Mem.z points at a string representation.
  13597. ** Usually this is encoded in the same unicode encoding as the main
  13598. ** database (see below for exceptions). If the MEM_Term flag is also
  13599. ** set, then the string is nul terminated. The MEM_Int and MEM_Real
  13600. ** flags may coexist with the MEM_Str flag.
  13601. */
  13602. #define MEM_Null 0x0001 /* Value is NULL */
  13603. #define MEM_Str 0x0002 /* Value is a string */
  13604. #define MEM_Int 0x0004 /* Value is an integer */
  13605. #define MEM_Real 0x0008 /* Value is a real number */
  13606. #define MEM_Blob 0x0010 /* Value is a BLOB */
  13607. #define MEM_AffMask 0x001f /* Mask of affinity bits */
  13608. #define MEM_RowSet 0x0020 /* Value is a RowSet object */
  13609. #define MEM_Frame 0x0040 /* Value is a VdbeFrame object */
  13610. #define MEM_Undefined 0x0080 /* Value is undefined */
  13611. #define MEM_Cleared 0x0100 /* NULL set by OP_Null, not from data */
  13612. #define MEM_TypeMask 0x01ff /* Mask of type bits */
  13613. /* Whenever Mem contains a valid string or blob representation, one of
  13614. ** the following flags must be set to determine the memory management
  13615. ** policy for Mem.z. The MEM_Term flag tells us whether or not the
  13616. ** string is \000 or \u0000 terminated
  13617. */
  13618. #define MEM_Term 0x0200 /* String rep is nul terminated */
  13619. #define MEM_Dyn 0x0400 /* Need to call Mem.xDel() on Mem.z */
  13620. #define MEM_Static 0x0800 /* Mem.z points to a static string */
  13621. #define MEM_Ephem 0x1000 /* Mem.z points to an ephemeral string */
  13622. #define MEM_Agg 0x2000 /* Mem.z points to an agg function context */
  13623. #define MEM_Zero 0x4000 /* Mem.i contains count of 0s appended to blob */
  13624. #ifdef SQLITE_OMIT_INCRBLOB
  13625. #undef MEM_Zero
  13626. #define MEM_Zero 0x0000
  13627. #endif
  13628. /*
  13629. ** Clear any existing type flags from a Mem and replace them with f
  13630. */
  13631. #define MemSetTypeFlag(p, f) \
  13632. ((p)->flags = ((p)->flags&~(MEM_TypeMask|MEM_Zero))|f)
  13633. /*
  13634. ** Return true if a memory cell is not marked as invalid. This macro
  13635. ** is for use inside assert() statements only.
  13636. */
  13637. #ifdef SQLITE_DEBUG
  13638. #define memIsValid(M) ((M)->flags & MEM_Undefined)==0
  13639. #endif
  13640. /*
  13641. ** Each auxiliary data pointer stored by a user defined function
  13642. ** implementation calling sqlite3_set_auxdata() is stored in an instance
  13643. ** of this structure. All such structures associated with a single VM
  13644. ** are stored in a linked list headed at Vdbe.pAuxData. All are destroyed
  13645. ** when the VM is halted (if not before).
  13646. */
  13647. struct AuxData {
  13648. int iOp; /* Instruction number of OP_Function opcode */
  13649. int iArg; /* Index of function argument. */
  13650. void *pAux; /* Aux data pointer */
  13651. void (*xDelete)(void *); /* Destructor for the aux data */
  13652. AuxData *pNext; /* Next element in list */
  13653. };
  13654. /*
  13655. ** The "context" argument for an installable function. A pointer to an
  13656. ** instance of this structure is the first argument to the routines used
  13657. ** implement the SQL functions.
  13658. **
  13659. ** There is a typedef for this structure in sqlite.h. So all routines,
  13660. ** even the public interface to SQLite, can use a pointer to this structure.
  13661. ** But this file is the only place where the internal details of this
  13662. ** structure are known.
  13663. **
  13664. ** This structure is defined inside of vdbeInt.h because it uses substructures
  13665. ** (Mem) which are only defined there.
  13666. */
  13667. struct sqlite3_context {
  13668. Mem *pOut; /* The return value is stored here */
  13669. FuncDef *pFunc; /* Pointer to function information */
  13670. Mem *pMem; /* Memory cell used to store aggregate context */
  13671. Vdbe *pVdbe; /* The VM that owns this context */
  13672. int iOp; /* Instruction number of OP_Function */
  13673. int isError; /* Error code returned by the function. */
  13674. u8 skipFlag; /* Skip accumulator loading if true */
  13675. u8 fErrorOrAux; /* isError!=0 or pVdbe->pAuxData modified */
  13676. };
  13677. /*
  13678. ** An Explain object accumulates indented output which is helpful
  13679. ** in describing recursive data structures.
  13680. */
  13681. struct Explain {
  13682. Vdbe *pVdbe; /* Attach the explanation to this Vdbe */
  13683. StrAccum str; /* The string being accumulated */
  13684. int nIndent; /* Number of elements in aIndent */
  13685. u16 aIndent[100]; /* Levels of indentation */
  13686. char zBase[100]; /* Initial space */
  13687. };
  13688. /* A bitfield type for use inside of structures. Always follow with :N where
  13689. ** N is the number of bits.
  13690. */
  13691. typedef unsigned bft; /* Bit Field Type */
  13692. /*
  13693. ** An instance of the virtual machine. This structure contains the complete
  13694. ** state of the virtual machine.
  13695. **
  13696. ** The "sqlite3_stmt" structure pointer that is returned by sqlite3_prepare()
  13697. ** is really a pointer to an instance of this structure.
  13698. **
  13699. ** The Vdbe.inVtabMethod variable is set to non-zero for the duration of
  13700. ** any virtual table method invocations made by the vdbe program. It is
  13701. ** set to 2 for xDestroy method calls and 1 for all other methods. This
  13702. ** variable is used for two purposes: to allow xDestroy methods to execute
  13703. ** "DROP TABLE" statements and to prevent some nasty side effects of
  13704. ** malloc failure when SQLite is invoked recursively by a virtual table
  13705. ** method function.
  13706. */
  13707. struct Vdbe {
  13708. sqlite3 *db; /* The database connection that owns this statement */
  13709. Op *aOp; /* Space to hold the virtual machine's program */
  13710. Mem *aMem; /* The memory locations */
  13711. Mem **apArg; /* Arguments to currently executing user function */
  13712. Mem *aColName; /* Column names to return */
  13713. Mem *pResultSet; /* Pointer to an array of results */
  13714. Parse *pParse; /* Parsing context used to create this Vdbe */
  13715. int nMem; /* Number of memory locations currently allocated */
  13716. int nOp; /* Number of instructions in the program */
  13717. int nCursor; /* Number of slots in apCsr[] */
  13718. u32 magic; /* Magic number for sanity checking */
  13719. char *zErrMsg; /* Error message written here */
  13720. Vdbe *pPrev,*pNext; /* Linked list of VDBEs with the same Vdbe.db */
  13721. VdbeCursor **apCsr; /* One element of this array for each open cursor */
  13722. Mem *aVar; /* Values for the OP_Variable opcode. */
  13723. char **azVar; /* Name of variables */
  13724. ynVar nVar; /* Number of entries in aVar[] */
  13725. ynVar nzVar; /* Number of entries in azVar[] */
  13726. u32 cacheCtr; /* VdbeCursor row cache generation counter */
  13727. int pc; /* The program counter */
  13728. int rc; /* Value to return */
  13729. u16 nResColumn; /* Number of columns in one row of the result set */
  13730. u8 errorAction; /* Recovery action to do in case of an error */
  13731. u8 minWriteFileFormat; /* Minimum file format for writable database files */
  13732. bft explain:2; /* True if EXPLAIN present on SQL command */
  13733. bft inVtabMethod:2; /* See comments above */
  13734. bft changeCntOn:1; /* True to update the change-counter */
  13735. bft expired:1; /* True if the VM needs to be recompiled */
  13736. bft runOnlyOnce:1; /* Automatically expire on reset */
  13737. bft usesStmtJournal:1; /* True if uses a statement journal */
  13738. bft readOnly:1; /* True for statements that do not write */
  13739. bft bIsReader:1; /* True for statements that read */
  13740. bft isPrepareV2:1; /* True if prepared with prepare_v2() */
  13741. bft doingRerun:1; /* True if rerunning after an auto-reprepare */
  13742. int nChange; /* Number of db changes made since last reset */
  13743. yDbMask btreeMask; /* Bitmask of db->aDb[] entries referenced */
  13744. yDbMask lockMask; /* Subset of btreeMask that requires a lock */
  13745. int iStatement; /* Statement number (or 0 if has not opened stmt) */
  13746. u32 aCounter[5]; /* Counters used by sqlite3_stmt_status() */
  13747. #ifndef SQLITE_OMIT_TRACE
  13748. i64 startTime; /* Time when query started - used for profiling */
  13749. #endif
  13750. i64 iCurrentTime; /* Value of julianday('now') for this statement */
  13751. i64 nFkConstraint; /* Number of imm. FK constraints this VM */
  13752. i64 nStmtDefCons; /* Number of def. constraints when stmt started */
  13753. i64 nStmtDefImmCons; /* Number of def. imm constraints when stmt started */
  13754. char *zSql; /* Text of the SQL statement that generated this */
  13755. void *pFree; /* Free this when deleting the vdbe */
  13756. VdbeFrame *pFrame; /* Parent frame */
  13757. VdbeFrame *pDelFrame; /* List of frame objects to free on VM reset */
  13758. int nFrame; /* Number of frames in pFrame list */
  13759. u32 expmask; /* Binding to these vars invalidates VM */
  13760. SubProgram *pProgram; /* Linked list of all sub-programs used by VM */
  13761. int nOnceFlag; /* Size of array aOnceFlag[] */
  13762. u8 *aOnceFlag; /* Flags for OP_Once */
  13763. AuxData *pAuxData; /* Linked list of auxdata allocations */
  13764. };
  13765. /*
  13766. ** The following are allowed values for Vdbe.magic
  13767. */
  13768. #define VDBE_MAGIC_INIT 0x26bceaa5 /* Building a VDBE program */
  13769. #define VDBE_MAGIC_RUN 0xbdf20da3 /* VDBE is ready to execute */
  13770. #define VDBE_MAGIC_HALT 0x519c2973 /* VDBE has completed execution */
  13771. #define VDBE_MAGIC_DEAD 0xb606c3c8 /* The VDBE has been deallocated */
  13772. /*
  13773. ** Function prototypes
  13774. */
  13775. SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *, VdbeCursor*);
  13776. void sqliteVdbePopStack(Vdbe*,int);
  13777. SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor*);
  13778. SQLITE_PRIVATE int sqlite3VdbeCursorRestore(VdbeCursor*);
  13779. #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
  13780. SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE*, int, Op*);
  13781. #endif
  13782. SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32);
  13783. SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem*, int);
  13784. SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(unsigned char*, Mem*, u32);
  13785. SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(const unsigned char*, u32, Mem*);
  13786. SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(Vdbe*, int, int);
  13787. int sqlite2BtreeKeyCompare(BtCursor *, const void *, int, int, int *);
  13788. SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(sqlite3*,VdbeCursor*,UnpackedRecord*,int*);
  13789. SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3*, BtCursor*, i64*);
  13790. SQLITE_PRIVATE int sqlite3VdbeExec(Vdbe*);
  13791. SQLITE_PRIVATE int sqlite3VdbeList(Vdbe*);
  13792. SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe*);
  13793. SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *, int);
  13794. SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem*);
  13795. SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem*, const Mem*);
  13796. SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem*, const Mem*, int);
  13797. SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem*, Mem*);
  13798. SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem*);
  13799. SQLITE_PRIVATE int sqlite3VdbeMemSetStr(Mem*, const char*, int, u8, void(*)(void*));
  13800. SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem*, i64);
  13801. #ifdef SQLITE_OMIT_FLOATING_POINT
  13802. # define sqlite3VdbeMemSetDouble sqlite3VdbeMemSetInt64
  13803. #else
  13804. SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem*, double);
  13805. #endif
  13806. SQLITE_PRIVATE void sqlite3VdbeMemInit(Mem*,sqlite3*,u16);
  13807. SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem*);
  13808. SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem*,int);
  13809. SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem*);
  13810. SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem*);
  13811. SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem*, u8, u8);
  13812. SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem*);
  13813. SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem*);
  13814. SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem*);
  13815. SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem*);
  13816. SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem*);
  13817. SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem*);
  13818. SQLITE_PRIVATE void sqlite3VdbeMemCast(Mem*,u8,u8);
  13819. SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(BtCursor*,u32,u32,int,Mem*);
  13820. SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p);
  13821. #define VdbeMemDynamic(X) \
  13822. (((X)->flags&(MEM_Agg|MEM_Dyn|MEM_RowSet|MEM_Frame))!=0)
  13823. SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem*, FuncDef*);
  13824. SQLITE_PRIVATE const char *sqlite3OpcodeName(int);
  13825. SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve);
  13826. SQLITE_PRIVATE int sqlite3VdbeMemClearAndResize(Mem *pMem, int n);
  13827. SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *, int);
  13828. SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame*);
  13829. SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *);
  13830. SQLITE_PRIVATE int sqlite3VdbeTransferError(Vdbe *p);
  13831. SQLITE_PRIVATE int sqlite3VdbeSorterInit(sqlite3 *, int, VdbeCursor *);
  13832. SQLITE_PRIVATE void sqlite3VdbeSorterReset(sqlite3 *, VdbeSorter *);
  13833. SQLITE_PRIVATE void sqlite3VdbeSorterClose(sqlite3 *, VdbeCursor *);
  13834. SQLITE_PRIVATE int sqlite3VdbeSorterRowkey(const VdbeCursor *, Mem *);
  13835. SQLITE_PRIVATE int sqlite3VdbeSorterNext(sqlite3 *, const VdbeCursor *, int *);
  13836. SQLITE_PRIVATE int sqlite3VdbeSorterRewind(const VdbeCursor *, int *);
  13837. SQLITE_PRIVATE int sqlite3VdbeSorterWrite(const VdbeCursor *, Mem *);
  13838. SQLITE_PRIVATE int sqlite3VdbeSorterCompare(const VdbeCursor *, Mem *, int, int *);
  13839. #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
  13840. SQLITE_PRIVATE void sqlite3VdbeEnter(Vdbe*);
  13841. SQLITE_PRIVATE void sqlite3VdbeLeave(Vdbe*);
  13842. #else
  13843. # define sqlite3VdbeEnter(X)
  13844. # define sqlite3VdbeLeave(X)
  13845. #endif
  13846. #ifdef SQLITE_DEBUG
  13847. SQLITE_PRIVATE void sqlite3VdbeMemAboutToChange(Vdbe*,Mem*);
  13848. SQLITE_PRIVATE int sqlite3VdbeCheckMemInvariants(Mem*);
  13849. #endif
  13850. #ifndef SQLITE_OMIT_FOREIGN_KEY
  13851. SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *, int);
  13852. #else
  13853. # define sqlite3VdbeCheckFk(p,i) 0
  13854. #endif
  13855. SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem*, u8);
  13856. #ifdef SQLITE_DEBUG
  13857. SQLITE_PRIVATE void sqlite3VdbePrintSql(Vdbe*);
  13858. SQLITE_PRIVATE void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf);
  13859. #endif
  13860. SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem);
  13861. #ifndef SQLITE_OMIT_INCRBLOB
  13862. SQLITE_PRIVATE int sqlite3VdbeMemExpandBlob(Mem *);
  13863. #define ExpandBlob(P) (((P)->flags&MEM_Zero)?sqlite3VdbeMemExpandBlob(P):0)
  13864. #else
  13865. #define sqlite3VdbeMemExpandBlob(x) SQLITE_OK
  13866. #define ExpandBlob(P) SQLITE_OK
  13867. #endif
  13868. #endif /* !defined(_VDBEINT_H_) */
  13869. /************** End of vdbeInt.h *********************************************/
  13870. /************** Continuing where we left off in status.c *********************/
  13871. /*
  13872. ** Variables in which to record status information.
  13873. */
  13874. typedef struct sqlite3StatType sqlite3StatType;
  13875. static SQLITE_WSD struct sqlite3StatType {
  13876. int nowValue[10]; /* Current value */
  13877. int mxValue[10]; /* Maximum value */
  13878. } sqlite3Stat = { {0,}, {0,} };
  13879. /* The "wsdStat" macro will resolve to the status information
  13880. ** state vector. If writable static data is unsupported on the target,
  13881. ** we have to locate the state vector at run-time. In the more common
  13882. ** case where writable static data is supported, wsdStat can refer directly
  13883. ** to the "sqlite3Stat" state vector declared above.
  13884. */
  13885. #ifdef SQLITE_OMIT_WSD
  13886. # define wsdStatInit sqlite3StatType *x = &GLOBAL(sqlite3StatType,sqlite3Stat)
  13887. # define wsdStat x[0]
  13888. #else
  13889. # define wsdStatInit
  13890. # define wsdStat sqlite3Stat
  13891. #endif
  13892. /*
  13893. ** Return the current value of a status parameter.
  13894. */
  13895. SQLITE_PRIVATE int sqlite3StatusValue(int op){
  13896. wsdStatInit;
  13897. assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
  13898. return wsdStat.nowValue[op];
  13899. }
  13900. /*
  13901. ** Add N to the value of a status record. It is assumed that the
  13902. ** caller holds appropriate locks.
  13903. */
  13904. SQLITE_PRIVATE void sqlite3StatusAdd(int op, int N){
  13905. wsdStatInit;
  13906. assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
  13907. wsdStat.nowValue[op] += N;
  13908. if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
  13909. wsdStat.mxValue[op] = wsdStat.nowValue[op];
  13910. }
  13911. }
  13912. /*
  13913. ** Set the value of a status to X.
  13914. */
  13915. SQLITE_PRIVATE void sqlite3StatusSet(int op, int X){
  13916. wsdStatInit;
  13917. assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
  13918. wsdStat.nowValue[op] = X;
  13919. if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
  13920. wsdStat.mxValue[op] = wsdStat.nowValue[op];
  13921. }
  13922. }
  13923. /*
  13924. ** Query status information.
  13925. **
  13926. ** This implementation assumes that reading or writing an aligned
  13927. ** 32-bit integer is an atomic operation. If that assumption is not true,
  13928. ** then this routine is not threadsafe.
  13929. */
  13930. SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag){
  13931. wsdStatInit;
  13932. if( op<0 || op>=ArraySize(wsdStat.nowValue) ){
  13933. return SQLITE_MISUSE_BKPT;
  13934. }
  13935. #ifdef SQLITE_ENABLE_API_ARMOR
  13936. if( pCurrent==0 || pHighwater==0 ) return SQLITE_MISUSE_BKPT;
  13937. #endif
  13938. *pCurrent = wsdStat.nowValue[op];
  13939. *pHighwater = wsdStat.mxValue[op];
  13940. if( resetFlag ){
  13941. wsdStat.mxValue[op] = wsdStat.nowValue[op];
  13942. }
  13943. return SQLITE_OK;
  13944. }
  13945. /*
  13946. ** Query status information for a single database connection
  13947. */
  13948. SQLITE_API int sqlite3_db_status(
  13949. sqlite3 *db, /* The database connection whose status is desired */
  13950. int op, /* Status verb */
  13951. int *pCurrent, /* Write current value here */
  13952. int *pHighwater, /* Write high-water mark here */
  13953. int resetFlag /* Reset high-water mark if true */
  13954. ){
  13955. int rc = SQLITE_OK; /* Return code */
  13956. #ifdef SQLITE_ENABLE_API_ARMOR
  13957. if( !sqlite3SafetyCheckOk(db) || pCurrent==0|| pHighwater==0 ){
  13958. return SQLITE_MISUSE_BKPT;
  13959. }
  13960. #endif
  13961. sqlite3_mutex_enter(db->mutex);
  13962. switch( op ){
  13963. case SQLITE_DBSTATUS_LOOKASIDE_USED: {
  13964. *pCurrent = db->lookaside.nOut;
  13965. *pHighwater = db->lookaside.mxOut;
  13966. if( resetFlag ){
  13967. db->lookaside.mxOut = db->lookaside.nOut;
  13968. }
  13969. break;
  13970. }
  13971. case SQLITE_DBSTATUS_LOOKASIDE_HIT:
  13972. case SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE:
  13973. case SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL: {
  13974. testcase( op==SQLITE_DBSTATUS_LOOKASIDE_HIT );
  13975. testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE );
  13976. testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL );
  13977. assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)>=0 );
  13978. assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)<3 );
  13979. *pCurrent = 0;
  13980. *pHighwater = db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT];
  13981. if( resetFlag ){
  13982. db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT] = 0;
  13983. }
  13984. break;
  13985. }
  13986. /*
  13987. ** Return an approximation for the amount of memory currently used
  13988. ** by all pagers associated with the given database connection. The
  13989. ** highwater mark is meaningless and is returned as zero.
  13990. */
  13991. case SQLITE_DBSTATUS_CACHE_USED: {
  13992. int totalUsed = 0;
  13993. int i;
  13994. sqlite3BtreeEnterAll(db);
  13995. for(i=0; i<db->nDb; i++){
  13996. Btree *pBt = db->aDb[i].pBt;
  13997. if( pBt ){
  13998. Pager *pPager = sqlite3BtreePager(pBt);
  13999. totalUsed += sqlite3PagerMemUsed(pPager);
  14000. }
  14001. }
  14002. sqlite3BtreeLeaveAll(db);
  14003. *pCurrent = totalUsed;
  14004. *pHighwater = 0;
  14005. break;
  14006. }
  14007. /*
  14008. ** *pCurrent gets an accurate estimate of the amount of memory used
  14009. ** to store the schema for all databases (main, temp, and any ATTACHed
  14010. ** databases. *pHighwater is set to zero.
  14011. */
  14012. case SQLITE_DBSTATUS_SCHEMA_USED: {
  14013. int i; /* Used to iterate through schemas */
  14014. int nByte = 0; /* Used to accumulate return value */
  14015. sqlite3BtreeEnterAll(db);
  14016. db->pnBytesFreed = &nByte;
  14017. for(i=0; i<db->nDb; i++){
  14018. Schema *pSchema = db->aDb[i].pSchema;
  14019. if( ALWAYS(pSchema!=0) ){
  14020. HashElem *p;
  14021. nByte += sqlite3GlobalConfig.m.xRoundup(sizeof(HashElem)) * (
  14022. pSchema->tblHash.count
  14023. + pSchema->trigHash.count
  14024. + pSchema->idxHash.count
  14025. + pSchema->fkeyHash.count
  14026. );
  14027. nByte += sqlite3MallocSize(pSchema->tblHash.ht);
  14028. nByte += sqlite3MallocSize(pSchema->trigHash.ht);
  14029. nByte += sqlite3MallocSize(pSchema->idxHash.ht);
  14030. nByte += sqlite3MallocSize(pSchema->fkeyHash.ht);
  14031. for(p=sqliteHashFirst(&pSchema->trigHash); p; p=sqliteHashNext(p)){
  14032. sqlite3DeleteTrigger(db, (Trigger*)sqliteHashData(p));
  14033. }
  14034. for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){
  14035. sqlite3DeleteTable(db, (Table *)sqliteHashData(p));
  14036. }
  14037. }
  14038. }
  14039. db->pnBytesFreed = 0;
  14040. sqlite3BtreeLeaveAll(db);
  14041. *pHighwater = 0;
  14042. *pCurrent = nByte;
  14043. break;
  14044. }
  14045. /*
  14046. ** *pCurrent gets an accurate estimate of the amount of memory used
  14047. ** to store all prepared statements.
  14048. ** *pHighwater is set to zero.
  14049. */
  14050. case SQLITE_DBSTATUS_STMT_USED: {
  14051. struct Vdbe *pVdbe; /* Used to iterate through VMs */
  14052. int nByte = 0; /* Used to accumulate return value */
  14053. db->pnBytesFreed = &nByte;
  14054. for(pVdbe=db->pVdbe; pVdbe; pVdbe=pVdbe->pNext){
  14055. sqlite3VdbeClearObject(db, pVdbe);
  14056. sqlite3DbFree(db, pVdbe);
  14057. }
  14058. db->pnBytesFreed = 0;
  14059. *pHighwater = 0; /* IMP: R-64479-57858 */
  14060. *pCurrent = nByte;
  14061. break;
  14062. }
  14063. /*
  14064. ** Set *pCurrent to the total cache hits or misses encountered by all
  14065. ** pagers the database handle is connected to. *pHighwater is always set
  14066. ** to zero.
  14067. */
  14068. case SQLITE_DBSTATUS_CACHE_HIT:
  14069. case SQLITE_DBSTATUS_CACHE_MISS:
  14070. case SQLITE_DBSTATUS_CACHE_WRITE:{
  14071. int i;
  14072. int nRet = 0;
  14073. assert( SQLITE_DBSTATUS_CACHE_MISS==SQLITE_DBSTATUS_CACHE_HIT+1 );
  14074. assert( SQLITE_DBSTATUS_CACHE_WRITE==SQLITE_DBSTATUS_CACHE_HIT+2 );
  14075. for(i=0; i<db->nDb; i++){
  14076. if( db->aDb[i].pBt ){
  14077. Pager *pPager = sqlite3BtreePager(db->aDb[i].pBt);
  14078. sqlite3PagerCacheStat(pPager, op, resetFlag, &nRet);
  14079. }
  14080. }
  14081. *pHighwater = 0; /* IMP: R-42420-56072 */
  14082. /* IMP: R-54100-20147 */
  14083. /* IMP: R-29431-39229 */
  14084. *pCurrent = nRet;
  14085. break;
  14086. }
  14087. /* Set *pCurrent to non-zero if there are unresolved deferred foreign
  14088. ** key constraints. Set *pCurrent to zero if all foreign key constraints
  14089. ** have been satisfied. The *pHighwater is always set to zero.
  14090. */
  14091. case SQLITE_DBSTATUS_DEFERRED_FKS: {
  14092. *pHighwater = 0; /* IMP: R-11967-56545 */
  14093. *pCurrent = db->nDeferredImmCons>0 || db->nDeferredCons>0;
  14094. break;
  14095. }
  14096. default: {
  14097. rc = SQLITE_ERROR;
  14098. }
  14099. }
  14100. sqlite3_mutex_leave(db->mutex);
  14101. return rc;
  14102. }
  14103. /************** End of status.c **********************************************/
  14104. /************** Begin file date.c ********************************************/
  14105. /*
  14106. ** 2003 October 31
  14107. **
  14108. ** The author disclaims copyright to this source code. In place of
  14109. ** a legal notice, here is a blessing:
  14110. **
  14111. ** May you do good and not evil.
  14112. ** May you find forgiveness for yourself and forgive others.
  14113. ** May you share freely, never taking more than you give.
  14114. **
  14115. *************************************************************************
  14116. ** This file contains the C functions that implement date and time
  14117. ** functions for SQLite.
  14118. **
  14119. ** There is only one exported symbol in this file - the function
  14120. ** sqlite3RegisterDateTimeFunctions() found at the bottom of the file.
  14121. ** All other code has file scope.
  14122. **
  14123. ** SQLite processes all times and dates as Julian Day numbers. The
  14124. ** dates and times are stored as the number of days since noon
  14125. ** in Greenwich on November 24, 4714 B.C. according to the Gregorian
  14126. ** calendar system.
  14127. **
  14128. ** 1970-01-01 00:00:00 is JD 2440587.5
  14129. ** 2000-01-01 00:00:00 is JD 2451544.5
  14130. **
  14131. ** This implementation requires years to be expressed as a 4-digit number
  14132. ** which means that only dates between 0000-01-01 and 9999-12-31 can
  14133. ** be represented, even though julian day numbers allow a much wider
  14134. ** range of dates.
  14135. **
  14136. ** The Gregorian calendar system is used for all dates and times,
  14137. ** even those that predate the Gregorian calendar. Historians usually
  14138. ** use the Julian calendar for dates prior to 1582-10-15 and for some
  14139. ** dates afterwards, depending on locale. Beware of this difference.
  14140. **
  14141. ** The conversion algorithms are implemented based on descriptions
  14142. ** in the following text:
  14143. **
  14144. ** Jean Meeus
  14145. ** Astronomical Algorithms, 2nd Edition, 1998
  14146. ** ISBM 0-943396-61-1
  14147. ** Willmann-Bell, Inc
  14148. ** Richmond, Virginia (USA)
  14149. */
  14150. /* #include <stdlib.h> */
  14151. /* #include <assert.h> */
  14152. #include <time.h>
  14153. #ifndef SQLITE_OMIT_DATETIME_FUNCS
  14154. /*
  14155. ** A structure for holding a single date and time.
  14156. */
  14157. typedef struct DateTime DateTime;
  14158. struct DateTime {
  14159. sqlite3_int64 iJD; /* The julian day number times 86400000 */
  14160. int Y, M, D; /* Year, month, and day */
  14161. int h, m; /* Hour and minutes */
  14162. int tz; /* Timezone offset in minutes */
  14163. double s; /* Seconds */
  14164. char validYMD; /* True (1) if Y,M,D are valid */
  14165. char validHMS; /* True (1) if h,m,s are valid */
  14166. char validJD; /* True (1) if iJD is valid */
  14167. char validTZ; /* True (1) if tz is valid */
  14168. };
  14169. /*
  14170. ** Convert zDate into one or more integers. Additional arguments
  14171. ** come in groups of 5 as follows:
  14172. **
  14173. ** N number of digits in the integer
  14174. ** min minimum allowed value of the integer
  14175. ** max maximum allowed value of the integer
  14176. ** nextC first character after the integer
  14177. ** pVal where to write the integers value.
  14178. **
  14179. ** Conversions continue until one with nextC==0 is encountered.
  14180. ** The function returns the number of successful conversions.
  14181. */
  14182. static int getDigits(const char *zDate, ...){
  14183. va_list ap;
  14184. int val;
  14185. int N;
  14186. int min;
  14187. int max;
  14188. int nextC;
  14189. int *pVal;
  14190. int cnt = 0;
  14191. va_start(ap, zDate);
  14192. do{
  14193. N = va_arg(ap, int);
  14194. min = va_arg(ap, int);
  14195. max = va_arg(ap, int);
  14196. nextC = va_arg(ap, int);
  14197. pVal = va_arg(ap, int*);
  14198. val = 0;
  14199. while( N-- ){
  14200. if( !sqlite3Isdigit(*zDate) ){
  14201. goto end_getDigits;
  14202. }
  14203. val = val*10 + *zDate - '0';
  14204. zDate++;
  14205. }
  14206. if( val<min || val>max || (nextC!=0 && nextC!=*zDate) ){
  14207. goto end_getDigits;
  14208. }
  14209. *pVal = val;
  14210. zDate++;
  14211. cnt++;
  14212. }while( nextC );
  14213. end_getDigits:
  14214. va_end(ap);
  14215. return cnt;
  14216. }
  14217. /*
  14218. ** Parse a timezone extension on the end of a date-time.
  14219. ** The extension is of the form:
  14220. **
  14221. ** (+/-)HH:MM
  14222. **
  14223. ** Or the "zulu" notation:
  14224. **
  14225. ** Z
  14226. **
  14227. ** If the parse is successful, write the number of minutes
  14228. ** of change in p->tz and return 0. If a parser error occurs,
  14229. ** return non-zero.
  14230. **
  14231. ** A missing specifier is not considered an error.
  14232. */
  14233. static int parseTimezone(const char *zDate, DateTime *p){
  14234. int sgn = 0;
  14235. int nHr, nMn;
  14236. int c;
  14237. while( sqlite3Isspace(*zDate) ){ zDate++; }
  14238. p->tz = 0;
  14239. c = *zDate;
  14240. if( c=='-' ){
  14241. sgn = -1;
  14242. }else if( c=='+' ){
  14243. sgn = +1;
  14244. }else if( c=='Z' || c=='z' ){
  14245. zDate++;
  14246. goto zulu_time;
  14247. }else{
  14248. return c!=0;
  14249. }
  14250. zDate++;
  14251. if( getDigits(zDate, 2, 0, 14, ':', &nHr, 2, 0, 59, 0, &nMn)!=2 ){
  14252. return 1;
  14253. }
  14254. zDate += 5;
  14255. p->tz = sgn*(nMn + nHr*60);
  14256. zulu_time:
  14257. while( sqlite3Isspace(*zDate) ){ zDate++; }
  14258. return *zDate!=0;
  14259. }
  14260. /*
  14261. ** Parse times of the form HH:MM or HH:MM:SS or HH:MM:SS.FFFF.
  14262. ** The HH, MM, and SS must each be exactly 2 digits. The
  14263. ** fractional seconds FFFF can be one or more digits.
  14264. **
  14265. ** Return 1 if there is a parsing error and 0 on success.
  14266. */
  14267. static int parseHhMmSs(const char *zDate, DateTime *p){
  14268. int h, m, s;
  14269. double ms = 0.0;
  14270. if( getDigits(zDate, 2, 0, 24, ':', &h, 2, 0, 59, 0, &m)!=2 ){
  14271. return 1;
  14272. }
  14273. zDate += 5;
  14274. if( *zDate==':' ){
  14275. zDate++;
  14276. if( getDigits(zDate, 2, 0, 59, 0, &s)!=1 ){
  14277. return 1;
  14278. }
  14279. zDate += 2;
  14280. if( *zDate=='.' && sqlite3Isdigit(zDate[1]) ){
  14281. double rScale = 1.0;
  14282. zDate++;
  14283. while( sqlite3Isdigit(*zDate) ){
  14284. ms = ms*10.0 + *zDate - '0';
  14285. rScale *= 10.0;
  14286. zDate++;
  14287. }
  14288. ms /= rScale;
  14289. }
  14290. }else{
  14291. s = 0;
  14292. }
  14293. p->validJD = 0;
  14294. p->validHMS = 1;
  14295. p->h = h;
  14296. p->m = m;
  14297. p->s = s + ms;
  14298. if( parseTimezone(zDate, p) ) return 1;
  14299. p->validTZ = (p->tz!=0)?1:0;
  14300. return 0;
  14301. }
  14302. /*
  14303. ** Convert from YYYY-MM-DD HH:MM:SS to julian day. We always assume
  14304. ** that the YYYY-MM-DD is according to the Gregorian calendar.
  14305. **
  14306. ** Reference: Meeus page 61
  14307. */
  14308. static void computeJD(DateTime *p){
  14309. int Y, M, D, A, B, X1, X2;
  14310. if( p->validJD ) return;
  14311. if( p->validYMD ){
  14312. Y = p->Y;
  14313. M = p->M;
  14314. D = p->D;
  14315. }else{
  14316. Y = 2000; /* If no YMD specified, assume 2000-Jan-01 */
  14317. M = 1;
  14318. D = 1;
  14319. }
  14320. if( M<=2 ){
  14321. Y--;
  14322. M += 12;
  14323. }
  14324. A = Y/100;
  14325. B = 2 - A + (A/4);
  14326. X1 = 36525*(Y+4716)/100;
  14327. X2 = 306001*(M+1)/10000;
  14328. p->iJD = (sqlite3_int64)((X1 + X2 + D + B - 1524.5 ) * 86400000);
  14329. p->validJD = 1;
  14330. if( p->validHMS ){
  14331. p->iJD += p->h*3600000 + p->m*60000 + (sqlite3_int64)(p->s*1000);
  14332. if( p->validTZ ){
  14333. p->iJD -= p->tz*60000;
  14334. p->validYMD = 0;
  14335. p->validHMS = 0;
  14336. p->validTZ = 0;
  14337. }
  14338. }
  14339. }
  14340. /*
  14341. ** Parse dates of the form
  14342. **
  14343. ** YYYY-MM-DD HH:MM:SS.FFF
  14344. ** YYYY-MM-DD HH:MM:SS
  14345. ** YYYY-MM-DD HH:MM
  14346. ** YYYY-MM-DD
  14347. **
  14348. ** Write the result into the DateTime structure and return 0
  14349. ** on success and 1 if the input string is not a well-formed
  14350. ** date.
  14351. */
  14352. static int parseYyyyMmDd(const char *zDate, DateTime *p){
  14353. int Y, M, D, neg;
  14354. if( zDate[0]=='-' ){
  14355. zDate++;
  14356. neg = 1;
  14357. }else{
  14358. neg = 0;
  14359. }
  14360. if( getDigits(zDate,4,0,9999,'-',&Y,2,1,12,'-',&M,2,1,31,0,&D)!=3 ){
  14361. return 1;
  14362. }
  14363. zDate += 10;
  14364. while( sqlite3Isspace(*zDate) || 'T'==*(u8*)zDate ){ zDate++; }
  14365. if( parseHhMmSs(zDate, p)==0 ){
  14366. /* We got the time */
  14367. }else if( *zDate==0 ){
  14368. p->validHMS = 0;
  14369. }else{
  14370. return 1;
  14371. }
  14372. p->validJD = 0;
  14373. p->validYMD = 1;
  14374. p->Y = neg ? -Y : Y;
  14375. p->M = M;
  14376. p->D = D;
  14377. if( p->validTZ ){
  14378. computeJD(p);
  14379. }
  14380. return 0;
  14381. }
  14382. /*
  14383. ** Set the time to the current time reported by the VFS.
  14384. **
  14385. ** Return the number of errors.
  14386. */
  14387. static int setDateTimeToCurrent(sqlite3_context *context, DateTime *p){
  14388. p->iJD = sqlite3StmtCurrentTime(context);
  14389. if( p->iJD>0 ){
  14390. p->validJD = 1;
  14391. return 0;
  14392. }else{
  14393. return 1;
  14394. }
  14395. }
  14396. /*
  14397. ** Attempt to parse the given string into a Julian Day Number. Return
  14398. ** the number of errors.
  14399. **
  14400. ** The following are acceptable forms for the input string:
  14401. **
  14402. ** YYYY-MM-DD HH:MM:SS.FFF +/-HH:MM
  14403. ** DDDD.DD
  14404. ** now
  14405. **
  14406. ** In the first form, the +/-HH:MM is always optional. The fractional
  14407. ** seconds extension (the ".FFF") is optional. The seconds portion
  14408. ** (":SS.FFF") is option. The year and date can be omitted as long
  14409. ** as there is a time string. The time string can be omitted as long
  14410. ** as there is a year and date.
  14411. */
  14412. static int parseDateOrTime(
  14413. sqlite3_context *context,
  14414. const char *zDate,
  14415. DateTime *p
  14416. ){
  14417. double r;
  14418. if( parseYyyyMmDd(zDate,p)==0 ){
  14419. return 0;
  14420. }else if( parseHhMmSs(zDate, p)==0 ){
  14421. return 0;
  14422. }else if( sqlite3StrICmp(zDate,"now")==0){
  14423. return setDateTimeToCurrent(context, p);
  14424. }else if( sqlite3AtoF(zDate, &r, sqlite3Strlen30(zDate), SQLITE_UTF8) ){
  14425. p->iJD = (sqlite3_int64)(r*86400000.0 + 0.5);
  14426. p->validJD = 1;
  14427. return 0;
  14428. }
  14429. return 1;
  14430. }
  14431. /*
  14432. ** Compute the Year, Month, and Day from the julian day number.
  14433. */
  14434. static void computeYMD(DateTime *p){
  14435. int Z, A, B, C, D, E, X1;
  14436. if( p->validYMD ) return;
  14437. if( !p->validJD ){
  14438. p->Y = 2000;
  14439. p->M = 1;
  14440. p->D = 1;
  14441. }else{
  14442. Z = (int)((p->iJD + 43200000)/86400000);
  14443. A = (int)((Z - 1867216.25)/36524.25);
  14444. A = Z + 1 + A - (A/4);
  14445. B = A + 1524;
  14446. C = (int)((B - 122.1)/365.25);
  14447. D = (36525*C)/100;
  14448. E = (int)((B-D)/30.6001);
  14449. X1 = (int)(30.6001*E);
  14450. p->D = B - D - X1;
  14451. p->M = E<14 ? E-1 : E-13;
  14452. p->Y = p->M>2 ? C - 4716 : C - 4715;
  14453. }
  14454. p->validYMD = 1;
  14455. }
  14456. /*
  14457. ** Compute the Hour, Minute, and Seconds from the julian day number.
  14458. */
  14459. static void computeHMS(DateTime *p){
  14460. int s;
  14461. if( p->validHMS ) return;
  14462. computeJD(p);
  14463. s = (int)((p->iJD + 43200000) % 86400000);
  14464. p->s = s/1000.0;
  14465. s = (int)p->s;
  14466. p->s -= s;
  14467. p->h = s/3600;
  14468. s -= p->h*3600;
  14469. p->m = s/60;
  14470. p->s += s - p->m*60;
  14471. p->validHMS = 1;
  14472. }
  14473. /*
  14474. ** Compute both YMD and HMS
  14475. */
  14476. static void computeYMD_HMS(DateTime *p){
  14477. computeYMD(p);
  14478. computeHMS(p);
  14479. }
  14480. /*
  14481. ** Clear the YMD and HMS and the TZ
  14482. */
  14483. static void clearYMD_HMS_TZ(DateTime *p){
  14484. p->validYMD = 0;
  14485. p->validHMS = 0;
  14486. p->validTZ = 0;
  14487. }
  14488. /*
  14489. ** On recent Windows platforms, the localtime_s() function is available
  14490. ** as part of the "Secure CRT". It is essentially equivalent to
  14491. ** localtime_r() available under most POSIX platforms, except that the
  14492. ** order of the parameters is reversed.
  14493. **
  14494. ** See http://msdn.microsoft.com/en-us/library/a442x3ye(VS.80).aspx.
  14495. **
  14496. ** If the user has not indicated to use localtime_r() or localtime_s()
  14497. ** already, check for an MSVC build environment that provides
  14498. ** localtime_s().
  14499. */
  14500. #if !defined(HAVE_LOCALTIME_R) && !defined(HAVE_LOCALTIME_S) && \
  14501. defined(_MSC_VER) && defined(_CRT_INSECURE_DEPRECATE)
  14502. #define HAVE_LOCALTIME_S 1
  14503. #endif
  14504. #ifndef SQLITE_OMIT_LOCALTIME
  14505. /*
  14506. ** The following routine implements the rough equivalent of localtime_r()
  14507. ** using whatever operating-system specific localtime facility that
  14508. ** is available. This routine returns 0 on success and
  14509. ** non-zero on any kind of error.
  14510. **
  14511. ** If the sqlite3GlobalConfig.bLocaltimeFault variable is true then this
  14512. ** routine will always fail.
  14513. **
  14514. ** EVIDENCE-OF: R-62172-00036 In this implementation, the standard C
  14515. ** library function localtime_r() is used to assist in the calculation of
  14516. ** local time.
  14517. */
  14518. static int osLocaltime(time_t *t, struct tm *pTm){
  14519. int rc;
  14520. #if (!defined(HAVE_LOCALTIME_R) || !HAVE_LOCALTIME_R) \
  14521. && (!defined(HAVE_LOCALTIME_S) || !HAVE_LOCALTIME_S)
  14522. struct tm *pX;
  14523. #if SQLITE_THREADSAFE>0
  14524. sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  14525. #endif
  14526. sqlite3_mutex_enter(mutex);
  14527. pX = localtime(t);
  14528. #ifndef SQLITE_OMIT_BUILTIN_TEST
  14529. if( sqlite3GlobalConfig.bLocaltimeFault ) pX = 0;
  14530. #endif
  14531. if( pX ) *pTm = *pX;
  14532. sqlite3_mutex_leave(mutex);
  14533. rc = pX==0;
  14534. #else
  14535. #ifndef SQLITE_OMIT_BUILTIN_TEST
  14536. if( sqlite3GlobalConfig.bLocaltimeFault ) return 1;
  14537. #endif
  14538. #if defined(HAVE_LOCALTIME_R) && HAVE_LOCALTIME_R
  14539. rc = localtime_r(t, pTm)==0;
  14540. #else
  14541. rc = localtime_s(pTm, t);
  14542. #endif /* HAVE_LOCALTIME_R */
  14543. #endif /* HAVE_LOCALTIME_R || HAVE_LOCALTIME_S */
  14544. return rc;
  14545. }
  14546. #endif /* SQLITE_OMIT_LOCALTIME */
  14547. #ifndef SQLITE_OMIT_LOCALTIME
  14548. /*
  14549. ** Compute the difference (in milliseconds) between localtime and UTC
  14550. ** (a.k.a. GMT) for the time value p where p is in UTC. If no error occurs,
  14551. ** return this value and set *pRc to SQLITE_OK.
  14552. **
  14553. ** Or, if an error does occur, set *pRc to SQLITE_ERROR. The returned value
  14554. ** is undefined in this case.
  14555. */
  14556. static sqlite3_int64 localtimeOffset(
  14557. DateTime *p, /* Date at which to calculate offset */
  14558. sqlite3_context *pCtx, /* Write error here if one occurs */
  14559. int *pRc /* OUT: Error code. SQLITE_OK or ERROR */
  14560. ){
  14561. DateTime x, y;
  14562. time_t t;
  14563. struct tm sLocal;
  14564. /* Initialize the contents of sLocal to avoid a compiler warning. */
  14565. memset(&sLocal, 0, sizeof(sLocal));
  14566. x = *p;
  14567. computeYMD_HMS(&x);
  14568. if( x.Y<1971 || x.Y>=2038 ){
  14569. /* EVIDENCE-OF: R-55269-29598 The localtime_r() C function normally only
  14570. ** works for years between 1970 and 2037. For dates outside this range,
  14571. ** SQLite attempts to map the year into an equivalent year within this
  14572. ** range, do the calculation, then map the year back.
  14573. */
  14574. x.Y = 2000;
  14575. x.M = 1;
  14576. x.D = 1;
  14577. x.h = 0;
  14578. x.m = 0;
  14579. x.s = 0.0;
  14580. } else {
  14581. int s = (int)(x.s + 0.5);
  14582. x.s = s;
  14583. }
  14584. x.tz = 0;
  14585. x.validJD = 0;
  14586. computeJD(&x);
  14587. t = (time_t)(x.iJD/1000 - 21086676*(i64)10000);
  14588. if( osLocaltime(&t, &sLocal) ){
  14589. sqlite3_result_error(pCtx, "local time unavailable", -1);
  14590. *pRc = SQLITE_ERROR;
  14591. return 0;
  14592. }
  14593. y.Y = sLocal.tm_year + 1900;
  14594. y.M = sLocal.tm_mon + 1;
  14595. y.D = sLocal.tm_mday;
  14596. y.h = sLocal.tm_hour;
  14597. y.m = sLocal.tm_min;
  14598. y.s = sLocal.tm_sec;
  14599. y.validYMD = 1;
  14600. y.validHMS = 1;
  14601. y.validJD = 0;
  14602. y.validTZ = 0;
  14603. computeJD(&y);
  14604. *pRc = SQLITE_OK;
  14605. return y.iJD - x.iJD;
  14606. }
  14607. #endif /* SQLITE_OMIT_LOCALTIME */
  14608. /*
  14609. ** Process a modifier to a date-time stamp. The modifiers are
  14610. ** as follows:
  14611. **
  14612. ** NNN days
  14613. ** NNN hours
  14614. ** NNN minutes
  14615. ** NNN.NNNN seconds
  14616. ** NNN months
  14617. ** NNN years
  14618. ** start of month
  14619. ** start of year
  14620. ** start of week
  14621. ** start of day
  14622. ** weekday N
  14623. ** unixepoch
  14624. ** localtime
  14625. ** utc
  14626. **
  14627. ** Return 0 on success and 1 if there is any kind of error. If the error
  14628. ** is in a system call (i.e. localtime()), then an error message is written
  14629. ** to context pCtx. If the error is an unrecognized modifier, no error is
  14630. ** written to pCtx.
  14631. */
  14632. static int parseModifier(sqlite3_context *pCtx, const char *zMod, DateTime *p){
  14633. int rc = 1;
  14634. int n;
  14635. double r;
  14636. char *z, zBuf[30];
  14637. z = zBuf;
  14638. for(n=0; n<ArraySize(zBuf)-1 && zMod[n]; n++){
  14639. z[n] = (char)sqlite3UpperToLower[(u8)zMod[n]];
  14640. }
  14641. z[n] = 0;
  14642. switch( z[0] ){
  14643. #ifndef SQLITE_OMIT_LOCALTIME
  14644. case 'l': {
  14645. /* localtime
  14646. **
  14647. ** Assuming the current time value is UTC (a.k.a. GMT), shift it to
  14648. ** show local time.
  14649. */
  14650. if( strcmp(z, "localtime")==0 ){
  14651. computeJD(p);
  14652. p->iJD += localtimeOffset(p, pCtx, &rc);
  14653. clearYMD_HMS_TZ(p);
  14654. }
  14655. break;
  14656. }
  14657. #endif
  14658. case 'u': {
  14659. /*
  14660. ** unixepoch
  14661. **
  14662. ** Treat the current value of p->iJD as the number of
  14663. ** seconds since 1970. Convert to a real julian day number.
  14664. */
  14665. if( strcmp(z, "unixepoch")==0 && p->validJD ){
  14666. p->iJD = (p->iJD + 43200)/86400 + 21086676*(i64)10000000;
  14667. clearYMD_HMS_TZ(p);
  14668. rc = 0;
  14669. }
  14670. #ifndef SQLITE_OMIT_LOCALTIME
  14671. else if( strcmp(z, "utc")==0 ){
  14672. sqlite3_int64 c1;
  14673. computeJD(p);
  14674. c1 = localtimeOffset(p, pCtx, &rc);
  14675. if( rc==SQLITE_OK ){
  14676. p->iJD -= c1;
  14677. clearYMD_HMS_TZ(p);
  14678. p->iJD += c1 - localtimeOffset(p, pCtx, &rc);
  14679. }
  14680. }
  14681. #endif
  14682. break;
  14683. }
  14684. case 'w': {
  14685. /*
  14686. ** weekday N
  14687. **
  14688. ** Move the date to the same time on the next occurrence of
  14689. ** weekday N where 0==Sunday, 1==Monday, and so forth. If the
  14690. ** date is already on the appropriate weekday, this is a no-op.
  14691. */
  14692. if( strncmp(z, "weekday ", 8)==0
  14693. && sqlite3AtoF(&z[8], &r, sqlite3Strlen30(&z[8]), SQLITE_UTF8)
  14694. && (n=(int)r)==r && n>=0 && r<7 ){
  14695. sqlite3_int64 Z;
  14696. computeYMD_HMS(p);
  14697. p->validTZ = 0;
  14698. p->validJD = 0;
  14699. computeJD(p);
  14700. Z = ((p->iJD + 129600000)/86400000) % 7;
  14701. if( Z>n ) Z -= 7;
  14702. p->iJD += (n - Z)*86400000;
  14703. clearYMD_HMS_TZ(p);
  14704. rc = 0;
  14705. }
  14706. break;
  14707. }
  14708. case 's': {
  14709. /*
  14710. ** start of TTTTT
  14711. **
  14712. ** Move the date backwards to the beginning of the current day,
  14713. ** or month or year.
  14714. */
  14715. if( strncmp(z, "start of ", 9)!=0 ) break;
  14716. z += 9;
  14717. computeYMD(p);
  14718. p->validHMS = 1;
  14719. p->h = p->m = 0;
  14720. p->s = 0.0;
  14721. p->validTZ = 0;
  14722. p->validJD = 0;
  14723. if( strcmp(z,"month")==0 ){
  14724. p->D = 1;
  14725. rc = 0;
  14726. }else if( strcmp(z,"year")==0 ){
  14727. computeYMD(p);
  14728. p->M = 1;
  14729. p->D = 1;
  14730. rc = 0;
  14731. }else if( strcmp(z,"day")==0 ){
  14732. rc = 0;
  14733. }
  14734. break;
  14735. }
  14736. case '+':
  14737. case '-':
  14738. case '0':
  14739. case '1':
  14740. case '2':
  14741. case '3':
  14742. case '4':
  14743. case '5':
  14744. case '6':
  14745. case '7':
  14746. case '8':
  14747. case '9': {
  14748. double rRounder;
  14749. for(n=1; z[n] && z[n]!=':' && !sqlite3Isspace(z[n]); n++){}
  14750. if( !sqlite3AtoF(z, &r, n, SQLITE_UTF8) ){
  14751. rc = 1;
  14752. break;
  14753. }
  14754. if( z[n]==':' ){
  14755. /* A modifier of the form (+|-)HH:MM:SS.FFF adds (or subtracts) the
  14756. ** specified number of hours, minutes, seconds, and fractional seconds
  14757. ** to the time. The ".FFF" may be omitted. The ":SS.FFF" may be
  14758. ** omitted.
  14759. */
  14760. const char *z2 = z;
  14761. DateTime tx;
  14762. sqlite3_int64 day;
  14763. if( !sqlite3Isdigit(*z2) ) z2++;
  14764. memset(&tx, 0, sizeof(tx));
  14765. if( parseHhMmSs(z2, &tx) ) break;
  14766. computeJD(&tx);
  14767. tx.iJD -= 43200000;
  14768. day = tx.iJD/86400000;
  14769. tx.iJD -= day*86400000;
  14770. if( z[0]=='-' ) tx.iJD = -tx.iJD;
  14771. computeJD(p);
  14772. clearYMD_HMS_TZ(p);
  14773. p->iJD += tx.iJD;
  14774. rc = 0;
  14775. break;
  14776. }
  14777. z += n;
  14778. while( sqlite3Isspace(*z) ) z++;
  14779. n = sqlite3Strlen30(z);
  14780. if( n>10 || n<3 ) break;
  14781. if( z[n-1]=='s' ){ z[n-1] = 0; n--; }
  14782. computeJD(p);
  14783. rc = 0;
  14784. rRounder = r<0 ? -0.5 : +0.5;
  14785. if( n==3 && strcmp(z,"day")==0 ){
  14786. p->iJD += (sqlite3_int64)(r*86400000.0 + rRounder);
  14787. }else if( n==4 && strcmp(z,"hour")==0 ){
  14788. p->iJD += (sqlite3_int64)(r*(86400000.0/24.0) + rRounder);
  14789. }else if( n==6 && strcmp(z,"minute")==0 ){
  14790. p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0)) + rRounder);
  14791. }else if( n==6 && strcmp(z,"second")==0 ){
  14792. p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0*60.0)) + rRounder);
  14793. }else if( n==5 && strcmp(z,"month")==0 ){
  14794. int x, y;
  14795. computeYMD_HMS(p);
  14796. p->M += (int)r;
  14797. x = p->M>0 ? (p->M-1)/12 : (p->M-12)/12;
  14798. p->Y += x;
  14799. p->M -= x*12;
  14800. p->validJD = 0;
  14801. computeJD(p);
  14802. y = (int)r;
  14803. if( y!=r ){
  14804. p->iJD += (sqlite3_int64)((r - y)*30.0*86400000.0 + rRounder);
  14805. }
  14806. }else if( n==4 && strcmp(z,"year")==0 ){
  14807. int y = (int)r;
  14808. computeYMD_HMS(p);
  14809. p->Y += y;
  14810. p->validJD = 0;
  14811. computeJD(p);
  14812. if( y!=r ){
  14813. p->iJD += (sqlite3_int64)((r - y)*365.0*86400000.0 + rRounder);
  14814. }
  14815. }else{
  14816. rc = 1;
  14817. }
  14818. clearYMD_HMS_TZ(p);
  14819. break;
  14820. }
  14821. default: {
  14822. break;
  14823. }
  14824. }
  14825. return rc;
  14826. }
  14827. /*
  14828. ** Process time function arguments. argv[0] is a date-time stamp.
  14829. ** argv[1] and following are modifiers. Parse them all and write
  14830. ** the resulting time into the DateTime structure p. Return 0
  14831. ** on success and 1 if there are any errors.
  14832. **
  14833. ** If there are zero parameters (if even argv[0] is undefined)
  14834. ** then assume a default value of "now" for argv[0].
  14835. */
  14836. static int isDate(
  14837. sqlite3_context *context,
  14838. int argc,
  14839. sqlite3_value **argv,
  14840. DateTime *p
  14841. ){
  14842. int i;
  14843. const unsigned char *z;
  14844. int eType;
  14845. memset(p, 0, sizeof(*p));
  14846. if( argc==0 ){
  14847. return setDateTimeToCurrent(context, p);
  14848. }
  14849. if( (eType = sqlite3_value_type(argv[0]))==SQLITE_FLOAT
  14850. || eType==SQLITE_INTEGER ){
  14851. p->iJD = (sqlite3_int64)(sqlite3_value_double(argv[0])*86400000.0 + 0.5);
  14852. p->validJD = 1;
  14853. }else{
  14854. z = sqlite3_value_text(argv[0]);
  14855. if( !z || parseDateOrTime(context, (char*)z, p) ){
  14856. return 1;
  14857. }
  14858. }
  14859. for(i=1; i<argc; i++){
  14860. z = sqlite3_value_text(argv[i]);
  14861. if( z==0 || parseModifier(context, (char*)z, p) ) return 1;
  14862. }
  14863. return 0;
  14864. }
  14865. /*
  14866. ** The following routines implement the various date and time functions
  14867. ** of SQLite.
  14868. */
  14869. /*
  14870. ** julianday( TIMESTRING, MOD, MOD, ...)
  14871. **
  14872. ** Return the julian day number of the date specified in the arguments
  14873. */
  14874. static void juliandayFunc(
  14875. sqlite3_context *context,
  14876. int argc,
  14877. sqlite3_value **argv
  14878. ){
  14879. DateTime x;
  14880. if( isDate(context, argc, argv, &x)==0 ){
  14881. computeJD(&x);
  14882. sqlite3_result_double(context, x.iJD/86400000.0);
  14883. }
  14884. }
  14885. /*
  14886. ** datetime( TIMESTRING, MOD, MOD, ...)
  14887. **
  14888. ** Return YYYY-MM-DD HH:MM:SS
  14889. */
  14890. static void datetimeFunc(
  14891. sqlite3_context *context,
  14892. int argc,
  14893. sqlite3_value **argv
  14894. ){
  14895. DateTime x;
  14896. if( isDate(context, argc, argv, &x)==0 ){
  14897. char zBuf[100];
  14898. computeYMD_HMS(&x);
  14899. sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d %02d:%02d:%02d",
  14900. x.Y, x.M, x.D, x.h, x.m, (int)(x.s));
  14901. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  14902. }
  14903. }
  14904. /*
  14905. ** time( TIMESTRING, MOD, MOD, ...)
  14906. **
  14907. ** Return HH:MM:SS
  14908. */
  14909. static void timeFunc(
  14910. sqlite3_context *context,
  14911. int argc,
  14912. sqlite3_value **argv
  14913. ){
  14914. DateTime x;
  14915. if( isDate(context, argc, argv, &x)==0 ){
  14916. char zBuf[100];
  14917. computeHMS(&x);
  14918. sqlite3_snprintf(sizeof(zBuf), zBuf, "%02d:%02d:%02d", x.h, x.m, (int)x.s);
  14919. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  14920. }
  14921. }
  14922. /*
  14923. ** date( TIMESTRING, MOD, MOD, ...)
  14924. **
  14925. ** Return YYYY-MM-DD
  14926. */
  14927. static void dateFunc(
  14928. sqlite3_context *context,
  14929. int argc,
  14930. sqlite3_value **argv
  14931. ){
  14932. DateTime x;
  14933. if( isDate(context, argc, argv, &x)==0 ){
  14934. char zBuf[100];
  14935. computeYMD(&x);
  14936. sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d", x.Y, x.M, x.D);
  14937. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  14938. }
  14939. }
  14940. /*
  14941. ** strftime( FORMAT, TIMESTRING, MOD, MOD, ...)
  14942. **
  14943. ** Return a string described by FORMAT. Conversions as follows:
  14944. **
  14945. ** %d day of month
  14946. ** %f ** fractional seconds SS.SSS
  14947. ** %H hour 00-24
  14948. ** %j day of year 000-366
  14949. ** %J ** Julian day number
  14950. ** %m month 01-12
  14951. ** %M minute 00-59
  14952. ** %s seconds since 1970-01-01
  14953. ** %S seconds 00-59
  14954. ** %w day of week 0-6 sunday==0
  14955. ** %W week of year 00-53
  14956. ** %Y year 0000-9999
  14957. ** %% %
  14958. */
  14959. static void strftimeFunc(
  14960. sqlite3_context *context,
  14961. int argc,
  14962. sqlite3_value **argv
  14963. ){
  14964. DateTime x;
  14965. u64 n;
  14966. size_t i,j;
  14967. char *z;
  14968. sqlite3 *db;
  14969. const char *zFmt = (const char*)sqlite3_value_text(argv[0]);
  14970. char zBuf[100];
  14971. if( zFmt==0 || isDate(context, argc-1, argv+1, &x) ) return;
  14972. db = sqlite3_context_db_handle(context);
  14973. for(i=0, n=1; zFmt[i]; i++, n++){
  14974. if( zFmt[i]=='%' ){
  14975. switch( zFmt[i+1] ){
  14976. case 'd':
  14977. case 'H':
  14978. case 'm':
  14979. case 'M':
  14980. case 'S':
  14981. case 'W':
  14982. n++;
  14983. /* fall thru */
  14984. case 'w':
  14985. case '%':
  14986. break;
  14987. case 'f':
  14988. n += 8;
  14989. break;
  14990. case 'j':
  14991. n += 3;
  14992. break;
  14993. case 'Y':
  14994. n += 8;
  14995. break;
  14996. case 's':
  14997. case 'J':
  14998. n += 50;
  14999. break;
  15000. default:
  15001. return; /* ERROR. return a NULL */
  15002. }
  15003. i++;
  15004. }
  15005. }
  15006. testcase( n==sizeof(zBuf)-1 );
  15007. testcase( n==sizeof(zBuf) );
  15008. testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
  15009. testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH] );
  15010. if( n<sizeof(zBuf) ){
  15011. z = zBuf;
  15012. }else if( n>(u64)db->aLimit[SQLITE_LIMIT_LENGTH] ){
  15013. sqlite3_result_error_toobig(context);
  15014. return;
  15015. }else{
  15016. z = sqlite3DbMallocRaw(db, (int)n);
  15017. if( z==0 ){
  15018. sqlite3_result_error_nomem(context);
  15019. return;
  15020. }
  15021. }
  15022. computeJD(&x);
  15023. computeYMD_HMS(&x);
  15024. for(i=j=0; zFmt[i]; i++){
  15025. if( zFmt[i]!='%' ){
  15026. z[j++] = zFmt[i];
  15027. }else{
  15028. i++;
  15029. switch( zFmt[i] ){
  15030. case 'd': sqlite3_snprintf(3, &z[j],"%02d",x.D); j+=2; break;
  15031. case 'f': {
  15032. double s = x.s;
  15033. if( s>59.999 ) s = 59.999;
  15034. sqlite3_snprintf(7, &z[j],"%06.3f", s);
  15035. j += sqlite3Strlen30(&z[j]);
  15036. break;
  15037. }
  15038. case 'H': sqlite3_snprintf(3, &z[j],"%02d",x.h); j+=2; break;
  15039. case 'W': /* Fall thru */
  15040. case 'j': {
  15041. int nDay; /* Number of days since 1st day of year */
  15042. DateTime y = x;
  15043. y.validJD = 0;
  15044. y.M = 1;
  15045. y.D = 1;
  15046. computeJD(&y);
  15047. nDay = (int)((x.iJD-y.iJD+43200000)/86400000);
  15048. if( zFmt[i]=='W' ){
  15049. int wd; /* 0=Monday, 1=Tuesday, ... 6=Sunday */
  15050. wd = (int)(((x.iJD+43200000)/86400000)%7);
  15051. sqlite3_snprintf(3, &z[j],"%02d",(nDay+7-wd)/7);
  15052. j += 2;
  15053. }else{
  15054. sqlite3_snprintf(4, &z[j],"%03d",nDay+1);
  15055. j += 3;
  15056. }
  15057. break;
  15058. }
  15059. case 'J': {
  15060. sqlite3_snprintf(20, &z[j],"%.16g",x.iJD/86400000.0);
  15061. j+=sqlite3Strlen30(&z[j]);
  15062. break;
  15063. }
  15064. case 'm': sqlite3_snprintf(3, &z[j],"%02d",x.M); j+=2; break;
  15065. case 'M': sqlite3_snprintf(3, &z[j],"%02d",x.m); j+=2; break;
  15066. case 's': {
  15067. sqlite3_snprintf(30,&z[j],"%lld",
  15068. (i64)(x.iJD/1000 - 21086676*(i64)10000));
  15069. j += sqlite3Strlen30(&z[j]);
  15070. break;
  15071. }
  15072. case 'S': sqlite3_snprintf(3,&z[j],"%02d",(int)x.s); j+=2; break;
  15073. case 'w': {
  15074. z[j++] = (char)(((x.iJD+129600000)/86400000) % 7) + '0';
  15075. break;
  15076. }
  15077. case 'Y': {
  15078. sqlite3_snprintf(5,&z[j],"%04d",x.Y); j+=sqlite3Strlen30(&z[j]);
  15079. break;
  15080. }
  15081. default: z[j++] = '%'; break;
  15082. }
  15083. }
  15084. }
  15085. z[j] = 0;
  15086. sqlite3_result_text(context, z, -1,
  15087. z==zBuf ? SQLITE_TRANSIENT : SQLITE_DYNAMIC);
  15088. }
  15089. /*
  15090. ** current_time()
  15091. **
  15092. ** This function returns the same value as time('now').
  15093. */
  15094. static void ctimeFunc(
  15095. sqlite3_context *context,
  15096. int NotUsed,
  15097. sqlite3_value **NotUsed2
  15098. ){
  15099. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  15100. timeFunc(context, 0, 0);
  15101. }
  15102. /*
  15103. ** current_date()
  15104. **
  15105. ** This function returns the same value as date('now').
  15106. */
  15107. static void cdateFunc(
  15108. sqlite3_context *context,
  15109. int NotUsed,
  15110. sqlite3_value **NotUsed2
  15111. ){
  15112. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  15113. dateFunc(context, 0, 0);
  15114. }
  15115. /*
  15116. ** current_timestamp()
  15117. **
  15118. ** This function returns the same value as datetime('now').
  15119. */
  15120. static void ctimestampFunc(
  15121. sqlite3_context *context,
  15122. int NotUsed,
  15123. sqlite3_value **NotUsed2
  15124. ){
  15125. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  15126. datetimeFunc(context, 0, 0);
  15127. }
  15128. #endif /* !defined(SQLITE_OMIT_DATETIME_FUNCS) */
  15129. #ifdef SQLITE_OMIT_DATETIME_FUNCS
  15130. /*
  15131. ** If the library is compiled to omit the full-scale date and time
  15132. ** handling (to get a smaller binary), the following minimal version
  15133. ** of the functions current_time(), current_date() and current_timestamp()
  15134. ** are included instead. This is to support column declarations that
  15135. ** include "DEFAULT CURRENT_TIME" etc.
  15136. **
  15137. ** This function uses the C-library functions time(), gmtime()
  15138. ** and strftime(). The format string to pass to strftime() is supplied
  15139. ** as the user-data for the function.
  15140. */
  15141. static void currentTimeFunc(
  15142. sqlite3_context *context,
  15143. int argc,
  15144. sqlite3_value **argv
  15145. ){
  15146. time_t t;
  15147. char *zFormat = (char *)sqlite3_user_data(context);
  15148. sqlite3 *db;
  15149. sqlite3_int64 iT;
  15150. struct tm *pTm;
  15151. struct tm sNow;
  15152. char zBuf[20];
  15153. UNUSED_PARAMETER(argc);
  15154. UNUSED_PARAMETER(argv);
  15155. iT = sqlite3StmtCurrentTime(context);
  15156. if( iT<=0 ) return;
  15157. t = iT/1000 - 10000*(sqlite3_int64)21086676;
  15158. #ifdef HAVE_GMTIME_R
  15159. pTm = gmtime_r(&t, &sNow);
  15160. #else
  15161. sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  15162. pTm = gmtime(&t);
  15163. if( pTm ) memcpy(&sNow, pTm, sizeof(sNow));
  15164. sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  15165. #endif
  15166. if( pTm ){
  15167. strftime(zBuf, 20, zFormat, &sNow);
  15168. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  15169. }
  15170. }
  15171. #endif
  15172. /*
  15173. ** This function registered all of the above C functions as SQL
  15174. ** functions. This should be the only routine in this file with
  15175. ** external linkage.
  15176. */
  15177. SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void){
  15178. static SQLITE_WSD FuncDef aDateTimeFuncs[] = {
  15179. #ifndef SQLITE_OMIT_DATETIME_FUNCS
  15180. FUNCTION(julianday, -1, 0, 0, juliandayFunc ),
  15181. FUNCTION(date, -1, 0, 0, dateFunc ),
  15182. FUNCTION(time, -1, 0, 0, timeFunc ),
  15183. FUNCTION(datetime, -1, 0, 0, datetimeFunc ),
  15184. FUNCTION(strftime, -1, 0, 0, strftimeFunc ),
  15185. FUNCTION(current_time, 0, 0, 0, ctimeFunc ),
  15186. FUNCTION(current_timestamp, 0, 0, 0, ctimestampFunc),
  15187. FUNCTION(current_date, 0, 0, 0, cdateFunc ),
  15188. #else
  15189. STR_FUNCTION(current_time, 0, "%H:%M:%S", 0, currentTimeFunc),
  15190. STR_FUNCTION(current_date, 0, "%Y-%m-%d", 0, currentTimeFunc),
  15191. STR_FUNCTION(current_timestamp, 0, "%Y-%m-%d %H:%M:%S", 0, currentTimeFunc),
  15192. #endif
  15193. };
  15194. int i;
  15195. FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
  15196. FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aDateTimeFuncs);
  15197. for(i=0; i<ArraySize(aDateTimeFuncs); i++){
  15198. sqlite3FuncDefInsert(pHash, &aFunc[i]);
  15199. }
  15200. }
  15201. /************** End of date.c ************************************************/
  15202. /************** Begin file os.c **********************************************/
  15203. /*
  15204. ** 2005 November 29
  15205. **
  15206. ** The author disclaims copyright to this source code. In place of
  15207. ** a legal notice, here is a blessing:
  15208. **
  15209. ** May you do good and not evil.
  15210. ** May you find forgiveness for yourself and forgive others.
  15211. ** May you share freely, never taking more than you give.
  15212. **
  15213. ******************************************************************************
  15214. **
  15215. ** This file contains OS interface code that is common to all
  15216. ** architectures.
  15217. */
  15218. #define _SQLITE_OS_C_ 1
  15219. #undef _SQLITE_OS_C_
  15220. /*
  15221. ** The default SQLite sqlite3_vfs implementations do not allocate
  15222. ** memory (actually, os_unix.c allocates a small amount of memory
  15223. ** from within OsOpen()), but some third-party implementations may.
  15224. ** So we test the effects of a malloc() failing and the sqlite3OsXXX()
  15225. ** function returning SQLITE_IOERR_NOMEM using the DO_OS_MALLOC_TEST macro.
  15226. **
  15227. ** The following functions are instrumented for malloc() failure
  15228. ** testing:
  15229. **
  15230. ** sqlite3OsRead()
  15231. ** sqlite3OsWrite()
  15232. ** sqlite3OsSync()
  15233. ** sqlite3OsFileSize()
  15234. ** sqlite3OsLock()
  15235. ** sqlite3OsCheckReservedLock()
  15236. ** sqlite3OsFileControl()
  15237. ** sqlite3OsShmMap()
  15238. ** sqlite3OsOpen()
  15239. ** sqlite3OsDelete()
  15240. ** sqlite3OsAccess()
  15241. ** sqlite3OsFullPathname()
  15242. **
  15243. */
  15244. #if defined(SQLITE_TEST)
  15245. SQLITE_API int sqlite3_memdebug_vfs_oom_test = 1;
  15246. #define DO_OS_MALLOC_TEST(x) \
  15247. if (sqlite3_memdebug_vfs_oom_test && (!x || !sqlite3IsMemJournal(x))) { \
  15248. void *pTstAlloc = sqlite3Malloc(10); \
  15249. if (!pTstAlloc) return SQLITE_IOERR_NOMEM; \
  15250. sqlite3_free(pTstAlloc); \
  15251. }
  15252. #else
  15253. #define DO_OS_MALLOC_TEST(x)
  15254. #endif
  15255. /*
  15256. ** The following routines are convenience wrappers around methods
  15257. ** of the sqlite3_file object. This is mostly just syntactic sugar. All
  15258. ** of this would be completely automatic if SQLite were coded using
  15259. ** C++ instead of plain old C.
  15260. */
  15261. SQLITE_PRIVATE int sqlite3OsClose(sqlite3_file *pId){
  15262. int rc = SQLITE_OK;
  15263. if( pId->pMethods ){
  15264. rc = pId->pMethods->xClose(pId);
  15265. pId->pMethods = 0;
  15266. }
  15267. return rc;
  15268. }
  15269. SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file *id, void *pBuf, int amt, i64 offset){
  15270. DO_OS_MALLOC_TEST(id);
  15271. return id->pMethods->xRead(id, pBuf, amt, offset);
  15272. }
  15273. SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file *id, const void *pBuf, int amt, i64 offset){
  15274. DO_OS_MALLOC_TEST(id);
  15275. return id->pMethods->xWrite(id, pBuf, amt, offset);
  15276. }
  15277. SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file *id, i64 size){
  15278. return id->pMethods->xTruncate(id, size);
  15279. }
  15280. SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file *id, int flags){
  15281. DO_OS_MALLOC_TEST(id);
  15282. return id->pMethods->xSync(id, flags);
  15283. }
  15284. SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file *id, i64 *pSize){
  15285. DO_OS_MALLOC_TEST(id);
  15286. return id->pMethods->xFileSize(id, pSize);
  15287. }
  15288. SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file *id, int lockType){
  15289. DO_OS_MALLOC_TEST(id);
  15290. return id->pMethods->xLock(id, lockType);
  15291. }
  15292. SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file *id, int lockType){
  15293. return id->pMethods->xUnlock(id, lockType);
  15294. }
  15295. SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut){
  15296. DO_OS_MALLOC_TEST(id);
  15297. return id->pMethods->xCheckReservedLock(id, pResOut);
  15298. }
  15299. /*
  15300. ** Use sqlite3OsFileControl() when we are doing something that might fail
  15301. ** and we need to know about the failures. Use sqlite3OsFileControlHint()
  15302. ** when simply tossing information over the wall to the VFS and we do not
  15303. ** really care if the VFS receives and understands the information since it
  15304. ** is only a hint and can be safely ignored. The sqlite3OsFileControlHint()
  15305. ** routine has no return value since the return value would be meaningless.
  15306. */
  15307. SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file *id, int op, void *pArg){
  15308. #ifdef SQLITE_TEST
  15309. if( op!=SQLITE_FCNTL_COMMIT_PHASETWO ){
  15310. /* Faults are not injected into COMMIT_PHASETWO because, assuming SQLite
  15311. ** is using a regular VFS, it is called after the corresponding
  15312. ** transaction has been committed. Injecting a fault at this point
  15313. ** confuses the test scripts - the COMMIT comand returns SQLITE_NOMEM
  15314. ** but the transaction is committed anyway.
  15315. **
  15316. ** The core must call OsFileControl() though, not OsFileControlHint(),
  15317. ** as if a custom VFS (e.g. zipvfs) returns an error here, it probably
  15318. ** means the commit really has failed and an error should be returned
  15319. ** to the user. */
  15320. DO_OS_MALLOC_TEST(id);
  15321. }
  15322. #endif
  15323. return id->pMethods->xFileControl(id, op, pArg);
  15324. }
  15325. SQLITE_PRIVATE void sqlite3OsFileControlHint(sqlite3_file *id, int op, void *pArg){
  15326. (void)id->pMethods->xFileControl(id, op, pArg);
  15327. }
  15328. SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id){
  15329. int (*xSectorSize)(sqlite3_file*) = id->pMethods->xSectorSize;
  15330. return (xSectorSize ? xSectorSize(id) : SQLITE_DEFAULT_SECTOR_SIZE);
  15331. }
  15332. SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id){
  15333. return id->pMethods->xDeviceCharacteristics(id);
  15334. }
  15335. SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int offset, int n, int flags){
  15336. return id->pMethods->xShmLock(id, offset, n, flags);
  15337. }
  15338. SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id){
  15339. id->pMethods->xShmBarrier(id);
  15340. }
  15341. SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int deleteFlag){
  15342. return id->pMethods->xShmUnmap(id, deleteFlag);
  15343. }
  15344. SQLITE_PRIVATE int sqlite3OsShmMap(
  15345. sqlite3_file *id, /* Database file handle */
  15346. int iPage,
  15347. int pgsz,
  15348. int bExtend, /* True to extend file if necessary */
  15349. void volatile **pp /* OUT: Pointer to mapping */
  15350. ){
  15351. DO_OS_MALLOC_TEST(id);
  15352. return id->pMethods->xShmMap(id, iPage, pgsz, bExtend, pp);
  15353. }
  15354. #if SQLITE_MAX_MMAP_SIZE>0
  15355. /* The real implementation of xFetch and xUnfetch */
  15356. SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64 iOff, int iAmt, void **pp){
  15357. DO_OS_MALLOC_TEST(id);
  15358. return id->pMethods->xFetch(id, iOff, iAmt, pp);
  15359. }
  15360. SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *id, i64 iOff, void *p){
  15361. return id->pMethods->xUnfetch(id, iOff, p);
  15362. }
  15363. #else
  15364. /* No-op stubs to use when memory-mapped I/O is disabled */
  15365. SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64 iOff, int iAmt, void **pp){
  15366. *pp = 0;
  15367. return SQLITE_OK;
  15368. }
  15369. SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *id, i64 iOff, void *p){
  15370. return SQLITE_OK;
  15371. }
  15372. #endif
  15373. /*
  15374. ** The next group of routines are convenience wrappers around the
  15375. ** VFS methods.
  15376. */
  15377. SQLITE_PRIVATE int sqlite3OsOpen(
  15378. sqlite3_vfs *pVfs,
  15379. const char *zPath,
  15380. sqlite3_file *pFile,
  15381. int flags,
  15382. int *pFlagsOut
  15383. ){
  15384. int rc;
  15385. DO_OS_MALLOC_TEST(0);
  15386. /* 0x87f7f is a mask of SQLITE_OPEN_ flags that are valid to be passed
  15387. ** down into the VFS layer. Some SQLITE_OPEN_ flags (for example,
  15388. ** SQLITE_OPEN_FULLMUTEX or SQLITE_OPEN_SHAREDCACHE) are blocked before
  15389. ** reaching the VFS. */
  15390. rc = pVfs->xOpen(pVfs, zPath, pFile, flags & 0x87f7f, pFlagsOut);
  15391. assert( rc==SQLITE_OK || pFile->pMethods==0 );
  15392. return rc;
  15393. }
  15394. SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
  15395. DO_OS_MALLOC_TEST(0);
  15396. assert( dirSync==0 || dirSync==1 );
  15397. return pVfs->xDelete(pVfs, zPath, dirSync);
  15398. }
  15399. SQLITE_PRIVATE int sqlite3OsAccess(
  15400. sqlite3_vfs *pVfs,
  15401. const char *zPath,
  15402. int flags,
  15403. int *pResOut
  15404. ){
  15405. DO_OS_MALLOC_TEST(0);
  15406. return pVfs->xAccess(pVfs, zPath, flags, pResOut);
  15407. }
  15408. SQLITE_PRIVATE int sqlite3OsFullPathname(
  15409. sqlite3_vfs *pVfs,
  15410. const char *zPath,
  15411. int nPathOut,
  15412. char *zPathOut
  15413. ){
  15414. DO_OS_MALLOC_TEST(0);
  15415. zPathOut[0] = 0;
  15416. return pVfs->xFullPathname(pVfs, zPath, nPathOut, zPathOut);
  15417. }
  15418. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  15419. SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *pVfs, const char *zPath){
  15420. return pVfs->xDlOpen(pVfs, zPath);
  15421. }
  15422. SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
  15423. pVfs->xDlError(pVfs, nByte, zBufOut);
  15424. }
  15425. SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *pVfs, void *pHdle, const char *zSym))(void){
  15426. return pVfs->xDlSym(pVfs, pHdle, zSym);
  15427. }
  15428. SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *pVfs, void *pHandle){
  15429. pVfs->xDlClose(pVfs, pHandle);
  15430. }
  15431. #endif /* SQLITE_OMIT_LOAD_EXTENSION */
  15432. SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
  15433. return pVfs->xRandomness(pVfs, nByte, zBufOut);
  15434. }
  15435. SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *pVfs, int nMicro){
  15436. return pVfs->xSleep(pVfs, nMicro);
  15437. }
  15438. SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *pTimeOut){
  15439. int rc;
  15440. /* IMPLEMENTATION-OF: R-49045-42493 SQLite will use the xCurrentTimeInt64()
  15441. ** method to get the current date and time if that method is available
  15442. ** (if iVersion is 2 or greater and the function pointer is not NULL) and
  15443. ** will fall back to xCurrentTime() if xCurrentTimeInt64() is
  15444. ** unavailable.
  15445. */
  15446. if( pVfs->iVersion>=2 && pVfs->xCurrentTimeInt64 ){
  15447. rc = pVfs->xCurrentTimeInt64(pVfs, pTimeOut);
  15448. }else{
  15449. double r;
  15450. rc = pVfs->xCurrentTime(pVfs, &r);
  15451. *pTimeOut = (sqlite3_int64)(r*86400000.0);
  15452. }
  15453. return rc;
  15454. }
  15455. SQLITE_PRIVATE int sqlite3OsOpenMalloc(
  15456. sqlite3_vfs *pVfs,
  15457. const char *zFile,
  15458. sqlite3_file **ppFile,
  15459. int flags,
  15460. int *pOutFlags
  15461. ){
  15462. int rc = SQLITE_NOMEM;
  15463. sqlite3_file *pFile;
  15464. pFile = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile);
  15465. if( pFile ){
  15466. rc = sqlite3OsOpen(pVfs, zFile, pFile, flags, pOutFlags);
  15467. if( rc!=SQLITE_OK ){
  15468. sqlite3_free(pFile);
  15469. }else{
  15470. *ppFile = pFile;
  15471. }
  15472. }
  15473. return rc;
  15474. }
  15475. SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *pFile){
  15476. int rc = SQLITE_OK;
  15477. assert( pFile );
  15478. rc = sqlite3OsClose(pFile);
  15479. sqlite3_free(pFile);
  15480. return rc;
  15481. }
  15482. /*
  15483. ** This function is a wrapper around the OS specific implementation of
  15484. ** sqlite3_os_init(). The purpose of the wrapper is to provide the
  15485. ** ability to simulate a malloc failure, so that the handling of an
  15486. ** error in sqlite3_os_init() by the upper layers can be tested.
  15487. */
  15488. SQLITE_PRIVATE int sqlite3OsInit(void){
  15489. void *p = sqlite3_malloc(10);
  15490. if( p==0 ) return SQLITE_NOMEM;
  15491. sqlite3_free(p);
  15492. return sqlite3_os_init();
  15493. }
  15494. /*
  15495. ** The list of all registered VFS implementations.
  15496. */
  15497. static sqlite3_vfs * SQLITE_WSD vfsList = 0;
  15498. #define vfsList GLOBAL(sqlite3_vfs *, vfsList)
  15499. /*
  15500. ** Locate a VFS by name. If no name is given, simply return the
  15501. ** first VFS on the list.
  15502. */
  15503. SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfs){
  15504. sqlite3_vfs *pVfs = 0;
  15505. #if SQLITE_THREADSAFE
  15506. sqlite3_mutex *mutex;
  15507. #endif
  15508. #ifndef SQLITE_OMIT_AUTOINIT
  15509. int rc = sqlite3_initialize();
  15510. if( rc ) return 0;
  15511. #endif
  15512. #if SQLITE_THREADSAFE
  15513. mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  15514. #endif
  15515. sqlite3_mutex_enter(mutex);
  15516. for(pVfs = vfsList; pVfs; pVfs=pVfs->pNext){
  15517. if( zVfs==0 ) break;
  15518. if( strcmp(zVfs, pVfs->zName)==0 ) break;
  15519. }
  15520. sqlite3_mutex_leave(mutex);
  15521. return pVfs;
  15522. }
  15523. /*
  15524. ** Unlink a VFS from the linked list
  15525. */
  15526. static void vfsUnlink(sqlite3_vfs *pVfs){
  15527. assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) );
  15528. if( pVfs==0 ){
  15529. /* No-op */
  15530. }else if( vfsList==pVfs ){
  15531. vfsList = pVfs->pNext;
  15532. }else if( vfsList ){
  15533. sqlite3_vfs *p = vfsList;
  15534. while( p->pNext && p->pNext!=pVfs ){
  15535. p = p->pNext;
  15536. }
  15537. if( p->pNext==pVfs ){
  15538. p->pNext = pVfs->pNext;
  15539. }
  15540. }
  15541. }
  15542. /*
  15543. ** Register a VFS with the system. It is harmless to register the same
  15544. ** VFS multiple times. The new VFS becomes the default if makeDflt is
  15545. ** true.
  15546. */
  15547. SQLITE_API int sqlite3_vfs_register(sqlite3_vfs *pVfs, int makeDflt){
  15548. MUTEX_LOGIC(sqlite3_mutex *mutex;)
  15549. #ifndef SQLITE_OMIT_AUTOINIT
  15550. int rc = sqlite3_initialize();
  15551. if( rc ) return rc;
  15552. #endif
  15553. #ifdef SQLITE_ENABLE_API_ARMOR
  15554. if( pVfs==0 ) return SQLITE_MISUSE_BKPT;
  15555. #endif
  15556. MUTEX_LOGIC( mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
  15557. sqlite3_mutex_enter(mutex);
  15558. vfsUnlink(pVfs);
  15559. if( makeDflt || vfsList==0 ){
  15560. pVfs->pNext = vfsList;
  15561. vfsList = pVfs;
  15562. }else{
  15563. pVfs->pNext = vfsList->pNext;
  15564. vfsList->pNext = pVfs;
  15565. }
  15566. assert(vfsList);
  15567. sqlite3_mutex_leave(mutex);
  15568. return SQLITE_OK;
  15569. }
  15570. /*
  15571. ** Unregister a VFS so that it is no longer accessible.
  15572. */
  15573. SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs *pVfs){
  15574. #if SQLITE_THREADSAFE
  15575. sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  15576. #endif
  15577. sqlite3_mutex_enter(mutex);
  15578. vfsUnlink(pVfs);
  15579. sqlite3_mutex_leave(mutex);
  15580. return SQLITE_OK;
  15581. }
  15582. /************** End of os.c **************************************************/
  15583. /************** Begin file fault.c *******************************************/
  15584. /*
  15585. ** 2008 Jan 22
  15586. **
  15587. ** The author disclaims copyright to this source code. In place of
  15588. ** a legal notice, here is a blessing:
  15589. **
  15590. ** May you do good and not evil.
  15591. ** May you find forgiveness for yourself and forgive others.
  15592. ** May you share freely, never taking more than you give.
  15593. **
  15594. *************************************************************************
  15595. **
  15596. ** This file contains code to support the concept of "benign"
  15597. ** malloc failures (when the xMalloc() or xRealloc() method of the
  15598. ** sqlite3_mem_methods structure fails to allocate a block of memory
  15599. ** and returns 0).
  15600. **
  15601. ** Most malloc failures are non-benign. After they occur, SQLite
  15602. ** abandons the current operation and returns an error code (usually
  15603. ** SQLITE_NOMEM) to the user. However, sometimes a fault is not necessarily
  15604. ** fatal. For example, if a malloc fails while resizing a hash table, this
  15605. ** is completely recoverable simply by not carrying out the resize. The
  15606. ** hash table will continue to function normally. So a malloc failure
  15607. ** during a hash table resize is a benign fault.
  15608. */
  15609. #ifndef SQLITE_OMIT_BUILTIN_TEST
  15610. /*
  15611. ** Global variables.
  15612. */
  15613. typedef struct BenignMallocHooks BenignMallocHooks;
  15614. static SQLITE_WSD struct BenignMallocHooks {
  15615. void (*xBenignBegin)(void);
  15616. void (*xBenignEnd)(void);
  15617. } sqlite3Hooks = { 0, 0 };
  15618. /* The "wsdHooks" macro will resolve to the appropriate BenignMallocHooks
  15619. ** structure. If writable static data is unsupported on the target,
  15620. ** we have to locate the state vector at run-time. In the more common
  15621. ** case where writable static data is supported, wsdHooks can refer directly
  15622. ** to the "sqlite3Hooks" state vector declared above.
  15623. */
  15624. #ifdef SQLITE_OMIT_WSD
  15625. # define wsdHooksInit \
  15626. BenignMallocHooks *x = &GLOBAL(BenignMallocHooks,sqlite3Hooks)
  15627. # define wsdHooks x[0]
  15628. #else
  15629. # define wsdHooksInit
  15630. # define wsdHooks sqlite3Hooks
  15631. #endif
  15632. /*
  15633. ** Register hooks to call when sqlite3BeginBenignMalloc() and
  15634. ** sqlite3EndBenignMalloc() are called, respectively.
  15635. */
  15636. SQLITE_PRIVATE void sqlite3BenignMallocHooks(
  15637. void (*xBenignBegin)(void),
  15638. void (*xBenignEnd)(void)
  15639. ){
  15640. wsdHooksInit;
  15641. wsdHooks.xBenignBegin = xBenignBegin;
  15642. wsdHooks.xBenignEnd = xBenignEnd;
  15643. }
  15644. /*
  15645. ** This (sqlite3EndBenignMalloc()) is called by SQLite code to indicate that
  15646. ** subsequent malloc failures are benign. A call to sqlite3EndBenignMalloc()
  15647. ** indicates that subsequent malloc failures are non-benign.
  15648. */
  15649. SQLITE_PRIVATE void sqlite3BeginBenignMalloc(void){
  15650. wsdHooksInit;
  15651. if( wsdHooks.xBenignBegin ){
  15652. wsdHooks.xBenignBegin();
  15653. }
  15654. }
  15655. SQLITE_PRIVATE void sqlite3EndBenignMalloc(void){
  15656. wsdHooksInit;
  15657. if( wsdHooks.xBenignEnd ){
  15658. wsdHooks.xBenignEnd();
  15659. }
  15660. }
  15661. #endif /* #ifndef SQLITE_OMIT_BUILTIN_TEST */
  15662. /************** End of fault.c ***********************************************/
  15663. /************** Begin file mem0.c ********************************************/
  15664. /*
  15665. ** 2008 October 28
  15666. **
  15667. ** The author disclaims copyright to this source code. In place of
  15668. ** a legal notice, here is a blessing:
  15669. **
  15670. ** May you do good and not evil.
  15671. ** May you find forgiveness for yourself and forgive others.
  15672. ** May you share freely, never taking more than you give.
  15673. **
  15674. *************************************************************************
  15675. **
  15676. ** This file contains a no-op memory allocation drivers for use when
  15677. ** SQLITE_ZERO_MALLOC is defined. The allocation drivers implemented
  15678. ** here always fail. SQLite will not operate with these drivers. These
  15679. ** are merely placeholders. Real drivers must be substituted using
  15680. ** sqlite3_config() before SQLite will operate.
  15681. */
  15682. /*
  15683. ** This version of the memory allocator is the default. It is
  15684. ** used when no other memory allocator is specified using compile-time
  15685. ** macros.
  15686. */
  15687. #ifdef SQLITE_ZERO_MALLOC
  15688. /*
  15689. ** No-op versions of all memory allocation routines
  15690. */
  15691. static void *sqlite3MemMalloc(int nByte){ return 0; }
  15692. static void sqlite3MemFree(void *pPrior){ return; }
  15693. static void *sqlite3MemRealloc(void *pPrior, int nByte){ return 0; }
  15694. static int sqlite3MemSize(void *pPrior){ return 0; }
  15695. static int sqlite3MemRoundup(int n){ return n; }
  15696. static int sqlite3MemInit(void *NotUsed){ return SQLITE_OK; }
  15697. static void sqlite3MemShutdown(void *NotUsed){ return; }
  15698. /*
  15699. ** This routine is the only routine in this file with external linkage.
  15700. **
  15701. ** Populate the low-level memory allocation function pointers in
  15702. ** sqlite3GlobalConfig.m with pointers to the routines in this file.
  15703. */
  15704. SQLITE_PRIVATE void sqlite3MemSetDefault(void){
  15705. static const sqlite3_mem_methods defaultMethods = {
  15706. sqlite3MemMalloc,
  15707. sqlite3MemFree,
  15708. sqlite3MemRealloc,
  15709. sqlite3MemSize,
  15710. sqlite3MemRoundup,
  15711. sqlite3MemInit,
  15712. sqlite3MemShutdown,
  15713. 0
  15714. };
  15715. sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
  15716. }
  15717. #endif /* SQLITE_ZERO_MALLOC */
  15718. /************** End of mem0.c ************************************************/
  15719. /************** Begin file mem1.c ********************************************/
  15720. /*
  15721. ** 2007 August 14
  15722. **
  15723. ** The author disclaims copyright to this source code. In place of
  15724. ** a legal notice, here is a blessing:
  15725. **
  15726. ** May you do good and not evil.
  15727. ** May you find forgiveness for yourself and forgive others.
  15728. ** May you share freely, never taking more than you give.
  15729. **
  15730. *************************************************************************
  15731. **
  15732. ** This file contains low-level memory allocation drivers for when
  15733. ** SQLite will use the standard C-library malloc/realloc/free interface
  15734. ** to obtain the memory it needs.
  15735. **
  15736. ** This file contains implementations of the low-level memory allocation
  15737. ** routines specified in the sqlite3_mem_methods object. The content of
  15738. ** this file is only used if SQLITE_SYSTEM_MALLOC is defined. The
  15739. ** SQLITE_SYSTEM_MALLOC macro is defined automatically if neither the
  15740. ** SQLITE_MEMDEBUG nor the SQLITE_WIN32_MALLOC macros are defined. The
  15741. ** default configuration is to use memory allocation routines in this
  15742. ** file.
  15743. **
  15744. ** C-preprocessor macro summary:
  15745. **
  15746. ** HAVE_MALLOC_USABLE_SIZE The configure script sets this symbol if
  15747. ** the malloc_usable_size() interface exists
  15748. ** on the target platform. Or, this symbol
  15749. ** can be set manually, if desired.
  15750. ** If an equivalent interface exists by
  15751. ** a different name, using a separate -D
  15752. ** option to rename it.
  15753. **
  15754. ** SQLITE_WITHOUT_ZONEMALLOC Some older macs lack support for the zone
  15755. ** memory allocator. Set this symbol to enable
  15756. ** building on older macs.
  15757. **
  15758. ** SQLITE_WITHOUT_MSIZE Set this symbol to disable the use of
  15759. ** _msize() on windows systems. This might
  15760. ** be necessary when compiling for Delphi,
  15761. ** for example.
  15762. */
  15763. /*
  15764. ** This version of the memory allocator is the default. It is
  15765. ** used when no other memory allocator is specified using compile-time
  15766. ** macros.
  15767. */
  15768. #ifdef SQLITE_SYSTEM_MALLOC
  15769. #if defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC)
  15770. /*
  15771. ** Use the zone allocator available on apple products unless the
  15772. ** SQLITE_WITHOUT_ZONEMALLOC symbol is defined.
  15773. */
  15774. #include <sys/sysctl.h>
  15775. #include <malloc/malloc.h>
  15776. #include <libkern/OSAtomic.h>
  15777. static malloc_zone_t* _sqliteZone_;
  15778. #define SQLITE_MALLOC(x) malloc_zone_malloc(_sqliteZone_, (x))
  15779. #define SQLITE_FREE(x) malloc_zone_free(_sqliteZone_, (x));
  15780. #define SQLITE_REALLOC(x,y) malloc_zone_realloc(_sqliteZone_, (x), (y))
  15781. #define SQLITE_MALLOCSIZE(x) \
  15782. (_sqliteZone_ ? _sqliteZone_->size(_sqliteZone_,x) : malloc_size(x))
  15783. #else /* if not __APPLE__ */
  15784. /*
  15785. ** Use standard C library malloc and free on non-Apple systems.
  15786. ** Also used by Apple systems if SQLITE_WITHOUT_ZONEMALLOC is defined.
  15787. */
  15788. #define SQLITE_MALLOC(x) malloc(x)
  15789. #define SQLITE_FREE(x) free(x)
  15790. #define SQLITE_REALLOC(x,y) realloc((x),(y))
  15791. /*
  15792. ** The malloc.h header file is needed for malloc_usable_size() function
  15793. ** on some systems (e.g. Linux).
  15794. */
  15795. #if defined(HAVE_MALLOC_H) && defined(HAVE_MALLOC_USABLE_SIZE)
  15796. # define SQLITE_USE_MALLOC_H
  15797. # define SQLITE_USE_MALLOC_USABLE_SIZE
  15798. /*
  15799. ** The MSVCRT has malloc_usable_size(), but it is called _msize(). The
  15800. ** use of _msize() is automatic, but can be disabled by compiling with
  15801. ** -DSQLITE_WITHOUT_MSIZE. Using the _msize() function also requires
  15802. ** the malloc.h header file.
  15803. */
  15804. #elif defined(_MSC_VER) && !defined(SQLITE_WITHOUT_MSIZE)
  15805. # define SQLITE_USE_MALLOC_H
  15806. # define SQLITE_USE_MSIZE
  15807. #endif
  15808. /*
  15809. ** Include the malloc.h header file, if necessary. Also set define macro
  15810. ** SQLITE_MALLOCSIZE to the appropriate function name, which is _msize()
  15811. ** for MSVC and malloc_usable_size() for most other systems (e.g. Linux).
  15812. ** The memory size function can always be overridden manually by defining
  15813. ** the macro SQLITE_MALLOCSIZE to the desired function name.
  15814. */
  15815. #if defined(SQLITE_USE_MALLOC_H)
  15816. # include <malloc.h>
  15817. # if defined(SQLITE_USE_MALLOC_USABLE_SIZE)
  15818. # if !defined(SQLITE_MALLOCSIZE)
  15819. # define SQLITE_MALLOCSIZE(x) malloc_usable_size(x)
  15820. # endif
  15821. # elif defined(SQLITE_USE_MSIZE)
  15822. # if !defined(SQLITE_MALLOCSIZE)
  15823. # define SQLITE_MALLOCSIZE _msize
  15824. # endif
  15825. # endif
  15826. #endif /* defined(SQLITE_USE_MALLOC_H) */
  15827. #endif /* __APPLE__ or not __APPLE__ */
  15828. /*
  15829. ** Like malloc(), but remember the size of the allocation
  15830. ** so that we can find it later using sqlite3MemSize().
  15831. **
  15832. ** For this low-level routine, we are guaranteed that nByte>0 because
  15833. ** cases of nByte<=0 will be intercepted and dealt with by higher level
  15834. ** routines.
  15835. */
  15836. static void *sqlite3MemMalloc(int nByte){
  15837. #ifdef SQLITE_MALLOCSIZE
  15838. void *p = SQLITE_MALLOC( nByte );
  15839. if( p==0 ){
  15840. testcase( sqlite3GlobalConfig.xLog!=0 );
  15841. sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
  15842. }
  15843. return p;
  15844. #else
  15845. sqlite3_int64 *p;
  15846. assert( nByte>0 );
  15847. nByte = ROUND8(nByte);
  15848. p = SQLITE_MALLOC( nByte+8 );
  15849. if( p ){
  15850. p[0] = nByte;
  15851. p++;
  15852. }else{
  15853. testcase( sqlite3GlobalConfig.xLog!=0 );
  15854. sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
  15855. }
  15856. return (void *)p;
  15857. #endif
  15858. }
  15859. /*
  15860. ** Like free() but works for allocations obtained from sqlite3MemMalloc()
  15861. ** or sqlite3MemRealloc().
  15862. **
  15863. ** For this low-level routine, we already know that pPrior!=0 since
  15864. ** cases where pPrior==0 will have been intecepted and dealt with
  15865. ** by higher-level routines.
  15866. */
  15867. static void sqlite3MemFree(void *pPrior){
  15868. #ifdef SQLITE_MALLOCSIZE
  15869. SQLITE_FREE(pPrior);
  15870. #else
  15871. sqlite3_int64 *p = (sqlite3_int64*)pPrior;
  15872. assert( pPrior!=0 );
  15873. p--;
  15874. SQLITE_FREE(p);
  15875. #endif
  15876. }
  15877. /*
  15878. ** Report the allocated size of a prior return from xMalloc()
  15879. ** or xRealloc().
  15880. */
  15881. static int sqlite3MemSize(void *pPrior){
  15882. #ifdef SQLITE_MALLOCSIZE
  15883. return pPrior ? (int)SQLITE_MALLOCSIZE(pPrior) : 0;
  15884. #else
  15885. sqlite3_int64 *p;
  15886. if( pPrior==0 ) return 0;
  15887. p = (sqlite3_int64*)pPrior;
  15888. p--;
  15889. return (int)p[0];
  15890. #endif
  15891. }
  15892. /*
  15893. ** Like realloc(). Resize an allocation previously obtained from
  15894. ** sqlite3MemMalloc().
  15895. **
  15896. ** For this low-level interface, we know that pPrior!=0. Cases where
  15897. ** pPrior==0 while have been intercepted by higher-level routine and
  15898. ** redirected to xMalloc. Similarly, we know that nByte>0 because
  15899. ** cases where nByte<=0 will have been intercepted by higher-level
  15900. ** routines and redirected to xFree.
  15901. */
  15902. static void *sqlite3MemRealloc(void *pPrior, int nByte){
  15903. #ifdef SQLITE_MALLOCSIZE
  15904. void *p = SQLITE_REALLOC(pPrior, nByte);
  15905. if( p==0 ){
  15906. testcase( sqlite3GlobalConfig.xLog!=0 );
  15907. sqlite3_log(SQLITE_NOMEM,
  15908. "failed memory resize %u to %u bytes",
  15909. SQLITE_MALLOCSIZE(pPrior), nByte);
  15910. }
  15911. return p;
  15912. #else
  15913. sqlite3_int64 *p = (sqlite3_int64*)pPrior;
  15914. assert( pPrior!=0 && nByte>0 );
  15915. assert( nByte==ROUND8(nByte) ); /* EV: R-46199-30249 */
  15916. p--;
  15917. p = SQLITE_REALLOC(p, nByte+8 );
  15918. if( p ){
  15919. p[0] = nByte;
  15920. p++;
  15921. }else{
  15922. testcase( sqlite3GlobalConfig.xLog!=0 );
  15923. sqlite3_log(SQLITE_NOMEM,
  15924. "failed memory resize %u to %u bytes",
  15925. sqlite3MemSize(pPrior), nByte);
  15926. }
  15927. return (void*)p;
  15928. #endif
  15929. }
  15930. /*
  15931. ** Round up a request size to the next valid allocation size.
  15932. */
  15933. static int sqlite3MemRoundup(int n){
  15934. return ROUND8(n);
  15935. }
  15936. /*
  15937. ** Initialize this module.
  15938. */
  15939. static int sqlite3MemInit(void *NotUsed){
  15940. #if defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC)
  15941. int cpuCount;
  15942. size_t len;
  15943. if( _sqliteZone_ ){
  15944. return SQLITE_OK;
  15945. }
  15946. len = sizeof(cpuCount);
  15947. /* One usually wants to use hw.acctivecpu for MT decisions, but not here */
  15948. sysctlbyname("hw.ncpu", &cpuCount, &len, NULL, 0);
  15949. if( cpuCount>1 ){
  15950. /* defer MT decisions to system malloc */
  15951. _sqliteZone_ = malloc_default_zone();
  15952. }else{
  15953. /* only 1 core, use our own zone to contention over global locks,
  15954. ** e.g. we have our own dedicated locks */
  15955. bool success;
  15956. malloc_zone_t* newzone = malloc_create_zone(4096, 0);
  15957. malloc_set_zone_name(newzone, "Sqlite_Heap");
  15958. do{
  15959. success = OSAtomicCompareAndSwapPtrBarrier(NULL, newzone,
  15960. (void * volatile *)&_sqliteZone_);
  15961. }while(!_sqliteZone_);
  15962. if( !success ){
  15963. /* somebody registered a zone first */
  15964. malloc_destroy_zone(newzone);
  15965. }
  15966. }
  15967. #endif
  15968. UNUSED_PARAMETER(NotUsed);
  15969. return SQLITE_OK;
  15970. }
  15971. /*
  15972. ** Deinitialize this module.
  15973. */
  15974. static void sqlite3MemShutdown(void *NotUsed){
  15975. UNUSED_PARAMETER(NotUsed);
  15976. return;
  15977. }
  15978. /*
  15979. ** This routine is the only routine in this file with external linkage.
  15980. **
  15981. ** Populate the low-level memory allocation function pointers in
  15982. ** sqlite3GlobalConfig.m with pointers to the routines in this file.
  15983. */
  15984. SQLITE_PRIVATE void sqlite3MemSetDefault(void){
  15985. static const sqlite3_mem_methods defaultMethods = {
  15986. sqlite3MemMalloc,
  15987. sqlite3MemFree,
  15988. sqlite3MemRealloc,
  15989. sqlite3MemSize,
  15990. sqlite3MemRoundup,
  15991. sqlite3MemInit,
  15992. sqlite3MemShutdown,
  15993. 0
  15994. };
  15995. sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
  15996. }
  15997. #endif /* SQLITE_SYSTEM_MALLOC */
  15998. /************** End of mem1.c ************************************************/
  15999. /************** Begin file mem2.c ********************************************/
  16000. /*
  16001. ** 2007 August 15
  16002. **
  16003. ** The author disclaims copyright to this source code. In place of
  16004. ** a legal notice, here is a blessing:
  16005. **
  16006. ** May you do good and not evil.
  16007. ** May you find forgiveness for yourself and forgive others.
  16008. ** May you share freely, never taking more than you give.
  16009. **
  16010. *************************************************************************
  16011. **
  16012. ** This file contains low-level memory allocation drivers for when
  16013. ** SQLite will use the standard C-library malloc/realloc/free interface
  16014. ** to obtain the memory it needs while adding lots of additional debugging
  16015. ** information to each allocation in order to help detect and fix memory
  16016. ** leaks and memory usage errors.
  16017. **
  16018. ** This file contains implementations of the low-level memory allocation
  16019. ** routines specified in the sqlite3_mem_methods object.
  16020. */
  16021. /*
  16022. ** This version of the memory allocator is used only if the
  16023. ** SQLITE_MEMDEBUG macro is defined
  16024. */
  16025. #ifdef SQLITE_MEMDEBUG
  16026. /*
  16027. ** The backtrace functionality is only available with GLIBC
  16028. */
  16029. #ifdef __GLIBC__
  16030. extern int backtrace(void**,int);
  16031. extern void backtrace_symbols_fd(void*const*,int,int);
  16032. #else
  16033. # define backtrace(A,B) 1
  16034. # define backtrace_symbols_fd(A,B,C)
  16035. #endif
  16036. /* #include <stdio.h> */
  16037. /*
  16038. ** Each memory allocation looks like this:
  16039. **
  16040. ** ------------------------------------------------------------------------
  16041. ** | Title | backtrace pointers | MemBlockHdr | allocation | EndGuard |
  16042. ** ------------------------------------------------------------------------
  16043. **
  16044. ** The application code sees only a pointer to the allocation. We have
  16045. ** to back up from the allocation pointer to find the MemBlockHdr. The
  16046. ** MemBlockHdr tells us the size of the allocation and the number of
  16047. ** backtrace pointers. There is also a guard word at the end of the
  16048. ** MemBlockHdr.
  16049. */
  16050. struct MemBlockHdr {
  16051. i64 iSize; /* Size of this allocation */
  16052. struct MemBlockHdr *pNext, *pPrev; /* Linked list of all unfreed memory */
  16053. char nBacktrace; /* Number of backtraces on this alloc */
  16054. char nBacktraceSlots; /* Available backtrace slots */
  16055. u8 nTitle; /* Bytes of title; includes '\0' */
  16056. u8 eType; /* Allocation type code */
  16057. int iForeGuard; /* Guard word for sanity */
  16058. };
  16059. /*
  16060. ** Guard words
  16061. */
  16062. #define FOREGUARD 0x80F5E153
  16063. #define REARGUARD 0xE4676B53
  16064. /*
  16065. ** Number of malloc size increments to track.
  16066. */
  16067. #define NCSIZE 1000
  16068. /*
  16069. ** All of the static variables used by this module are collected
  16070. ** into a single structure named "mem". This is to keep the
  16071. ** static variables organized and to reduce namespace pollution
  16072. ** when this module is combined with other in the amalgamation.
  16073. */
  16074. static struct {
  16075. /*
  16076. ** Mutex to control access to the memory allocation subsystem.
  16077. */
  16078. sqlite3_mutex *mutex;
  16079. /*
  16080. ** Head and tail of a linked list of all outstanding allocations
  16081. */
  16082. struct MemBlockHdr *pFirst;
  16083. struct MemBlockHdr *pLast;
  16084. /*
  16085. ** The number of levels of backtrace to save in new allocations.
  16086. */
  16087. int nBacktrace;
  16088. void (*xBacktrace)(int, int, void **);
  16089. /*
  16090. ** Title text to insert in front of each block
  16091. */
  16092. int nTitle; /* Bytes of zTitle to save. Includes '\0' and padding */
  16093. char zTitle[100]; /* The title text */
  16094. /*
  16095. ** sqlite3MallocDisallow() increments the following counter.
  16096. ** sqlite3MallocAllow() decrements it.
  16097. */
  16098. int disallow; /* Do not allow memory allocation */
  16099. /*
  16100. ** Gather statistics on the sizes of memory allocations.
  16101. ** nAlloc[i] is the number of allocation attempts of i*8
  16102. ** bytes. i==NCSIZE is the number of allocation attempts for
  16103. ** sizes more than NCSIZE*8 bytes.
  16104. */
  16105. int nAlloc[NCSIZE]; /* Total number of allocations */
  16106. int nCurrent[NCSIZE]; /* Current number of allocations */
  16107. int mxCurrent[NCSIZE]; /* Highwater mark for nCurrent */
  16108. } mem;
  16109. /*
  16110. ** Adjust memory usage statistics
  16111. */
  16112. static void adjustStats(int iSize, int increment){
  16113. int i = ROUND8(iSize)/8;
  16114. if( i>NCSIZE-1 ){
  16115. i = NCSIZE - 1;
  16116. }
  16117. if( increment>0 ){
  16118. mem.nAlloc[i]++;
  16119. mem.nCurrent[i]++;
  16120. if( mem.nCurrent[i]>mem.mxCurrent[i] ){
  16121. mem.mxCurrent[i] = mem.nCurrent[i];
  16122. }
  16123. }else{
  16124. mem.nCurrent[i]--;
  16125. assert( mem.nCurrent[i]>=0 );
  16126. }
  16127. }
  16128. /*
  16129. ** Given an allocation, find the MemBlockHdr for that allocation.
  16130. **
  16131. ** This routine checks the guards at either end of the allocation and
  16132. ** if they are incorrect it asserts.
  16133. */
  16134. static struct MemBlockHdr *sqlite3MemsysGetHeader(void *pAllocation){
  16135. struct MemBlockHdr *p;
  16136. int *pInt;
  16137. u8 *pU8;
  16138. int nReserve;
  16139. p = (struct MemBlockHdr*)pAllocation;
  16140. p--;
  16141. assert( p->iForeGuard==(int)FOREGUARD );
  16142. nReserve = ROUND8(p->iSize);
  16143. pInt = (int*)pAllocation;
  16144. pU8 = (u8*)pAllocation;
  16145. assert( pInt[nReserve/sizeof(int)]==(int)REARGUARD );
  16146. /* This checks any of the "extra" bytes allocated due
  16147. ** to rounding up to an 8 byte boundary to ensure
  16148. ** they haven't been overwritten.
  16149. */
  16150. while( nReserve-- > p->iSize ) assert( pU8[nReserve]==0x65 );
  16151. return p;
  16152. }
  16153. /*
  16154. ** Return the number of bytes currently allocated at address p.
  16155. */
  16156. static int sqlite3MemSize(void *p){
  16157. struct MemBlockHdr *pHdr;
  16158. if( !p ){
  16159. return 0;
  16160. }
  16161. pHdr = sqlite3MemsysGetHeader(p);
  16162. return (int)pHdr->iSize;
  16163. }
  16164. /*
  16165. ** Initialize the memory allocation subsystem.
  16166. */
  16167. static int sqlite3MemInit(void *NotUsed){
  16168. UNUSED_PARAMETER(NotUsed);
  16169. assert( (sizeof(struct MemBlockHdr)&7) == 0 );
  16170. if( !sqlite3GlobalConfig.bMemstat ){
  16171. /* If memory status is enabled, then the malloc.c wrapper will already
  16172. ** hold the STATIC_MEM mutex when the routines here are invoked. */
  16173. mem.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
  16174. }
  16175. return SQLITE_OK;
  16176. }
  16177. /*
  16178. ** Deinitialize the memory allocation subsystem.
  16179. */
  16180. static void sqlite3MemShutdown(void *NotUsed){
  16181. UNUSED_PARAMETER(NotUsed);
  16182. mem.mutex = 0;
  16183. }
  16184. /*
  16185. ** Round up a request size to the next valid allocation size.
  16186. */
  16187. static int sqlite3MemRoundup(int n){
  16188. return ROUND8(n);
  16189. }
  16190. /*
  16191. ** Fill a buffer with pseudo-random bytes. This is used to preset
  16192. ** the content of a new memory allocation to unpredictable values and
  16193. ** to clear the content of a freed allocation to unpredictable values.
  16194. */
  16195. static void randomFill(char *pBuf, int nByte){
  16196. unsigned int x, y, r;
  16197. x = SQLITE_PTR_TO_INT(pBuf);
  16198. y = nByte | 1;
  16199. while( nByte >= 4 ){
  16200. x = (x>>1) ^ (-(int)(x&1) & 0xd0000001);
  16201. y = y*1103515245 + 12345;
  16202. r = x ^ y;
  16203. *(int*)pBuf = r;
  16204. pBuf += 4;
  16205. nByte -= 4;
  16206. }
  16207. while( nByte-- > 0 ){
  16208. x = (x>>1) ^ (-(int)(x&1) & 0xd0000001);
  16209. y = y*1103515245 + 12345;
  16210. r = x ^ y;
  16211. *(pBuf++) = r & 0xff;
  16212. }
  16213. }
  16214. /*
  16215. ** Allocate nByte bytes of memory.
  16216. */
  16217. static void *sqlite3MemMalloc(int nByte){
  16218. struct MemBlockHdr *pHdr;
  16219. void **pBt;
  16220. char *z;
  16221. int *pInt;
  16222. void *p = 0;
  16223. int totalSize;
  16224. int nReserve;
  16225. sqlite3_mutex_enter(mem.mutex);
  16226. assert( mem.disallow==0 );
  16227. nReserve = ROUND8(nByte);
  16228. totalSize = nReserve + sizeof(*pHdr) + sizeof(int) +
  16229. mem.nBacktrace*sizeof(void*) + mem.nTitle;
  16230. p = malloc(totalSize);
  16231. if( p ){
  16232. z = p;
  16233. pBt = (void**)&z[mem.nTitle];
  16234. pHdr = (struct MemBlockHdr*)&pBt[mem.nBacktrace];
  16235. pHdr->pNext = 0;
  16236. pHdr->pPrev = mem.pLast;
  16237. if( mem.pLast ){
  16238. mem.pLast->pNext = pHdr;
  16239. }else{
  16240. mem.pFirst = pHdr;
  16241. }
  16242. mem.pLast = pHdr;
  16243. pHdr->iForeGuard = FOREGUARD;
  16244. pHdr->eType = MEMTYPE_HEAP;
  16245. pHdr->nBacktraceSlots = mem.nBacktrace;
  16246. pHdr->nTitle = mem.nTitle;
  16247. if( mem.nBacktrace ){
  16248. void *aAddr[40];
  16249. pHdr->nBacktrace = backtrace(aAddr, mem.nBacktrace+1)-1;
  16250. memcpy(pBt, &aAddr[1], pHdr->nBacktrace*sizeof(void*));
  16251. assert(pBt[0]);
  16252. if( mem.xBacktrace ){
  16253. mem.xBacktrace(nByte, pHdr->nBacktrace-1, &aAddr[1]);
  16254. }
  16255. }else{
  16256. pHdr->nBacktrace = 0;
  16257. }
  16258. if( mem.nTitle ){
  16259. memcpy(z, mem.zTitle, mem.nTitle);
  16260. }
  16261. pHdr->iSize = nByte;
  16262. adjustStats(nByte, +1);
  16263. pInt = (int*)&pHdr[1];
  16264. pInt[nReserve/sizeof(int)] = REARGUARD;
  16265. randomFill((char*)pInt, nByte);
  16266. memset(((char*)pInt)+nByte, 0x65, nReserve-nByte);
  16267. p = (void*)pInt;
  16268. }
  16269. sqlite3_mutex_leave(mem.mutex);
  16270. return p;
  16271. }
  16272. /*
  16273. ** Free memory.
  16274. */
  16275. static void sqlite3MemFree(void *pPrior){
  16276. struct MemBlockHdr *pHdr;
  16277. void **pBt;
  16278. char *z;
  16279. assert( sqlite3GlobalConfig.bMemstat || sqlite3GlobalConfig.bCoreMutex==0
  16280. || mem.mutex!=0 );
  16281. pHdr = sqlite3MemsysGetHeader(pPrior);
  16282. pBt = (void**)pHdr;
  16283. pBt -= pHdr->nBacktraceSlots;
  16284. sqlite3_mutex_enter(mem.mutex);
  16285. if( pHdr->pPrev ){
  16286. assert( pHdr->pPrev->pNext==pHdr );
  16287. pHdr->pPrev->pNext = pHdr->pNext;
  16288. }else{
  16289. assert( mem.pFirst==pHdr );
  16290. mem.pFirst = pHdr->pNext;
  16291. }
  16292. if( pHdr->pNext ){
  16293. assert( pHdr->pNext->pPrev==pHdr );
  16294. pHdr->pNext->pPrev = pHdr->pPrev;
  16295. }else{
  16296. assert( mem.pLast==pHdr );
  16297. mem.pLast = pHdr->pPrev;
  16298. }
  16299. z = (char*)pBt;
  16300. z -= pHdr->nTitle;
  16301. adjustStats((int)pHdr->iSize, -1);
  16302. randomFill(z, sizeof(void*)*pHdr->nBacktraceSlots + sizeof(*pHdr) +
  16303. (int)pHdr->iSize + sizeof(int) + pHdr->nTitle);
  16304. free(z);
  16305. sqlite3_mutex_leave(mem.mutex);
  16306. }
  16307. /*
  16308. ** Change the size of an existing memory allocation.
  16309. **
  16310. ** For this debugging implementation, we *always* make a copy of the
  16311. ** allocation into a new place in memory. In this way, if the
  16312. ** higher level code is using pointer to the old allocation, it is
  16313. ** much more likely to break and we are much more liking to find
  16314. ** the error.
  16315. */
  16316. static void *sqlite3MemRealloc(void *pPrior, int nByte){
  16317. struct MemBlockHdr *pOldHdr;
  16318. void *pNew;
  16319. assert( mem.disallow==0 );
  16320. assert( (nByte & 7)==0 ); /* EV: R-46199-30249 */
  16321. pOldHdr = sqlite3MemsysGetHeader(pPrior);
  16322. pNew = sqlite3MemMalloc(nByte);
  16323. if( pNew ){
  16324. memcpy(pNew, pPrior, (int)(nByte<pOldHdr->iSize ? nByte : pOldHdr->iSize));
  16325. if( nByte>pOldHdr->iSize ){
  16326. randomFill(&((char*)pNew)[pOldHdr->iSize], nByte - (int)pOldHdr->iSize);
  16327. }
  16328. sqlite3MemFree(pPrior);
  16329. }
  16330. return pNew;
  16331. }
  16332. /*
  16333. ** Populate the low-level memory allocation function pointers in
  16334. ** sqlite3GlobalConfig.m with pointers to the routines in this file.
  16335. */
  16336. SQLITE_PRIVATE void sqlite3MemSetDefault(void){
  16337. static const sqlite3_mem_methods defaultMethods = {
  16338. sqlite3MemMalloc,
  16339. sqlite3MemFree,
  16340. sqlite3MemRealloc,
  16341. sqlite3MemSize,
  16342. sqlite3MemRoundup,
  16343. sqlite3MemInit,
  16344. sqlite3MemShutdown,
  16345. 0
  16346. };
  16347. sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
  16348. }
  16349. /*
  16350. ** Set the "type" of an allocation.
  16351. */
  16352. SQLITE_PRIVATE void sqlite3MemdebugSetType(void *p, u8 eType){
  16353. if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
  16354. struct MemBlockHdr *pHdr;
  16355. pHdr = sqlite3MemsysGetHeader(p);
  16356. assert( pHdr->iForeGuard==FOREGUARD );
  16357. pHdr->eType = eType;
  16358. }
  16359. }
  16360. /*
  16361. ** Return TRUE if the mask of type in eType matches the type of the
  16362. ** allocation p. Also return true if p==NULL.
  16363. **
  16364. ** This routine is designed for use within an assert() statement, to
  16365. ** verify the type of an allocation. For example:
  16366. **
  16367. ** assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
  16368. */
  16369. SQLITE_PRIVATE int sqlite3MemdebugHasType(void *p, u8 eType){
  16370. int rc = 1;
  16371. if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
  16372. struct MemBlockHdr *pHdr;
  16373. pHdr = sqlite3MemsysGetHeader(p);
  16374. assert( pHdr->iForeGuard==FOREGUARD ); /* Allocation is valid */
  16375. if( (pHdr->eType&eType)==0 ){
  16376. rc = 0;
  16377. }
  16378. }
  16379. return rc;
  16380. }
  16381. /*
  16382. ** Return TRUE if the mask of type in eType matches no bits of the type of the
  16383. ** allocation p. Also return true if p==NULL.
  16384. **
  16385. ** This routine is designed for use within an assert() statement, to
  16386. ** verify the type of an allocation. For example:
  16387. **
  16388. ** assert( sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
  16389. */
  16390. SQLITE_PRIVATE int sqlite3MemdebugNoType(void *p, u8 eType){
  16391. int rc = 1;
  16392. if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
  16393. struct MemBlockHdr *pHdr;
  16394. pHdr = sqlite3MemsysGetHeader(p);
  16395. assert( pHdr->iForeGuard==FOREGUARD ); /* Allocation is valid */
  16396. if( (pHdr->eType&eType)!=0 ){
  16397. rc = 0;
  16398. }
  16399. }
  16400. return rc;
  16401. }
  16402. /*
  16403. ** Set the number of backtrace levels kept for each allocation.
  16404. ** A value of zero turns off backtracing. The number is always rounded
  16405. ** up to a multiple of 2.
  16406. */
  16407. SQLITE_PRIVATE void sqlite3MemdebugBacktrace(int depth){
  16408. if( depth<0 ){ depth = 0; }
  16409. if( depth>20 ){ depth = 20; }
  16410. depth = (depth+1)&0xfe;
  16411. mem.nBacktrace = depth;
  16412. }
  16413. SQLITE_PRIVATE void sqlite3MemdebugBacktraceCallback(void (*xBacktrace)(int, int, void **)){
  16414. mem.xBacktrace = xBacktrace;
  16415. }
  16416. /*
  16417. ** Set the title string for subsequent allocations.
  16418. */
  16419. SQLITE_PRIVATE void sqlite3MemdebugSettitle(const char *zTitle){
  16420. unsigned int n = sqlite3Strlen30(zTitle) + 1;
  16421. sqlite3_mutex_enter(mem.mutex);
  16422. if( n>=sizeof(mem.zTitle) ) n = sizeof(mem.zTitle)-1;
  16423. memcpy(mem.zTitle, zTitle, n);
  16424. mem.zTitle[n] = 0;
  16425. mem.nTitle = ROUND8(n);
  16426. sqlite3_mutex_leave(mem.mutex);
  16427. }
  16428. SQLITE_PRIVATE void sqlite3MemdebugSync(){
  16429. struct MemBlockHdr *pHdr;
  16430. for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
  16431. void **pBt = (void**)pHdr;
  16432. pBt -= pHdr->nBacktraceSlots;
  16433. mem.xBacktrace((int)pHdr->iSize, pHdr->nBacktrace-1, &pBt[1]);
  16434. }
  16435. }
  16436. /*
  16437. ** Open the file indicated and write a log of all unfreed memory
  16438. ** allocations into that log.
  16439. */
  16440. SQLITE_PRIVATE void sqlite3MemdebugDump(const char *zFilename){
  16441. FILE *out;
  16442. struct MemBlockHdr *pHdr;
  16443. void **pBt;
  16444. int i;
  16445. out = fopen(zFilename, "w");
  16446. if( out==0 ){
  16447. fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
  16448. zFilename);
  16449. return;
  16450. }
  16451. for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
  16452. char *z = (char*)pHdr;
  16453. z -= pHdr->nBacktraceSlots*sizeof(void*) + pHdr->nTitle;
  16454. fprintf(out, "**** %lld bytes at %p from %s ****\n",
  16455. pHdr->iSize, &pHdr[1], pHdr->nTitle ? z : "???");
  16456. if( pHdr->nBacktrace ){
  16457. fflush(out);
  16458. pBt = (void**)pHdr;
  16459. pBt -= pHdr->nBacktraceSlots;
  16460. backtrace_symbols_fd(pBt, pHdr->nBacktrace, fileno(out));
  16461. fprintf(out, "\n");
  16462. }
  16463. }
  16464. fprintf(out, "COUNTS:\n");
  16465. for(i=0; i<NCSIZE-1; i++){
  16466. if( mem.nAlloc[i] ){
  16467. fprintf(out, " %5d: %10d %10d %10d\n",
  16468. i*8, mem.nAlloc[i], mem.nCurrent[i], mem.mxCurrent[i]);
  16469. }
  16470. }
  16471. if( mem.nAlloc[NCSIZE-1] ){
  16472. fprintf(out, " %5d: %10d %10d %10d\n",
  16473. NCSIZE*8-8, mem.nAlloc[NCSIZE-1],
  16474. mem.nCurrent[NCSIZE-1], mem.mxCurrent[NCSIZE-1]);
  16475. }
  16476. fclose(out);
  16477. }
  16478. /*
  16479. ** Return the number of times sqlite3MemMalloc() has been called.
  16480. */
  16481. SQLITE_PRIVATE int sqlite3MemdebugMallocCount(){
  16482. int i;
  16483. int nTotal = 0;
  16484. for(i=0; i<NCSIZE; i++){
  16485. nTotal += mem.nAlloc[i];
  16486. }
  16487. return nTotal;
  16488. }
  16489. #endif /* SQLITE_MEMDEBUG */
  16490. /************** End of mem2.c ************************************************/
  16491. /************** Begin file mem3.c ********************************************/
  16492. /*
  16493. ** 2007 October 14
  16494. **
  16495. ** The author disclaims copyright to this source code. In place of
  16496. ** a legal notice, here is a blessing:
  16497. **
  16498. ** May you do good and not evil.
  16499. ** May you find forgiveness for yourself and forgive others.
  16500. ** May you share freely, never taking more than you give.
  16501. **
  16502. *************************************************************************
  16503. ** This file contains the C functions that implement a memory
  16504. ** allocation subsystem for use by SQLite.
  16505. **
  16506. ** This version of the memory allocation subsystem omits all
  16507. ** use of malloc(). The SQLite user supplies a block of memory
  16508. ** before calling sqlite3_initialize() from which allocations
  16509. ** are made and returned by the xMalloc() and xRealloc()
  16510. ** implementations. Once sqlite3_initialize() has been called,
  16511. ** the amount of memory available to SQLite is fixed and cannot
  16512. ** be changed.
  16513. **
  16514. ** This version of the memory allocation subsystem is included
  16515. ** in the build only if SQLITE_ENABLE_MEMSYS3 is defined.
  16516. */
  16517. /*
  16518. ** This version of the memory allocator is only built into the library
  16519. ** SQLITE_ENABLE_MEMSYS3 is defined. Defining this symbol does not
  16520. ** mean that the library will use a memory-pool by default, just that
  16521. ** it is available. The mempool allocator is activated by calling
  16522. ** sqlite3_config().
  16523. */
  16524. #ifdef SQLITE_ENABLE_MEMSYS3
  16525. /*
  16526. ** Maximum size (in Mem3Blocks) of a "small" chunk.
  16527. */
  16528. #define MX_SMALL 10
  16529. /*
  16530. ** Number of freelist hash slots
  16531. */
  16532. #define N_HASH 61
  16533. /*
  16534. ** A memory allocation (also called a "chunk") consists of two or
  16535. ** more blocks where each block is 8 bytes. The first 8 bytes are
  16536. ** a header that is not returned to the user.
  16537. **
  16538. ** A chunk is two or more blocks that is either checked out or
  16539. ** free. The first block has format u.hdr. u.hdr.size4x is 4 times the
  16540. ** size of the allocation in blocks if the allocation is free.
  16541. ** The u.hdr.size4x&1 bit is true if the chunk is checked out and
  16542. ** false if the chunk is on the freelist. The u.hdr.size4x&2 bit
  16543. ** is true if the previous chunk is checked out and false if the
  16544. ** previous chunk is free. The u.hdr.prevSize field is the size of
  16545. ** the previous chunk in blocks if the previous chunk is on the
  16546. ** freelist. If the previous chunk is checked out, then
  16547. ** u.hdr.prevSize can be part of the data for that chunk and should
  16548. ** not be read or written.
  16549. **
  16550. ** We often identify a chunk by its index in mem3.aPool[]. When
  16551. ** this is done, the chunk index refers to the second block of
  16552. ** the chunk. In this way, the first chunk has an index of 1.
  16553. ** A chunk index of 0 means "no such chunk" and is the equivalent
  16554. ** of a NULL pointer.
  16555. **
  16556. ** The second block of free chunks is of the form u.list. The
  16557. ** two fields form a double-linked list of chunks of related sizes.
  16558. ** Pointers to the head of the list are stored in mem3.aiSmall[]
  16559. ** for smaller chunks and mem3.aiHash[] for larger chunks.
  16560. **
  16561. ** The second block of a chunk is user data if the chunk is checked
  16562. ** out. If a chunk is checked out, the user data may extend into
  16563. ** the u.hdr.prevSize value of the following chunk.
  16564. */
  16565. typedef struct Mem3Block Mem3Block;
  16566. struct Mem3Block {
  16567. union {
  16568. struct {
  16569. u32 prevSize; /* Size of previous chunk in Mem3Block elements */
  16570. u32 size4x; /* 4x the size of current chunk in Mem3Block elements */
  16571. } hdr;
  16572. struct {
  16573. u32 next; /* Index in mem3.aPool[] of next free chunk */
  16574. u32 prev; /* Index in mem3.aPool[] of previous free chunk */
  16575. } list;
  16576. } u;
  16577. };
  16578. /*
  16579. ** All of the static variables used by this module are collected
  16580. ** into a single structure named "mem3". This is to keep the
  16581. ** static variables organized and to reduce namespace pollution
  16582. ** when this module is combined with other in the amalgamation.
  16583. */
  16584. static SQLITE_WSD struct Mem3Global {
  16585. /*
  16586. ** Memory available for allocation. nPool is the size of the array
  16587. ** (in Mem3Blocks) pointed to by aPool less 2.
  16588. */
  16589. u32 nPool;
  16590. Mem3Block *aPool;
  16591. /*
  16592. ** True if we are evaluating an out-of-memory callback.
  16593. */
  16594. int alarmBusy;
  16595. /*
  16596. ** Mutex to control access to the memory allocation subsystem.
  16597. */
  16598. sqlite3_mutex *mutex;
  16599. /*
  16600. ** The minimum amount of free space that we have seen.
  16601. */
  16602. u32 mnMaster;
  16603. /*
  16604. ** iMaster is the index of the master chunk. Most new allocations
  16605. ** occur off of this chunk. szMaster is the size (in Mem3Blocks)
  16606. ** of the current master. iMaster is 0 if there is not master chunk.
  16607. ** The master chunk is not in either the aiHash[] or aiSmall[].
  16608. */
  16609. u32 iMaster;
  16610. u32 szMaster;
  16611. /*
  16612. ** Array of lists of free blocks according to the block size
  16613. ** for smaller chunks, or a hash on the block size for larger
  16614. ** chunks.
  16615. */
  16616. u32 aiSmall[MX_SMALL-1]; /* For sizes 2 through MX_SMALL, inclusive */
  16617. u32 aiHash[N_HASH]; /* For sizes MX_SMALL+1 and larger */
  16618. } mem3 = { 97535575 };
  16619. #define mem3 GLOBAL(struct Mem3Global, mem3)
  16620. /*
  16621. ** Unlink the chunk at mem3.aPool[i] from list it is currently
  16622. ** on. *pRoot is the list that i is a member of.
  16623. */
  16624. static void memsys3UnlinkFromList(u32 i, u32 *pRoot){
  16625. u32 next = mem3.aPool[i].u.list.next;
  16626. u32 prev = mem3.aPool[i].u.list.prev;
  16627. assert( sqlite3_mutex_held(mem3.mutex) );
  16628. if( prev==0 ){
  16629. *pRoot = next;
  16630. }else{
  16631. mem3.aPool[prev].u.list.next = next;
  16632. }
  16633. if( next ){
  16634. mem3.aPool[next].u.list.prev = prev;
  16635. }
  16636. mem3.aPool[i].u.list.next = 0;
  16637. mem3.aPool[i].u.list.prev = 0;
  16638. }
  16639. /*
  16640. ** Unlink the chunk at index i from
  16641. ** whatever list is currently a member of.
  16642. */
  16643. static void memsys3Unlink(u32 i){
  16644. u32 size, hash;
  16645. assert( sqlite3_mutex_held(mem3.mutex) );
  16646. assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
  16647. assert( i>=1 );
  16648. size = mem3.aPool[i-1].u.hdr.size4x/4;
  16649. assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
  16650. assert( size>=2 );
  16651. if( size <= MX_SMALL ){
  16652. memsys3UnlinkFromList(i, &mem3.aiSmall[size-2]);
  16653. }else{
  16654. hash = size % N_HASH;
  16655. memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
  16656. }
  16657. }
  16658. /*
  16659. ** Link the chunk at mem3.aPool[i] so that is on the list rooted
  16660. ** at *pRoot.
  16661. */
  16662. static void memsys3LinkIntoList(u32 i, u32 *pRoot){
  16663. assert( sqlite3_mutex_held(mem3.mutex) );
  16664. mem3.aPool[i].u.list.next = *pRoot;
  16665. mem3.aPool[i].u.list.prev = 0;
  16666. if( *pRoot ){
  16667. mem3.aPool[*pRoot].u.list.prev = i;
  16668. }
  16669. *pRoot = i;
  16670. }
  16671. /*
  16672. ** Link the chunk at index i into either the appropriate
  16673. ** small chunk list, or into the large chunk hash table.
  16674. */
  16675. static void memsys3Link(u32 i){
  16676. u32 size, hash;
  16677. assert( sqlite3_mutex_held(mem3.mutex) );
  16678. assert( i>=1 );
  16679. assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
  16680. size = mem3.aPool[i-1].u.hdr.size4x/4;
  16681. assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
  16682. assert( size>=2 );
  16683. if( size <= MX_SMALL ){
  16684. memsys3LinkIntoList(i, &mem3.aiSmall[size-2]);
  16685. }else{
  16686. hash = size % N_HASH;
  16687. memsys3LinkIntoList(i, &mem3.aiHash[hash]);
  16688. }
  16689. }
  16690. /*
  16691. ** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
  16692. ** will already be held (obtained by code in malloc.c) if
  16693. ** sqlite3GlobalConfig.bMemStat is true.
  16694. */
  16695. static void memsys3Enter(void){
  16696. if( sqlite3GlobalConfig.bMemstat==0 && mem3.mutex==0 ){
  16697. mem3.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
  16698. }
  16699. sqlite3_mutex_enter(mem3.mutex);
  16700. }
  16701. static void memsys3Leave(void){
  16702. sqlite3_mutex_leave(mem3.mutex);
  16703. }
  16704. /*
  16705. ** Called when we are unable to satisfy an allocation of nBytes.
  16706. */
  16707. static void memsys3OutOfMemory(int nByte){
  16708. if( !mem3.alarmBusy ){
  16709. mem3.alarmBusy = 1;
  16710. assert( sqlite3_mutex_held(mem3.mutex) );
  16711. sqlite3_mutex_leave(mem3.mutex);
  16712. sqlite3_release_memory(nByte);
  16713. sqlite3_mutex_enter(mem3.mutex);
  16714. mem3.alarmBusy = 0;
  16715. }
  16716. }
  16717. /*
  16718. ** Chunk i is a free chunk that has been unlinked. Adjust its
  16719. ** size parameters for check-out and return a pointer to the
  16720. ** user portion of the chunk.
  16721. */
  16722. static void *memsys3Checkout(u32 i, u32 nBlock){
  16723. u32 x;
  16724. assert( sqlite3_mutex_held(mem3.mutex) );
  16725. assert( i>=1 );
  16726. assert( mem3.aPool[i-1].u.hdr.size4x/4==nBlock );
  16727. assert( mem3.aPool[i+nBlock-1].u.hdr.prevSize==nBlock );
  16728. x = mem3.aPool[i-1].u.hdr.size4x;
  16729. mem3.aPool[i-1].u.hdr.size4x = nBlock*4 | 1 | (x&2);
  16730. mem3.aPool[i+nBlock-1].u.hdr.prevSize = nBlock;
  16731. mem3.aPool[i+nBlock-1].u.hdr.size4x |= 2;
  16732. return &mem3.aPool[i];
  16733. }
  16734. /*
  16735. ** Carve a piece off of the end of the mem3.iMaster free chunk.
  16736. ** Return a pointer to the new allocation. Or, if the master chunk
  16737. ** is not large enough, return 0.
  16738. */
  16739. static void *memsys3FromMaster(u32 nBlock){
  16740. assert( sqlite3_mutex_held(mem3.mutex) );
  16741. assert( mem3.szMaster>=nBlock );
  16742. if( nBlock>=mem3.szMaster-1 ){
  16743. /* Use the entire master */
  16744. void *p = memsys3Checkout(mem3.iMaster, mem3.szMaster);
  16745. mem3.iMaster = 0;
  16746. mem3.szMaster = 0;
  16747. mem3.mnMaster = 0;
  16748. return p;
  16749. }else{
  16750. /* Split the master block. Return the tail. */
  16751. u32 newi, x;
  16752. newi = mem3.iMaster + mem3.szMaster - nBlock;
  16753. assert( newi > mem3.iMaster+1 );
  16754. mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = nBlock;
  16755. mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x |= 2;
  16756. mem3.aPool[newi-1].u.hdr.size4x = nBlock*4 + 1;
  16757. mem3.szMaster -= nBlock;
  16758. mem3.aPool[newi-1].u.hdr.prevSize = mem3.szMaster;
  16759. x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
  16760. mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
  16761. if( mem3.szMaster < mem3.mnMaster ){
  16762. mem3.mnMaster = mem3.szMaster;
  16763. }
  16764. return (void*)&mem3.aPool[newi];
  16765. }
  16766. }
  16767. /*
  16768. ** *pRoot is the head of a list of free chunks of the same size
  16769. ** or same size hash. In other words, *pRoot is an entry in either
  16770. ** mem3.aiSmall[] or mem3.aiHash[].
  16771. **
  16772. ** This routine examines all entries on the given list and tries
  16773. ** to coalesce each entries with adjacent free chunks.
  16774. **
  16775. ** If it sees a chunk that is larger than mem3.iMaster, it replaces
  16776. ** the current mem3.iMaster with the new larger chunk. In order for
  16777. ** this mem3.iMaster replacement to work, the master chunk must be
  16778. ** linked into the hash tables. That is not the normal state of
  16779. ** affairs, of course. The calling routine must link the master
  16780. ** chunk before invoking this routine, then must unlink the (possibly
  16781. ** changed) master chunk once this routine has finished.
  16782. */
  16783. static void memsys3Merge(u32 *pRoot){
  16784. u32 iNext, prev, size, i, x;
  16785. assert( sqlite3_mutex_held(mem3.mutex) );
  16786. for(i=*pRoot; i>0; i=iNext){
  16787. iNext = mem3.aPool[i].u.list.next;
  16788. size = mem3.aPool[i-1].u.hdr.size4x;
  16789. assert( (size&1)==0 );
  16790. if( (size&2)==0 ){
  16791. memsys3UnlinkFromList(i, pRoot);
  16792. assert( i > mem3.aPool[i-1].u.hdr.prevSize );
  16793. prev = i - mem3.aPool[i-1].u.hdr.prevSize;
  16794. if( prev==iNext ){
  16795. iNext = mem3.aPool[prev].u.list.next;
  16796. }
  16797. memsys3Unlink(prev);
  16798. size = i + size/4 - prev;
  16799. x = mem3.aPool[prev-1].u.hdr.size4x & 2;
  16800. mem3.aPool[prev-1].u.hdr.size4x = size*4 | x;
  16801. mem3.aPool[prev+size-1].u.hdr.prevSize = size;
  16802. memsys3Link(prev);
  16803. i = prev;
  16804. }else{
  16805. size /= 4;
  16806. }
  16807. if( size>mem3.szMaster ){
  16808. mem3.iMaster = i;
  16809. mem3.szMaster = size;
  16810. }
  16811. }
  16812. }
  16813. /*
  16814. ** Return a block of memory of at least nBytes in size.
  16815. ** Return NULL if unable.
  16816. **
  16817. ** This function assumes that the necessary mutexes, if any, are
  16818. ** already held by the caller. Hence "Unsafe".
  16819. */
  16820. static void *memsys3MallocUnsafe(int nByte){
  16821. u32 i;
  16822. u32 nBlock;
  16823. u32 toFree;
  16824. assert( sqlite3_mutex_held(mem3.mutex) );
  16825. assert( sizeof(Mem3Block)==8 );
  16826. if( nByte<=12 ){
  16827. nBlock = 2;
  16828. }else{
  16829. nBlock = (nByte + 11)/8;
  16830. }
  16831. assert( nBlock>=2 );
  16832. /* STEP 1:
  16833. ** Look for an entry of the correct size in either the small
  16834. ** chunk table or in the large chunk hash table. This is
  16835. ** successful most of the time (about 9 times out of 10).
  16836. */
  16837. if( nBlock <= MX_SMALL ){
  16838. i = mem3.aiSmall[nBlock-2];
  16839. if( i>0 ){
  16840. memsys3UnlinkFromList(i, &mem3.aiSmall[nBlock-2]);
  16841. return memsys3Checkout(i, nBlock);
  16842. }
  16843. }else{
  16844. int hash = nBlock % N_HASH;
  16845. for(i=mem3.aiHash[hash]; i>0; i=mem3.aPool[i].u.list.next){
  16846. if( mem3.aPool[i-1].u.hdr.size4x/4==nBlock ){
  16847. memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
  16848. return memsys3Checkout(i, nBlock);
  16849. }
  16850. }
  16851. }
  16852. /* STEP 2:
  16853. ** Try to satisfy the allocation by carving a piece off of the end
  16854. ** of the master chunk. This step usually works if step 1 fails.
  16855. */
  16856. if( mem3.szMaster>=nBlock ){
  16857. return memsys3FromMaster(nBlock);
  16858. }
  16859. /* STEP 3:
  16860. ** Loop through the entire memory pool. Coalesce adjacent free
  16861. ** chunks. Recompute the master chunk as the largest free chunk.
  16862. ** Then try again to satisfy the allocation by carving a piece off
  16863. ** of the end of the master chunk. This step happens very
  16864. ** rarely (we hope!)
  16865. */
  16866. for(toFree=nBlock*16; toFree<(mem3.nPool*16); toFree *= 2){
  16867. memsys3OutOfMemory(toFree);
  16868. if( mem3.iMaster ){
  16869. memsys3Link(mem3.iMaster);
  16870. mem3.iMaster = 0;
  16871. mem3.szMaster = 0;
  16872. }
  16873. for(i=0; i<N_HASH; i++){
  16874. memsys3Merge(&mem3.aiHash[i]);
  16875. }
  16876. for(i=0; i<MX_SMALL-1; i++){
  16877. memsys3Merge(&mem3.aiSmall[i]);
  16878. }
  16879. if( mem3.szMaster ){
  16880. memsys3Unlink(mem3.iMaster);
  16881. if( mem3.szMaster>=nBlock ){
  16882. return memsys3FromMaster(nBlock);
  16883. }
  16884. }
  16885. }
  16886. /* If none of the above worked, then we fail. */
  16887. return 0;
  16888. }
  16889. /*
  16890. ** Free an outstanding memory allocation.
  16891. **
  16892. ** This function assumes that the necessary mutexes, if any, are
  16893. ** already held by the caller. Hence "Unsafe".
  16894. */
  16895. static void memsys3FreeUnsafe(void *pOld){
  16896. Mem3Block *p = (Mem3Block*)pOld;
  16897. int i;
  16898. u32 size, x;
  16899. assert( sqlite3_mutex_held(mem3.mutex) );
  16900. assert( p>mem3.aPool && p<&mem3.aPool[mem3.nPool] );
  16901. i = p - mem3.aPool;
  16902. assert( (mem3.aPool[i-1].u.hdr.size4x&1)==1 );
  16903. size = mem3.aPool[i-1].u.hdr.size4x/4;
  16904. assert( i+size<=mem3.nPool+1 );
  16905. mem3.aPool[i-1].u.hdr.size4x &= ~1;
  16906. mem3.aPool[i+size-1].u.hdr.prevSize = size;
  16907. mem3.aPool[i+size-1].u.hdr.size4x &= ~2;
  16908. memsys3Link(i);
  16909. /* Try to expand the master using the newly freed chunk */
  16910. if( mem3.iMaster ){
  16911. while( (mem3.aPool[mem3.iMaster-1].u.hdr.size4x&2)==0 ){
  16912. size = mem3.aPool[mem3.iMaster-1].u.hdr.prevSize;
  16913. mem3.iMaster -= size;
  16914. mem3.szMaster += size;
  16915. memsys3Unlink(mem3.iMaster);
  16916. x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
  16917. mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
  16918. mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
  16919. }
  16920. x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
  16921. while( (mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x&1)==0 ){
  16922. memsys3Unlink(mem3.iMaster+mem3.szMaster);
  16923. mem3.szMaster += mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x/4;
  16924. mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
  16925. mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
  16926. }
  16927. }
  16928. }
  16929. /*
  16930. ** Return the size of an outstanding allocation, in bytes. The
  16931. ** size returned omits the 8-byte header overhead. This only
  16932. ** works for chunks that are currently checked out.
  16933. */
  16934. static int memsys3Size(void *p){
  16935. Mem3Block *pBlock;
  16936. if( p==0 ) return 0;
  16937. pBlock = (Mem3Block*)p;
  16938. assert( (pBlock[-1].u.hdr.size4x&1)!=0 );
  16939. return (pBlock[-1].u.hdr.size4x&~3)*2 - 4;
  16940. }
  16941. /*
  16942. ** Round up a request size to the next valid allocation size.
  16943. */
  16944. static int memsys3Roundup(int n){
  16945. if( n<=12 ){
  16946. return 12;
  16947. }else{
  16948. return ((n+11)&~7) - 4;
  16949. }
  16950. }
  16951. /*
  16952. ** Allocate nBytes of memory.
  16953. */
  16954. static void *memsys3Malloc(int nBytes){
  16955. sqlite3_int64 *p;
  16956. assert( nBytes>0 ); /* malloc.c filters out 0 byte requests */
  16957. memsys3Enter();
  16958. p = memsys3MallocUnsafe(nBytes);
  16959. memsys3Leave();
  16960. return (void*)p;
  16961. }
  16962. /*
  16963. ** Free memory.
  16964. */
  16965. static void memsys3Free(void *pPrior){
  16966. assert( pPrior );
  16967. memsys3Enter();
  16968. memsys3FreeUnsafe(pPrior);
  16969. memsys3Leave();
  16970. }
  16971. /*
  16972. ** Change the size of an existing memory allocation
  16973. */
  16974. static void *memsys3Realloc(void *pPrior, int nBytes){
  16975. int nOld;
  16976. void *p;
  16977. if( pPrior==0 ){
  16978. return sqlite3_malloc(nBytes);
  16979. }
  16980. if( nBytes<=0 ){
  16981. sqlite3_free(pPrior);
  16982. return 0;
  16983. }
  16984. nOld = memsys3Size(pPrior);
  16985. if( nBytes<=nOld && nBytes>=nOld-128 ){
  16986. return pPrior;
  16987. }
  16988. memsys3Enter();
  16989. p = memsys3MallocUnsafe(nBytes);
  16990. if( p ){
  16991. if( nOld<nBytes ){
  16992. memcpy(p, pPrior, nOld);
  16993. }else{
  16994. memcpy(p, pPrior, nBytes);
  16995. }
  16996. memsys3FreeUnsafe(pPrior);
  16997. }
  16998. memsys3Leave();
  16999. return p;
  17000. }
  17001. /*
  17002. ** Initialize this module.
  17003. */
  17004. static int memsys3Init(void *NotUsed){
  17005. UNUSED_PARAMETER(NotUsed);
  17006. if( !sqlite3GlobalConfig.pHeap ){
  17007. return SQLITE_ERROR;
  17008. }
  17009. /* Store a pointer to the memory block in global structure mem3. */
  17010. assert( sizeof(Mem3Block)==8 );
  17011. mem3.aPool = (Mem3Block *)sqlite3GlobalConfig.pHeap;
  17012. mem3.nPool = (sqlite3GlobalConfig.nHeap / sizeof(Mem3Block)) - 2;
  17013. /* Initialize the master block. */
  17014. mem3.szMaster = mem3.nPool;
  17015. mem3.mnMaster = mem3.szMaster;
  17016. mem3.iMaster = 1;
  17017. mem3.aPool[0].u.hdr.size4x = (mem3.szMaster<<2) + 2;
  17018. mem3.aPool[mem3.nPool].u.hdr.prevSize = mem3.nPool;
  17019. mem3.aPool[mem3.nPool].u.hdr.size4x = 1;
  17020. return SQLITE_OK;
  17021. }
  17022. /*
  17023. ** Deinitialize this module.
  17024. */
  17025. static void memsys3Shutdown(void *NotUsed){
  17026. UNUSED_PARAMETER(NotUsed);
  17027. mem3.mutex = 0;
  17028. return;
  17029. }
  17030. /*
  17031. ** Open the file indicated and write a log of all unfreed memory
  17032. ** allocations into that log.
  17033. */
  17034. SQLITE_PRIVATE void sqlite3Memsys3Dump(const char *zFilename){
  17035. #ifdef SQLITE_DEBUG
  17036. FILE *out;
  17037. u32 i, j;
  17038. u32 size;
  17039. if( zFilename==0 || zFilename[0]==0 ){
  17040. out = stdout;
  17041. }else{
  17042. out = fopen(zFilename, "w");
  17043. if( out==0 ){
  17044. fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
  17045. zFilename);
  17046. return;
  17047. }
  17048. }
  17049. memsys3Enter();
  17050. fprintf(out, "CHUNKS:\n");
  17051. for(i=1; i<=mem3.nPool; i+=size/4){
  17052. size = mem3.aPool[i-1].u.hdr.size4x;
  17053. if( size/4<=1 ){
  17054. fprintf(out, "%p size error\n", &mem3.aPool[i]);
  17055. assert( 0 );
  17056. break;
  17057. }
  17058. if( (size&1)==0 && mem3.aPool[i+size/4-1].u.hdr.prevSize!=size/4 ){
  17059. fprintf(out, "%p tail size does not match\n", &mem3.aPool[i]);
  17060. assert( 0 );
  17061. break;
  17062. }
  17063. if( ((mem3.aPool[i+size/4-1].u.hdr.size4x&2)>>1)!=(size&1) ){
  17064. fprintf(out, "%p tail checkout bit is incorrect\n", &mem3.aPool[i]);
  17065. assert( 0 );
  17066. break;
  17067. }
  17068. if( size&1 ){
  17069. fprintf(out, "%p %6d bytes checked out\n", &mem3.aPool[i], (size/4)*8-8);
  17070. }else{
  17071. fprintf(out, "%p %6d bytes free%s\n", &mem3.aPool[i], (size/4)*8-8,
  17072. i==mem3.iMaster ? " **master**" : "");
  17073. }
  17074. }
  17075. for(i=0; i<MX_SMALL-1; i++){
  17076. if( mem3.aiSmall[i]==0 ) continue;
  17077. fprintf(out, "small(%2d):", i);
  17078. for(j = mem3.aiSmall[i]; j>0; j=mem3.aPool[j].u.list.next){
  17079. fprintf(out, " %p(%d)", &mem3.aPool[j],
  17080. (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
  17081. }
  17082. fprintf(out, "\n");
  17083. }
  17084. for(i=0; i<N_HASH; i++){
  17085. if( mem3.aiHash[i]==0 ) continue;
  17086. fprintf(out, "hash(%2d):", i);
  17087. for(j = mem3.aiHash[i]; j>0; j=mem3.aPool[j].u.list.next){
  17088. fprintf(out, " %p(%d)", &mem3.aPool[j],
  17089. (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
  17090. }
  17091. fprintf(out, "\n");
  17092. }
  17093. fprintf(out, "master=%d\n", mem3.iMaster);
  17094. fprintf(out, "nowUsed=%d\n", mem3.nPool*8 - mem3.szMaster*8);
  17095. fprintf(out, "mxUsed=%d\n", mem3.nPool*8 - mem3.mnMaster*8);
  17096. sqlite3_mutex_leave(mem3.mutex);
  17097. if( out==stdout ){
  17098. fflush(stdout);
  17099. }else{
  17100. fclose(out);
  17101. }
  17102. #else
  17103. UNUSED_PARAMETER(zFilename);
  17104. #endif
  17105. }
  17106. /*
  17107. ** This routine is the only routine in this file with external
  17108. ** linkage.
  17109. **
  17110. ** Populate the low-level memory allocation function pointers in
  17111. ** sqlite3GlobalConfig.m with pointers to the routines in this file. The
  17112. ** arguments specify the block of memory to manage.
  17113. **
  17114. ** This routine is only called by sqlite3_config(), and therefore
  17115. ** is not required to be threadsafe (it is not).
  17116. */
  17117. SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void){
  17118. static const sqlite3_mem_methods mempoolMethods = {
  17119. memsys3Malloc,
  17120. memsys3Free,
  17121. memsys3Realloc,
  17122. memsys3Size,
  17123. memsys3Roundup,
  17124. memsys3Init,
  17125. memsys3Shutdown,
  17126. 0
  17127. };
  17128. return &mempoolMethods;
  17129. }
  17130. #endif /* SQLITE_ENABLE_MEMSYS3 */
  17131. /************** End of mem3.c ************************************************/
  17132. /************** Begin file mem5.c ********************************************/
  17133. /*
  17134. ** 2007 October 14
  17135. **
  17136. ** The author disclaims copyright to this source code. In place of
  17137. ** a legal notice, here is a blessing:
  17138. **
  17139. ** May you do good and not evil.
  17140. ** May you find forgiveness for yourself and forgive others.
  17141. ** May you share freely, never taking more than you give.
  17142. **
  17143. *************************************************************************
  17144. ** This file contains the C functions that implement a memory
  17145. ** allocation subsystem for use by SQLite.
  17146. **
  17147. ** This version of the memory allocation subsystem omits all
  17148. ** use of malloc(). The application gives SQLite a block of memory
  17149. ** before calling sqlite3_initialize() from which allocations
  17150. ** are made and returned by the xMalloc() and xRealloc()
  17151. ** implementations. Once sqlite3_initialize() has been called,
  17152. ** the amount of memory available to SQLite is fixed and cannot
  17153. ** be changed.
  17154. **
  17155. ** This version of the memory allocation subsystem is included
  17156. ** in the build only if SQLITE_ENABLE_MEMSYS5 is defined.
  17157. **
  17158. ** This memory allocator uses the following algorithm:
  17159. **
  17160. ** 1. All memory allocations sizes are rounded up to a power of 2.
  17161. **
  17162. ** 2. If two adjacent free blocks are the halves of a larger block,
  17163. ** then the two blocks are coalesced into the single larger block.
  17164. **
  17165. ** 3. New memory is allocated from the first available free block.
  17166. **
  17167. ** This algorithm is described in: J. M. Robson. "Bounds for Some Functions
  17168. ** Concerning Dynamic Storage Allocation". Journal of the Association for
  17169. ** Computing Machinery, Volume 21, Number 8, July 1974, pages 491-499.
  17170. **
  17171. ** Let n be the size of the largest allocation divided by the minimum
  17172. ** allocation size (after rounding all sizes up to a power of 2.) Let M
  17173. ** be the maximum amount of memory ever outstanding at one time. Let
  17174. ** N be the total amount of memory available for allocation. Robson
  17175. ** proved that this memory allocator will never breakdown due to
  17176. ** fragmentation as long as the following constraint holds:
  17177. **
  17178. ** N >= M*(1 + log2(n)/2) - n + 1
  17179. **
  17180. ** The sqlite3_status() logic tracks the maximum values of n and M so
  17181. ** that an application can, at any time, verify this constraint.
  17182. */
  17183. /*
  17184. ** This version of the memory allocator is used only when
  17185. ** SQLITE_ENABLE_MEMSYS5 is defined.
  17186. */
  17187. #ifdef SQLITE_ENABLE_MEMSYS5
  17188. /*
  17189. ** A minimum allocation is an instance of the following structure.
  17190. ** Larger allocations are an array of these structures where the
  17191. ** size of the array is a power of 2.
  17192. **
  17193. ** The size of this object must be a power of two. That fact is
  17194. ** verified in memsys5Init().
  17195. */
  17196. typedef struct Mem5Link Mem5Link;
  17197. struct Mem5Link {
  17198. int next; /* Index of next free chunk */
  17199. int prev; /* Index of previous free chunk */
  17200. };
  17201. /*
  17202. ** Maximum size of any allocation is ((1<<LOGMAX)*mem5.szAtom). Since
  17203. ** mem5.szAtom is always at least 8 and 32-bit integers are used,
  17204. ** it is not actually possible to reach this limit.
  17205. */
  17206. #define LOGMAX 30
  17207. /*
  17208. ** Masks used for mem5.aCtrl[] elements.
  17209. */
  17210. #define CTRL_LOGSIZE 0x1f /* Log2 Size of this block */
  17211. #define CTRL_FREE 0x20 /* True if not checked out */
  17212. /*
  17213. ** All of the static variables used by this module are collected
  17214. ** into a single structure named "mem5". This is to keep the
  17215. ** static variables organized and to reduce namespace pollution
  17216. ** when this module is combined with other in the amalgamation.
  17217. */
  17218. static SQLITE_WSD struct Mem5Global {
  17219. /*
  17220. ** Memory available for allocation
  17221. */
  17222. int szAtom; /* Smallest possible allocation in bytes */
  17223. int nBlock; /* Number of szAtom sized blocks in zPool */
  17224. u8 *zPool; /* Memory available to be allocated */
  17225. /*
  17226. ** Mutex to control access to the memory allocation subsystem.
  17227. */
  17228. sqlite3_mutex *mutex;
  17229. /*
  17230. ** Performance statistics
  17231. */
  17232. u64 nAlloc; /* Total number of calls to malloc */
  17233. u64 totalAlloc; /* Total of all malloc calls - includes internal frag */
  17234. u64 totalExcess; /* Total internal fragmentation */
  17235. u32 currentOut; /* Current checkout, including internal fragmentation */
  17236. u32 currentCount; /* Current number of distinct checkouts */
  17237. u32 maxOut; /* Maximum instantaneous currentOut */
  17238. u32 maxCount; /* Maximum instantaneous currentCount */
  17239. u32 maxRequest; /* Largest allocation (exclusive of internal frag) */
  17240. /*
  17241. ** Lists of free blocks. aiFreelist[0] is a list of free blocks of
  17242. ** size mem5.szAtom. aiFreelist[1] holds blocks of size szAtom*2.
  17243. ** and so forth.
  17244. */
  17245. int aiFreelist[LOGMAX+1];
  17246. /*
  17247. ** Space for tracking which blocks are checked out and the size
  17248. ** of each block. One byte per block.
  17249. */
  17250. u8 *aCtrl;
  17251. } mem5;
  17252. /*
  17253. ** Access the static variable through a macro for SQLITE_OMIT_WSD.
  17254. */
  17255. #define mem5 GLOBAL(struct Mem5Global, mem5)
  17256. /*
  17257. ** Assuming mem5.zPool is divided up into an array of Mem5Link
  17258. ** structures, return a pointer to the idx-th such link.
  17259. */
  17260. #define MEM5LINK(idx) ((Mem5Link *)(&mem5.zPool[(idx)*mem5.szAtom]))
  17261. /*
  17262. ** Unlink the chunk at mem5.aPool[i] from list it is currently
  17263. ** on. It should be found on mem5.aiFreelist[iLogsize].
  17264. */
  17265. static void memsys5Unlink(int i, int iLogsize){
  17266. int next, prev;
  17267. assert( i>=0 && i<mem5.nBlock );
  17268. assert( iLogsize>=0 && iLogsize<=LOGMAX );
  17269. assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
  17270. next = MEM5LINK(i)->next;
  17271. prev = MEM5LINK(i)->prev;
  17272. if( prev<0 ){
  17273. mem5.aiFreelist[iLogsize] = next;
  17274. }else{
  17275. MEM5LINK(prev)->next = next;
  17276. }
  17277. if( next>=0 ){
  17278. MEM5LINK(next)->prev = prev;
  17279. }
  17280. }
  17281. /*
  17282. ** Link the chunk at mem5.aPool[i] so that is on the iLogsize
  17283. ** free list.
  17284. */
  17285. static void memsys5Link(int i, int iLogsize){
  17286. int x;
  17287. assert( sqlite3_mutex_held(mem5.mutex) );
  17288. assert( i>=0 && i<mem5.nBlock );
  17289. assert( iLogsize>=0 && iLogsize<=LOGMAX );
  17290. assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
  17291. x = MEM5LINK(i)->next = mem5.aiFreelist[iLogsize];
  17292. MEM5LINK(i)->prev = -1;
  17293. if( x>=0 ){
  17294. assert( x<mem5.nBlock );
  17295. MEM5LINK(x)->prev = i;
  17296. }
  17297. mem5.aiFreelist[iLogsize] = i;
  17298. }
  17299. /*
  17300. ** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
  17301. ** will already be held (obtained by code in malloc.c) if
  17302. ** sqlite3GlobalConfig.bMemStat is true.
  17303. */
  17304. static void memsys5Enter(void){
  17305. sqlite3_mutex_enter(mem5.mutex);
  17306. }
  17307. static void memsys5Leave(void){
  17308. sqlite3_mutex_leave(mem5.mutex);
  17309. }
  17310. /*
  17311. ** Return the size of an outstanding allocation, in bytes. The
  17312. ** size returned omits the 8-byte header overhead. This only
  17313. ** works for chunks that are currently checked out.
  17314. */
  17315. static int memsys5Size(void *p){
  17316. int iSize = 0;
  17317. if( p ){
  17318. int i = (int)(((u8 *)p-mem5.zPool)/mem5.szAtom);
  17319. assert( i>=0 && i<mem5.nBlock );
  17320. iSize = mem5.szAtom * (1 << (mem5.aCtrl[i]&CTRL_LOGSIZE));
  17321. }
  17322. return iSize;
  17323. }
  17324. /*
  17325. ** Return a block of memory of at least nBytes in size.
  17326. ** Return NULL if unable. Return NULL if nBytes==0.
  17327. **
  17328. ** The caller guarantees that nByte is positive.
  17329. **
  17330. ** The caller has obtained a mutex prior to invoking this
  17331. ** routine so there is never any chance that two or more
  17332. ** threads can be in this routine at the same time.
  17333. */
  17334. static void *memsys5MallocUnsafe(int nByte){
  17335. int i; /* Index of a mem5.aPool[] slot */
  17336. int iBin; /* Index into mem5.aiFreelist[] */
  17337. int iFullSz; /* Size of allocation rounded up to power of 2 */
  17338. int iLogsize; /* Log2 of iFullSz/POW2_MIN */
  17339. /* nByte must be a positive */
  17340. assert( nByte>0 );
  17341. /* Keep track of the maximum allocation request. Even unfulfilled
  17342. ** requests are counted */
  17343. if( (u32)nByte>mem5.maxRequest ){
  17344. mem5.maxRequest = nByte;
  17345. }
  17346. /* Abort if the requested allocation size is larger than the largest
  17347. ** power of two that we can represent using 32-bit signed integers.
  17348. */
  17349. if( nByte > 0x40000000 ){
  17350. return 0;
  17351. }
  17352. /* Round nByte up to the next valid power of two */
  17353. for(iFullSz=mem5.szAtom, iLogsize=0; iFullSz<nByte; iFullSz *= 2, iLogsize++){}
  17354. /* Make sure mem5.aiFreelist[iLogsize] contains at least one free
  17355. ** block. If not, then split a block of the next larger power of
  17356. ** two in order to create a new free block of size iLogsize.
  17357. */
  17358. for(iBin=iLogsize; iBin<=LOGMAX && mem5.aiFreelist[iBin]<0; iBin++){}
  17359. if( iBin>LOGMAX ){
  17360. testcase( sqlite3GlobalConfig.xLog!=0 );
  17361. sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes", nByte);
  17362. return 0;
  17363. }
  17364. i = mem5.aiFreelist[iBin];
  17365. memsys5Unlink(i, iBin);
  17366. while( iBin>iLogsize ){
  17367. int newSize;
  17368. iBin--;
  17369. newSize = 1 << iBin;
  17370. mem5.aCtrl[i+newSize] = CTRL_FREE | iBin;
  17371. memsys5Link(i+newSize, iBin);
  17372. }
  17373. mem5.aCtrl[i] = iLogsize;
  17374. /* Update allocator performance statistics. */
  17375. mem5.nAlloc++;
  17376. mem5.totalAlloc += iFullSz;
  17377. mem5.totalExcess += iFullSz - nByte;
  17378. mem5.currentCount++;
  17379. mem5.currentOut += iFullSz;
  17380. if( mem5.maxCount<mem5.currentCount ) mem5.maxCount = mem5.currentCount;
  17381. if( mem5.maxOut<mem5.currentOut ) mem5.maxOut = mem5.currentOut;
  17382. #ifdef SQLITE_DEBUG
  17383. /* Make sure the allocated memory does not assume that it is set to zero
  17384. ** or retains a value from a previous allocation */
  17385. memset(&mem5.zPool[i*mem5.szAtom], 0xAA, iFullSz);
  17386. #endif
  17387. /* Return a pointer to the allocated memory. */
  17388. return (void*)&mem5.zPool[i*mem5.szAtom];
  17389. }
  17390. /*
  17391. ** Free an outstanding memory allocation.
  17392. */
  17393. static void memsys5FreeUnsafe(void *pOld){
  17394. u32 size, iLogsize;
  17395. int iBlock;
  17396. /* Set iBlock to the index of the block pointed to by pOld in
  17397. ** the array of mem5.szAtom byte blocks pointed to by mem5.zPool.
  17398. */
  17399. iBlock = (int)(((u8 *)pOld-mem5.zPool)/mem5.szAtom);
  17400. /* Check that the pointer pOld points to a valid, non-free block. */
  17401. assert( iBlock>=0 && iBlock<mem5.nBlock );
  17402. assert( ((u8 *)pOld-mem5.zPool)%mem5.szAtom==0 );
  17403. assert( (mem5.aCtrl[iBlock] & CTRL_FREE)==0 );
  17404. iLogsize = mem5.aCtrl[iBlock] & CTRL_LOGSIZE;
  17405. size = 1<<iLogsize;
  17406. assert( iBlock+size-1<(u32)mem5.nBlock );
  17407. mem5.aCtrl[iBlock] |= CTRL_FREE;
  17408. mem5.aCtrl[iBlock+size-1] |= CTRL_FREE;
  17409. assert( mem5.currentCount>0 );
  17410. assert( mem5.currentOut>=(size*mem5.szAtom) );
  17411. mem5.currentCount--;
  17412. mem5.currentOut -= size*mem5.szAtom;
  17413. assert( mem5.currentOut>0 || mem5.currentCount==0 );
  17414. assert( mem5.currentCount>0 || mem5.currentOut==0 );
  17415. mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
  17416. while( ALWAYS(iLogsize<LOGMAX) ){
  17417. int iBuddy;
  17418. if( (iBlock>>iLogsize) & 1 ){
  17419. iBuddy = iBlock - size;
  17420. }else{
  17421. iBuddy = iBlock + size;
  17422. }
  17423. assert( iBuddy>=0 );
  17424. if( (iBuddy+(1<<iLogsize))>mem5.nBlock ) break;
  17425. if( mem5.aCtrl[iBuddy]!=(CTRL_FREE | iLogsize) ) break;
  17426. memsys5Unlink(iBuddy, iLogsize);
  17427. iLogsize++;
  17428. if( iBuddy<iBlock ){
  17429. mem5.aCtrl[iBuddy] = CTRL_FREE | iLogsize;
  17430. mem5.aCtrl[iBlock] = 0;
  17431. iBlock = iBuddy;
  17432. }else{
  17433. mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
  17434. mem5.aCtrl[iBuddy] = 0;
  17435. }
  17436. size *= 2;
  17437. }
  17438. #ifdef SQLITE_DEBUG
  17439. /* Overwrite freed memory with the 0x55 bit pattern to verify that it is
  17440. ** not used after being freed */
  17441. memset(&mem5.zPool[iBlock*mem5.szAtom], 0x55, size);
  17442. #endif
  17443. memsys5Link(iBlock, iLogsize);
  17444. }
  17445. /*
  17446. ** Allocate nBytes of memory.
  17447. */
  17448. static void *memsys5Malloc(int nBytes){
  17449. sqlite3_int64 *p = 0;
  17450. if( nBytes>0 ){
  17451. memsys5Enter();
  17452. p = memsys5MallocUnsafe(nBytes);
  17453. memsys5Leave();
  17454. }
  17455. return (void*)p;
  17456. }
  17457. /*
  17458. ** Free memory.
  17459. **
  17460. ** The outer layer memory allocator prevents this routine from
  17461. ** being called with pPrior==0.
  17462. */
  17463. static void memsys5Free(void *pPrior){
  17464. assert( pPrior!=0 );
  17465. memsys5Enter();
  17466. memsys5FreeUnsafe(pPrior);
  17467. memsys5Leave();
  17468. }
  17469. /*
  17470. ** Change the size of an existing memory allocation.
  17471. **
  17472. ** The outer layer memory allocator prevents this routine from
  17473. ** being called with pPrior==0.
  17474. **
  17475. ** nBytes is always a value obtained from a prior call to
  17476. ** memsys5Round(). Hence nBytes is always a non-negative power
  17477. ** of two. If nBytes==0 that means that an oversize allocation
  17478. ** (an allocation larger than 0x40000000) was requested and this
  17479. ** routine should return 0 without freeing pPrior.
  17480. */
  17481. static void *memsys5Realloc(void *pPrior, int nBytes){
  17482. int nOld;
  17483. void *p;
  17484. assert( pPrior!=0 );
  17485. assert( (nBytes&(nBytes-1))==0 ); /* EV: R-46199-30249 */
  17486. assert( nBytes>=0 );
  17487. if( nBytes==0 ){
  17488. return 0;
  17489. }
  17490. nOld = memsys5Size(pPrior);
  17491. if( nBytes<=nOld ){
  17492. return pPrior;
  17493. }
  17494. memsys5Enter();
  17495. p = memsys5MallocUnsafe(nBytes);
  17496. if( p ){
  17497. memcpy(p, pPrior, nOld);
  17498. memsys5FreeUnsafe(pPrior);
  17499. }
  17500. memsys5Leave();
  17501. return p;
  17502. }
  17503. /*
  17504. ** Round up a request size to the next valid allocation size. If
  17505. ** the allocation is too large to be handled by this allocation system,
  17506. ** return 0.
  17507. **
  17508. ** All allocations must be a power of two and must be expressed by a
  17509. ** 32-bit signed integer. Hence the largest allocation is 0x40000000
  17510. ** or 1073741824 bytes.
  17511. */
  17512. static int memsys5Roundup(int n){
  17513. int iFullSz;
  17514. if( n > 0x40000000 ) return 0;
  17515. for(iFullSz=mem5.szAtom; iFullSz<n; iFullSz *= 2);
  17516. return iFullSz;
  17517. }
  17518. /*
  17519. ** Return the ceiling of the logarithm base 2 of iValue.
  17520. **
  17521. ** Examples: memsys5Log(1) -> 0
  17522. ** memsys5Log(2) -> 1
  17523. ** memsys5Log(4) -> 2
  17524. ** memsys5Log(5) -> 3
  17525. ** memsys5Log(8) -> 3
  17526. ** memsys5Log(9) -> 4
  17527. */
  17528. static int memsys5Log(int iValue){
  17529. int iLog;
  17530. for(iLog=0; (iLog<(int)((sizeof(int)*8)-1)) && (1<<iLog)<iValue; iLog++);
  17531. return iLog;
  17532. }
  17533. /*
  17534. ** Initialize the memory allocator.
  17535. **
  17536. ** This routine is not threadsafe. The caller must be holding a mutex
  17537. ** to prevent multiple threads from entering at the same time.
  17538. */
  17539. static int memsys5Init(void *NotUsed){
  17540. int ii; /* Loop counter */
  17541. int nByte; /* Number of bytes of memory available to this allocator */
  17542. u8 *zByte; /* Memory usable by this allocator */
  17543. int nMinLog; /* Log base 2 of minimum allocation size in bytes */
  17544. int iOffset; /* An offset into mem5.aCtrl[] */
  17545. UNUSED_PARAMETER(NotUsed);
  17546. /* For the purposes of this routine, disable the mutex */
  17547. mem5.mutex = 0;
  17548. /* The size of a Mem5Link object must be a power of two. Verify that
  17549. ** this is case.
  17550. */
  17551. assert( (sizeof(Mem5Link)&(sizeof(Mem5Link)-1))==0 );
  17552. nByte = sqlite3GlobalConfig.nHeap;
  17553. zByte = (u8*)sqlite3GlobalConfig.pHeap;
  17554. assert( zByte!=0 ); /* sqlite3_config() does not allow otherwise */
  17555. /* boundaries on sqlite3GlobalConfig.mnReq are enforced in sqlite3_config() */
  17556. nMinLog = memsys5Log(sqlite3GlobalConfig.mnReq);
  17557. mem5.szAtom = (1<<nMinLog);
  17558. while( (int)sizeof(Mem5Link)>mem5.szAtom ){
  17559. mem5.szAtom = mem5.szAtom << 1;
  17560. }
  17561. mem5.nBlock = (nByte / (mem5.szAtom+sizeof(u8)));
  17562. mem5.zPool = zByte;
  17563. mem5.aCtrl = (u8 *)&mem5.zPool[mem5.nBlock*mem5.szAtom];
  17564. for(ii=0; ii<=LOGMAX; ii++){
  17565. mem5.aiFreelist[ii] = -1;
  17566. }
  17567. iOffset = 0;
  17568. for(ii=LOGMAX; ii>=0; ii--){
  17569. int nAlloc = (1<<ii);
  17570. if( (iOffset+nAlloc)<=mem5.nBlock ){
  17571. mem5.aCtrl[iOffset] = ii | CTRL_FREE;
  17572. memsys5Link(iOffset, ii);
  17573. iOffset += nAlloc;
  17574. }
  17575. assert((iOffset+nAlloc)>mem5.nBlock);
  17576. }
  17577. /* If a mutex is required for normal operation, allocate one */
  17578. if( sqlite3GlobalConfig.bMemstat==0 ){
  17579. mem5.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
  17580. }
  17581. return SQLITE_OK;
  17582. }
  17583. /*
  17584. ** Deinitialize this module.
  17585. */
  17586. static void memsys5Shutdown(void *NotUsed){
  17587. UNUSED_PARAMETER(NotUsed);
  17588. mem5.mutex = 0;
  17589. return;
  17590. }
  17591. #ifdef SQLITE_TEST
  17592. /*
  17593. ** Open the file indicated and write a log of all unfreed memory
  17594. ** allocations into that log.
  17595. */
  17596. SQLITE_PRIVATE void sqlite3Memsys5Dump(const char *zFilename){
  17597. FILE *out;
  17598. int i, j, n;
  17599. int nMinLog;
  17600. if( zFilename==0 || zFilename[0]==0 ){
  17601. out = stdout;
  17602. }else{
  17603. out = fopen(zFilename, "w");
  17604. if( out==0 ){
  17605. fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
  17606. zFilename);
  17607. return;
  17608. }
  17609. }
  17610. memsys5Enter();
  17611. nMinLog = memsys5Log(mem5.szAtom);
  17612. for(i=0; i<=LOGMAX && i+nMinLog<32; i++){
  17613. for(n=0, j=mem5.aiFreelist[i]; j>=0; j = MEM5LINK(j)->next, n++){}
  17614. fprintf(out, "freelist items of size %d: %d\n", mem5.szAtom << i, n);
  17615. }
  17616. fprintf(out, "mem5.nAlloc = %llu\n", mem5.nAlloc);
  17617. fprintf(out, "mem5.totalAlloc = %llu\n", mem5.totalAlloc);
  17618. fprintf(out, "mem5.totalExcess = %llu\n", mem5.totalExcess);
  17619. fprintf(out, "mem5.currentOut = %u\n", mem5.currentOut);
  17620. fprintf(out, "mem5.currentCount = %u\n", mem5.currentCount);
  17621. fprintf(out, "mem5.maxOut = %u\n", mem5.maxOut);
  17622. fprintf(out, "mem5.maxCount = %u\n", mem5.maxCount);
  17623. fprintf(out, "mem5.maxRequest = %u\n", mem5.maxRequest);
  17624. memsys5Leave();
  17625. if( out==stdout ){
  17626. fflush(stdout);
  17627. }else{
  17628. fclose(out);
  17629. }
  17630. }
  17631. #endif
  17632. /*
  17633. ** This routine is the only routine in this file with external
  17634. ** linkage. It returns a pointer to a static sqlite3_mem_methods
  17635. ** struct populated with the memsys5 methods.
  17636. */
  17637. SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void){
  17638. static const sqlite3_mem_methods memsys5Methods = {
  17639. memsys5Malloc,
  17640. memsys5Free,
  17641. memsys5Realloc,
  17642. memsys5Size,
  17643. memsys5Roundup,
  17644. memsys5Init,
  17645. memsys5Shutdown,
  17646. 0
  17647. };
  17648. return &memsys5Methods;
  17649. }
  17650. #endif /* SQLITE_ENABLE_MEMSYS5 */
  17651. /************** End of mem5.c ************************************************/
  17652. /************** Begin file mutex.c *******************************************/
  17653. /*
  17654. ** 2007 August 14
  17655. **
  17656. ** The author disclaims copyright to this source code. In place of
  17657. ** a legal notice, here is a blessing:
  17658. **
  17659. ** May you do good and not evil.
  17660. ** May you find forgiveness for yourself and forgive others.
  17661. ** May you share freely, never taking more than you give.
  17662. **
  17663. *************************************************************************
  17664. ** This file contains the C functions that implement mutexes.
  17665. **
  17666. ** This file contains code that is common across all mutex implementations.
  17667. */
  17668. #if defined(SQLITE_DEBUG) && !defined(SQLITE_MUTEX_OMIT)
  17669. /*
  17670. ** For debugging purposes, record when the mutex subsystem is initialized
  17671. ** and uninitialized so that we can assert() if there is an attempt to
  17672. ** allocate a mutex while the system is uninitialized.
  17673. */
  17674. static SQLITE_WSD int mutexIsInit = 0;
  17675. #endif /* SQLITE_DEBUG */
  17676. #ifndef SQLITE_MUTEX_OMIT
  17677. /*
  17678. ** Initialize the mutex system.
  17679. */
  17680. SQLITE_PRIVATE int sqlite3MutexInit(void){
  17681. int rc = SQLITE_OK;
  17682. if( !sqlite3GlobalConfig.mutex.xMutexAlloc ){
  17683. /* If the xMutexAlloc method has not been set, then the user did not
  17684. ** install a mutex implementation via sqlite3_config() prior to
  17685. ** sqlite3_initialize() being called. This block copies pointers to
  17686. ** the default implementation into the sqlite3GlobalConfig structure.
  17687. */
  17688. sqlite3_mutex_methods const *pFrom;
  17689. sqlite3_mutex_methods *pTo = &sqlite3GlobalConfig.mutex;
  17690. if( sqlite3GlobalConfig.bCoreMutex ){
  17691. pFrom = sqlite3DefaultMutex();
  17692. }else{
  17693. pFrom = sqlite3NoopMutex();
  17694. }
  17695. memcpy(pTo, pFrom, offsetof(sqlite3_mutex_methods, xMutexAlloc));
  17696. memcpy(&pTo->xMutexFree, &pFrom->xMutexFree,
  17697. sizeof(*pTo) - offsetof(sqlite3_mutex_methods, xMutexFree));
  17698. pTo->xMutexAlloc = pFrom->xMutexAlloc;
  17699. }
  17700. rc = sqlite3GlobalConfig.mutex.xMutexInit();
  17701. #ifdef SQLITE_DEBUG
  17702. GLOBAL(int, mutexIsInit) = 1;
  17703. #endif
  17704. return rc;
  17705. }
  17706. /*
  17707. ** Shutdown the mutex system. This call frees resources allocated by
  17708. ** sqlite3MutexInit().
  17709. */
  17710. SQLITE_PRIVATE int sqlite3MutexEnd(void){
  17711. int rc = SQLITE_OK;
  17712. if( sqlite3GlobalConfig.mutex.xMutexEnd ){
  17713. rc = sqlite3GlobalConfig.mutex.xMutexEnd();
  17714. }
  17715. #ifdef SQLITE_DEBUG
  17716. GLOBAL(int, mutexIsInit) = 0;
  17717. #endif
  17718. return rc;
  17719. }
  17720. /*
  17721. ** Retrieve a pointer to a static mutex or allocate a new dynamic one.
  17722. */
  17723. SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int id){
  17724. #ifndef SQLITE_OMIT_AUTOINIT
  17725. if( id<=SQLITE_MUTEX_RECURSIVE && sqlite3_initialize() ) return 0;
  17726. if( id>SQLITE_MUTEX_RECURSIVE && sqlite3MutexInit() ) return 0;
  17727. #endif
  17728. return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
  17729. }
  17730. SQLITE_PRIVATE sqlite3_mutex *sqlite3MutexAlloc(int id){
  17731. if( !sqlite3GlobalConfig.bCoreMutex ){
  17732. return 0;
  17733. }
  17734. assert( GLOBAL(int, mutexIsInit) );
  17735. return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
  17736. }
  17737. /*
  17738. ** Free a dynamic mutex.
  17739. */
  17740. SQLITE_API void sqlite3_mutex_free(sqlite3_mutex *p){
  17741. if( p ){
  17742. sqlite3GlobalConfig.mutex.xMutexFree(p);
  17743. }
  17744. }
  17745. /*
  17746. ** Obtain the mutex p. If some other thread already has the mutex, block
  17747. ** until it can be obtained.
  17748. */
  17749. SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex *p){
  17750. if( p ){
  17751. sqlite3GlobalConfig.mutex.xMutexEnter(p);
  17752. }
  17753. }
  17754. /*
  17755. ** Obtain the mutex p. If successful, return SQLITE_OK. Otherwise, if another
  17756. ** thread holds the mutex and it cannot be obtained, return SQLITE_BUSY.
  17757. */
  17758. SQLITE_API int sqlite3_mutex_try(sqlite3_mutex *p){
  17759. int rc = SQLITE_OK;
  17760. if( p ){
  17761. return sqlite3GlobalConfig.mutex.xMutexTry(p);
  17762. }
  17763. return rc;
  17764. }
  17765. /*
  17766. ** The sqlite3_mutex_leave() routine exits a mutex that was previously
  17767. ** entered by the same thread. The behavior is undefined if the mutex
  17768. ** is not currently entered. If a NULL pointer is passed as an argument
  17769. ** this function is a no-op.
  17770. */
  17771. SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex *p){
  17772. if( p ){
  17773. sqlite3GlobalConfig.mutex.xMutexLeave(p);
  17774. }
  17775. }
  17776. #ifndef NDEBUG
  17777. /*
  17778. ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
  17779. ** intended for use inside assert() statements.
  17780. */
  17781. SQLITE_API int sqlite3_mutex_held(sqlite3_mutex *p){
  17782. return p==0 || sqlite3GlobalConfig.mutex.xMutexHeld(p);
  17783. }
  17784. SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex *p){
  17785. return p==0 || sqlite3GlobalConfig.mutex.xMutexNotheld(p);
  17786. }
  17787. #endif
  17788. #endif /* !defined(SQLITE_MUTEX_OMIT) */
  17789. /************** End of mutex.c ***********************************************/
  17790. /************** Begin file mutex_noop.c **************************************/
  17791. /*
  17792. ** 2008 October 07
  17793. **
  17794. ** The author disclaims copyright to this source code. In place of
  17795. ** a legal notice, here is a blessing:
  17796. **
  17797. ** May you do good and not evil.
  17798. ** May you find forgiveness for yourself and forgive others.
  17799. ** May you share freely, never taking more than you give.
  17800. **
  17801. *************************************************************************
  17802. ** This file contains the C functions that implement mutexes.
  17803. **
  17804. ** This implementation in this file does not provide any mutual
  17805. ** exclusion and is thus suitable for use only in applications
  17806. ** that use SQLite in a single thread. The routines defined
  17807. ** here are place-holders. Applications can substitute working
  17808. ** mutex routines at start-time using the
  17809. **
  17810. ** sqlite3_config(SQLITE_CONFIG_MUTEX,...)
  17811. **
  17812. ** interface.
  17813. **
  17814. ** If compiled with SQLITE_DEBUG, then additional logic is inserted
  17815. ** that does error checking on mutexes to make sure they are being
  17816. ** called correctly.
  17817. */
  17818. #ifndef SQLITE_MUTEX_OMIT
  17819. #ifndef SQLITE_DEBUG
  17820. /*
  17821. ** Stub routines for all mutex methods.
  17822. **
  17823. ** This routines provide no mutual exclusion or error checking.
  17824. */
  17825. static int noopMutexInit(void){ return SQLITE_OK; }
  17826. static int noopMutexEnd(void){ return SQLITE_OK; }
  17827. static sqlite3_mutex *noopMutexAlloc(int id){
  17828. UNUSED_PARAMETER(id);
  17829. return (sqlite3_mutex*)8;
  17830. }
  17831. static void noopMutexFree(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
  17832. static void noopMutexEnter(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
  17833. static int noopMutexTry(sqlite3_mutex *p){
  17834. UNUSED_PARAMETER(p);
  17835. return SQLITE_OK;
  17836. }
  17837. static void noopMutexLeave(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
  17838. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){
  17839. static const sqlite3_mutex_methods sMutex = {
  17840. noopMutexInit,
  17841. noopMutexEnd,
  17842. noopMutexAlloc,
  17843. noopMutexFree,
  17844. noopMutexEnter,
  17845. noopMutexTry,
  17846. noopMutexLeave,
  17847. 0,
  17848. 0,
  17849. };
  17850. return &sMutex;
  17851. }
  17852. #endif /* !SQLITE_DEBUG */
  17853. #ifdef SQLITE_DEBUG
  17854. /*
  17855. ** In this implementation, error checking is provided for testing
  17856. ** and debugging purposes. The mutexes still do not provide any
  17857. ** mutual exclusion.
  17858. */
  17859. /*
  17860. ** The mutex object
  17861. */
  17862. typedef struct sqlite3_debug_mutex {
  17863. int id; /* The mutex type */
  17864. int cnt; /* Number of entries without a matching leave */
  17865. } sqlite3_debug_mutex;
  17866. /*
  17867. ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
  17868. ** intended for use inside assert() statements.
  17869. */
  17870. static int debugMutexHeld(sqlite3_mutex *pX){
  17871. sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
  17872. return p==0 || p->cnt>0;
  17873. }
  17874. static int debugMutexNotheld(sqlite3_mutex *pX){
  17875. sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
  17876. return p==0 || p->cnt==0;
  17877. }
  17878. /*
  17879. ** Initialize and deinitialize the mutex subsystem.
  17880. */
  17881. static int debugMutexInit(void){ return SQLITE_OK; }
  17882. static int debugMutexEnd(void){ return SQLITE_OK; }
  17883. /*
  17884. ** The sqlite3_mutex_alloc() routine allocates a new
  17885. ** mutex and returns a pointer to it. If it returns NULL
  17886. ** that means that a mutex could not be allocated.
  17887. */
  17888. static sqlite3_mutex *debugMutexAlloc(int id){
  17889. static sqlite3_debug_mutex aStatic[SQLITE_MUTEX_STATIC_APP3 - 1];
  17890. sqlite3_debug_mutex *pNew = 0;
  17891. switch( id ){
  17892. case SQLITE_MUTEX_FAST:
  17893. case SQLITE_MUTEX_RECURSIVE: {
  17894. pNew = sqlite3Malloc(sizeof(*pNew));
  17895. if( pNew ){
  17896. pNew->id = id;
  17897. pNew->cnt = 0;
  17898. }
  17899. break;
  17900. }
  17901. default: {
  17902. assert( id-2 >= 0 );
  17903. assert( id-2 < (int)(sizeof(aStatic)/sizeof(aStatic[0])) );
  17904. pNew = &aStatic[id-2];
  17905. pNew->id = id;
  17906. break;
  17907. }
  17908. }
  17909. return (sqlite3_mutex*)pNew;
  17910. }
  17911. /*
  17912. ** This routine deallocates a previously allocated mutex.
  17913. */
  17914. static void debugMutexFree(sqlite3_mutex *pX){
  17915. sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
  17916. assert( p->cnt==0 );
  17917. assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
  17918. sqlite3_free(p);
  17919. }
  17920. /*
  17921. ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
  17922. ** to enter a mutex. If another thread is already within the mutex,
  17923. ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
  17924. ** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK
  17925. ** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can
  17926. ** be entered multiple times by the same thread. In such cases the,
  17927. ** mutex must be exited an equal number of times before another thread
  17928. ** can enter. If the same thread tries to enter any other kind of mutex
  17929. ** more than once, the behavior is undefined.
  17930. */
  17931. static void debugMutexEnter(sqlite3_mutex *pX){
  17932. sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
  17933. assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
  17934. p->cnt++;
  17935. }
  17936. static int debugMutexTry(sqlite3_mutex *pX){
  17937. sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
  17938. assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
  17939. p->cnt++;
  17940. return SQLITE_OK;
  17941. }
  17942. /*
  17943. ** The sqlite3_mutex_leave() routine exits a mutex that was
  17944. ** previously entered by the same thread. The behavior
  17945. ** is undefined if the mutex is not currently entered or
  17946. ** is not currently allocated. SQLite will never do either.
  17947. */
  17948. static void debugMutexLeave(sqlite3_mutex *pX){
  17949. sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
  17950. assert( debugMutexHeld(pX) );
  17951. p->cnt--;
  17952. assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
  17953. }
  17954. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){
  17955. static const sqlite3_mutex_methods sMutex = {
  17956. debugMutexInit,
  17957. debugMutexEnd,
  17958. debugMutexAlloc,
  17959. debugMutexFree,
  17960. debugMutexEnter,
  17961. debugMutexTry,
  17962. debugMutexLeave,
  17963. debugMutexHeld,
  17964. debugMutexNotheld
  17965. };
  17966. return &sMutex;
  17967. }
  17968. #endif /* SQLITE_DEBUG */
  17969. /*
  17970. ** If compiled with SQLITE_MUTEX_NOOP, then the no-op mutex implementation
  17971. ** is used regardless of the run-time threadsafety setting.
  17972. */
  17973. #ifdef SQLITE_MUTEX_NOOP
  17974. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
  17975. return sqlite3NoopMutex();
  17976. }
  17977. #endif /* defined(SQLITE_MUTEX_NOOP) */
  17978. #endif /* !defined(SQLITE_MUTEX_OMIT) */
  17979. /************** End of mutex_noop.c ******************************************/
  17980. /************** Begin file mutex_unix.c **************************************/
  17981. /*
  17982. ** 2007 August 28
  17983. **
  17984. ** The author disclaims copyright to this source code. In place of
  17985. ** a legal notice, here is a blessing:
  17986. **
  17987. ** May you do good and not evil.
  17988. ** May you find forgiveness for yourself and forgive others.
  17989. ** May you share freely, never taking more than you give.
  17990. **
  17991. *************************************************************************
  17992. ** This file contains the C functions that implement mutexes for pthreads
  17993. */
  17994. /*
  17995. ** The code in this file is only used if we are compiling threadsafe
  17996. ** under unix with pthreads.
  17997. **
  17998. ** Note that this implementation requires a version of pthreads that
  17999. ** supports recursive mutexes.
  18000. */
  18001. #ifdef SQLITE_MUTEX_PTHREADS
  18002. #include <pthread.h>
  18003. /*
  18004. ** The sqlite3_mutex.id, sqlite3_mutex.nRef, and sqlite3_mutex.owner fields
  18005. ** are necessary under two condidtions: (1) Debug builds and (2) using
  18006. ** home-grown mutexes. Encapsulate these conditions into a single #define.
  18007. */
  18008. #if defined(SQLITE_DEBUG) || defined(SQLITE_HOMEGROWN_RECURSIVE_MUTEX)
  18009. # define SQLITE_MUTEX_NREF 1
  18010. #else
  18011. # define SQLITE_MUTEX_NREF 0
  18012. #endif
  18013. /*
  18014. ** Each recursive mutex is an instance of the following structure.
  18015. */
  18016. struct sqlite3_mutex {
  18017. pthread_mutex_t mutex; /* Mutex controlling the lock */
  18018. #if SQLITE_MUTEX_NREF
  18019. int id; /* Mutex type */
  18020. volatile int nRef; /* Number of entrances */
  18021. volatile pthread_t owner; /* Thread that is within this mutex */
  18022. int trace; /* True to trace changes */
  18023. #endif
  18024. };
  18025. #if SQLITE_MUTEX_NREF
  18026. #define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER, 0, 0, (pthread_t)0, 0 }
  18027. #else
  18028. #define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER }
  18029. #endif
  18030. /*
  18031. ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
  18032. ** intended for use only inside assert() statements. On some platforms,
  18033. ** there might be race conditions that can cause these routines to
  18034. ** deliver incorrect results. In particular, if pthread_equal() is
  18035. ** not an atomic operation, then these routines might delivery
  18036. ** incorrect results. On most platforms, pthread_equal() is a
  18037. ** comparison of two integers and is therefore atomic. But we are
  18038. ** told that HPUX is not such a platform. If so, then these routines
  18039. ** will not always work correctly on HPUX.
  18040. **
  18041. ** On those platforms where pthread_equal() is not atomic, SQLite
  18042. ** should be compiled without -DSQLITE_DEBUG and with -DNDEBUG to
  18043. ** make sure no assert() statements are evaluated and hence these
  18044. ** routines are never called.
  18045. */
  18046. #if !defined(NDEBUG) || defined(SQLITE_DEBUG)
  18047. static int pthreadMutexHeld(sqlite3_mutex *p){
  18048. return (p->nRef!=0 && pthread_equal(p->owner, pthread_self()));
  18049. }
  18050. static int pthreadMutexNotheld(sqlite3_mutex *p){
  18051. return p->nRef==0 || pthread_equal(p->owner, pthread_self())==0;
  18052. }
  18053. #endif
  18054. /*
  18055. ** Initialize and deinitialize the mutex subsystem.
  18056. */
  18057. static int pthreadMutexInit(void){ return SQLITE_OK; }
  18058. static int pthreadMutexEnd(void){ return SQLITE_OK; }
  18059. /*
  18060. ** The sqlite3_mutex_alloc() routine allocates a new
  18061. ** mutex and returns a pointer to it. If it returns NULL
  18062. ** that means that a mutex could not be allocated. SQLite
  18063. ** will unwind its stack and return an error. The argument
  18064. ** to sqlite3_mutex_alloc() is one of these integer constants:
  18065. **
  18066. ** <ul>
  18067. ** <li> SQLITE_MUTEX_FAST
  18068. ** <li> SQLITE_MUTEX_RECURSIVE
  18069. ** <li> SQLITE_MUTEX_STATIC_MASTER
  18070. ** <li> SQLITE_MUTEX_STATIC_MEM
  18071. ** <li> SQLITE_MUTEX_STATIC_OPEN
  18072. ** <li> SQLITE_MUTEX_STATIC_PRNG
  18073. ** <li> SQLITE_MUTEX_STATIC_LRU
  18074. ** <li> SQLITE_MUTEX_STATIC_PMEM
  18075. ** <li> SQLITE_MUTEX_STATIC_APP1
  18076. ** <li> SQLITE_MUTEX_STATIC_APP2
  18077. ** <li> SQLITE_MUTEX_STATIC_APP3
  18078. ** </ul>
  18079. **
  18080. ** The first two constants cause sqlite3_mutex_alloc() to create
  18081. ** a new mutex. The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
  18082. ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
  18083. ** The mutex implementation does not need to make a distinction
  18084. ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
  18085. ** not want to. But SQLite will only request a recursive mutex in
  18086. ** cases where it really needs one. If a faster non-recursive mutex
  18087. ** implementation is available on the host platform, the mutex subsystem
  18088. ** might return such a mutex in response to SQLITE_MUTEX_FAST.
  18089. **
  18090. ** The other allowed parameters to sqlite3_mutex_alloc() each return
  18091. ** a pointer to a static preexisting mutex. Six static mutexes are
  18092. ** used by the current version of SQLite. Future versions of SQLite
  18093. ** may add additional static mutexes. Static mutexes are for internal
  18094. ** use by SQLite only. Applications that use SQLite mutexes should
  18095. ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
  18096. ** SQLITE_MUTEX_RECURSIVE.
  18097. **
  18098. ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
  18099. ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
  18100. ** returns a different mutex on every call. But for the static
  18101. ** mutex types, the same mutex is returned on every call that has
  18102. ** the same type number.
  18103. */
  18104. static sqlite3_mutex *pthreadMutexAlloc(int iType){
  18105. static sqlite3_mutex staticMutexes[] = {
  18106. SQLITE3_MUTEX_INITIALIZER,
  18107. SQLITE3_MUTEX_INITIALIZER,
  18108. SQLITE3_MUTEX_INITIALIZER,
  18109. SQLITE3_MUTEX_INITIALIZER,
  18110. SQLITE3_MUTEX_INITIALIZER,
  18111. SQLITE3_MUTEX_INITIALIZER,
  18112. SQLITE3_MUTEX_INITIALIZER,
  18113. SQLITE3_MUTEX_INITIALIZER,
  18114. SQLITE3_MUTEX_INITIALIZER
  18115. };
  18116. sqlite3_mutex *p;
  18117. switch( iType ){
  18118. case SQLITE_MUTEX_RECURSIVE: {
  18119. p = sqlite3MallocZero( sizeof(*p) );
  18120. if( p ){
  18121. #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
  18122. /* If recursive mutexes are not available, we will have to
  18123. ** build our own. See below. */
  18124. pthread_mutex_init(&p->mutex, 0);
  18125. #else
  18126. /* Use a recursive mutex if it is available */
  18127. pthread_mutexattr_t recursiveAttr;
  18128. pthread_mutexattr_init(&recursiveAttr);
  18129. pthread_mutexattr_settype(&recursiveAttr, PTHREAD_MUTEX_RECURSIVE);
  18130. pthread_mutex_init(&p->mutex, &recursiveAttr);
  18131. pthread_mutexattr_destroy(&recursiveAttr);
  18132. #endif
  18133. #if SQLITE_MUTEX_NREF
  18134. p->id = iType;
  18135. #endif
  18136. }
  18137. break;
  18138. }
  18139. case SQLITE_MUTEX_FAST: {
  18140. p = sqlite3MallocZero( sizeof(*p) );
  18141. if( p ){
  18142. #if SQLITE_MUTEX_NREF
  18143. p->id = iType;
  18144. #endif
  18145. pthread_mutex_init(&p->mutex, 0);
  18146. }
  18147. break;
  18148. }
  18149. default: {
  18150. #ifdef SQLITE_ENABLE_API_ARMOR
  18151. if( iType-2<0 || iType-2>=ArraySize(staticMutexes) ){
  18152. (void)SQLITE_MISUSE_BKPT;
  18153. return 0;
  18154. }
  18155. #endif
  18156. p = &staticMutexes[iType-2];
  18157. #if SQLITE_MUTEX_NREF
  18158. p->id = iType;
  18159. #endif
  18160. break;
  18161. }
  18162. }
  18163. return p;
  18164. }
  18165. /*
  18166. ** This routine deallocates a previously
  18167. ** allocated mutex. SQLite is careful to deallocate every
  18168. ** mutex that it allocates.
  18169. */
  18170. static void pthreadMutexFree(sqlite3_mutex *p){
  18171. assert( p->nRef==0 );
  18172. assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
  18173. pthread_mutex_destroy(&p->mutex);
  18174. sqlite3_free(p);
  18175. }
  18176. /*
  18177. ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
  18178. ** to enter a mutex. If another thread is already within the mutex,
  18179. ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
  18180. ** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK
  18181. ** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can
  18182. ** be entered multiple times by the same thread. In such cases the,
  18183. ** mutex must be exited an equal number of times before another thread
  18184. ** can enter. If the same thread tries to enter any other kind of mutex
  18185. ** more than once, the behavior is undefined.
  18186. */
  18187. static void pthreadMutexEnter(sqlite3_mutex *p){
  18188. assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
  18189. #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
  18190. /* If recursive mutexes are not available, then we have to grow
  18191. ** our own. This implementation assumes that pthread_equal()
  18192. ** is atomic - that it cannot be deceived into thinking self
  18193. ** and p->owner are equal if p->owner changes between two values
  18194. ** that are not equal to self while the comparison is taking place.
  18195. ** This implementation also assumes a coherent cache - that
  18196. ** separate processes cannot read different values from the same
  18197. ** address at the same time. If either of these two conditions
  18198. ** are not met, then the mutexes will fail and problems will result.
  18199. */
  18200. {
  18201. pthread_t self = pthread_self();
  18202. if( p->nRef>0 && pthread_equal(p->owner, self) ){
  18203. p->nRef++;
  18204. }else{
  18205. pthread_mutex_lock(&p->mutex);
  18206. assert( p->nRef==0 );
  18207. p->owner = self;
  18208. p->nRef = 1;
  18209. }
  18210. }
  18211. #else
  18212. /* Use the built-in recursive mutexes if they are available.
  18213. */
  18214. pthread_mutex_lock(&p->mutex);
  18215. #if SQLITE_MUTEX_NREF
  18216. assert( p->nRef>0 || p->owner==0 );
  18217. p->owner = pthread_self();
  18218. p->nRef++;
  18219. #endif
  18220. #endif
  18221. #ifdef SQLITE_DEBUG
  18222. if( p->trace ){
  18223. printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
  18224. }
  18225. #endif
  18226. }
  18227. static int pthreadMutexTry(sqlite3_mutex *p){
  18228. int rc;
  18229. assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
  18230. #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
  18231. /* If recursive mutexes are not available, then we have to grow
  18232. ** our own. This implementation assumes that pthread_equal()
  18233. ** is atomic - that it cannot be deceived into thinking self
  18234. ** and p->owner are equal if p->owner changes between two values
  18235. ** that are not equal to self while the comparison is taking place.
  18236. ** This implementation also assumes a coherent cache - that
  18237. ** separate processes cannot read different values from the same
  18238. ** address at the same time. If either of these two conditions
  18239. ** are not met, then the mutexes will fail and problems will result.
  18240. */
  18241. {
  18242. pthread_t self = pthread_self();
  18243. if( p->nRef>0 && pthread_equal(p->owner, self) ){
  18244. p->nRef++;
  18245. rc = SQLITE_OK;
  18246. }else if( pthread_mutex_trylock(&p->mutex)==0 ){
  18247. assert( p->nRef==0 );
  18248. p->owner = self;
  18249. p->nRef = 1;
  18250. rc = SQLITE_OK;
  18251. }else{
  18252. rc = SQLITE_BUSY;
  18253. }
  18254. }
  18255. #else
  18256. /* Use the built-in recursive mutexes if they are available.
  18257. */
  18258. if( pthread_mutex_trylock(&p->mutex)==0 ){
  18259. #if SQLITE_MUTEX_NREF
  18260. p->owner = pthread_self();
  18261. p->nRef++;
  18262. #endif
  18263. rc = SQLITE_OK;
  18264. }else{
  18265. rc = SQLITE_BUSY;
  18266. }
  18267. #endif
  18268. #ifdef SQLITE_DEBUG
  18269. if( rc==SQLITE_OK && p->trace ){
  18270. printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
  18271. }
  18272. #endif
  18273. return rc;
  18274. }
  18275. /*
  18276. ** The sqlite3_mutex_leave() routine exits a mutex that was
  18277. ** previously entered by the same thread. The behavior
  18278. ** is undefined if the mutex is not currently entered or
  18279. ** is not currently allocated. SQLite will never do either.
  18280. */
  18281. static void pthreadMutexLeave(sqlite3_mutex *p){
  18282. assert( pthreadMutexHeld(p) );
  18283. #if SQLITE_MUTEX_NREF
  18284. p->nRef--;
  18285. if( p->nRef==0 ) p->owner = 0;
  18286. #endif
  18287. assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
  18288. #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
  18289. if( p->nRef==0 ){
  18290. pthread_mutex_unlock(&p->mutex);
  18291. }
  18292. #else
  18293. pthread_mutex_unlock(&p->mutex);
  18294. #endif
  18295. #ifdef SQLITE_DEBUG
  18296. if( p->trace ){
  18297. printf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
  18298. }
  18299. #endif
  18300. }
  18301. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
  18302. static const sqlite3_mutex_methods sMutex = {
  18303. pthreadMutexInit,
  18304. pthreadMutexEnd,
  18305. pthreadMutexAlloc,
  18306. pthreadMutexFree,
  18307. pthreadMutexEnter,
  18308. pthreadMutexTry,
  18309. pthreadMutexLeave,
  18310. #ifdef SQLITE_DEBUG
  18311. pthreadMutexHeld,
  18312. pthreadMutexNotheld
  18313. #else
  18314. 0,
  18315. 0
  18316. #endif
  18317. };
  18318. return &sMutex;
  18319. }
  18320. #endif /* SQLITE_MUTEX_PTHREADS */
  18321. /************** End of mutex_unix.c ******************************************/
  18322. /************** Begin file mutex_w32.c ***************************************/
  18323. /*
  18324. ** 2007 August 14
  18325. **
  18326. ** The author disclaims copyright to this source code. In place of
  18327. ** a legal notice, here is a blessing:
  18328. **
  18329. ** May you do good and not evil.
  18330. ** May you find forgiveness for yourself and forgive others.
  18331. ** May you share freely, never taking more than you give.
  18332. **
  18333. *************************************************************************
  18334. ** This file contains the C functions that implement mutexes for Win32.
  18335. */
  18336. #if SQLITE_OS_WIN
  18337. /*
  18338. ** Include code that is common to all os_*.c files
  18339. */
  18340. /************** Include os_common.h in the middle of mutex_w32.c *************/
  18341. /************** Begin file os_common.h ***************************************/
  18342. /*
  18343. ** 2004 May 22
  18344. **
  18345. ** The author disclaims copyright to this source code. In place of
  18346. ** a legal notice, here is a blessing:
  18347. **
  18348. ** May you do good and not evil.
  18349. ** May you find forgiveness for yourself and forgive others.
  18350. ** May you share freely, never taking more than you give.
  18351. **
  18352. ******************************************************************************
  18353. **
  18354. ** This file contains macros and a little bit of code that is common to
  18355. ** all of the platform-specific files (os_*.c) and is #included into those
  18356. ** files.
  18357. **
  18358. ** This file should be #included by the os_*.c files only. It is not a
  18359. ** general purpose header file.
  18360. */
  18361. #ifndef _OS_COMMON_H_
  18362. #define _OS_COMMON_H_
  18363. /*
  18364. ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
  18365. ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
  18366. ** switch. The following code should catch this problem at compile-time.
  18367. */
  18368. #ifdef MEMORY_DEBUG
  18369. # error "The MEMORY_DEBUG macro is obsolete. Use SQLITE_DEBUG instead."
  18370. #endif
  18371. #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
  18372. # ifndef SQLITE_DEBUG_OS_TRACE
  18373. # define SQLITE_DEBUG_OS_TRACE 0
  18374. # endif
  18375. int sqlite3OSTrace = SQLITE_DEBUG_OS_TRACE;
  18376. # define OSTRACE(X) if( sqlite3OSTrace ) sqlite3DebugPrintf X
  18377. #else
  18378. # define OSTRACE(X)
  18379. #endif
  18380. /*
  18381. ** Macros for performance tracing. Normally turned off. Only works
  18382. ** on i486 hardware.
  18383. */
  18384. #ifdef SQLITE_PERFORMANCE_TRACE
  18385. /*
  18386. ** hwtime.h contains inline assembler code for implementing
  18387. ** high-performance timing routines.
  18388. */
  18389. /************** Include hwtime.h in the middle of os_common.h ****************/
  18390. /************** Begin file hwtime.h ******************************************/
  18391. /*
  18392. ** 2008 May 27
  18393. **
  18394. ** The author disclaims copyright to this source code. In place of
  18395. ** a legal notice, here is a blessing:
  18396. **
  18397. ** May you do good and not evil.
  18398. ** May you find forgiveness for yourself and forgive others.
  18399. ** May you share freely, never taking more than you give.
  18400. **
  18401. ******************************************************************************
  18402. **
  18403. ** This file contains inline asm code for retrieving "high-performance"
  18404. ** counters for x86 class CPUs.
  18405. */
  18406. #ifndef _HWTIME_H_
  18407. #define _HWTIME_H_
  18408. /*
  18409. ** The following routine only works on pentium-class (or newer) processors.
  18410. ** It uses the RDTSC opcode to read the cycle count value out of the
  18411. ** processor and returns that value. This can be used for high-res
  18412. ** profiling.
  18413. */
  18414. #if (defined(__GNUC__) || defined(_MSC_VER)) && \
  18415. (defined(i386) || defined(__i386__) || defined(_M_IX86))
  18416. #if defined(__GNUC__)
  18417. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  18418. unsigned int lo, hi;
  18419. __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
  18420. return (sqlite_uint64)hi << 32 | lo;
  18421. }
  18422. #elif defined(_MSC_VER)
  18423. __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
  18424. __asm {
  18425. rdtsc
  18426. ret ; return value at EDX:EAX
  18427. }
  18428. }
  18429. #endif
  18430. #elif (defined(__GNUC__) && defined(__x86_64__))
  18431. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  18432. unsigned long val;
  18433. __asm__ __volatile__ ("rdtsc" : "=A" (val));
  18434. return val;
  18435. }
  18436. #elif (defined(__GNUC__) && defined(__ppc__))
  18437. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  18438. unsigned long long retval;
  18439. unsigned long junk;
  18440. __asm__ __volatile__ ("\n\
  18441. 1: mftbu %1\n\
  18442. mftb %L0\n\
  18443. mftbu %0\n\
  18444. cmpw %0,%1\n\
  18445. bne 1b"
  18446. : "=r" (retval), "=r" (junk));
  18447. return retval;
  18448. }
  18449. #else
  18450. #error Need implementation of sqlite3Hwtime() for your platform.
  18451. /*
  18452. ** To compile without implementing sqlite3Hwtime() for your platform,
  18453. ** you can remove the above #error and use the following
  18454. ** stub function. You will lose timing support for many
  18455. ** of the debugging and testing utilities, but it should at
  18456. ** least compile and run.
  18457. */
  18458. SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
  18459. #endif
  18460. #endif /* !defined(_HWTIME_H_) */
  18461. /************** End of hwtime.h **********************************************/
  18462. /************** Continuing where we left off in os_common.h ******************/
  18463. static sqlite_uint64 g_start;
  18464. static sqlite_uint64 g_elapsed;
  18465. #define TIMER_START g_start=sqlite3Hwtime()
  18466. #define TIMER_END g_elapsed=sqlite3Hwtime()-g_start
  18467. #define TIMER_ELAPSED g_elapsed
  18468. #else
  18469. #define TIMER_START
  18470. #define TIMER_END
  18471. #define TIMER_ELAPSED ((sqlite_uint64)0)
  18472. #endif
  18473. /*
  18474. ** If we compile with the SQLITE_TEST macro set, then the following block
  18475. ** of code will give us the ability to simulate a disk I/O error. This
  18476. ** is used for testing the I/O recovery logic.
  18477. */
  18478. #ifdef SQLITE_TEST
  18479. SQLITE_API int sqlite3_io_error_hit = 0; /* Total number of I/O Errors */
  18480. SQLITE_API int sqlite3_io_error_hardhit = 0; /* Number of non-benign errors */
  18481. SQLITE_API int sqlite3_io_error_pending = 0; /* Count down to first I/O error */
  18482. SQLITE_API int sqlite3_io_error_persist = 0; /* True if I/O errors persist */
  18483. SQLITE_API int sqlite3_io_error_benign = 0; /* True if errors are benign */
  18484. SQLITE_API int sqlite3_diskfull_pending = 0;
  18485. SQLITE_API int sqlite3_diskfull = 0;
  18486. #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
  18487. #define SimulateIOError(CODE) \
  18488. if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
  18489. || sqlite3_io_error_pending-- == 1 ) \
  18490. { local_ioerr(); CODE; }
  18491. static void local_ioerr(){
  18492. IOTRACE(("IOERR\n"));
  18493. sqlite3_io_error_hit++;
  18494. if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
  18495. }
  18496. #define SimulateDiskfullError(CODE) \
  18497. if( sqlite3_diskfull_pending ){ \
  18498. if( sqlite3_diskfull_pending == 1 ){ \
  18499. local_ioerr(); \
  18500. sqlite3_diskfull = 1; \
  18501. sqlite3_io_error_hit = 1; \
  18502. CODE; \
  18503. }else{ \
  18504. sqlite3_diskfull_pending--; \
  18505. } \
  18506. }
  18507. #else
  18508. #define SimulateIOErrorBenign(X)
  18509. #define SimulateIOError(A)
  18510. #define SimulateDiskfullError(A)
  18511. #endif
  18512. /*
  18513. ** When testing, keep a count of the number of open files.
  18514. */
  18515. #ifdef SQLITE_TEST
  18516. SQLITE_API int sqlite3_open_file_count = 0;
  18517. #define OpenCounter(X) sqlite3_open_file_count+=(X)
  18518. #else
  18519. #define OpenCounter(X)
  18520. #endif
  18521. #endif /* !defined(_OS_COMMON_H_) */
  18522. /************** End of os_common.h *******************************************/
  18523. /************** Continuing where we left off in mutex_w32.c ******************/
  18524. /*
  18525. ** Include the header file for the Windows VFS.
  18526. */
  18527. /************** Include os_win.h in the middle of mutex_w32.c ****************/
  18528. /************** Begin file os_win.h ******************************************/
  18529. /*
  18530. ** 2013 November 25
  18531. **
  18532. ** The author disclaims copyright to this source code. In place of
  18533. ** a legal notice, here is a blessing:
  18534. **
  18535. ** May you do good and not evil.
  18536. ** May you find forgiveness for yourself and forgive others.
  18537. ** May you share freely, never taking more than you give.
  18538. **
  18539. ******************************************************************************
  18540. **
  18541. ** This file contains code that is specific to Windows.
  18542. */
  18543. #ifndef _OS_WIN_H_
  18544. #define _OS_WIN_H_
  18545. /*
  18546. ** Include the primary Windows SDK header file.
  18547. */
  18548. #include "windows.h"
  18549. #ifdef __CYGWIN__
  18550. # include <sys/cygwin.h>
  18551. # include <errno.h> /* amalgamator: dontcache */
  18552. #endif
  18553. /*
  18554. ** Determine if we are dealing with Windows NT.
  18555. **
  18556. ** We ought to be able to determine if we are compiling for Windows 9x or
  18557. ** Windows NT using the _WIN32_WINNT macro as follows:
  18558. **
  18559. ** #if defined(_WIN32_WINNT)
  18560. ** # define SQLITE_OS_WINNT 1
  18561. ** #else
  18562. ** # define SQLITE_OS_WINNT 0
  18563. ** #endif
  18564. **
  18565. ** However, Visual Studio 2005 does not set _WIN32_WINNT by default, as
  18566. ** it ought to, so the above test does not work. We'll just assume that
  18567. ** everything is Windows NT unless the programmer explicitly says otherwise
  18568. ** by setting SQLITE_OS_WINNT to 0.
  18569. */
  18570. #if SQLITE_OS_WIN && !defined(SQLITE_OS_WINNT)
  18571. # define SQLITE_OS_WINNT 1
  18572. #endif
  18573. /*
  18574. ** Determine if we are dealing with Windows CE - which has a much reduced
  18575. ** API.
  18576. */
  18577. #if defined(_WIN32_WCE)
  18578. # define SQLITE_OS_WINCE 1
  18579. #else
  18580. # define SQLITE_OS_WINCE 0
  18581. #endif
  18582. /*
  18583. ** Determine if we are dealing with WinRT, which provides only a subset of
  18584. ** the full Win32 API.
  18585. */
  18586. #if !defined(SQLITE_OS_WINRT)
  18587. # define SQLITE_OS_WINRT 0
  18588. #endif
  18589. /*
  18590. ** For WinCE, some API function parameters do not appear to be declared as
  18591. ** volatile.
  18592. */
  18593. #if SQLITE_OS_WINCE
  18594. # define SQLITE_WIN32_VOLATILE
  18595. #else
  18596. # define SQLITE_WIN32_VOLATILE volatile
  18597. #endif
  18598. #endif /* _OS_WIN_H_ */
  18599. /************** End of os_win.h **********************************************/
  18600. /************** Continuing where we left off in mutex_w32.c ******************/
  18601. #endif
  18602. /*
  18603. ** The code in this file is only used if we are compiling multithreaded
  18604. ** on a Win32 system.
  18605. */
  18606. #ifdef SQLITE_MUTEX_W32
  18607. /*
  18608. ** Each recursive mutex is an instance of the following structure.
  18609. */
  18610. struct sqlite3_mutex {
  18611. CRITICAL_SECTION mutex; /* Mutex controlling the lock */
  18612. int id; /* Mutex type */
  18613. #ifdef SQLITE_DEBUG
  18614. volatile int nRef; /* Number of enterances */
  18615. volatile DWORD owner; /* Thread holding this mutex */
  18616. volatile int trace; /* True to trace changes */
  18617. #endif
  18618. };
  18619. /*
  18620. ** These are the initializer values used when declaring a "static" mutex
  18621. ** on Win32. It should be noted that all mutexes require initialization
  18622. ** on the Win32 platform.
  18623. */
  18624. #define SQLITE_W32_MUTEX_INITIALIZER { 0 }
  18625. #ifdef SQLITE_DEBUG
  18626. #define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0, \
  18627. 0L, (DWORD)0, 0 }
  18628. #else
  18629. #define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0 }
  18630. #endif
  18631. #ifdef SQLITE_DEBUG
  18632. /*
  18633. ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
  18634. ** intended for use only inside assert() statements.
  18635. */
  18636. static int winMutexHeld(sqlite3_mutex *p){
  18637. return p->nRef!=0 && p->owner==GetCurrentThreadId();
  18638. }
  18639. static int winMutexNotheld2(sqlite3_mutex *p, DWORD tid){
  18640. return p->nRef==0 || p->owner!=tid;
  18641. }
  18642. static int winMutexNotheld(sqlite3_mutex *p){
  18643. DWORD tid = GetCurrentThreadId();
  18644. return winMutexNotheld2(p, tid);
  18645. }
  18646. #endif
  18647. /*
  18648. ** Initialize and deinitialize the mutex subsystem.
  18649. */
  18650. static sqlite3_mutex winMutex_staticMutexes[] = {
  18651. SQLITE3_MUTEX_INITIALIZER,
  18652. SQLITE3_MUTEX_INITIALIZER,
  18653. SQLITE3_MUTEX_INITIALIZER,
  18654. SQLITE3_MUTEX_INITIALIZER,
  18655. SQLITE3_MUTEX_INITIALIZER,
  18656. SQLITE3_MUTEX_INITIALIZER,
  18657. SQLITE3_MUTEX_INITIALIZER,
  18658. SQLITE3_MUTEX_INITIALIZER,
  18659. SQLITE3_MUTEX_INITIALIZER
  18660. };
  18661. static int winMutex_isInit = 0;
  18662. static int winMutex_isNt = -1; /* <0 means "need to query" */
  18663. /* As the winMutexInit() and winMutexEnd() functions are called as part
  18664. ** of the sqlite3_initialize() and sqlite3_shutdown() processing, the
  18665. ** "interlocked" magic used here is probably not strictly necessary.
  18666. */
  18667. static LONG SQLITE_WIN32_VOLATILE winMutex_lock = 0;
  18668. SQLITE_API int sqlite3_win32_is_nt(void); /* os_win.c */
  18669. SQLITE_API void sqlite3_win32_sleep(DWORD milliseconds); /* os_win.c */
  18670. static int winMutexInit(void){
  18671. /* The first to increment to 1 does actual initialization */
  18672. if( InterlockedCompareExchange(&winMutex_lock, 1, 0)==0 ){
  18673. int i;
  18674. for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
  18675. #if SQLITE_OS_WINRT
  18676. InitializeCriticalSectionEx(&winMutex_staticMutexes[i].mutex, 0, 0);
  18677. #else
  18678. InitializeCriticalSection(&winMutex_staticMutexes[i].mutex);
  18679. #endif
  18680. }
  18681. winMutex_isInit = 1;
  18682. }else{
  18683. /* Another thread is (in the process of) initializing the static
  18684. ** mutexes */
  18685. while( !winMutex_isInit ){
  18686. sqlite3_win32_sleep(1);
  18687. }
  18688. }
  18689. return SQLITE_OK;
  18690. }
  18691. static int winMutexEnd(void){
  18692. /* The first to decrement to 0 does actual shutdown
  18693. ** (which should be the last to shutdown.) */
  18694. if( InterlockedCompareExchange(&winMutex_lock, 0, 1)==1 ){
  18695. if( winMutex_isInit==1 ){
  18696. int i;
  18697. for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
  18698. DeleteCriticalSection(&winMutex_staticMutexes[i].mutex);
  18699. }
  18700. winMutex_isInit = 0;
  18701. }
  18702. }
  18703. return SQLITE_OK;
  18704. }
  18705. /*
  18706. ** The sqlite3_mutex_alloc() routine allocates a new
  18707. ** mutex and returns a pointer to it. If it returns NULL
  18708. ** that means that a mutex could not be allocated. SQLite
  18709. ** will unwind its stack and return an error. The argument
  18710. ** to sqlite3_mutex_alloc() is one of these integer constants:
  18711. **
  18712. ** <ul>
  18713. ** <li> SQLITE_MUTEX_FAST
  18714. ** <li> SQLITE_MUTEX_RECURSIVE
  18715. ** <li> SQLITE_MUTEX_STATIC_MASTER
  18716. ** <li> SQLITE_MUTEX_STATIC_MEM
  18717. ** <li> SQLITE_MUTEX_STATIC_OPEN
  18718. ** <li> SQLITE_MUTEX_STATIC_PRNG
  18719. ** <li> SQLITE_MUTEX_STATIC_LRU
  18720. ** <li> SQLITE_MUTEX_STATIC_PMEM
  18721. ** <li> SQLITE_MUTEX_STATIC_APP1
  18722. ** <li> SQLITE_MUTEX_STATIC_APP2
  18723. ** <li> SQLITE_MUTEX_STATIC_APP3
  18724. ** </ul>
  18725. **
  18726. ** The first two constants cause sqlite3_mutex_alloc() to create
  18727. ** a new mutex. The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
  18728. ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
  18729. ** The mutex implementation does not need to make a distinction
  18730. ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
  18731. ** not want to. But SQLite will only request a recursive mutex in
  18732. ** cases where it really needs one. If a faster non-recursive mutex
  18733. ** implementation is available on the host platform, the mutex subsystem
  18734. ** might return such a mutex in response to SQLITE_MUTEX_FAST.
  18735. **
  18736. ** The other allowed parameters to sqlite3_mutex_alloc() each return
  18737. ** a pointer to a static preexisting mutex. Six static mutexes are
  18738. ** used by the current version of SQLite. Future versions of SQLite
  18739. ** may add additional static mutexes. Static mutexes are for internal
  18740. ** use by SQLite only. Applications that use SQLite mutexes should
  18741. ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
  18742. ** SQLITE_MUTEX_RECURSIVE.
  18743. **
  18744. ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
  18745. ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
  18746. ** returns a different mutex on every call. But for the static
  18747. ** mutex types, the same mutex is returned on every call that has
  18748. ** the same type number.
  18749. */
  18750. static sqlite3_mutex *winMutexAlloc(int iType){
  18751. sqlite3_mutex *p;
  18752. switch( iType ){
  18753. case SQLITE_MUTEX_FAST:
  18754. case SQLITE_MUTEX_RECURSIVE: {
  18755. p = sqlite3MallocZero( sizeof(*p) );
  18756. if( p ){
  18757. #ifdef SQLITE_DEBUG
  18758. p->id = iType;
  18759. #ifdef SQLITE_WIN32_MUTEX_TRACE_DYNAMIC
  18760. p->trace = 1;
  18761. #endif
  18762. #endif
  18763. #if SQLITE_OS_WINRT
  18764. InitializeCriticalSectionEx(&p->mutex, 0, 0);
  18765. #else
  18766. InitializeCriticalSection(&p->mutex);
  18767. #endif
  18768. }
  18769. break;
  18770. }
  18771. default: {
  18772. assert( iType-2 >= 0 );
  18773. assert( iType-2 < ArraySize(winMutex_staticMutexes) );
  18774. assert( winMutex_isInit==1 );
  18775. p = &winMutex_staticMutexes[iType-2];
  18776. #ifdef SQLITE_DEBUG
  18777. p->id = iType;
  18778. #ifdef SQLITE_WIN32_MUTEX_TRACE_STATIC
  18779. p->trace = 1;
  18780. #endif
  18781. #endif
  18782. break;
  18783. }
  18784. }
  18785. return p;
  18786. }
  18787. /*
  18788. ** This routine deallocates a previously
  18789. ** allocated mutex. SQLite is careful to deallocate every
  18790. ** mutex that it allocates.
  18791. */
  18792. static void winMutexFree(sqlite3_mutex *p){
  18793. assert( p );
  18794. #ifdef SQLITE_DEBUG
  18795. assert( p->nRef==0 && p->owner==0 );
  18796. assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
  18797. #endif
  18798. assert( winMutex_isInit==1 );
  18799. DeleteCriticalSection(&p->mutex);
  18800. sqlite3_free(p);
  18801. }
  18802. /*
  18803. ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
  18804. ** to enter a mutex. If another thread is already within the mutex,
  18805. ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
  18806. ** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK
  18807. ** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can
  18808. ** be entered multiple times by the same thread. In such cases the,
  18809. ** mutex must be exited an equal number of times before another thread
  18810. ** can enter. If the same thread tries to enter any other kind of mutex
  18811. ** more than once, the behavior is undefined.
  18812. */
  18813. static void winMutexEnter(sqlite3_mutex *p){
  18814. #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
  18815. DWORD tid = GetCurrentThreadId();
  18816. #endif
  18817. #ifdef SQLITE_DEBUG
  18818. assert( p );
  18819. assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
  18820. #else
  18821. assert( p );
  18822. #endif
  18823. assert( winMutex_isInit==1 );
  18824. EnterCriticalSection(&p->mutex);
  18825. #ifdef SQLITE_DEBUG
  18826. assert( p->nRef>0 || p->owner==0 );
  18827. p->owner = tid;
  18828. p->nRef++;
  18829. if( p->trace ){
  18830. OSTRACE(("ENTER-MUTEX tid=%lu, mutex=%p (%d), nRef=%d\n",
  18831. tid, p, p->trace, p->nRef));
  18832. }
  18833. #endif
  18834. }
  18835. static int winMutexTry(sqlite3_mutex *p){
  18836. #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
  18837. DWORD tid = GetCurrentThreadId();
  18838. #endif
  18839. int rc = SQLITE_BUSY;
  18840. assert( p );
  18841. assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
  18842. /*
  18843. ** The sqlite3_mutex_try() routine is very rarely used, and when it
  18844. ** is used it is merely an optimization. So it is OK for it to always
  18845. ** fail.
  18846. **
  18847. ** The TryEnterCriticalSection() interface is only available on WinNT.
  18848. ** And some windows compilers complain if you try to use it without
  18849. ** first doing some #defines that prevent SQLite from building on Win98.
  18850. ** For that reason, we will omit this optimization for now. See
  18851. ** ticket #2685.
  18852. */
  18853. #if defined(_WIN32_WINNT) && _WIN32_WINNT >= 0x0400
  18854. assert( winMutex_isInit==1 );
  18855. assert( winMutex_isNt>=-1 && winMutex_isNt<=1 );
  18856. if( winMutex_isNt<0 ){
  18857. winMutex_isNt = sqlite3_win32_is_nt();
  18858. }
  18859. assert( winMutex_isNt==0 || winMutex_isNt==1 );
  18860. if( winMutex_isNt && TryEnterCriticalSection(&p->mutex) ){
  18861. #ifdef SQLITE_DEBUG
  18862. p->owner = tid;
  18863. p->nRef++;
  18864. #endif
  18865. rc = SQLITE_OK;
  18866. }
  18867. #else
  18868. UNUSED_PARAMETER(p);
  18869. #endif
  18870. #ifdef SQLITE_DEBUG
  18871. if( p->trace ){
  18872. OSTRACE(("TRY-MUTEX tid=%lu, mutex=%p (%d), owner=%lu, nRef=%d, rc=%s\n",
  18873. tid, p, p->trace, p->owner, p->nRef, sqlite3ErrName(rc)));
  18874. }
  18875. #endif
  18876. return rc;
  18877. }
  18878. /*
  18879. ** The sqlite3_mutex_leave() routine exits a mutex that was
  18880. ** previously entered by the same thread. The behavior
  18881. ** is undefined if the mutex is not currently entered or
  18882. ** is not currently allocated. SQLite will never do either.
  18883. */
  18884. static void winMutexLeave(sqlite3_mutex *p){
  18885. #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
  18886. DWORD tid = GetCurrentThreadId();
  18887. #endif
  18888. assert( p );
  18889. #ifdef SQLITE_DEBUG
  18890. assert( p->nRef>0 );
  18891. assert( p->owner==tid );
  18892. p->nRef--;
  18893. if( p->nRef==0 ) p->owner = 0;
  18894. assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
  18895. #endif
  18896. assert( winMutex_isInit==1 );
  18897. LeaveCriticalSection(&p->mutex);
  18898. #ifdef SQLITE_DEBUG
  18899. if( p->trace ){
  18900. OSTRACE(("LEAVE-MUTEX tid=%lu, mutex=%p (%d), nRef=%d\n",
  18901. tid, p, p->trace, p->nRef));
  18902. }
  18903. #endif
  18904. }
  18905. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
  18906. static const sqlite3_mutex_methods sMutex = {
  18907. winMutexInit,
  18908. winMutexEnd,
  18909. winMutexAlloc,
  18910. winMutexFree,
  18911. winMutexEnter,
  18912. winMutexTry,
  18913. winMutexLeave,
  18914. #ifdef SQLITE_DEBUG
  18915. winMutexHeld,
  18916. winMutexNotheld
  18917. #else
  18918. 0,
  18919. 0
  18920. #endif
  18921. };
  18922. return &sMutex;
  18923. }
  18924. #endif /* SQLITE_MUTEX_W32 */
  18925. /************** End of mutex_w32.c *******************************************/
  18926. /************** Begin file malloc.c ******************************************/
  18927. /*
  18928. ** 2001 September 15
  18929. **
  18930. ** The author disclaims copyright to this source code. In place of
  18931. ** a legal notice, here is a blessing:
  18932. **
  18933. ** May you do good and not evil.
  18934. ** May you find forgiveness for yourself and forgive others.
  18935. ** May you share freely, never taking more than you give.
  18936. **
  18937. *************************************************************************
  18938. **
  18939. ** Memory allocation functions used throughout sqlite.
  18940. */
  18941. /* #include <stdarg.h> */
  18942. /*
  18943. ** Attempt to release up to n bytes of non-essential memory currently
  18944. ** held by SQLite. An example of non-essential memory is memory used to
  18945. ** cache database pages that are not currently in use.
  18946. */
  18947. SQLITE_API int sqlite3_release_memory(int n){
  18948. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  18949. return sqlite3PcacheReleaseMemory(n);
  18950. #else
  18951. /* IMPLEMENTATION-OF: R-34391-24921 The sqlite3_release_memory() routine
  18952. ** is a no-op returning zero if SQLite is not compiled with
  18953. ** SQLITE_ENABLE_MEMORY_MANAGEMENT. */
  18954. UNUSED_PARAMETER(n);
  18955. return 0;
  18956. #endif
  18957. }
  18958. /*
  18959. ** An instance of the following object records the location of
  18960. ** each unused scratch buffer.
  18961. */
  18962. typedef struct ScratchFreeslot {
  18963. struct ScratchFreeslot *pNext; /* Next unused scratch buffer */
  18964. } ScratchFreeslot;
  18965. /*
  18966. ** State information local to the memory allocation subsystem.
  18967. */
  18968. static SQLITE_WSD struct Mem0Global {
  18969. sqlite3_mutex *mutex; /* Mutex to serialize access */
  18970. /*
  18971. ** The alarm callback and its arguments. The mem0.mutex lock will
  18972. ** be held while the callback is running. Recursive calls into
  18973. ** the memory subsystem are allowed, but no new callbacks will be
  18974. ** issued.
  18975. */
  18976. sqlite3_int64 alarmThreshold;
  18977. void (*alarmCallback)(void*, sqlite3_int64,int);
  18978. void *alarmArg;
  18979. /*
  18980. ** Pointers to the end of sqlite3GlobalConfig.pScratch memory
  18981. ** (so that a range test can be used to determine if an allocation
  18982. ** being freed came from pScratch) and a pointer to the list of
  18983. ** unused scratch allocations.
  18984. */
  18985. void *pScratchEnd;
  18986. ScratchFreeslot *pScratchFree;
  18987. u32 nScratchFree;
  18988. /*
  18989. ** True if heap is nearly "full" where "full" is defined by the
  18990. ** sqlite3_soft_heap_limit() setting.
  18991. */
  18992. int nearlyFull;
  18993. } mem0 = { 0, 0, 0, 0, 0, 0, 0, 0 };
  18994. #define mem0 GLOBAL(struct Mem0Global, mem0)
  18995. /*
  18996. ** This routine runs when the memory allocator sees that the
  18997. ** total memory allocation is about to exceed the soft heap
  18998. ** limit.
  18999. */
  19000. static void softHeapLimitEnforcer(
  19001. void *NotUsed,
  19002. sqlite3_int64 NotUsed2,
  19003. int allocSize
  19004. ){
  19005. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  19006. sqlite3_release_memory(allocSize);
  19007. }
  19008. /*
  19009. ** Change the alarm callback
  19010. */
  19011. static int sqlite3MemoryAlarm(
  19012. void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
  19013. void *pArg,
  19014. sqlite3_int64 iThreshold
  19015. ){
  19016. int nUsed;
  19017. sqlite3_mutex_enter(mem0.mutex);
  19018. mem0.alarmCallback = xCallback;
  19019. mem0.alarmArg = pArg;
  19020. mem0.alarmThreshold = iThreshold;
  19021. nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
  19022. mem0.nearlyFull = (iThreshold>0 && iThreshold<=nUsed);
  19023. sqlite3_mutex_leave(mem0.mutex);
  19024. return SQLITE_OK;
  19025. }
  19026. #ifndef SQLITE_OMIT_DEPRECATED
  19027. /*
  19028. ** Deprecated external interface. Internal/core SQLite code
  19029. ** should call sqlite3MemoryAlarm.
  19030. */
  19031. SQLITE_API int sqlite3_memory_alarm(
  19032. void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
  19033. void *pArg,
  19034. sqlite3_int64 iThreshold
  19035. ){
  19036. return sqlite3MemoryAlarm(xCallback, pArg, iThreshold);
  19037. }
  19038. #endif
  19039. /*
  19040. ** Set the soft heap-size limit for the library. Passing a zero or
  19041. ** negative value indicates no limit.
  19042. */
  19043. SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 n){
  19044. sqlite3_int64 priorLimit;
  19045. sqlite3_int64 excess;
  19046. #ifndef SQLITE_OMIT_AUTOINIT
  19047. int rc = sqlite3_initialize();
  19048. if( rc ) return -1;
  19049. #endif
  19050. sqlite3_mutex_enter(mem0.mutex);
  19051. priorLimit = mem0.alarmThreshold;
  19052. sqlite3_mutex_leave(mem0.mutex);
  19053. if( n<0 ) return priorLimit;
  19054. if( n>0 ){
  19055. sqlite3MemoryAlarm(softHeapLimitEnforcer, 0, n);
  19056. }else{
  19057. sqlite3MemoryAlarm(0, 0, 0);
  19058. }
  19059. excess = sqlite3_memory_used() - n;
  19060. if( excess>0 ) sqlite3_release_memory((int)(excess & 0x7fffffff));
  19061. return priorLimit;
  19062. }
  19063. SQLITE_API void sqlite3_soft_heap_limit(int n){
  19064. if( n<0 ) n = 0;
  19065. sqlite3_soft_heap_limit64(n);
  19066. }
  19067. /*
  19068. ** Initialize the memory allocation subsystem.
  19069. */
  19070. SQLITE_PRIVATE int sqlite3MallocInit(void){
  19071. if( sqlite3GlobalConfig.m.xMalloc==0 ){
  19072. sqlite3MemSetDefault();
  19073. }
  19074. memset(&mem0, 0, sizeof(mem0));
  19075. if( sqlite3GlobalConfig.bCoreMutex ){
  19076. mem0.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
  19077. }
  19078. if( sqlite3GlobalConfig.pScratch && sqlite3GlobalConfig.szScratch>=100
  19079. && sqlite3GlobalConfig.nScratch>0 ){
  19080. int i, n, sz;
  19081. ScratchFreeslot *pSlot;
  19082. sz = ROUNDDOWN8(sqlite3GlobalConfig.szScratch);
  19083. sqlite3GlobalConfig.szScratch = sz;
  19084. pSlot = (ScratchFreeslot*)sqlite3GlobalConfig.pScratch;
  19085. n = sqlite3GlobalConfig.nScratch;
  19086. mem0.pScratchFree = pSlot;
  19087. mem0.nScratchFree = n;
  19088. for(i=0; i<n-1; i++){
  19089. pSlot->pNext = (ScratchFreeslot*)(sz+(char*)pSlot);
  19090. pSlot = pSlot->pNext;
  19091. }
  19092. pSlot->pNext = 0;
  19093. mem0.pScratchEnd = (void*)&pSlot[1];
  19094. }else{
  19095. mem0.pScratchEnd = 0;
  19096. sqlite3GlobalConfig.pScratch = 0;
  19097. sqlite3GlobalConfig.szScratch = 0;
  19098. sqlite3GlobalConfig.nScratch = 0;
  19099. }
  19100. if( sqlite3GlobalConfig.pPage==0 || sqlite3GlobalConfig.szPage<512
  19101. || sqlite3GlobalConfig.nPage<1 ){
  19102. sqlite3GlobalConfig.pPage = 0;
  19103. sqlite3GlobalConfig.szPage = 0;
  19104. sqlite3GlobalConfig.nPage = 0;
  19105. }
  19106. return sqlite3GlobalConfig.m.xInit(sqlite3GlobalConfig.m.pAppData);
  19107. }
  19108. /*
  19109. ** Return true if the heap is currently under memory pressure - in other
  19110. ** words if the amount of heap used is close to the limit set by
  19111. ** sqlite3_soft_heap_limit().
  19112. */
  19113. SQLITE_PRIVATE int sqlite3HeapNearlyFull(void){
  19114. return mem0.nearlyFull;
  19115. }
  19116. /*
  19117. ** Deinitialize the memory allocation subsystem.
  19118. */
  19119. SQLITE_PRIVATE void sqlite3MallocEnd(void){
  19120. if( sqlite3GlobalConfig.m.xShutdown ){
  19121. sqlite3GlobalConfig.m.xShutdown(sqlite3GlobalConfig.m.pAppData);
  19122. }
  19123. memset(&mem0, 0, sizeof(mem0));
  19124. }
  19125. /*
  19126. ** Return the amount of memory currently checked out.
  19127. */
  19128. SQLITE_API sqlite3_int64 sqlite3_memory_used(void){
  19129. int n, mx;
  19130. sqlite3_int64 res;
  19131. sqlite3_status(SQLITE_STATUS_MEMORY_USED, &n, &mx, 0);
  19132. res = (sqlite3_int64)n; /* Work around bug in Borland C. Ticket #3216 */
  19133. return res;
  19134. }
  19135. /*
  19136. ** Return the maximum amount of memory that has ever been
  19137. ** checked out since either the beginning of this process
  19138. ** or since the most recent reset.
  19139. */
  19140. SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag){
  19141. int n, mx;
  19142. sqlite3_int64 res;
  19143. sqlite3_status(SQLITE_STATUS_MEMORY_USED, &n, &mx, resetFlag);
  19144. res = (sqlite3_int64)mx; /* Work around bug in Borland C. Ticket #3216 */
  19145. return res;
  19146. }
  19147. /*
  19148. ** Trigger the alarm
  19149. */
  19150. static void sqlite3MallocAlarm(int nByte){
  19151. void (*xCallback)(void*,sqlite3_int64,int);
  19152. sqlite3_int64 nowUsed;
  19153. void *pArg;
  19154. if( mem0.alarmCallback==0 ) return;
  19155. xCallback = mem0.alarmCallback;
  19156. nowUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
  19157. pArg = mem0.alarmArg;
  19158. mem0.alarmCallback = 0;
  19159. sqlite3_mutex_leave(mem0.mutex);
  19160. xCallback(pArg, nowUsed, nByte);
  19161. sqlite3_mutex_enter(mem0.mutex);
  19162. mem0.alarmCallback = xCallback;
  19163. mem0.alarmArg = pArg;
  19164. }
  19165. /*
  19166. ** Do a memory allocation with statistics and alarms. Assume the
  19167. ** lock is already held.
  19168. */
  19169. static int mallocWithAlarm(int n, void **pp){
  19170. int nFull;
  19171. void *p;
  19172. assert( sqlite3_mutex_held(mem0.mutex) );
  19173. nFull = sqlite3GlobalConfig.m.xRoundup(n);
  19174. sqlite3StatusSet(SQLITE_STATUS_MALLOC_SIZE, n);
  19175. if( mem0.alarmCallback!=0 ){
  19176. int nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
  19177. if( nUsed >= mem0.alarmThreshold - nFull ){
  19178. mem0.nearlyFull = 1;
  19179. sqlite3MallocAlarm(nFull);
  19180. }else{
  19181. mem0.nearlyFull = 0;
  19182. }
  19183. }
  19184. p = sqlite3GlobalConfig.m.xMalloc(nFull);
  19185. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  19186. if( p==0 && mem0.alarmCallback ){
  19187. sqlite3MallocAlarm(nFull);
  19188. p = sqlite3GlobalConfig.m.xMalloc(nFull);
  19189. }
  19190. #endif
  19191. if( p ){
  19192. nFull = sqlite3MallocSize(p);
  19193. sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, nFull);
  19194. sqlite3StatusAdd(SQLITE_STATUS_MALLOC_COUNT, 1);
  19195. }
  19196. *pp = p;
  19197. return nFull;
  19198. }
  19199. /*
  19200. ** Allocate memory. This routine is like sqlite3_malloc() except that it
  19201. ** assumes the memory subsystem has already been initialized.
  19202. */
  19203. SQLITE_PRIVATE void *sqlite3Malloc(u64 n){
  19204. void *p;
  19205. if( n==0 || n>=0x7fffff00 ){
  19206. /* A memory allocation of a number of bytes which is near the maximum
  19207. ** signed integer value might cause an integer overflow inside of the
  19208. ** xMalloc(). Hence we limit the maximum size to 0x7fffff00, giving
  19209. ** 255 bytes of overhead. SQLite itself will never use anything near
  19210. ** this amount. The only way to reach the limit is with sqlite3_malloc() */
  19211. p = 0;
  19212. }else if( sqlite3GlobalConfig.bMemstat ){
  19213. sqlite3_mutex_enter(mem0.mutex);
  19214. mallocWithAlarm((int)n, &p);
  19215. sqlite3_mutex_leave(mem0.mutex);
  19216. }else{
  19217. p = sqlite3GlobalConfig.m.xMalloc((int)n);
  19218. }
  19219. assert( EIGHT_BYTE_ALIGNMENT(p) ); /* IMP: R-11148-40995 */
  19220. return p;
  19221. }
  19222. /*
  19223. ** This version of the memory allocation is for use by the application.
  19224. ** First make sure the memory subsystem is initialized, then do the
  19225. ** allocation.
  19226. */
  19227. SQLITE_API void *sqlite3_malloc(int n){
  19228. #ifndef SQLITE_OMIT_AUTOINIT
  19229. if( sqlite3_initialize() ) return 0;
  19230. #endif
  19231. return n<=0 ? 0 : sqlite3Malloc(n);
  19232. }
  19233. SQLITE_API void *sqlite3_malloc64(sqlite3_uint64 n){
  19234. #ifndef SQLITE_OMIT_AUTOINIT
  19235. if( sqlite3_initialize() ) return 0;
  19236. #endif
  19237. return sqlite3Malloc(n);
  19238. }
  19239. /*
  19240. ** Each thread may only have a single outstanding allocation from
  19241. ** xScratchMalloc(). We verify this constraint in the single-threaded
  19242. ** case by setting scratchAllocOut to 1 when an allocation
  19243. ** is outstanding clearing it when the allocation is freed.
  19244. */
  19245. #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
  19246. static int scratchAllocOut = 0;
  19247. #endif
  19248. /*
  19249. ** Allocate memory that is to be used and released right away.
  19250. ** This routine is similar to alloca() in that it is not intended
  19251. ** for situations where the memory might be held long-term. This
  19252. ** routine is intended to get memory to old large transient data
  19253. ** structures that would not normally fit on the stack of an
  19254. ** embedded processor.
  19255. */
  19256. SQLITE_PRIVATE void *sqlite3ScratchMalloc(int n){
  19257. void *p;
  19258. assert( n>0 );
  19259. sqlite3_mutex_enter(mem0.mutex);
  19260. sqlite3StatusSet(SQLITE_STATUS_SCRATCH_SIZE, n);
  19261. if( mem0.nScratchFree && sqlite3GlobalConfig.szScratch>=n ){
  19262. p = mem0.pScratchFree;
  19263. mem0.pScratchFree = mem0.pScratchFree->pNext;
  19264. mem0.nScratchFree--;
  19265. sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_USED, 1);
  19266. sqlite3_mutex_leave(mem0.mutex);
  19267. }else{
  19268. sqlite3_mutex_leave(mem0.mutex);
  19269. p = sqlite3Malloc(n);
  19270. if( sqlite3GlobalConfig.bMemstat && p ){
  19271. sqlite3_mutex_enter(mem0.mutex);
  19272. sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_OVERFLOW, sqlite3MallocSize(p));
  19273. sqlite3_mutex_leave(mem0.mutex);
  19274. }
  19275. sqlite3MemdebugSetType(p, MEMTYPE_SCRATCH);
  19276. }
  19277. assert( sqlite3_mutex_notheld(mem0.mutex) );
  19278. #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
  19279. /* Verify that no more than two scratch allocations per thread
  19280. ** are outstanding at one time. (This is only checked in the
  19281. ** single-threaded case since checking in the multi-threaded case
  19282. ** would be much more complicated.) */
  19283. assert( scratchAllocOut<=1 );
  19284. if( p ) scratchAllocOut++;
  19285. #endif
  19286. return p;
  19287. }
  19288. SQLITE_PRIVATE void sqlite3ScratchFree(void *p){
  19289. if( p ){
  19290. #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
  19291. /* Verify that no more than two scratch allocation per thread
  19292. ** is outstanding at one time. (This is only checked in the
  19293. ** single-threaded case since checking in the multi-threaded case
  19294. ** would be much more complicated.) */
  19295. assert( scratchAllocOut>=1 && scratchAllocOut<=2 );
  19296. scratchAllocOut--;
  19297. #endif
  19298. if( p>=sqlite3GlobalConfig.pScratch && p<mem0.pScratchEnd ){
  19299. /* Release memory from the SQLITE_CONFIG_SCRATCH allocation */
  19300. ScratchFreeslot *pSlot;
  19301. pSlot = (ScratchFreeslot*)p;
  19302. sqlite3_mutex_enter(mem0.mutex);
  19303. pSlot->pNext = mem0.pScratchFree;
  19304. mem0.pScratchFree = pSlot;
  19305. mem0.nScratchFree++;
  19306. assert( mem0.nScratchFree <= (u32)sqlite3GlobalConfig.nScratch );
  19307. sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_USED, -1);
  19308. sqlite3_mutex_leave(mem0.mutex);
  19309. }else{
  19310. /* Release memory back to the heap */
  19311. assert( sqlite3MemdebugHasType(p, MEMTYPE_SCRATCH) );
  19312. assert( sqlite3MemdebugNoType(p, ~MEMTYPE_SCRATCH) );
  19313. sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
  19314. if( sqlite3GlobalConfig.bMemstat ){
  19315. int iSize = sqlite3MallocSize(p);
  19316. sqlite3_mutex_enter(mem0.mutex);
  19317. sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_OVERFLOW, -iSize);
  19318. sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, -iSize);
  19319. sqlite3StatusAdd(SQLITE_STATUS_MALLOC_COUNT, -1);
  19320. sqlite3GlobalConfig.m.xFree(p);
  19321. sqlite3_mutex_leave(mem0.mutex);
  19322. }else{
  19323. sqlite3GlobalConfig.m.xFree(p);
  19324. }
  19325. }
  19326. }
  19327. }
  19328. /*
  19329. ** TRUE if p is a lookaside memory allocation from db
  19330. */
  19331. #ifndef SQLITE_OMIT_LOOKASIDE
  19332. static int isLookaside(sqlite3 *db, void *p){
  19333. return p>=db->lookaside.pStart && p<db->lookaside.pEnd;
  19334. }
  19335. #else
  19336. #define isLookaside(A,B) 0
  19337. #endif
  19338. /*
  19339. ** Return the size of a memory allocation previously obtained from
  19340. ** sqlite3Malloc() or sqlite3_malloc().
  19341. */
  19342. SQLITE_PRIVATE int sqlite3MallocSize(void *p){
  19343. assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
  19344. return sqlite3GlobalConfig.m.xSize(p);
  19345. }
  19346. SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3 *db, void *p){
  19347. if( db==0 ){
  19348. assert( sqlite3MemdebugNoType(p, ~MEMTYPE_HEAP) );
  19349. assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
  19350. return sqlite3MallocSize(p);
  19351. }else{
  19352. assert( sqlite3_mutex_held(db->mutex) );
  19353. if( isLookaside(db, p) ){
  19354. return db->lookaside.sz;
  19355. }else{
  19356. assert( sqlite3MemdebugHasType(p, (MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
  19357. assert( sqlite3MemdebugNoType(p, ~(MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
  19358. return sqlite3GlobalConfig.m.xSize(p);
  19359. }
  19360. }
  19361. }
  19362. SQLITE_API sqlite3_uint64 sqlite3_msize(void *p){
  19363. assert( sqlite3MemdebugNoType(p, ~MEMTYPE_HEAP) );
  19364. assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
  19365. return (sqlite3_uint64)sqlite3GlobalConfig.m.xSize(p);
  19366. }
  19367. /*
  19368. ** Free memory previously obtained from sqlite3Malloc().
  19369. */
  19370. SQLITE_API void sqlite3_free(void *p){
  19371. if( p==0 ) return; /* IMP: R-49053-54554 */
  19372. assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
  19373. assert( sqlite3MemdebugNoType(p, ~MEMTYPE_HEAP) );
  19374. if( sqlite3GlobalConfig.bMemstat ){
  19375. sqlite3_mutex_enter(mem0.mutex);
  19376. sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, -sqlite3MallocSize(p));
  19377. sqlite3StatusAdd(SQLITE_STATUS_MALLOC_COUNT, -1);
  19378. sqlite3GlobalConfig.m.xFree(p);
  19379. sqlite3_mutex_leave(mem0.mutex);
  19380. }else{
  19381. sqlite3GlobalConfig.m.xFree(p);
  19382. }
  19383. }
  19384. /*
  19385. ** Add the size of memory allocation "p" to the count in
  19386. ** *db->pnBytesFreed.
  19387. */
  19388. static SQLITE_NOINLINE void measureAllocationSize(sqlite3 *db, void *p){
  19389. *db->pnBytesFreed += sqlite3DbMallocSize(db,p);
  19390. }
  19391. /*
  19392. ** Free memory that might be associated with a particular database
  19393. ** connection.
  19394. */
  19395. SQLITE_PRIVATE void sqlite3DbFree(sqlite3 *db, void *p){
  19396. assert( db==0 || sqlite3_mutex_held(db->mutex) );
  19397. if( p==0 ) return;
  19398. if( db ){
  19399. if( db->pnBytesFreed ){
  19400. measureAllocationSize(db, p);
  19401. return;
  19402. }
  19403. if( isLookaside(db, p) ){
  19404. LookasideSlot *pBuf = (LookasideSlot*)p;
  19405. #if SQLITE_DEBUG
  19406. /* Trash all content in the buffer being freed */
  19407. memset(p, 0xaa, db->lookaside.sz);
  19408. #endif
  19409. pBuf->pNext = db->lookaside.pFree;
  19410. db->lookaside.pFree = pBuf;
  19411. db->lookaside.nOut--;
  19412. return;
  19413. }
  19414. }
  19415. assert( sqlite3MemdebugHasType(p, (MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
  19416. assert( sqlite3MemdebugNoType(p, ~(MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
  19417. assert( db!=0 || sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
  19418. sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
  19419. sqlite3_free(p);
  19420. }
  19421. /*
  19422. ** Change the size of an existing memory allocation
  19423. */
  19424. SQLITE_PRIVATE void *sqlite3Realloc(void *pOld, u64 nBytes){
  19425. int nOld, nNew, nDiff;
  19426. void *pNew;
  19427. assert( sqlite3MemdebugHasType(pOld, MEMTYPE_HEAP) );
  19428. assert( sqlite3MemdebugNoType(pOld, ~MEMTYPE_HEAP) );
  19429. if( pOld==0 ){
  19430. return sqlite3Malloc(nBytes); /* IMP: R-04300-56712 */
  19431. }
  19432. if( nBytes==0 ){
  19433. sqlite3_free(pOld); /* IMP: R-26507-47431 */
  19434. return 0;
  19435. }
  19436. if( nBytes>=0x7fffff00 ){
  19437. /* The 0x7ffff00 limit term is explained in comments on sqlite3Malloc() */
  19438. return 0;
  19439. }
  19440. nOld = sqlite3MallocSize(pOld);
  19441. /* IMPLEMENTATION-OF: R-46199-30249 SQLite guarantees that the second
  19442. ** argument to xRealloc is always a value returned by a prior call to
  19443. ** xRoundup. */
  19444. nNew = sqlite3GlobalConfig.m.xRoundup((int)nBytes);
  19445. if( nOld==nNew ){
  19446. pNew = pOld;
  19447. }else if( sqlite3GlobalConfig.bMemstat ){
  19448. sqlite3_mutex_enter(mem0.mutex);
  19449. sqlite3StatusSet(SQLITE_STATUS_MALLOC_SIZE, (int)nBytes);
  19450. nDiff = nNew - nOld;
  19451. if( sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED) >=
  19452. mem0.alarmThreshold-nDiff ){
  19453. sqlite3MallocAlarm(nDiff);
  19454. }
  19455. pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
  19456. if( pNew==0 && mem0.alarmCallback ){
  19457. sqlite3MallocAlarm((int)nBytes);
  19458. pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
  19459. }
  19460. if( pNew ){
  19461. nNew = sqlite3MallocSize(pNew);
  19462. sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, nNew-nOld);
  19463. }
  19464. sqlite3_mutex_leave(mem0.mutex);
  19465. }else{
  19466. pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
  19467. }
  19468. assert( EIGHT_BYTE_ALIGNMENT(pNew) ); /* IMP: R-11148-40995 */
  19469. return pNew;
  19470. }
  19471. /*
  19472. ** The public interface to sqlite3Realloc. Make sure that the memory
  19473. ** subsystem is initialized prior to invoking sqliteRealloc.
  19474. */
  19475. SQLITE_API void *sqlite3_realloc(void *pOld, int n){
  19476. #ifndef SQLITE_OMIT_AUTOINIT
  19477. if( sqlite3_initialize() ) return 0;
  19478. #endif
  19479. if( n<0 ) n = 0; /* IMP: R-26507-47431 */
  19480. return sqlite3Realloc(pOld, n);
  19481. }
  19482. SQLITE_API void *sqlite3_realloc64(void *pOld, sqlite3_uint64 n){
  19483. #ifndef SQLITE_OMIT_AUTOINIT
  19484. if( sqlite3_initialize() ) return 0;
  19485. #endif
  19486. return sqlite3Realloc(pOld, n);
  19487. }
  19488. /*
  19489. ** Allocate and zero memory.
  19490. */
  19491. SQLITE_PRIVATE void *sqlite3MallocZero(u64 n){
  19492. void *p = sqlite3Malloc(n);
  19493. if( p ){
  19494. memset(p, 0, (size_t)n);
  19495. }
  19496. return p;
  19497. }
  19498. /*
  19499. ** Allocate and zero memory. If the allocation fails, make
  19500. ** the mallocFailed flag in the connection pointer.
  19501. */
  19502. SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3 *db, u64 n){
  19503. void *p = sqlite3DbMallocRaw(db, n);
  19504. if( p ){
  19505. memset(p, 0, (size_t)n);
  19506. }
  19507. return p;
  19508. }
  19509. /*
  19510. ** Allocate and zero memory. If the allocation fails, make
  19511. ** the mallocFailed flag in the connection pointer.
  19512. **
  19513. ** If db!=0 and db->mallocFailed is true (indicating a prior malloc
  19514. ** failure on the same database connection) then always return 0.
  19515. ** Hence for a particular database connection, once malloc starts
  19516. ** failing, it fails consistently until mallocFailed is reset.
  19517. ** This is an important assumption. There are many places in the
  19518. ** code that do things like this:
  19519. **
  19520. ** int *a = (int*)sqlite3DbMallocRaw(db, 100);
  19521. ** int *b = (int*)sqlite3DbMallocRaw(db, 200);
  19522. ** if( b ) a[10] = 9;
  19523. **
  19524. ** In other words, if a subsequent malloc (ex: "b") worked, it is assumed
  19525. ** that all prior mallocs (ex: "a") worked too.
  19526. */
  19527. SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3 *db, u64 n){
  19528. void *p;
  19529. assert( db==0 || sqlite3_mutex_held(db->mutex) );
  19530. assert( db==0 || db->pnBytesFreed==0 );
  19531. #ifndef SQLITE_OMIT_LOOKASIDE
  19532. if( db ){
  19533. LookasideSlot *pBuf;
  19534. if( db->mallocFailed ){
  19535. return 0;
  19536. }
  19537. if( db->lookaside.bEnabled ){
  19538. if( n>db->lookaside.sz ){
  19539. db->lookaside.anStat[1]++;
  19540. }else if( (pBuf = db->lookaside.pFree)==0 ){
  19541. db->lookaside.anStat[2]++;
  19542. }else{
  19543. db->lookaside.pFree = pBuf->pNext;
  19544. db->lookaside.nOut++;
  19545. db->lookaside.anStat[0]++;
  19546. if( db->lookaside.nOut>db->lookaside.mxOut ){
  19547. db->lookaside.mxOut = db->lookaside.nOut;
  19548. }
  19549. return (void*)pBuf;
  19550. }
  19551. }
  19552. }
  19553. #else
  19554. if( db && db->mallocFailed ){
  19555. return 0;
  19556. }
  19557. #endif
  19558. p = sqlite3Malloc(n);
  19559. if( !p && db ){
  19560. db->mallocFailed = 1;
  19561. }
  19562. sqlite3MemdebugSetType(p,
  19563. (db && db->lookaside.bEnabled) ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP);
  19564. return p;
  19565. }
  19566. /*
  19567. ** Resize the block of memory pointed to by p to n bytes. If the
  19568. ** resize fails, set the mallocFailed flag in the connection object.
  19569. */
  19570. SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *db, void *p, u64 n){
  19571. void *pNew = 0;
  19572. assert( db!=0 );
  19573. assert( sqlite3_mutex_held(db->mutex) );
  19574. if( db->mallocFailed==0 ){
  19575. if( p==0 ){
  19576. return sqlite3DbMallocRaw(db, n);
  19577. }
  19578. if( isLookaside(db, p) ){
  19579. if( n<=db->lookaside.sz ){
  19580. return p;
  19581. }
  19582. pNew = sqlite3DbMallocRaw(db, n);
  19583. if( pNew ){
  19584. memcpy(pNew, p, db->lookaside.sz);
  19585. sqlite3DbFree(db, p);
  19586. }
  19587. }else{
  19588. assert( sqlite3MemdebugHasType(p, (MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
  19589. assert( sqlite3MemdebugNoType(p, ~(MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
  19590. sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
  19591. pNew = sqlite3_realloc64(p, n);
  19592. if( !pNew ){
  19593. db->mallocFailed = 1;
  19594. }
  19595. sqlite3MemdebugSetType(pNew,
  19596. (db->lookaside.bEnabled ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP));
  19597. }
  19598. }
  19599. return pNew;
  19600. }
  19601. /*
  19602. ** Attempt to reallocate p. If the reallocation fails, then free p
  19603. ** and set the mallocFailed flag in the database connection.
  19604. */
  19605. SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *db, void *p, u64 n){
  19606. void *pNew;
  19607. pNew = sqlite3DbRealloc(db, p, n);
  19608. if( !pNew ){
  19609. sqlite3DbFree(db, p);
  19610. }
  19611. return pNew;
  19612. }
  19613. /*
  19614. ** Make a copy of a string in memory obtained from sqliteMalloc(). These
  19615. ** functions call sqlite3MallocRaw() directly instead of sqliteMalloc(). This
  19616. ** is because when memory debugging is turned on, these two functions are
  19617. ** called via macros that record the current file and line number in the
  19618. ** ThreadData structure.
  19619. */
  19620. SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3 *db, const char *z){
  19621. char *zNew;
  19622. size_t n;
  19623. if( z==0 ){
  19624. return 0;
  19625. }
  19626. n = sqlite3Strlen30(z) + 1;
  19627. assert( (n&0x7fffffff)==n );
  19628. zNew = sqlite3DbMallocRaw(db, (int)n);
  19629. if( zNew ){
  19630. memcpy(zNew, z, n);
  19631. }
  19632. return zNew;
  19633. }
  19634. SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3 *db, const char *z, u64 n){
  19635. char *zNew;
  19636. if( z==0 ){
  19637. return 0;
  19638. }
  19639. assert( (n&0x7fffffff)==n );
  19640. zNew = sqlite3DbMallocRaw(db, n+1);
  19641. if( zNew ){
  19642. memcpy(zNew, z, (size_t)n);
  19643. zNew[n] = 0;
  19644. }
  19645. return zNew;
  19646. }
  19647. /*
  19648. ** Create a string from the zFromat argument and the va_list that follows.
  19649. ** Store the string in memory obtained from sqliteMalloc() and make *pz
  19650. ** point to that string.
  19651. */
  19652. SQLITE_PRIVATE void sqlite3SetString(char **pz, sqlite3 *db, const char *zFormat, ...){
  19653. va_list ap;
  19654. char *z;
  19655. va_start(ap, zFormat);
  19656. z = sqlite3VMPrintf(db, zFormat, ap);
  19657. va_end(ap);
  19658. sqlite3DbFree(db, *pz);
  19659. *pz = z;
  19660. }
  19661. /*
  19662. ** Take actions at the end of an API call to indicate an OOM error
  19663. */
  19664. static SQLITE_NOINLINE int apiOomError(sqlite3 *db){
  19665. db->mallocFailed = 0;
  19666. sqlite3Error(db, SQLITE_NOMEM);
  19667. return SQLITE_NOMEM;
  19668. }
  19669. /*
  19670. ** This function must be called before exiting any API function (i.e.
  19671. ** returning control to the user) that has called sqlite3_malloc or
  19672. ** sqlite3_realloc.
  19673. **
  19674. ** The returned value is normally a copy of the second argument to this
  19675. ** function. However, if a malloc() failure has occurred since the previous
  19676. ** invocation SQLITE_NOMEM is returned instead.
  19677. **
  19678. ** If the first argument, db, is not NULL and a malloc() error has occurred,
  19679. ** then the connection error-code (the value returned by sqlite3_errcode())
  19680. ** is set to SQLITE_NOMEM.
  19681. */
  19682. SQLITE_PRIVATE int sqlite3ApiExit(sqlite3* db, int rc){
  19683. /* If the db handle is not NULL, then we must hold the connection handle
  19684. ** mutex here. Otherwise the read (and possible write) of db->mallocFailed
  19685. ** is unsafe, as is the call to sqlite3Error().
  19686. */
  19687. assert( !db || sqlite3_mutex_held(db->mutex) );
  19688. if( db==0 ) return rc & 0xff;
  19689. if( db->mallocFailed || rc==SQLITE_IOERR_NOMEM ){
  19690. return apiOomError(db);
  19691. }
  19692. return rc & db->errMask;
  19693. }
  19694. /************** End of malloc.c **********************************************/
  19695. /************** Begin file printf.c ******************************************/
  19696. /*
  19697. ** The "printf" code that follows dates from the 1980's. It is in
  19698. ** the public domain. The original comments are included here for
  19699. ** completeness. They are very out-of-date but might be useful as
  19700. ** an historical reference. Most of the "enhancements" have been backed
  19701. ** out so that the functionality is now the same as standard printf().
  19702. **
  19703. **************************************************************************
  19704. **
  19705. ** This file contains code for a set of "printf"-like routines. These
  19706. ** routines format strings much like the printf() from the standard C
  19707. ** library, though the implementation here has enhancements to support
  19708. ** SQLlite.
  19709. */
  19710. /*
  19711. ** If the strchrnul() library function is available, then set
  19712. ** HAVE_STRCHRNUL. If that routine is not available, this module
  19713. ** will supply its own. The built-in version is slower than
  19714. ** the glibc version so the glibc version is definitely preferred.
  19715. */
  19716. #if !defined(HAVE_STRCHRNUL)
  19717. # define HAVE_STRCHRNUL 0
  19718. #endif
  19719. /*
  19720. ** Conversion types fall into various categories as defined by the
  19721. ** following enumeration.
  19722. */
  19723. #define etRADIX 1 /* Integer types. %d, %x, %o, and so forth */
  19724. #define etFLOAT 2 /* Floating point. %f */
  19725. #define etEXP 3 /* Exponentional notation. %e and %E */
  19726. #define etGENERIC 4 /* Floating or exponential, depending on exponent. %g */
  19727. #define etSIZE 5 /* Return number of characters processed so far. %n */
  19728. #define etSTRING 6 /* Strings. %s */
  19729. #define etDYNSTRING 7 /* Dynamically allocated strings. %z */
  19730. #define etPERCENT 8 /* Percent symbol. %% */
  19731. #define etCHARX 9 /* Characters. %c */
  19732. /* The rest are extensions, not normally found in printf() */
  19733. #define etSQLESCAPE 10 /* Strings with '\'' doubled. %q */
  19734. #define etSQLESCAPE2 11 /* Strings with '\'' doubled and enclosed in '',
  19735. NULL pointers replaced by SQL NULL. %Q */
  19736. #define etTOKEN 12 /* a pointer to a Token structure */
  19737. #define etSRCLIST 13 /* a pointer to a SrcList */
  19738. #define etPOINTER 14 /* The %p conversion */
  19739. #define etSQLESCAPE3 15 /* %w -> Strings with '\"' doubled */
  19740. #define etORDINAL 16 /* %r -> 1st, 2nd, 3rd, 4th, etc. English only */
  19741. #define etINVALID 0 /* Any unrecognized conversion type */
  19742. /*
  19743. ** An "etByte" is an 8-bit unsigned value.
  19744. */
  19745. typedef unsigned char etByte;
  19746. /*
  19747. ** Each builtin conversion character (ex: the 'd' in "%d") is described
  19748. ** by an instance of the following structure
  19749. */
  19750. typedef struct et_info { /* Information about each format field */
  19751. char fmttype; /* The format field code letter */
  19752. etByte base; /* The base for radix conversion */
  19753. etByte flags; /* One or more of FLAG_ constants below */
  19754. etByte type; /* Conversion paradigm */
  19755. etByte charset; /* Offset into aDigits[] of the digits string */
  19756. etByte prefix; /* Offset into aPrefix[] of the prefix string */
  19757. } et_info;
  19758. /*
  19759. ** Allowed values for et_info.flags
  19760. */
  19761. #define FLAG_SIGNED 1 /* True if the value to convert is signed */
  19762. #define FLAG_INTERN 2 /* True if for internal use only */
  19763. #define FLAG_STRING 4 /* Allow infinity precision */
  19764. /*
  19765. ** The following table is searched linearly, so it is good to put the
  19766. ** most frequently used conversion types first.
  19767. */
  19768. static const char aDigits[] = "0123456789ABCDEF0123456789abcdef";
  19769. static const char aPrefix[] = "-x0\000X0";
  19770. static const et_info fmtinfo[] = {
  19771. { 'd', 10, 1, etRADIX, 0, 0 },
  19772. { 's', 0, 4, etSTRING, 0, 0 },
  19773. { 'g', 0, 1, etGENERIC, 30, 0 },
  19774. { 'z', 0, 4, etDYNSTRING, 0, 0 },
  19775. { 'q', 0, 4, etSQLESCAPE, 0, 0 },
  19776. { 'Q', 0, 4, etSQLESCAPE2, 0, 0 },
  19777. { 'w', 0, 4, etSQLESCAPE3, 0, 0 },
  19778. { 'c', 0, 0, etCHARX, 0, 0 },
  19779. { 'o', 8, 0, etRADIX, 0, 2 },
  19780. { 'u', 10, 0, etRADIX, 0, 0 },
  19781. { 'x', 16, 0, etRADIX, 16, 1 },
  19782. { 'X', 16, 0, etRADIX, 0, 4 },
  19783. #ifndef SQLITE_OMIT_FLOATING_POINT
  19784. { 'f', 0, 1, etFLOAT, 0, 0 },
  19785. { 'e', 0, 1, etEXP, 30, 0 },
  19786. { 'E', 0, 1, etEXP, 14, 0 },
  19787. { 'G', 0, 1, etGENERIC, 14, 0 },
  19788. #endif
  19789. { 'i', 10, 1, etRADIX, 0, 0 },
  19790. { 'n', 0, 0, etSIZE, 0, 0 },
  19791. { '%', 0, 0, etPERCENT, 0, 0 },
  19792. { 'p', 16, 0, etPOINTER, 0, 1 },
  19793. /* All the rest have the FLAG_INTERN bit set and are thus for internal
  19794. ** use only */
  19795. { 'T', 0, 2, etTOKEN, 0, 0 },
  19796. { 'S', 0, 2, etSRCLIST, 0, 0 },
  19797. { 'r', 10, 3, etORDINAL, 0, 0 },
  19798. };
  19799. /*
  19800. ** If SQLITE_OMIT_FLOATING_POINT is defined, then none of the floating point
  19801. ** conversions will work.
  19802. */
  19803. #ifndef SQLITE_OMIT_FLOATING_POINT
  19804. /*
  19805. ** "*val" is a double such that 0.1 <= *val < 10.0
  19806. ** Return the ascii code for the leading digit of *val, then
  19807. ** multiply "*val" by 10.0 to renormalize.
  19808. **
  19809. ** Example:
  19810. ** input: *val = 3.14159
  19811. ** output: *val = 1.4159 function return = '3'
  19812. **
  19813. ** The counter *cnt is incremented each time. After counter exceeds
  19814. ** 16 (the number of significant digits in a 64-bit float) '0' is
  19815. ** always returned.
  19816. */
  19817. static char et_getdigit(LONGDOUBLE_TYPE *val, int *cnt){
  19818. int digit;
  19819. LONGDOUBLE_TYPE d;
  19820. if( (*cnt)<=0 ) return '0';
  19821. (*cnt)--;
  19822. digit = (int)*val;
  19823. d = digit;
  19824. digit += '0';
  19825. *val = (*val - d)*10.0;
  19826. return (char)digit;
  19827. }
  19828. #endif /* SQLITE_OMIT_FLOATING_POINT */
  19829. /*
  19830. ** Set the StrAccum object to an error mode.
  19831. */
  19832. static void setStrAccumError(StrAccum *p, u8 eError){
  19833. p->accError = eError;
  19834. p->nAlloc = 0;
  19835. }
  19836. /*
  19837. ** Extra argument values from a PrintfArguments object
  19838. */
  19839. static sqlite3_int64 getIntArg(PrintfArguments *p){
  19840. if( p->nArg<=p->nUsed ) return 0;
  19841. return sqlite3_value_int64(p->apArg[p->nUsed++]);
  19842. }
  19843. static double getDoubleArg(PrintfArguments *p){
  19844. if( p->nArg<=p->nUsed ) return 0.0;
  19845. return sqlite3_value_double(p->apArg[p->nUsed++]);
  19846. }
  19847. static char *getTextArg(PrintfArguments *p){
  19848. if( p->nArg<=p->nUsed ) return 0;
  19849. return (char*)sqlite3_value_text(p->apArg[p->nUsed++]);
  19850. }
  19851. /*
  19852. ** On machines with a small stack size, you can redefine the
  19853. ** SQLITE_PRINT_BUF_SIZE to be something smaller, if desired.
  19854. */
  19855. #ifndef SQLITE_PRINT_BUF_SIZE
  19856. # define SQLITE_PRINT_BUF_SIZE 70
  19857. #endif
  19858. #define etBUFSIZE SQLITE_PRINT_BUF_SIZE /* Size of the output buffer */
  19859. /*
  19860. ** Render a string given by "fmt" into the StrAccum object.
  19861. */
  19862. SQLITE_PRIVATE void sqlite3VXPrintf(
  19863. StrAccum *pAccum, /* Accumulate results here */
  19864. u32 bFlags, /* SQLITE_PRINTF_* flags */
  19865. const char *fmt, /* Format string */
  19866. va_list ap /* arguments */
  19867. ){
  19868. int c; /* Next character in the format string */
  19869. char *bufpt; /* Pointer to the conversion buffer */
  19870. int precision; /* Precision of the current field */
  19871. int length; /* Length of the field */
  19872. int idx; /* A general purpose loop counter */
  19873. int width; /* Width of the current field */
  19874. etByte flag_leftjustify; /* True if "-" flag is present */
  19875. etByte flag_plussign; /* True if "+" flag is present */
  19876. etByte flag_blanksign; /* True if " " flag is present */
  19877. etByte flag_alternateform; /* True if "#" flag is present */
  19878. etByte flag_altform2; /* True if "!" flag is present */
  19879. etByte flag_zeropad; /* True if field width constant starts with zero */
  19880. etByte flag_long; /* True if "l" flag is present */
  19881. etByte flag_longlong; /* True if the "ll" flag is present */
  19882. etByte done; /* Loop termination flag */
  19883. etByte xtype = 0; /* Conversion paradigm */
  19884. u8 bArgList; /* True for SQLITE_PRINTF_SQLFUNC */
  19885. u8 useIntern; /* Ok to use internal conversions (ex: %T) */
  19886. char prefix; /* Prefix character. "+" or "-" or " " or '\0'. */
  19887. sqlite_uint64 longvalue; /* Value for integer types */
  19888. LONGDOUBLE_TYPE realvalue; /* Value for real types */
  19889. const et_info *infop; /* Pointer to the appropriate info structure */
  19890. char *zOut; /* Rendering buffer */
  19891. int nOut; /* Size of the rendering buffer */
  19892. char *zExtra; /* Malloced memory used by some conversion */
  19893. #ifndef SQLITE_OMIT_FLOATING_POINT
  19894. int exp, e2; /* exponent of real numbers */
  19895. int nsd; /* Number of significant digits returned */
  19896. double rounder; /* Used for rounding floating point values */
  19897. etByte flag_dp; /* True if decimal point should be shown */
  19898. etByte flag_rtz; /* True if trailing zeros should be removed */
  19899. #endif
  19900. PrintfArguments *pArgList = 0; /* Arguments for SQLITE_PRINTF_SQLFUNC */
  19901. char buf[etBUFSIZE]; /* Conversion buffer */
  19902. #ifdef SQLITE_ENABLE_API_ARMOR
  19903. if( ap==0 ){
  19904. (void)SQLITE_MISUSE_BKPT;
  19905. sqlite3StrAccumReset(pAccum);
  19906. return;
  19907. }
  19908. #endif
  19909. bufpt = 0;
  19910. if( bFlags ){
  19911. if( (bArgList = (bFlags & SQLITE_PRINTF_SQLFUNC))!=0 ){
  19912. pArgList = va_arg(ap, PrintfArguments*);
  19913. }
  19914. useIntern = bFlags & SQLITE_PRINTF_INTERNAL;
  19915. }else{
  19916. bArgList = useIntern = 0;
  19917. }
  19918. for(; (c=(*fmt))!=0; ++fmt){
  19919. if( c!='%' ){
  19920. bufpt = (char *)fmt;
  19921. #if HAVE_STRCHRNUL
  19922. fmt = strchrnul(fmt, '%');
  19923. #else
  19924. do{ fmt++; }while( *fmt && *fmt != '%' );
  19925. #endif
  19926. sqlite3StrAccumAppend(pAccum, bufpt, (int)(fmt - bufpt));
  19927. if( *fmt==0 ) break;
  19928. }
  19929. if( (c=(*++fmt))==0 ){
  19930. sqlite3StrAccumAppend(pAccum, "%", 1);
  19931. break;
  19932. }
  19933. /* Find out what flags are present */
  19934. flag_leftjustify = flag_plussign = flag_blanksign =
  19935. flag_alternateform = flag_altform2 = flag_zeropad = 0;
  19936. done = 0;
  19937. do{
  19938. switch( c ){
  19939. case '-': flag_leftjustify = 1; break;
  19940. case '+': flag_plussign = 1; break;
  19941. case ' ': flag_blanksign = 1; break;
  19942. case '#': flag_alternateform = 1; break;
  19943. case '!': flag_altform2 = 1; break;
  19944. case '0': flag_zeropad = 1; break;
  19945. default: done = 1; break;
  19946. }
  19947. }while( !done && (c=(*++fmt))!=0 );
  19948. /* Get the field width */
  19949. width = 0;
  19950. if( c=='*' ){
  19951. if( bArgList ){
  19952. width = (int)getIntArg(pArgList);
  19953. }else{
  19954. width = va_arg(ap,int);
  19955. }
  19956. if( width<0 ){
  19957. flag_leftjustify = 1;
  19958. width = -width;
  19959. }
  19960. c = *++fmt;
  19961. }else{
  19962. while( c>='0' && c<='9' ){
  19963. width = width*10 + c - '0';
  19964. c = *++fmt;
  19965. }
  19966. }
  19967. /* Get the precision */
  19968. if( c=='.' ){
  19969. precision = 0;
  19970. c = *++fmt;
  19971. if( c=='*' ){
  19972. if( bArgList ){
  19973. precision = (int)getIntArg(pArgList);
  19974. }else{
  19975. precision = va_arg(ap,int);
  19976. }
  19977. if( precision<0 ) precision = -precision;
  19978. c = *++fmt;
  19979. }else{
  19980. while( c>='0' && c<='9' ){
  19981. precision = precision*10 + c - '0';
  19982. c = *++fmt;
  19983. }
  19984. }
  19985. }else{
  19986. precision = -1;
  19987. }
  19988. /* Get the conversion type modifier */
  19989. if( c=='l' ){
  19990. flag_long = 1;
  19991. c = *++fmt;
  19992. if( c=='l' ){
  19993. flag_longlong = 1;
  19994. c = *++fmt;
  19995. }else{
  19996. flag_longlong = 0;
  19997. }
  19998. }else{
  19999. flag_long = flag_longlong = 0;
  20000. }
  20001. /* Fetch the info entry for the field */
  20002. infop = &fmtinfo[0];
  20003. xtype = etINVALID;
  20004. for(idx=0; idx<ArraySize(fmtinfo); idx++){
  20005. if( c==fmtinfo[idx].fmttype ){
  20006. infop = &fmtinfo[idx];
  20007. if( useIntern || (infop->flags & FLAG_INTERN)==0 ){
  20008. xtype = infop->type;
  20009. }else{
  20010. return;
  20011. }
  20012. break;
  20013. }
  20014. }
  20015. zExtra = 0;
  20016. /*
  20017. ** At this point, variables are initialized as follows:
  20018. **
  20019. ** flag_alternateform TRUE if a '#' is present.
  20020. ** flag_altform2 TRUE if a '!' is present.
  20021. ** flag_plussign TRUE if a '+' is present.
  20022. ** flag_leftjustify TRUE if a '-' is present or if the
  20023. ** field width was negative.
  20024. ** flag_zeropad TRUE if the width began with 0.
  20025. ** flag_long TRUE if the letter 'l' (ell) prefixed
  20026. ** the conversion character.
  20027. ** flag_longlong TRUE if the letter 'll' (ell ell) prefixed
  20028. ** the conversion character.
  20029. ** flag_blanksign TRUE if a ' ' is present.
  20030. ** width The specified field width. This is
  20031. ** always non-negative. Zero is the default.
  20032. ** precision The specified precision. The default
  20033. ** is -1.
  20034. ** xtype The class of the conversion.
  20035. ** infop Pointer to the appropriate info struct.
  20036. */
  20037. switch( xtype ){
  20038. case etPOINTER:
  20039. flag_longlong = sizeof(char*)==sizeof(i64);
  20040. flag_long = sizeof(char*)==sizeof(long int);
  20041. /* Fall through into the next case */
  20042. case etORDINAL:
  20043. case etRADIX:
  20044. if( infop->flags & FLAG_SIGNED ){
  20045. i64 v;
  20046. if( bArgList ){
  20047. v = getIntArg(pArgList);
  20048. }else if( flag_longlong ){
  20049. v = va_arg(ap,i64);
  20050. }else if( flag_long ){
  20051. v = va_arg(ap,long int);
  20052. }else{
  20053. v = va_arg(ap,int);
  20054. }
  20055. if( v<0 ){
  20056. if( v==SMALLEST_INT64 ){
  20057. longvalue = ((u64)1)<<63;
  20058. }else{
  20059. longvalue = -v;
  20060. }
  20061. prefix = '-';
  20062. }else{
  20063. longvalue = v;
  20064. if( flag_plussign ) prefix = '+';
  20065. else if( flag_blanksign ) prefix = ' ';
  20066. else prefix = 0;
  20067. }
  20068. }else{
  20069. if( bArgList ){
  20070. longvalue = (u64)getIntArg(pArgList);
  20071. }else if( flag_longlong ){
  20072. longvalue = va_arg(ap,u64);
  20073. }else if( flag_long ){
  20074. longvalue = va_arg(ap,unsigned long int);
  20075. }else{
  20076. longvalue = va_arg(ap,unsigned int);
  20077. }
  20078. prefix = 0;
  20079. }
  20080. if( longvalue==0 ) flag_alternateform = 0;
  20081. if( flag_zeropad && precision<width-(prefix!=0) ){
  20082. precision = width-(prefix!=0);
  20083. }
  20084. if( precision<etBUFSIZE-10 ){
  20085. nOut = etBUFSIZE;
  20086. zOut = buf;
  20087. }else{
  20088. nOut = precision + 10;
  20089. zOut = zExtra = sqlite3Malloc( nOut );
  20090. if( zOut==0 ){
  20091. setStrAccumError(pAccum, STRACCUM_NOMEM);
  20092. return;
  20093. }
  20094. }
  20095. bufpt = &zOut[nOut-1];
  20096. if( xtype==etORDINAL ){
  20097. static const char zOrd[] = "thstndrd";
  20098. int x = (int)(longvalue % 10);
  20099. if( x>=4 || (longvalue/10)%10==1 ){
  20100. x = 0;
  20101. }
  20102. *(--bufpt) = zOrd[x*2+1];
  20103. *(--bufpt) = zOrd[x*2];
  20104. }
  20105. {
  20106. const char *cset = &aDigits[infop->charset];
  20107. u8 base = infop->base;
  20108. do{ /* Convert to ascii */
  20109. *(--bufpt) = cset[longvalue%base];
  20110. longvalue = longvalue/base;
  20111. }while( longvalue>0 );
  20112. }
  20113. length = (int)(&zOut[nOut-1]-bufpt);
  20114. for(idx=precision-length; idx>0; idx--){
  20115. *(--bufpt) = '0'; /* Zero pad */
  20116. }
  20117. if( prefix ) *(--bufpt) = prefix; /* Add sign */
  20118. if( flag_alternateform && infop->prefix ){ /* Add "0" or "0x" */
  20119. const char *pre;
  20120. char x;
  20121. pre = &aPrefix[infop->prefix];
  20122. for(; (x=(*pre))!=0; pre++) *(--bufpt) = x;
  20123. }
  20124. length = (int)(&zOut[nOut-1]-bufpt);
  20125. break;
  20126. case etFLOAT:
  20127. case etEXP:
  20128. case etGENERIC:
  20129. if( bArgList ){
  20130. realvalue = getDoubleArg(pArgList);
  20131. }else{
  20132. realvalue = va_arg(ap,double);
  20133. }
  20134. #ifdef SQLITE_OMIT_FLOATING_POINT
  20135. length = 0;
  20136. #else
  20137. if( precision<0 ) precision = 6; /* Set default precision */
  20138. if( realvalue<0.0 ){
  20139. realvalue = -realvalue;
  20140. prefix = '-';
  20141. }else{
  20142. if( flag_plussign ) prefix = '+';
  20143. else if( flag_blanksign ) prefix = ' ';
  20144. else prefix = 0;
  20145. }
  20146. if( xtype==etGENERIC && precision>0 ) precision--;
  20147. for(idx=precision, rounder=0.5; idx>0; idx--, rounder*=0.1){}
  20148. if( xtype==etFLOAT ) realvalue += rounder;
  20149. /* Normalize realvalue to within 10.0 > realvalue >= 1.0 */
  20150. exp = 0;
  20151. if( sqlite3IsNaN((double)realvalue) ){
  20152. bufpt = "NaN";
  20153. length = 3;
  20154. break;
  20155. }
  20156. if( realvalue>0.0 ){
  20157. LONGDOUBLE_TYPE scale = 1.0;
  20158. while( realvalue>=1e100*scale && exp<=350 ){ scale *= 1e100;exp+=100;}
  20159. while( realvalue>=1e64*scale && exp<=350 ){ scale *= 1e64; exp+=64; }
  20160. while( realvalue>=1e8*scale && exp<=350 ){ scale *= 1e8; exp+=8; }
  20161. while( realvalue>=10.0*scale && exp<=350 ){ scale *= 10.0; exp++; }
  20162. realvalue /= scale;
  20163. while( realvalue<1e-8 ){ realvalue *= 1e8; exp-=8; }
  20164. while( realvalue<1.0 ){ realvalue *= 10.0; exp--; }
  20165. if( exp>350 ){
  20166. if( prefix=='-' ){
  20167. bufpt = "-Inf";
  20168. }else if( prefix=='+' ){
  20169. bufpt = "+Inf";
  20170. }else{
  20171. bufpt = "Inf";
  20172. }
  20173. length = sqlite3Strlen30(bufpt);
  20174. break;
  20175. }
  20176. }
  20177. bufpt = buf;
  20178. /*
  20179. ** If the field type is etGENERIC, then convert to either etEXP
  20180. ** or etFLOAT, as appropriate.
  20181. */
  20182. if( xtype!=etFLOAT ){
  20183. realvalue += rounder;
  20184. if( realvalue>=10.0 ){ realvalue *= 0.1; exp++; }
  20185. }
  20186. if( xtype==etGENERIC ){
  20187. flag_rtz = !flag_alternateform;
  20188. if( exp<-4 || exp>precision ){
  20189. xtype = etEXP;
  20190. }else{
  20191. precision = precision - exp;
  20192. xtype = etFLOAT;
  20193. }
  20194. }else{
  20195. flag_rtz = flag_altform2;
  20196. }
  20197. if( xtype==etEXP ){
  20198. e2 = 0;
  20199. }else{
  20200. e2 = exp;
  20201. }
  20202. if( MAX(e2,0)+precision+width > etBUFSIZE - 15 ){
  20203. bufpt = zExtra = sqlite3Malloc( MAX(e2,0)+precision+width+15 );
  20204. if( bufpt==0 ){
  20205. setStrAccumError(pAccum, STRACCUM_NOMEM);
  20206. return;
  20207. }
  20208. }
  20209. zOut = bufpt;
  20210. nsd = 16 + flag_altform2*10;
  20211. flag_dp = (precision>0 ?1:0) | flag_alternateform | flag_altform2;
  20212. /* The sign in front of the number */
  20213. if( prefix ){
  20214. *(bufpt++) = prefix;
  20215. }
  20216. /* Digits prior to the decimal point */
  20217. if( e2<0 ){
  20218. *(bufpt++) = '0';
  20219. }else{
  20220. for(; e2>=0; e2--){
  20221. *(bufpt++) = et_getdigit(&realvalue,&nsd);
  20222. }
  20223. }
  20224. /* The decimal point */
  20225. if( flag_dp ){
  20226. *(bufpt++) = '.';
  20227. }
  20228. /* "0" digits after the decimal point but before the first
  20229. ** significant digit of the number */
  20230. for(e2++; e2<0; precision--, e2++){
  20231. assert( precision>0 );
  20232. *(bufpt++) = '0';
  20233. }
  20234. /* Significant digits after the decimal point */
  20235. while( (precision--)>0 ){
  20236. *(bufpt++) = et_getdigit(&realvalue,&nsd);
  20237. }
  20238. /* Remove trailing zeros and the "." if no digits follow the "." */
  20239. if( flag_rtz && flag_dp ){
  20240. while( bufpt[-1]=='0' ) *(--bufpt) = 0;
  20241. assert( bufpt>zOut );
  20242. if( bufpt[-1]=='.' ){
  20243. if( flag_altform2 ){
  20244. *(bufpt++) = '0';
  20245. }else{
  20246. *(--bufpt) = 0;
  20247. }
  20248. }
  20249. }
  20250. /* Add the "eNNN" suffix */
  20251. if( xtype==etEXP ){
  20252. *(bufpt++) = aDigits[infop->charset];
  20253. if( exp<0 ){
  20254. *(bufpt++) = '-'; exp = -exp;
  20255. }else{
  20256. *(bufpt++) = '+';
  20257. }
  20258. if( exp>=100 ){
  20259. *(bufpt++) = (char)((exp/100)+'0'); /* 100's digit */
  20260. exp %= 100;
  20261. }
  20262. *(bufpt++) = (char)(exp/10+'0'); /* 10's digit */
  20263. *(bufpt++) = (char)(exp%10+'0'); /* 1's digit */
  20264. }
  20265. *bufpt = 0;
  20266. /* The converted number is in buf[] and zero terminated. Output it.
  20267. ** Note that the number is in the usual order, not reversed as with
  20268. ** integer conversions. */
  20269. length = (int)(bufpt-zOut);
  20270. bufpt = zOut;
  20271. /* Special case: Add leading zeros if the flag_zeropad flag is
  20272. ** set and we are not left justified */
  20273. if( flag_zeropad && !flag_leftjustify && length < width){
  20274. int i;
  20275. int nPad = width - length;
  20276. for(i=width; i>=nPad; i--){
  20277. bufpt[i] = bufpt[i-nPad];
  20278. }
  20279. i = prefix!=0;
  20280. while( nPad-- ) bufpt[i++] = '0';
  20281. length = width;
  20282. }
  20283. #endif /* !defined(SQLITE_OMIT_FLOATING_POINT) */
  20284. break;
  20285. case etSIZE:
  20286. if( !bArgList ){
  20287. *(va_arg(ap,int*)) = pAccum->nChar;
  20288. }
  20289. length = width = 0;
  20290. break;
  20291. case etPERCENT:
  20292. buf[0] = '%';
  20293. bufpt = buf;
  20294. length = 1;
  20295. break;
  20296. case etCHARX:
  20297. if( bArgList ){
  20298. bufpt = getTextArg(pArgList);
  20299. c = bufpt ? bufpt[0] : 0;
  20300. }else{
  20301. c = va_arg(ap,int);
  20302. }
  20303. buf[0] = (char)c;
  20304. if( precision>=0 ){
  20305. for(idx=1; idx<precision; idx++) buf[idx] = (char)c;
  20306. length = precision;
  20307. }else{
  20308. length =1;
  20309. }
  20310. bufpt = buf;
  20311. break;
  20312. case etSTRING:
  20313. case etDYNSTRING:
  20314. if( bArgList ){
  20315. bufpt = getTextArg(pArgList);
  20316. }else{
  20317. bufpt = va_arg(ap,char*);
  20318. }
  20319. if( bufpt==0 ){
  20320. bufpt = "";
  20321. }else if( xtype==etDYNSTRING && !bArgList ){
  20322. zExtra = bufpt;
  20323. }
  20324. if( precision>=0 ){
  20325. for(length=0; length<precision && bufpt[length]; length++){}
  20326. }else{
  20327. length = sqlite3Strlen30(bufpt);
  20328. }
  20329. break;
  20330. case etSQLESCAPE:
  20331. case etSQLESCAPE2:
  20332. case etSQLESCAPE3: {
  20333. int i, j, k, n, isnull;
  20334. int needQuote;
  20335. char ch;
  20336. char q = ((xtype==etSQLESCAPE3)?'"':'\''); /* Quote character */
  20337. char *escarg;
  20338. if( bArgList ){
  20339. escarg = getTextArg(pArgList);
  20340. }else{
  20341. escarg = va_arg(ap,char*);
  20342. }
  20343. isnull = escarg==0;
  20344. if( isnull ) escarg = (xtype==etSQLESCAPE2 ? "NULL" : "(NULL)");
  20345. k = precision;
  20346. for(i=n=0; k!=0 && (ch=escarg[i])!=0; i++, k--){
  20347. if( ch==q ) n++;
  20348. }
  20349. needQuote = !isnull && xtype==etSQLESCAPE2;
  20350. n += i + 1 + needQuote*2;
  20351. if( n>etBUFSIZE ){
  20352. bufpt = zExtra = sqlite3Malloc( n );
  20353. if( bufpt==0 ){
  20354. setStrAccumError(pAccum, STRACCUM_NOMEM);
  20355. return;
  20356. }
  20357. }else{
  20358. bufpt = buf;
  20359. }
  20360. j = 0;
  20361. if( needQuote ) bufpt[j++] = q;
  20362. k = i;
  20363. for(i=0; i<k; i++){
  20364. bufpt[j++] = ch = escarg[i];
  20365. if( ch==q ) bufpt[j++] = ch;
  20366. }
  20367. if( needQuote ) bufpt[j++] = q;
  20368. bufpt[j] = 0;
  20369. length = j;
  20370. /* The precision in %q and %Q means how many input characters to
  20371. ** consume, not the length of the output...
  20372. ** if( precision>=0 && precision<length ) length = precision; */
  20373. break;
  20374. }
  20375. case etTOKEN: {
  20376. Token *pToken = va_arg(ap, Token*);
  20377. assert( bArgList==0 );
  20378. if( pToken && pToken->n ){
  20379. sqlite3StrAccumAppend(pAccum, (const char*)pToken->z, pToken->n);
  20380. }
  20381. length = width = 0;
  20382. break;
  20383. }
  20384. case etSRCLIST: {
  20385. SrcList *pSrc = va_arg(ap, SrcList*);
  20386. int k = va_arg(ap, int);
  20387. struct SrcList_item *pItem = &pSrc->a[k];
  20388. assert( bArgList==0 );
  20389. assert( k>=0 && k<pSrc->nSrc );
  20390. if( pItem->zDatabase ){
  20391. sqlite3StrAccumAppendAll(pAccum, pItem->zDatabase);
  20392. sqlite3StrAccumAppend(pAccum, ".", 1);
  20393. }
  20394. sqlite3StrAccumAppendAll(pAccum, pItem->zName);
  20395. length = width = 0;
  20396. break;
  20397. }
  20398. default: {
  20399. assert( xtype==etINVALID );
  20400. return;
  20401. }
  20402. }/* End switch over the format type */
  20403. /*
  20404. ** The text of the conversion is pointed to by "bufpt" and is
  20405. ** "length" characters long. The field width is "width". Do
  20406. ** the output.
  20407. */
  20408. width -= length;
  20409. if( width>0 && !flag_leftjustify ) sqlite3AppendSpace(pAccum, width);
  20410. sqlite3StrAccumAppend(pAccum, bufpt, length);
  20411. if( width>0 && flag_leftjustify ) sqlite3AppendSpace(pAccum, width);
  20412. if( zExtra ) sqlite3_free(zExtra);
  20413. }/* End for loop over the format string */
  20414. } /* End of function */
  20415. /*
  20416. ** Enlarge the memory allocation on a StrAccum object so that it is
  20417. ** able to accept at least N more bytes of text.
  20418. **
  20419. ** Return the number of bytes of text that StrAccum is able to accept
  20420. ** after the attempted enlargement. The value returned might be zero.
  20421. */
  20422. static int sqlite3StrAccumEnlarge(StrAccum *p, int N){
  20423. char *zNew;
  20424. assert( p->nChar+N >= p->nAlloc ); /* Only called if really needed */
  20425. if( p->accError ){
  20426. testcase(p->accError==STRACCUM_TOOBIG);
  20427. testcase(p->accError==STRACCUM_NOMEM);
  20428. return 0;
  20429. }
  20430. if( !p->useMalloc ){
  20431. N = p->nAlloc - p->nChar - 1;
  20432. setStrAccumError(p, STRACCUM_TOOBIG);
  20433. return N;
  20434. }else{
  20435. char *zOld = (p->zText==p->zBase ? 0 : p->zText);
  20436. i64 szNew = p->nChar;
  20437. szNew += N + 1;
  20438. if( szNew > p->mxAlloc ){
  20439. sqlite3StrAccumReset(p);
  20440. setStrAccumError(p, STRACCUM_TOOBIG);
  20441. return 0;
  20442. }else{
  20443. p->nAlloc = (int)szNew;
  20444. }
  20445. if( p->useMalloc==1 ){
  20446. zNew = sqlite3DbRealloc(p->db, zOld, p->nAlloc);
  20447. }else{
  20448. zNew = sqlite3_realloc(zOld, p->nAlloc);
  20449. }
  20450. if( zNew ){
  20451. assert( p->zText!=0 || p->nChar==0 );
  20452. if( zOld==0 && p->nChar>0 ) memcpy(zNew, p->zText, p->nChar);
  20453. p->zText = zNew;
  20454. }else{
  20455. sqlite3StrAccumReset(p);
  20456. setStrAccumError(p, STRACCUM_NOMEM);
  20457. return 0;
  20458. }
  20459. }
  20460. return N;
  20461. }
  20462. /*
  20463. ** Append N space characters to the given string buffer.
  20464. */
  20465. SQLITE_PRIVATE void sqlite3AppendSpace(StrAccum *p, int N){
  20466. if( p->nChar+N >= p->nAlloc && (N = sqlite3StrAccumEnlarge(p, N))<=0 ) return;
  20467. while( (N--)>0 ) p->zText[p->nChar++] = ' ';
  20468. }
  20469. /*
  20470. ** The StrAccum "p" is not large enough to accept N new bytes of z[].
  20471. ** So enlarge if first, then do the append.
  20472. **
  20473. ** This is a helper routine to sqlite3StrAccumAppend() that does special-case
  20474. ** work (enlarging the buffer) using tail recursion, so that the
  20475. ** sqlite3StrAccumAppend() routine can use fast calling semantics.
  20476. */
  20477. static void SQLITE_NOINLINE enlargeAndAppend(StrAccum *p, const char *z, int N){
  20478. N = sqlite3StrAccumEnlarge(p, N);
  20479. if( N>0 ){
  20480. memcpy(&p->zText[p->nChar], z, N);
  20481. p->nChar += N;
  20482. }
  20483. }
  20484. /*
  20485. ** Append N bytes of text from z to the StrAccum object. Increase the
  20486. ** size of the memory allocation for StrAccum if necessary.
  20487. */
  20488. SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum *p, const char *z, int N){
  20489. assert( z!=0 );
  20490. assert( p->zText!=0 || p->nChar==0 || p->accError );
  20491. assert( N>=0 );
  20492. assert( p->accError==0 || p->nAlloc==0 );
  20493. if( p->nChar+N >= p->nAlloc ){
  20494. enlargeAndAppend(p,z,N);
  20495. }else{
  20496. assert( p->zText );
  20497. p->nChar += N;
  20498. memcpy(&p->zText[p->nChar-N], z, N);
  20499. }
  20500. }
  20501. /*
  20502. ** Append the complete text of zero-terminated string z[] to the p string.
  20503. */
  20504. SQLITE_PRIVATE void sqlite3StrAccumAppendAll(StrAccum *p, const char *z){
  20505. sqlite3StrAccumAppend(p, z, sqlite3Strlen30(z));
  20506. }
  20507. /*
  20508. ** Finish off a string by making sure it is zero-terminated.
  20509. ** Return a pointer to the resulting string. Return a NULL
  20510. ** pointer if any kind of error was encountered.
  20511. */
  20512. SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum *p){
  20513. if( p->zText ){
  20514. p->zText[p->nChar] = 0;
  20515. if( p->useMalloc && p->zText==p->zBase ){
  20516. if( p->useMalloc==1 ){
  20517. p->zText = sqlite3DbMallocRaw(p->db, p->nChar+1 );
  20518. }else{
  20519. p->zText = sqlite3_malloc(p->nChar+1);
  20520. }
  20521. if( p->zText ){
  20522. memcpy(p->zText, p->zBase, p->nChar+1);
  20523. }else{
  20524. setStrAccumError(p, STRACCUM_NOMEM);
  20525. }
  20526. }
  20527. }
  20528. return p->zText;
  20529. }
  20530. /*
  20531. ** Reset an StrAccum string. Reclaim all malloced memory.
  20532. */
  20533. SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum *p){
  20534. if( p->zText!=p->zBase ){
  20535. if( p->useMalloc==1 ){
  20536. sqlite3DbFree(p->db, p->zText);
  20537. }else{
  20538. sqlite3_free(p->zText);
  20539. }
  20540. }
  20541. p->zText = 0;
  20542. }
  20543. /*
  20544. ** Initialize a string accumulator
  20545. */
  20546. SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum *p, char *zBase, int n, int mx){
  20547. p->zText = p->zBase = zBase;
  20548. p->db = 0;
  20549. p->nChar = 0;
  20550. p->nAlloc = n;
  20551. p->mxAlloc = mx;
  20552. p->useMalloc = 1;
  20553. p->accError = 0;
  20554. }
  20555. /*
  20556. ** Print into memory obtained from sqliteMalloc(). Use the internal
  20557. ** %-conversion extensions.
  20558. */
  20559. SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3 *db, const char *zFormat, va_list ap){
  20560. char *z;
  20561. char zBase[SQLITE_PRINT_BUF_SIZE];
  20562. StrAccum acc;
  20563. assert( db!=0 );
  20564. sqlite3StrAccumInit(&acc, zBase, sizeof(zBase),
  20565. db->aLimit[SQLITE_LIMIT_LENGTH]);
  20566. acc.db = db;
  20567. sqlite3VXPrintf(&acc, SQLITE_PRINTF_INTERNAL, zFormat, ap);
  20568. z = sqlite3StrAccumFinish(&acc);
  20569. if( acc.accError==STRACCUM_NOMEM ){
  20570. db->mallocFailed = 1;
  20571. }
  20572. return z;
  20573. }
  20574. /*
  20575. ** Print into memory obtained from sqliteMalloc(). Use the internal
  20576. ** %-conversion extensions.
  20577. */
  20578. SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3 *db, const char *zFormat, ...){
  20579. va_list ap;
  20580. char *z;
  20581. va_start(ap, zFormat);
  20582. z = sqlite3VMPrintf(db, zFormat, ap);
  20583. va_end(ap);
  20584. return z;
  20585. }
  20586. /*
  20587. ** Like sqlite3MPrintf(), but call sqlite3DbFree() on zStr after formatting
  20588. ** the string and before returning. This routine is intended to be used
  20589. ** to modify an existing string. For example:
  20590. **
  20591. ** x = sqlite3MPrintf(db, x, "prefix %s suffix", x);
  20592. **
  20593. */
  20594. SQLITE_PRIVATE char *sqlite3MAppendf(sqlite3 *db, char *zStr, const char *zFormat, ...){
  20595. va_list ap;
  20596. char *z;
  20597. va_start(ap, zFormat);
  20598. z = sqlite3VMPrintf(db, zFormat, ap);
  20599. va_end(ap);
  20600. sqlite3DbFree(db, zStr);
  20601. return z;
  20602. }
  20603. /*
  20604. ** Print into memory obtained from sqlite3_malloc(). Omit the internal
  20605. ** %-conversion extensions.
  20606. */
  20607. SQLITE_API char *sqlite3_vmprintf(const char *zFormat, va_list ap){
  20608. char *z;
  20609. char zBase[SQLITE_PRINT_BUF_SIZE];
  20610. StrAccum acc;
  20611. #ifdef SQLITE_ENABLE_API_ARMOR
  20612. if( zFormat==0 ){
  20613. (void)SQLITE_MISUSE_BKPT;
  20614. return 0;
  20615. }
  20616. #endif
  20617. #ifndef SQLITE_OMIT_AUTOINIT
  20618. if( sqlite3_initialize() ) return 0;
  20619. #endif
  20620. sqlite3StrAccumInit(&acc, zBase, sizeof(zBase), SQLITE_MAX_LENGTH);
  20621. acc.useMalloc = 2;
  20622. sqlite3VXPrintf(&acc, 0, zFormat, ap);
  20623. z = sqlite3StrAccumFinish(&acc);
  20624. return z;
  20625. }
  20626. /*
  20627. ** Print into memory obtained from sqlite3_malloc()(). Omit the internal
  20628. ** %-conversion extensions.
  20629. */
  20630. SQLITE_API char *sqlite3_mprintf(const char *zFormat, ...){
  20631. va_list ap;
  20632. char *z;
  20633. #ifndef SQLITE_OMIT_AUTOINIT
  20634. if( sqlite3_initialize() ) return 0;
  20635. #endif
  20636. va_start(ap, zFormat);
  20637. z = sqlite3_vmprintf(zFormat, ap);
  20638. va_end(ap);
  20639. return z;
  20640. }
  20641. /*
  20642. ** sqlite3_snprintf() works like snprintf() except that it ignores the
  20643. ** current locale settings. This is important for SQLite because we
  20644. ** are not able to use a "," as the decimal point in place of "." as
  20645. ** specified by some locales.
  20646. **
  20647. ** Oops: The first two arguments of sqlite3_snprintf() are backwards
  20648. ** from the snprintf() standard. Unfortunately, it is too late to change
  20649. ** this without breaking compatibility, so we just have to live with the
  20650. ** mistake.
  20651. **
  20652. ** sqlite3_vsnprintf() is the varargs version.
  20653. */
  20654. SQLITE_API char *sqlite3_vsnprintf(int n, char *zBuf, const char *zFormat, va_list ap){
  20655. StrAccum acc;
  20656. if( n<=0 ) return zBuf;
  20657. #ifdef SQLITE_ENABLE_API_ARMOR
  20658. if( zBuf==0 || zFormat==0 ) {
  20659. (void)SQLITE_MISUSE_BKPT;
  20660. if( zBuf && n>0 ) zBuf[0] = 0;
  20661. return zBuf;
  20662. }
  20663. #endif
  20664. sqlite3StrAccumInit(&acc, zBuf, n, 0);
  20665. acc.useMalloc = 0;
  20666. sqlite3VXPrintf(&acc, 0, zFormat, ap);
  20667. return sqlite3StrAccumFinish(&acc);
  20668. }
  20669. SQLITE_API char *sqlite3_snprintf(int n, char *zBuf, const char *zFormat, ...){
  20670. char *z;
  20671. va_list ap;
  20672. va_start(ap,zFormat);
  20673. z = sqlite3_vsnprintf(n, zBuf, zFormat, ap);
  20674. va_end(ap);
  20675. return z;
  20676. }
  20677. /*
  20678. ** This is the routine that actually formats the sqlite3_log() message.
  20679. ** We house it in a separate routine from sqlite3_log() to avoid using
  20680. ** stack space on small-stack systems when logging is disabled.
  20681. **
  20682. ** sqlite3_log() must render into a static buffer. It cannot dynamically
  20683. ** allocate memory because it might be called while the memory allocator
  20684. ** mutex is held.
  20685. */
  20686. static void renderLogMsg(int iErrCode, const char *zFormat, va_list ap){
  20687. StrAccum acc; /* String accumulator */
  20688. char zMsg[SQLITE_PRINT_BUF_SIZE*3]; /* Complete log message */
  20689. sqlite3StrAccumInit(&acc, zMsg, sizeof(zMsg), 0);
  20690. acc.useMalloc = 0;
  20691. sqlite3VXPrintf(&acc, 0, zFormat, ap);
  20692. sqlite3GlobalConfig.xLog(sqlite3GlobalConfig.pLogArg, iErrCode,
  20693. sqlite3StrAccumFinish(&acc));
  20694. }
  20695. /*
  20696. ** Format and write a message to the log if logging is enabled.
  20697. */
  20698. SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...){
  20699. va_list ap; /* Vararg list */
  20700. if( sqlite3GlobalConfig.xLog ){
  20701. va_start(ap, zFormat);
  20702. renderLogMsg(iErrCode, zFormat, ap);
  20703. va_end(ap);
  20704. }
  20705. }
  20706. #if defined(SQLITE_DEBUG)
  20707. /*
  20708. ** A version of printf() that understands %lld. Used for debugging.
  20709. ** The printf() built into some versions of windows does not understand %lld
  20710. ** and segfaults if you give it a long long int.
  20711. */
  20712. SQLITE_PRIVATE void sqlite3DebugPrintf(const char *zFormat, ...){
  20713. va_list ap;
  20714. StrAccum acc;
  20715. char zBuf[500];
  20716. sqlite3StrAccumInit(&acc, zBuf, sizeof(zBuf), 0);
  20717. acc.useMalloc = 0;
  20718. va_start(ap,zFormat);
  20719. sqlite3VXPrintf(&acc, 0, zFormat, ap);
  20720. va_end(ap);
  20721. sqlite3StrAccumFinish(&acc);
  20722. fprintf(stdout,"%s", zBuf);
  20723. fflush(stdout);
  20724. }
  20725. #endif
  20726. #ifdef SQLITE_DEBUG
  20727. /*************************************************************************
  20728. ** Routines for implementing the "TreeView" display of hierarchical
  20729. ** data structures for debugging.
  20730. **
  20731. ** The main entry points (coded elsewhere) are:
  20732. ** sqlite3TreeViewExpr(0, pExpr, 0);
  20733. ** sqlite3TreeViewExprList(0, pList, 0, 0);
  20734. ** sqlite3TreeViewSelect(0, pSelect, 0);
  20735. ** Insert calls to those routines while debugging in order to display
  20736. ** a diagram of Expr, ExprList, and Select objects.
  20737. **
  20738. */
  20739. /* Add a new subitem to the tree. The moreToFollow flag indicates that this
  20740. ** is not the last item in the tree. */
  20741. SQLITE_PRIVATE TreeView *sqlite3TreeViewPush(TreeView *p, u8 moreToFollow){
  20742. if( p==0 ){
  20743. p = sqlite3_malloc( sizeof(*p) );
  20744. if( p==0 ) return 0;
  20745. memset(p, 0, sizeof(*p));
  20746. }else{
  20747. p->iLevel++;
  20748. }
  20749. assert( moreToFollow==0 || moreToFollow==1 );
  20750. if( p->iLevel<sizeof(p->bLine) ) p->bLine[p->iLevel] = moreToFollow;
  20751. return p;
  20752. }
  20753. /* Finished with one layer of the tree */
  20754. SQLITE_PRIVATE void sqlite3TreeViewPop(TreeView *p){
  20755. if( p==0 ) return;
  20756. p->iLevel--;
  20757. if( p->iLevel<0 ) sqlite3_free(p);
  20758. }
  20759. /* Generate a single line of output for the tree, with a prefix that contains
  20760. ** all the appropriate tree lines */
  20761. SQLITE_PRIVATE void sqlite3TreeViewLine(TreeView *p, const char *zFormat, ...){
  20762. va_list ap;
  20763. int i;
  20764. StrAccum acc;
  20765. char zBuf[500];
  20766. sqlite3StrAccumInit(&acc, zBuf, sizeof(zBuf), 0);
  20767. acc.useMalloc = 0;
  20768. if( p ){
  20769. for(i=0; i<p->iLevel && i<sizeof(p->bLine)-1; i++){
  20770. sqlite3StrAccumAppend(&acc, p->bLine[i] ? "| " : " ", 4);
  20771. }
  20772. sqlite3StrAccumAppend(&acc, p->bLine[i] ? "|-- " : "'-- ", 4);
  20773. }
  20774. va_start(ap, zFormat);
  20775. sqlite3VXPrintf(&acc, 0, zFormat, ap);
  20776. va_end(ap);
  20777. if( zBuf[acc.nChar-1]!='\n' ) sqlite3StrAccumAppend(&acc, "\n", 1);
  20778. sqlite3StrAccumFinish(&acc);
  20779. fprintf(stdout,"%s", zBuf);
  20780. fflush(stdout);
  20781. }
  20782. /* Shorthand for starting a new tree item that consists of a single label */
  20783. SQLITE_PRIVATE void sqlite3TreeViewItem(TreeView *p, const char *zLabel, u8 moreToFollow){
  20784. p = sqlite3TreeViewPush(p, moreToFollow);
  20785. sqlite3TreeViewLine(p, "%s", zLabel);
  20786. }
  20787. #endif /* SQLITE_DEBUG */
  20788. /*
  20789. ** variable-argument wrapper around sqlite3VXPrintf().
  20790. */
  20791. SQLITE_PRIVATE void sqlite3XPrintf(StrAccum *p, u32 bFlags, const char *zFormat, ...){
  20792. va_list ap;
  20793. va_start(ap,zFormat);
  20794. sqlite3VXPrintf(p, bFlags, zFormat, ap);
  20795. va_end(ap);
  20796. }
  20797. /************** End of printf.c **********************************************/
  20798. /************** Begin file random.c ******************************************/
  20799. /*
  20800. ** 2001 September 15
  20801. **
  20802. ** The author disclaims copyright to this source code. In place of
  20803. ** a legal notice, here is a blessing:
  20804. **
  20805. ** May you do good and not evil.
  20806. ** May you find forgiveness for yourself and forgive others.
  20807. ** May you share freely, never taking more than you give.
  20808. **
  20809. *************************************************************************
  20810. ** This file contains code to implement a pseudo-random number
  20811. ** generator (PRNG) for SQLite.
  20812. **
  20813. ** Random numbers are used by some of the database backends in order
  20814. ** to generate random integer keys for tables or random filenames.
  20815. */
  20816. /* All threads share a single random number generator.
  20817. ** This structure is the current state of the generator.
  20818. */
  20819. static SQLITE_WSD struct sqlite3PrngType {
  20820. unsigned char isInit; /* True if initialized */
  20821. unsigned char i, j; /* State variables */
  20822. unsigned char s[256]; /* State variables */
  20823. } sqlite3Prng;
  20824. /*
  20825. ** Return N random bytes.
  20826. */
  20827. SQLITE_API void sqlite3_randomness(int N, void *pBuf){
  20828. unsigned char t;
  20829. unsigned char *zBuf = pBuf;
  20830. /* The "wsdPrng" macro will resolve to the pseudo-random number generator
  20831. ** state vector. If writable static data is unsupported on the target,
  20832. ** we have to locate the state vector at run-time. In the more common
  20833. ** case where writable static data is supported, wsdPrng can refer directly
  20834. ** to the "sqlite3Prng" state vector declared above.
  20835. */
  20836. #ifdef SQLITE_OMIT_WSD
  20837. struct sqlite3PrngType *p = &GLOBAL(struct sqlite3PrngType, sqlite3Prng);
  20838. # define wsdPrng p[0]
  20839. #else
  20840. # define wsdPrng sqlite3Prng
  20841. #endif
  20842. #if SQLITE_THREADSAFE
  20843. sqlite3_mutex *mutex;
  20844. #endif
  20845. #ifndef SQLITE_OMIT_AUTOINIT
  20846. if( sqlite3_initialize() ) return;
  20847. #endif
  20848. #if SQLITE_THREADSAFE
  20849. mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_PRNG);
  20850. #endif
  20851. sqlite3_mutex_enter(mutex);
  20852. if( N<=0 || pBuf==0 ){
  20853. wsdPrng.isInit = 0;
  20854. sqlite3_mutex_leave(mutex);
  20855. return;
  20856. }
  20857. /* Initialize the state of the random number generator once,
  20858. ** the first time this routine is called. The seed value does
  20859. ** not need to contain a lot of randomness since we are not
  20860. ** trying to do secure encryption or anything like that...
  20861. **
  20862. ** Nothing in this file or anywhere else in SQLite does any kind of
  20863. ** encryption. The RC4 algorithm is being used as a PRNG (pseudo-random
  20864. ** number generator) not as an encryption device.
  20865. */
  20866. if( !wsdPrng.isInit ){
  20867. int i;
  20868. char k[256];
  20869. wsdPrng.j = 0;
  20870. wsdPrng.i = 0;
  20871. sqlite3OsRandomness(sqlite3_vfs_find(0), 256, k);
  20872. for(i=0; i<256; i++){
  20873. wsdPrng.s[i] = (u8)i;
  20874. }
  20875. for(i=0; i<256; i++){
  20876. wsdPrng.j += wsdPrng.s[i] + k[i];
  20877. t = wsdPrng.s[wsdPrng.j];
  20878. wsdPrng.s[wsdPrng.j] = wsdPrng.s[i];
  20879. wsdPrng.s[i] = t;
  20880. }
  20881. wsdPrng.isInit = 1;
  20882. }
  20883. assert( N>0 );
  20884. do{
  20885. wsdPrng.i++;
  20886. t = wsdPrng.s[wsdPrng.i];
  20887. wsdPrng.j += t;
  20888. wsdPrng.s[wsdPrng.i] = wsdPrng.s[wsdPrng.j];
  20889. wsdPrng.s[wsdPrng.j] = t;
  20890. t += wsdPrng.s[wsdPrng.i];
  20891. *(zBuf++) = wsdPrng.s[t];
  20892. }while( --N );
  20893. sqlite3_mutex_leave(mutex);
  20894. }
  20895. #ifndef SQLITE_OMIT_BUILTIN_TEST
  20896. /*
  20897. ** For testing purposes, we sometimes want to preserve the state of
  20898. ** PRNG and restore the PRNG to its saved state at a later time, or
  20899. ** to reset the PRNG to its initial state. These routines accomplish
  20900. ** those tasks.
  20901. **
  20902. ** The sqlite3_test_control() interface calls these routines to
  20903. ** control the PRNG.
  20904. */
  20905. static SQLITE_WSD struct sqlite3PrngType sqlite3SavedPrng;
  20906. SQLITE_PRIVATE void sqlite3PrngSaveState(void){
  20907. memcpy(
  20908. &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
  20909. &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
  20910. sizeof(sqlite3Prng)
  20911. );
  20912. }
  20913. SQLITE_PRIVATE void sqlite3PrngRestoreState(void){
  20914. memcpy(
  20915. &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
  20916. &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
  20917. sizeof(sqlite3Prng)
  20918. );
  20919. }
  20920. #endif /* SQLITE_OMIT_BUILTIN_TEST */
  20921. /************** End of random.c **********************************************/
  20922. /************** Begin file threads.c *****************************************/
  20923. /*
  20924. ** 2012 July 21
  20925. **
  20926. ** The author disclaims copyright to this source code. In place of
  20927. ** a legal notice, here is a blessing:
  20928. **
  20929. ** May you do good and not evil.
  20930. ** May you find forgiveness for yourself and forgive others.
  20931. ** May you share freely, never taking more than you give.
  20932. **
  20933. ******************************************************************************
  20934. **
  20935. ** This file presents a simple cross-platform threading interface for
  20936. ** use internally by SQLite.
  20937. **
  20938. ** A "thread" can be created using sqlite3ThreadCreate(). This thread
  20939. ** runs independently of its creator until it is joined using
  20940. ** sqlite3ThreadJoin(), at which point it terminates.
  20941. **
  20942. ** Threads do not have to be real. It could be that the work of the
  20943. ** "thread" is done by the main thread at either the sqlite3ThreadCreate()
  20944. ** or sqlite3ThreadJoin() call. This is, in fact, what happens in
  20945. ** single threaded systems. Nothing in SQLite requires multiple threads.
  20946. ** This interface exists so that applications that want to take advantage
  20947. ** of multiple cores can do so, while also allowing applications to stay
  20948. ** single-threaded if desired.
  20949. */
  20950. #if SQLITE_MAX_WORKER_THREADS>0
  20951. /********************************* Unix Pthreads ****************************/
  20952. #if SQLITE_OS_UNIX && defined(SQLITE_MUTEX_PTHREADS) && SQLITE_THREADSAFE>0
  20953. #define SQLITE_THREADS_IMPLEMENTED 1 /* Prevent the single-thread code below */
  20954. /* #include <pthread.h> */
  20955. /* A running thread */
  20956. struct SQLiteThread {
  20957. pthread_t tid; /* Thread ID */
  20958. int done; /* Set to true when thread finishes */
  20959. void *pOut; /* Result returned by the thread */
  20960. void *(*xTask)(void*); /* The thread routine */
  20961. void *pIn; /* Argument to the thread */
  20962. };
  20963. /* Create a new thread */
  20964. SQLITE_PRIVATE int sqlite3ThreadCreate(
  20965. SQLiteThread **ppThread, /* OUT: Write the thread object here */
  20966. void *(*xTask)(void*), /* Routine to run in a separate thread */
  20967. void *pIn /* Argument passed into xTask() */
  20968. ){
  20969. SQLiteThread *p;
  20970. int rc;
  20971. assert( ppThread!=0 );
  20972. assert( xTask!=0 );
  20973. /* This routine is never used in single-threaded mode */
  20974. assert( sqlite3GlobalConfig.bCoreMutex!=0 );
  20975. *ppThread = 0;
  20976. p = sqlite3Malloc(sizeof(*p));
  20977. if( p==0 ) return SQLITE_NOMEM;
  20978. memset(p, 0, sizeof(*p));
  20979. p->xTask = xTask;
  20980. p->pIn = pIn;
  20981. if( sqlite3FaultSim(200) ){
  20982. rc = 1;
  20983. }else{
  20984. rc = pthread_create(&p->tid, 0, xTask, pIn);
  20985. }
  20986. if( rc ){
  20987. p->done = 1;
  20988. p->pOut = xTask(pIn);
  20989. }
  20990. *ppThread = p;
  20991. return SQLITE_OK;
  20992. }
  20993. /* Get the results of the thread */
  20994. SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread *p, void **ppOut){
  20995. int rc;
  20996. assert( ppOut!=0 );
  20997. if( NEVER(p==0) ) return SQLITE_NOMEM;
  20998. if( p->done ){
  20999. *ppOut = p->pOut;
  21000. rc = SQLITE_OK;
  21001. }else{
  21002. rc = pthread_join(p->tid, ppOut) ? SQLITE_ERROR : SQLITE_OK;
  21003. }
  21004. sqlite3_free(p);
  21005. return rc;
  21006. }
  21007. #endif /* SQLITE_OS_UNIX && defined(SQLITE_MUTEX_PTHREADS) */
  21008. /******************************** End Unix Pthreads *************************/
  21009. /********************************* Win32 Threads ****************************/
  21010. #if SQLITE_OS_WIN && !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_THREADSAFE>0
  21011. #define SQLITE_THREADS_IMPLEMENTED 1 /* Prevent the single-thread code below */
  21012. #include <process.h>
  21013. /* A running thread */
  21014. struct SQLiteThread {
  21015. void *tid; /* The thread handle */
  21016. unsigned id; /* The thread identifier */
  21017. void *(*xTask)(void*); /* The routine to run as a thread */
  21018. void *pIn; /* Argument to xTask */
  21019. void *pResult; /* Result of xTask */
  21020. };
  21021. /* Thread procedure Win32 compatibility shim */
  21022. static unsigned __stdcall sqlite3ThreadProc(
  21023. void *pArg /* IN: Pointer to the SQLiteThread structure */
  21024. ){
  21025. SQLiteThread *p = (SQLiteThread *)pArg;
  21026. assert( p!=0 );
  21027. #if 0
  21028. /*
  21029. ** This assert appears to trigger spuriously on certain
  21030. ** versions of Windows, possibly due to _beginthreadex()
  21031. ** and/or CreateThread() not fully setting their thread
  21032. ** ID parameter before starting the thread.
  21033. */
  21034. assert( p->id==GetCurrentThreadId() );
  21035. #endif
  21036. assert( p->xTask!=0 );
  21037. p->pResult = p->xTask(p->pIn);
  21038. _endthreadex(0);
  21039. return 0; /* NOT REACHED */
  21040. }
  21041. /* Create a new thread */
  21042. SQLITE_PRIVATE int sqlite3ThreadCreate(
  21043. SQLiteThread **ppThread, /* OUT: Write the thread object here */
  21044. void *(*xTask)(void*), /* Routine to run in a separate thread */
  21045. void *pIn /* Argument passed into xTask() */
  21046. ){
  21047. SQLiteThread *p;
  21048. assert( ppThread!=0 );
  21049. assert( xTask!=0 );
  21050. *ppThread = 0;
  21051. p = sqlite3Malloc(sizeof(*p));
  21052. if( p==0 ) return SQLITE_NOMEM;
  21053. if( sqlite3GlobalConfig.bCoreMutex==0 ){
  21054. memset(p, 0, sizeof(*p));
  21055. }else{
  21056. p->xTask = xTask;
  21057. p->pIn = pIn;
  21058. p->tid = (void*)_beginthreadex(0, 0, sqlite3ThreadProc, p, 0, &p->id);
  21059. if( p->tid==0 ){
  21060. memset(p, 0, sizeof(*p));
  21061. }
  21062. }
  21063. if( p->xTask==0 ){
  21064. p->id = GetCurrentThreadId();
  21065. p->pResult = xTask(pIn);
  21066. }
  21067. *ppThread = p;
  21068. return SQLITE_OK;
  21069. }
  21070. SQLITE_PRIVATE DWORD sqlite3Win32Wait(HANDLE hObject); /* os_win.c */
  21071. /* Get the results of the thread */
  21072. SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread *p, void **ppOut){
  21073. DWORD rc;
  21074. BOOL bRc;
  21075. assert( ppOut!=0 );
  21076. if( NEVER(p==0) ) return SQLITE_NOMEM;
  21077. if( p->xTask==0 ){
  21078. assert( p->id==GetCurrentThreadId() );
  21079. rc = WAIT_OBJECT_0;
  21080. assert( p->tid==0 );
  21081. }else{
  21082. assert( p->id!=0 && p->id!=GetCurrentThreadId() );
  21083. rc = sqlite3Win32Wait((HANDLE)p->tid);
  21084. assert( rc!=WAIT_IO_COMPLETION );
  21085. bRc = CloseHandle((HANDLE)p->tid);
  21086. assert( bRc );
  21087. }
  21088. if( rc==WAIT_OBJECT_0 ) *ppOut = p->pResult;
  21089. sqlite3_free(p);
  21090. return (rc==WAIT_OBJECT_0) ? SQLITE_OK : SQLITE_ERROR;
  21091. }
  21092. #endif /* SQLITE_OS_WIN && !SQLITE_OS_WINCE && !SQLITE_OS_WINRT */
  21093. /******************************** End Win32 Threads *************************/
  21094. /********************************* Single-Threaded **************************/
  21095. #ifndef SQLITE_THREADS_IMPLEMENTED
  21096. /*
  21097. ** This implementation does not actually create a new thread. It does the
  21098. ** work of the thread in the main thread, when either the thread is created
  21099. ** or when it is joined
  21100. */
  21101. /* A running thread */
  21102. struct SQLiteThread {
  21103. void *(*xTask)(void*); /* The routine to run as a thread */
  21104. void *pIn; /* Argument to xTask */
  21105. void *pResult; /* Result of xTask */
  21106. };
  21107. /* Create a new thread */
  21108. SQLITE_PRIVATE int sqlite3ThreadCreate(
  21109. SQLiteThread **ppThread, /* OUT: Write the thread object here */
  21110. void *(*xTask)(void*), /* Routine to run in a separate thread */
  21111. void *pIn /* Argument passed into xTask() */
  21112. ){
  21113. SQLiteThread *p;
  21114. assert( ppThread!=0 );
  21115. assert( xTask!=0 );
  21116. *ppThread = 0;
  21117. p = sqlite3Malloc(sizeof(*p));
  21118. if( p==0 ) return SQLITE_NOMEM;
  21119. if( (SQLITE_PTR_TO_INT(p)/17)&1 ){
  21120. p->xTask = xTask;
  21121. p->pIn = pIn;
  21122. }else{
  21123. p->xTask = 0;
  21124. p->pResult = xTask(pIn);
  21125. }
  21126. *ppThread = p;
  21127. return SQLITE_OK;
  21128. }
  21129. /* Get the results of the thread */
  21130. SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread *p, void **ppOut){
  21131. assert( ppOut!=0 );
  21132. if( NEVER(p==0) ) return SQLITE_NOMEM;
  21133. if( p->xTask ){
  21134. *ppOut = p->xTask(p->pIn);
  21135. }else{
  21136. *ppOut = p->pResult;
  21137. }
  21138. sqlite3_free(p);
  21139. #if defined(SQLITE_TEST)
  21140. {
  21141. void *pTstAlloc = sqlite3Malloc(10);
  21142. if (!pTstAlloc) return SQLITE_NOMEM;
  21143. sqlite3_free(pTstAlloc);
  21144. }
  21145. #endif
  21146. return SQLITE_OK;
  21147. }
  21148. #endif /* !defined(SQLITE_THREADS_IMPLEMENTED) */
  21149. /****************************** End Single-Threaded *************************/
  21150. #endif /* SQLITE_MAX_WORKER_THREADS>0 */
  21151. /************** End of threads.c *********************************************/
  21152. /************** Begin file utf.c *********************************************/
  21153. /*
  21154. ** 2004 April 13
  21155. **
  21156. ** The author disclaims copyright to this source code. In place of
  21157. ** a legal notice, here is a blessing:
  21158. **
  21159. ** May you do good and not evil.
  21160. ** May you find forgiveness for yourself and forgive others.
  21161. ** May you share freely, never taking more than you give.
  21162. **
  21163. *************************************************************************
  21164. ** This file contains routines used to translate between UTF-8,
  21165. ** UTF-16, UTF-16BE, and UTF-16LE.
  21166. **
  21167. ** Notes on UTF-8:
  21168. **
  21169. ** Byte-0 Byte-1 Byte-2 Byte-3 Value
  21170. ** 0xxxxxxx 00000000 00000000 0xxxxxxx
  21171. ** 110yyyyy 10xxxxxx 00000000 00000yyy yyxxxxxx
  21172. ** 1110zzzz 10yyyyyy 10xxxxxx 00000000 zzzzyyyy yyxxxxxx
  21173. ** 11110uuu 10uuzzzz 10yyyyyy 10xxxxxx 000uuuuu zzzzyyyy yyxxxxxx
  21174. **
  21175. **
  21176. ** Notes on UTF-16: (with wwww+1==uuuuu)
  21177. **
  21178. ** Word-0 Word-1 Value
  21179. ** 110110ww wwzzzzyy 110111yy yyxxxxxx 000uuuuu zzzzyyyy yyxxxxxx
  21180. ** zzzzyyyy yyxxxxxx 00000000 zzzzyyyy yyxxxxxx
  21181. **
  21182. **
  21183. ** BOM or Byte Order Mark:
  21184. ** 0xff 0xfe little-endian utf-16 follows
  21185. ** 0xfe 0xff big-endian utf-16 follows
  21186. **
  21187. */
  21188. /* #include <assert.h> */
  21189. #ifndef SQLITE_AMALGAMATION
  21190. /*
  21191. ** The following constant value is used by the SQLITE_BIGENDIAN and
  21192. ** SQLITE_LITTLEENDIAN macros.
  21193. */
  21194. SQLITE_PRIVATE const int sqlite3one = 1;
  21195. #endif /* SQLITE_AMALGAMATION */
  21196. /*
  21197. ** This lookup table is used to help decode the first byte of
  21198. ** a multi-byte UTF8 character.
  21199. */
  21200. static const unsigned char sqlite3Utf8Trans1[] = {
  21201. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  21202. 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
  21203. 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
  21204. 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
  21205. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  21206. 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
  21207. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  21208. 0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
  21209. };
  21210. #define WRITE_UTF8(zOut, c) { \
  21211. if( c<0x00080 ){ \
  21212. *zOut++ = (u8)(c&0xFF); \
  21213. } \
  21214. else if( c<0x00800 ){ \
  21215. *zOut++ = 0xC0 + (u8)((c>>6)&0x1F); \
  21216. *zOut++ = 0x80 + (u8)(c & 0x3F); \
  21217. } \
  21218. else if( c<0x10000 ){ \
  21219. *zOut++ = 0xE0 + (u8)((c>>12)&0x0F); \
  21220. *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \
  21221. *zOut++ = 0x80 + (u8)(c & 0x3F); \
  21222. }else{ \
  21223. *zOut++ = 0xF0 + (u8)((c>>18) & 0x07); \
  21224. *zOut++ = 0x80 + (u8)((c>>12) & 0x3F); \
  21225. *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \
  21226. *zOut++ = 0x80 + (u8)(c & 0x3F); \
  21227. } \
  21228. }
  21229. #define WRITE_UTF16LE(zOut, c) { \
  21230. if( c<=0xFFFF ){ \
  21231. *zOut++ = (u8)(c&0x00FF); \
  21232. *zOut++ = (u8)((c>>8)&0x00FF); \
  21233. }else{ \
  21234. *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0)); \
  21235. *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03)); \
  21236. *zOut++ = (u8)(c&0x00FF); \
  21237. *zOut++ = (u8)(0x00DC + ((c>>8)&0x03)); \
  21238. } \
  21239. }
  21240. #define WRITE_UTF16BE(zOut, c) { \
  21241. if( c<=0xFFFF ){ \
  21242. *zOut++ = (u8)((c>>8)&0x00FF); \
  21243. *zOut++ = (u8)(c&0x00FF); \
  21244. }else{ \
  21245. *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03)); \
  21246. *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0)); \
  21247. *zOut++ = (u8)(0x00DC + ((c>>8)&0x03)); \
  21248. *zOut++ = (u8)(c&0x00FF); \
  21249. } \
  21250. }
  21251. #define READ_UTF16LE(zIn, TERM, c){ \
  21252. c = (*zIn++); \
  21253. c += ((*zIn++)<<8); \
  21254. if( c>=0xD800 && c<0xE000 && TERM ){ \
  21255. int c2 = (*zIn++); \
  21256. c2 += ((*zIn++)<<8); \
  21257. c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10); \
  21258. } \
  21259. }
  21260. #define READ_UTF16BE(zIn, TERM, c){ \
  21261. c = ((*zIn++)<<8); \
  21262. c += (*zIn++); \
  21263. if( c>=0xD800 && c<0xE000 && TERM ){ \
  21264. int c2 = ((*zIn++)<<8); \
  21265. c2 += (*zIn++); \
  21266. c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10); \
  21267. } \
  21268. }
  21269. /*
  21270. ** Translate a single UTF-8 character. Return the unicode value.
  21271. **
  21272. ** During translation, assume that the byte that zTerm points
  21273. ** is a 0x00.
  21274. **
  21275. ** Write a pointer to the next unread byte back into *pzNext.
  21276. **
  21277. ** Notes On Invalid UTF-8:
  21278. **
  21279. ** * This routine never allows a 7-bit character (0x00 through 0x7f) to
  21280. ** be encoded as a multi-byte character. Any multi-byte character that
  21281. ** attempts to encode a value between 0x00 and 0x7f is rendered as 0xfffd.
  21282. **
  21283. ** * This routine never allows a UTF16 surrogate value to be encoded.
  21284. ** If a multi-byte character attempts to encode a value between
  21285. ** 0xd800 and 0xe000 then it is rendered as 0xfffd.
  21286. **
  21287. ** * Bytes in the range of 0x80 through 0xbf which occur as the first
  21288. ** byte of a character are interpreted as single-byte characters
  21289. ** and rendered as themselves even though they are technically
  21290. ** invalid characters.
  21291. **
  21292. ** * This routine accepts over-length UTF8 encodings
  21293. ** for unicode values 0x80 and greater. It does not change over-length
  21294. ** encodings to 0xfffd as some systems recommend.
  21295. */
  21296. #define READ_UTF8(zIn, zTerm, c) \
  21297. c = *(zIn++); \
  21298. if( c>=0xc0 ){ \
  21299. c = sqlite3Utf8Trans1[c-0xc0]; \
  21300. while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){ \
  21301. c = (c<<6) + (0x3f & *(zIn++)); \
  21302. } \
  21303. if( c<0x80 \
  21304. || (c&0xFFFFF800)==0xD800 \
  21305. || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; } \
  21306. }
  21307. SQLITE_PRIVATE u32 sqlite3Utf8Read(
  21308. const unsigned char **pz /* Pointer to string from which to read char */
  21309. ){
  21310. unsigned int c;
  21311. /* Same as READ_UTF8() above but without the zTerm parameter.
  21312. ** For this routine, we assume the UTF8 string is always zero-terminated.
  21313. */
  21314. c = *((*pz)++);
  21315. if( c>=0xc0 ){
  21316. c = sqlite3Utf8Trans1[c-0xc0];
  21317. while( (*(*pz) & 0xc0)==0x80 ){
  21318. c = (c<<6) + (0x3f & *((*pz)++));
  21319. }
  21320. if( c<0x80
  21321. || (c&0xFFFFF800)==0xD800
  21322. || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; }
  21323. }
  21324. return c;
  21325. }
  21326. /*
  21327. ** If the TRANSLATE_TRACE macro is defined, the value of each Mem is
  21328. ** printed on stderr on the way into and out of sqlite3VdbeMemTranslate().
  21329. */
  21330. /* #define TRANSLATE_TRACE 1 */
  21331. #ifndef SQLITE_OMIT_UTF16
  21332. /*
  21333. ** This routine transforms the internal text encoding used by pMem to
  21334. ** desiredEnc. It is an error if the string is already of the desired
  21335. ** encoding, or if *pMem does not contain a string value.
  21336. */
  21337. SQLITE_PRIVATE SQLITE_NOINLINE int sqlite3VdbeMemTranslate(Mem *pMem, u8 desiredEnc){
  21338. int len; /* Maximum length of output string in bytes */
  21339. unsigned char *zOut; /* Output buffer */
  21340. unsigned char *zIn; /* Input iterator */
  21341. unsigned char *zTerm; /* End of input */
  21342. unsigned char *z; /* Output iterator */
  21343. unsigned int c;
  21344. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  21345. assert( pMem->flags&MEM_Str );
  21346. assert( pMem->enc!=desiredEnc );
  21347. assert( pMem->enc!=0 );
  21348. assert( pMem->n>=0 );
  21349. #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
  21350. {
  21351. char zBuf[100];
  21352. sqlite3VdbeMemPrettyPrint(pMem, zBuf);
  21353. fprintf(stderr, "INPUT: %s\n", zBuf);
  21354. }
  21355. #endif
  21356. /* If the translation is between UTF-16 little and big endian, then
  21357. ** all that is required is to swap the byte order. This case is handled
  21358. ** differently from the others.
  21359. */
  21360. if( pMem->enc!=SQLITE_UTF8 && desiredEnc!=SQLITE_UTF8 ){
  21361. u8 temp;
  21362. int rc;
  21363. rc = sqlite3VdbeMemMakeWriteable(pMem);
  21364. if( rc!=SQLITE_OK ){
  21365. assert( rc==SQLITE_NOMEM );
  21366. return SQLITE_NOMEM;
  21367. }
  21368. zIn = (u8*)pMem->z;
  21369. zTerm = &zIn[pMem->n&~1];
  21370. while( zIn<zTerm ){
  21371. temp = *zIn;
  21372. *zIn = *(zIn+1);
  21373. zIn++;
  21374. *zIn++ = temp;
  21375. }
  21376. pMem->enc = desiredEnc;
  21377. goto translate_out;
  21378. }
  21379. /* Set len to the maximum number of bytes required in the output buffer. */
  21380. if( desiredEnc==SQLITE_UTF8 ){
  21381. /* When converting from UTF-16, the maximum growth results from
  21382. ** translating a 2-byte character to a 4-byte UTF-8 character.
  21383. ** A single byte is required for the output string
  21384. ** nul-terminator.
  21385. */
  21386. pMem->n &= ~1;
  21387. len = pMem->n * 2 + 1;
  21388. }else{
  21389. /* When converting from UTF-8 to UTF-16 the maximum growth is caused
  21390. ** when a 1-byte UTF-8 character is translated into a 2-byte UTF-16
  21391. ** character. Two bytes are required in the output buffer for the
  21392. ** nul-terminator.
  21393. */
  21394. len = pMem->n * 2 + 2;
  21395. }
  21396. /* Set zIn to point at the start of the input buffer and zTerm to point 1
  21397. ** byte past the end.
  21398. **
  21399. ** Variable zOut is set to point at the output buffer, space obtained
  21400. ** from sqlite3_malloc().
  21401. */
  21402. zIn = (u8*)pMem->z;
  21403. zTerm = &zIn[pMem->n];
  21404. zOut = sqlite3DbMallocRaw(pMem->db, len);
  21405. if( !zOut ){
  21406. return SQLITE_NOMEM;
  21407. }
  21408. z = zOut;
  21409. if( pMem->enc==SQLITE_UTF8 ){
  21410. if( desiredEnc==SQLITE_UTF16LE ){
  21411. /* UTF-8 -> UTF-16 Little-endian */
  21412. while( zIn<zTerm ){
  21413. READ_UTF8(zIn, zTerm, c);
  21414. WRITE_UTF16LE(z, c);
  21415. }
  21416. }else{
  21417. assert( desiredEnc==SQLITE_UTF16BE );
  21418. /* UTF-8 -> UTF-16 Big-endian */
  21419. while( zIn<zTerm ){
  21420. READ_UTF8(zIn, zTerm, c);
  21421. WRITE_UTF16BE(z, c);
  21422. }
  21423. }
  21424. pMem->n = (int)(z - zOut);
  21425. *z++ = 0;
  21426. }else{
  21427. assert( desiredEnc==SQLITE_UTF8 );
  21428. if( pMem->enc==SQLITE_UTF16LE ){
  21429. /* UTF-16 Little-endian -> UTF-8 */
  21430. while( zIn<zTerm ){
  21431. READ_UTF16LE(zIn, zIn<zTerm, c);
  21432. WRITE_UTF8(z, c);
  21433. }
  21434. }else{
  21435. /* UTF-16 Big-endian -> UTF-8 */
  21436. while( zIn<zTerm ){
  21437. READ_UTF16BE(zIn, zIn<zTerm, c);
  21438. WRITE_UTF8(z, c);
  21439. }
  21440. }
  21441. pMem->n = (int)(z - zOut);
  21442. }
  21443. *z = 0;
  21444. assert( (pMem->n+(desiredEnc==SQLITE_UTF8?1:2))<=len );
  21445. c = pMem->flags;
  21446. sqlite3VdbeMemRelease(pMem);
  21447. pMem->flags = MEM_Str|MEM_Term|(c&MEM_AffMask);
  21448. pMem->enc = desiredEnc;
  21449. pMem->z = (char*)zOut;
  21450. pMem->zMalloc = pMem->z;
  21451. pMem->szMalloc = sqlite3DbMallocSize(pMem->db, pMem->z);
  21452. translate_out:
  21453. #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
  21454. {
  21455. char zBuf[100];
  21456. sqlite3VdbeMemPrettyPrint(pMem, zBuf);
  21457. fprintf(stderr, "OUTPUT: %s\n", zBuf);
  21458. }
  21459. #endif
  21460. return SQLITE_OK;
  21461. }
  21462. /*
  21463. ** This routine checks for a byte-order mark at the beginning of the
  21464. ** UTF-16 string stored in *pMem. If one is present, it is removed and
  21465. ** the encoding of the Mem adjusted. This routine does not do any
  21466. ** byte-swapping, it just sets Mem.enc appropriately.
  21467. **
  21468. ** The allocation (static, dynamic etc.) and encoding of the Mem may be
  21469. ** changed by this function.
  21470. */
  21471. SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem){
  21472. int rc = SQLITE_OK;
  21473. u8 bom = 0;
  21474. assert( pMem->n>=0 );
  21475. if( pMem->n>1 ){
  21476. u8 b1 = *(u8 *)pMem->z;
  21477. u8 b2 = *(((u8 *)pMem->z) + 1);
  21478. if( b1==0xFE && b2==0xFF ){
  21479. bom = SQLITE_UTF16BE;
  21480. }
  21481. if( b1==0xFF && b2==0xFE ){
  21482. bom = SQLITE_UTF16LE;
  21483. }
  21484. }
  21485. if( bom ){
  21486. rc = sqlite3VdbeMemMakeWriteable(pMem);
  21487. if( rc==SQLITE_OK ){
  21488. pMem->n -= 2;
  21489. memmove(pMem->z, &pMem->z[2], pMem->n);
  21490. pMem->z[pMem->n] = '\0';
  21491. pMem->z[pMem->n+1] = '\0';
  21492. pMem->flags |= MEM_Term;
  21493. pMem->enc = bom;
  21494. }
  21495. }
  21496. return rc;
  21497. }
  21498. #endif /* SQLITE_OMIT_UTF16 */
  21499. /*
  21500. ** pZ is a UTF-8 encoded unicode string. If nByte is less than zero,
  21501. ** return the number of unicode characters in pZ up to (but not including)
  21502. ** the first 0x00 byte. If nByte is not less than zero, return the
  21503. ** number of unicode characters in the first nByte of pZ (or up to
  21504. ** the first 0x00, whichever comes first).
  21505. */
  21506. SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *zIn, int nByte){
  21507. int r = 0;
  21508. const u8 *z = (const u8*)zIn;
  21509. const u8 *zTerm;
  21510. if( nByte>=0 ){
  21511. zTerm = &z[nByte];
  21512. }else{
  21513. zTerm = (const u8*)(-1);
  21514. }
  21515. assert( z<=zTerm );
  21516. while( *z!=0 && z<zTerm ){
  21517. SQLITE_SKIP_UTF8(z);
  21518. r++;
  21519. }
  21520. return r;
  21521. }
  21522. /* This test function is not currently used by the automated test-suite.
  21523. ** Hence it is only available in debug builds.
  21524. */
  21525. #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
  21526. /*
  21527. ** Translate UTF-8 to UTF-8.
  21528. **
  21529. ** This has the effect of making sure that the string is well-formed
  21530. ** UTF-8. Miscoded characters are removed.
  21531. **
  21532. ** The translation is done in-place and aborted if the output
  21533. ** overruns the input.
  21534. */
  21535. SQLITE_PRIVATE int sqlite3Utf8To8(unsigned char *zIn){
  21536. unsigned char *zOut = zIn;
  21537. unsigned char *zStart = zIn;
  21538. u32 c;
  21539. while( zIn[0] && zOut<=zIn ){
  21540. c = sqlite3Utf8Read((const u8**)&zIn);
  21541. if( c!=0xfffd ){
  21542. WRITE_UTF8(zOut, c);
  21543. }
  21544. }
  21545. *zOut = 0;
  21546. return (int)(zOut - zStart);
  21547. }
  21548. #endif
  21549. #ifndef SQLITE_OMIT_UTF16
  21550. /*
  21551. ** Convert a UTF-16 string in the native encoding into a UTF-8 string.
  21552. ** Memory to hold the UTF-8 string is obtained from sqlite3_malloc and must
  21553. ** be freed by the calling function.
  21554. **
  21555. ** NULL is returned if there is an allocation error.
  21556. */
  21557. SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *db, const void *z, int nByte, u8 enc){
  21558. Mem m;
  21559. memset(&m, 0, sizeof(m));
  21560. m.db = db;
  21561. sqlite3VdbeMemSetStr(&m, z, nByte, enc, SQLITE_STATIC);
  21562. sqlite3VdbeChangeEncoding(&m, SQLITE_UTF8);
  21563. if( db->mallocFailed ){
  21564. sqlite3VdbeMemRelease(&m);
  21565. m.z = 0;
  21566. }
  21567. assert( (m.flags & MEM_Term)!=0 || db->mallocFailed );
  21568. assert( (m.flags & MEM_Str)!=0 || db->mallocFailed );
  21569. assert( m.z || db->mallocFailed );
  21570. return m.z;
  21571. }
  21572. /*
  21573. ** zIn is a UTF-16 encoded unicode string at least nChar characters long.
  21574. ** Return the number of bytes in the first nChar unicode characters
  21575. ** in pZ. nChar must be non-negative.
  21576. */
  21577. SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *zIn, int nChar){
  21578. int c;
  21579. unsigned char const *z = zIn;
  21580. int n = 0;
  21581. if( SQLITE_UTF16NATIVE==SQLITE_UTF16BE ){
  21582. while( n<nChar ){
  21583. READ_UTF16BE(z, 1, c);
  21584. n++;
  21585. }
  21586. }else{
  21587. while( n<nChar ){
  21588. READ_UTF16LE(z, 1, c);
  21589. n++;
  21590. }
  21591. }
  21592. return (int)(z-(unsigned char const *)zIn);
  21593. }
  21594. #if defined(SQLITE_TEST)
  21595. /*
  21596. ** This routine is called from the TCL test function "translate_selftest".
  21597. ** It checks that the primitives for serializing and deserializing
  21598. ** characters in each encoding are inverses of each other.
  21599. */
  21600. SQLITE_PRIVATE void sqlite3UtfSelfTest(void){
  21601. unsigned int i, t;
  21602. unsigned char zBuf[20];
  21603. unsigned char *z;
  21604. int n;
  21605. unsigned int c;
  21606. for(i=0; i<0x00110000; i++){
  21607. z = zBuf;
  21608. WRITE_UTF8(z, i);
  21609. n = (int)(z-zBuf);
  21610. assert( n>0 && n<=4 );
  21611. z[0] = 0;
  21612. z = zBuf;
  21613. c = sqlite3Utf8Read((const u8**)&z);
  21614. t = i;
  21615. if( i>=0xD800 && i<=0xDFFF ) t = 0xFFFD;
  21616. if( (i&0xFFFFFFFE)==0xFFFE ) t = 0xFFFD;
  21617. assert( c==t );
  21618. assert( (z-zBuf)==n );
  21619. }
  21620. for(i=0; i<0x00110000; i++){
  21621. if( i>=0xD800 && i<0xE000 ) continue;
  21622. z = zBuf;
  21623. WRITE_UTF16LE(z, i);
  21624. n = (int)(z-zBuf);
  21625. assert( n>0 && n<=4 );
  21626. z[0] = 0;
  21627. z = zBuf;
  21628. READ_UTF16LE(z, 1, c);
  21629. assert( c==i );
  21630. assert( (z-zBuf)==n );
  21631. }
  21632. for(i=0; i<0x00110000; i++){
  21633. if( i>=0xD800 && i<0xE000 ) continue;
  21634. z = zBuf;
  21635. WRITE_UTF16BE(z, i);
  21636. n = (int)(z-zBuf);
  21637. assert( n>0 && n<=4 );
  21638. z[0] = 0;
  21639. z = zBuf;
  21640. READ_UTF16BE(z, 1, c);
  21641. assert( c==i );
  21642. assert( (z-zBuf)==n );
  21643. }
  21644. }
  21645. #endif /* SQLITE_TEST */
  21646. #endif /* SQLITE_OMIT_UTF16 */
  21647. /************** End of utf.c *************************************************/
  21648. /************** Begin file util.c ********************************************/
  21649. /*
  21650. ** 2001 September 15
  21651. **
  21652. ** The author disclaims copyright to this source code. In place of
  21653. ** a legal notice, here is a blessing:
  21654. **
  21655. ** May you do good and not evil.
  21656. ** May you find forgiveness for yourself and forgive others.
  21657. ** May you share freely, never taking more than you give.
  21658. **
  21659. *************************************************************************
  21660. ** Utility functions used throughout sqlite.
  21661. **
  21662. ** This file contains functions for allocating memory, comparing
  21663. ** strings, and stuff like that.
  21664. **
  21665. */
  21666. /* #include <stdarg.h> */
  21667. #ifdef SQLITE_HAVE_ISNAN
  21668. # include <math.h>
  21669. #endif
  21670. /*
  21671. ** Routine needed to support the testcase() macro.
  21672. */
  21673. #ifdef SQLITE_COVERAGE_TEST
  21674. SQLITE_PRIVATE void sqlite3Coverage(int x){
  21675. static unsigned dummy = 0;
  21676. dummy += (unsigned)x;
  21677. }
  21678. #endif
  21679. /*
  21680. ** Give a callback to the test harness that can be used to simulate faults
  21681. ** in places where it is difficult or expensive to do so purely by means
  21682. ** of inputs.
  21683. **
  21684. ** The intent of the integer argument is to let the fault simulator know
  21685. ** which of multiple sqlite3FaultSim() calls has been hit.
  21686. **
  21687. ** Return whatever integer value the test callback returns, or return
  21688. ** SQLITE_OK if no test callback is installed.
  21689. */
  21690. #ifndef SQLITE_OMIT_BUILTIN_TEST
  21691. SQLITE_PRIVATE int sqlite3FaultSim(int iTest){
  21692. int (*xCallback)(int) = sqlite3GlobalConfig.xTestCallback;
  21693. return xCallback ? xCallback(iTest) : SQLITE_OK;
  21694. }
  21695. #endif
  21696. #ifndef SQLITE_OMIT_FLOATING_POINT
  21697. /*
  21698. ** Return true if the floating point value is Not a Number (NaN).
  21699. **
  21700. ** Use the math library isnan() function if compiled with SQLITE_HAVE_ISNAN.
  21701. ** Otherwise, we have our own implementation that works on most systems.
  21702. */
  21703. SQLITE_PRIVATE int sqlite3IsNaN(double x){
  21704. int rc; /* The value return */
  21705. #if !defined(SQLITE_HAVE_ISNAN)
  21706. /*
  21707. ** Systems that support the isnan() library function should probably
  21708. ** make use of it by compiling with -DSQLITE_HAVE_ISNAN. But we have
  21709. ** found that many systems do not have a working isnan() function so
  21710. ** this implementation is provided as an alternative.
  21711. **
  21712. ** This NaN test sometimes fails if compiled on GCC with -ffast-math.
  21713. ** On the other hand, the use of -ffast-math comes with the following
  21714. ** warning:
  21715. **
  21716. ** This option [-ffast-math] should never be turned on by any
  21717. ** -O option since it can result in incorrect output for programs
  21718. ** which depend on an exact implementation of IEEE or ISO
  21719. ** rules/specifications for math functions.
  21720. **
  21721. ** Under MSVC, this NaN test may fail if compiled with a floating-
  21722. ** point precision mode other than /fp:precise. From the MSDN
  21723. ** documentation:
  21724. **
  21725. ** The compiler [with /fp:precise] will properly handle comparisons
  21726. ** involving NaN. For example, x != x evaluates to true if x is NaN
  21727. ** ...
  21728. */
  21729. #ifdef __FAST_MATH__
  21730. # error SQLite will not work correctly with the -ffast-math option of GCC.
  21731. #endif
  21732. volatile double y = x;
  21733. volatile double z = y;
  21734. rc = (y!=z);
  21735. #else /* if defined(SQLITE_HAVE_ISNAN) */
  21736. rc = isnan(x);
  21737. #endif /* SQLITE_HAVE_ISNAN */
  21738. testcase( rc );
  21739. return rc;
  21740. }
  21741. #endif /* SQLITE_OMIT_FLOATING_POINT */
  21742. /*
  21743. ** Compute a string length that is limited to what can be stored in
  21744. ** lower 30 bits of a 32-bit signed integer.
  21745. **
  21746. ** The value returned will never be negative. Nor will it ever be greater
  21747. ** than the actual length of the string. For very long strings (greater
  21748. ** than 1GiB) the value returned might be less than the true string length.
  21749. */
  21750. SQLITE_PRIVATE int sqlite3Strlen30(const char *z){
  21751. const char *z2 = z;
  21752. if( z==0 ) return 0;
  21753. while( *z2 ){ z2++; }
  21754. return 0x3fffffff & (int)(z2 - z);
  21755. }
  21756. /*
  21757. ** Set the current error code to err_code and clear any prior error message.
  21758. */
  21759. SQLITE_PRIVATE void sqlite3Error(sqlite3 *db, int err_code){
  21760. assert( db!=0 );
  21761. db->errCode = err_code;
  21762. if( db->pErr ) sqlite3ValueSetNull(db->pErr);
  21763. }
  21764. /*
  21765. ** Set the most recent error code and error string for the sqlite
  21766. ** handle "db". The error code is set to "err_code".
  21767. **
  21768. ** If it is not NULL, string zFormat specifies the format of the
  21769. ** error string in the style of the printf functions: The following
  21770. ** format characters are allowed:
  21771. **
  21772. ** %s Insert a string
  21773. ** %z A string that should be freed after use
  21774. ** %d Insert an integer
  21775. ** %T Insert a token
  21776. ** %S Insert the first element of a SrcList
  21777. **
  21778. ** zFormat and any string tokens that follow it are assumed to be
  21779. ** encoded in UTF-8.
  21780. **
  21781. ** To clear the most recent error for sqlite handle "db", sqlite3Error
  21782. ** should be called with err_code set to SQLITE_OK and zFormat set
  21783. ** to NULL.
  21784. */
  21785. SQLITE_PRIVATE void sqlite3ErrorWithMsg(sqlite3 *db, int err_code, const char *zFormat, ...){
  21786. assert( db!=0 );
  21787. db->errCode = err_code;
  21788. if( zFormat==0 ){
  21789. sqlite3Error(db, err_code);
  21790. }else if( db->pErr || (db->pErr = sqlite3ValueNew(db))!=0 ){
  21791. char *z;
  21792. va_list ap;
  21793. va_start(ap, zFormat);
  21794. z = sqlite3VMPrintf(db, zFormat, ap);
  21795. va_end(ap);
  21796. sqlite3ValueSetStr(db->pErr, -1, z, SQLITE_UTF8, SQLITE_DYNAMIC);
  21797. }
  21798. }
  21799. /*
  21800. ** Add an error message to pParse->zErrMsg and increment pParse->nErr.
  21801. ** The following formatting characters are allowed:
  21802. **
  21803. ** %s Insert a string
  21804. ** %z A string that should be freed after use
  21805. ** %d Insert an integer
  21806. ** %T Insert a token
  21807. ** %S Insert the first element of a SrcList
  21808. **
  21809. ** This function should be used to report any error that occurs while
  21810. ** compiling an SQL statement (i.e. within sqlite3_prepare()). The
  21811. ** last thing the sqlite3_prepare() function does is copy the error
  21812. ** stored by this function into the database handle using sqlite3Error().
  21813. ** Functions sqlite3Error() or sqlite3ErrorWithMsg() should be used
  21814. ** during statement execution (sqlite3_step() etc.).
  21815. */
  21816. SQLITE_PRIVATE void sqlite3ErrorMsg(Parse *pParse, const char *zFormat, ...){
  21817. char *zMsg;
  21818. va_list ap;
  21819. sqlite3 *db = pParse->db;
  21820. va_start(ap, zFormat);
  21821. zMsg = sqlite3VMPrintf(db, zFormat, ap);
  21822. va_end(ap);
  21823. if( db->suppressErr ){
  21824. sqlite3DbFree(db, zMsg);
  21825. }else{
  21826. pParse->nErr++;
  21827. sqlite3DbFree(db, pParse->zErrMsg);
  21828. pParse->zErrMsg = zMsg;
  21829. pParse->rc = SQLITE_ERROR;
  21830. }
  21831. }
  21832. /*
  21833. ** Convert an SQL-style quoted string into a normal string by removing
  21834. ** the quote characters. The conversion is done in-place. If the
  21835. ** input does not begin with a quote character, then this routine
  21836. ** is a no-op.
  21837. **
  21838. ** The input string must be zero-terminated. A new zero-terminator
  21839. ** is added to the dequoted string.
  21840. **
  21841. ** The return value is -1 if no dequoting occurs or the length of the
  21842. ** dequoted string, exclusive of the zero terminator, if dequoting does
  21843. ** occur.
  21844. **
  21845. ** 2002-Feb-14: This routine is extended to remove MS-Access style
  21846. ** brackets from around identifiers. For example: "[a-b-c]" becomes
  21847. ** "a-b-c".
  21848. */
  21849. SQLITE_PRIVATE int sqlite3Dequote(char *z){
  21850. char quote;
  21851. int i, j;
  21852. if( z==0 ) return -1;
  21853. quote = z[0];
  21854. switch( quote ){
  21855. case '\'': break;
  21856. case '"': break;
  21857. case '`': break; /* For MySQL compatibility */
  21858. case '[': quote = ']'; break; /* For MS SqlServer compatibility */
  21859. default: return -1;
  21860. }
  21861. for(i=1, j=0;; i++){
  21862. assert( z[i] );
  21863. if( z[i]==quote ){
  21864. if( z[i+1]==quote ){
  21865. z[j++] = quote;
  21866. i++;
  21867. }else{
  21868. break;
  21869. }
  21870. }else{
  21871. z[j++] = z[i];
  21872. }
  21873. }
  21874. z[j] = 0;
  21875. return j;
  21876. }
  21877. /* Convenient short-hand */
  21878. #define UpperToLower sqlite3UpperToLower
  21879. /*
  21880. ** Some systems have stricmp(). Others have strcasecmp(). Because
  21881. ** there is no consistency, we will define our own.
  21882. **
  21883. ** IMPLEMENTATION-OF: R-30243-02494 The sqlite3_stricmp() and
  21884. ** sqlite3_strnicmp() APIs allow applications and extensions to compare
  21885. ** the contents of two buffers containing UTF-8 strings in a
  21886. ** case-independent fashion, using the same definition of "case
  21887. ** independence" that SQLite uses internally when comparing identifiers.
  21888. */
  21889. SQLITE_API int sqlite3_stricmp(const char *zLeft, const char *zRight){
  21890. register unsigned char *a, *b;
  21891. if( zLeft==0 ){
  21892. return zRight ? -1 : 0;
  21893. }else if( zRight==0 ){
  21894. return 1;
  21895. }
  21896. a = (unsigned char *)zLeft;
  21897. b = (unsigned char *)zRight;
  21898. while( *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
  21899. return UpperToLower[*a] - UpperToLower[*b];
  21900. }
  21901. SQLITE_API int sqlite3_strnicmp(const char *zLeft, const char *zRight, int N){
  21902. register unsigned char *a, *b;
  21903. if( zLeft==0 ){
  21904. return zRight ? -1 : 0;
  21905. }else if( zRight==0 ){
  21906. return 1;
  21907. }
  21908. a = (unsigned char *)zLeft;
  21909. b = (unsigned char *)zRight;
  21910. while( N-- > 0 && *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
  21911. return N<0 ? 0 : UpperToLower[*a] - UpperToLower[*b];
  21912. }
  21913. /*
  21914. ** The string z[] is an text representation of a real number.
  21915. ** Convert this string to a double and write it into *pResult.
  21916. **
  21917. ** The string z[] is length bytes in length (bytes, not characters) and
  21918. ** uses the encoding enc. The string is not necessarily zero-terminated.
  21919. **
  21920. ** Return TRUE if the result is a valid real number (or integer) and FALSE
  21921. ** if the string is empty or contains extraneous text. Valid numbers
  21922. ** are in one of these formats:
  21923. **
  21924. ** [+-]digits[E[+-]digits]
  21925. ** [+-]digits.[digits][E[+-]digits]
  21926. ** [+-].digits[E[+-]digits]
  21927. **
  21928. ** Leading and trailing whitespace is ignored for the purpose of determining
  21929. ** validity.
  21930. **
  21931. ** If some prefix of the input string is a valid number, this routine
  21932. ** returns FALSE but it still converts the prefix and writes the result
  21933. ** into *pResult.
  21934. */
  21935. SQLITE_PRIVATE int sqlite3AtoF(const char *z, double *pResult, int length, u8 enc){
  21936. #ifndef SQLITE_OMIT_FLOATING_POINT
  21937. int incr;
  21938. const char *zEnd = z + length;
  21939. /* sign * significand * (10 ^ (esign * exponent)) */
  21940. int sign = 1; /* sign of significand */
  21941. i64 s = 0; /* significand */
  21942. int d = 0; /* adjust exponent for shifting decimal point */
  21943. int esign = 1; /* sign of exponent */
  21944. int e = 0; /* exponent */
  21945. int eValid = 1; /* True exponent is either not used or is well-formed */
  21946. double result;
  21947. int nDigits = 0;
  21948. int nonNum = 0;
  21949. assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
  21950. *pResult = 0.0; /* Default return value, in case of an error */
  21951. if( enc==SQLITE_UTF8 ){
  21952. incr = 1;
  21953. }else{
  21954. int i;
  21955. incr = 2;
  21956. assert( SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
  21957. for(i=3-enc; i<length && z[i]==0; i+=2){}
  21958. nonNum = i<length;
  21959. zEnd = z+i+enc-3;
  21960. z += (enc&1);
  21961. }
  21962. /* skip leading spaces */
  21963. while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
  21964. if( z>=zEnd ) return 0;
  21965. /* get sign of significand */
  21966. if( *z=='-' ){
  21967. sign = -1;
  21968. z+=incr;
  21969. }else if( *z=='+' ){
  21970. z+=incr;
  21971. }
  21972. /* skip leading zeroes */
  21973. while( z<zEnd && z[0]=='0' ) z+=incr, nDigits++;
  21974. /* copy max significant digits to significand */
  21975. while( z<zEnd && sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
  21976. s = s*10 + (*z - '0');
  21977. z+=incr, nDigits++;
  21978. }
  21979. /* skip non-significant significand digits
  21980. ** (increase exponent by d to shift decimal left) */
  21981. while( z<zEnd && sqlite3Isdigit(*z) ) z+=incr, nDigits++, d++;
  21982. if( z>=zEnd ) goto do_atof_calc;
  21983. /* if decimal point is present */
  21984. if( *z=='.' ){
  21985. z+=incr;
  21986. /* copy digits from after decimal to significand
  21987. ** (decrease exponent by d to shift decimal right) */
  21988. while( z<zEnd && sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
  21989. s = s*10 + (*z - '0');
  21990. z+=incr, nDigits++, d--;
  21991. }
  21992. /* skip non-significant digits */
  21993. while( z<zEnd && sqlite3Isdigit(*z) ) z+=incr, nDigits++;
  21994. }
  21995. if( z>=zEnd ) goto do_atof_calc;
  21996. /* if exponent is present */
  21997. if( *z=='e' || *z=='E' ){
  21998. z+=incr;
  21999. eValid = 0;
  22000. if( z>=zEnd ) goto do_atof_calc;
  22001. /* get sign of exponent */
  22002. if( *z=='-' ){
  22003. esign = -1;
  22004. z+=incr;
  22005. }else if( *z=='+' ){
  22006. z+=incr;
  22007. }
  22008. /* copy digits to exponent */
  22009. while( z<zEnd && sqlite3Isdigit(*z) ){
  22010. e = e<10000 ? (e*10 + (*z - '0')) : 10000;
  22011. z+=incr;
  22012. eValid = 1;
  22013. }
  22014. }
  22015. /* skip trailing spaces */
  22016. if( nDigits && eValid ){
  22017. while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
  22018. }
  22019. do_atof_calc:
  22020. /* adjust exponent by d, and update sign */
  22021. e = (e*esign) + d;
  22022. if( e<0 ) {
  22023. esign = -1;
  22024. e *= -1;
  22025. } else {
  22026. esign = 1;
  22027. }
  22028. /* if 0 significand */
  22029. if( !s ) {
  22030. /* In the IEEE 754 standard, zero is signed.
  22031. ** Add the sign if we've seen at least one digit */
  22032. result = (sign<0 && nDigits) ? -(double)0 : (double)0;
  22033. } else {
  22034. /* attempt to reduce exponent */
  22035. if( esign>0 ){
  22036. while( s<(LARGEST_INT64/10) && e>0 ) e--,s*=10;
  22037. }else{
  22038. while( !(s%10) && e>0 ) e--,s/=10;
  22039. }
  22040. /* adjust the sign of significand */
  22041. s = sign<0 ? -s : s;
  22042. /* if exponent, scale significand as appropriate
  22043. ** and store in result. */
  22044. if( e ){
  22045. LONGDOUBLE_TYPE scale = 1.0;
  22046. /* attempt to handle extremely small/large numbers better */
  22047. if( e>307 && e<342 ){
  22048. while( e%308 ) { scale *= 1.0e+1; e -= 1; }
  22049. if( esign<0 ){
  22050. result = s / scale;
  22051. result /= 1.0e+308;
  22052. }else{
  22053. result = s * scale;
  22054. result *= 1.0e+308;
  22055. }
  22056. }else if( e>=342 ){
  22057. if( esign<0 ){
  22058. result = 0.0*s;
  22059. }else{
  22060. result = 1e308*1e308*s; /* Infinity */
  22061. }
  22062. }else{
  22063. /* 1.0e+22 is the largest power of 10 than can be
  22064. ** represented exactly. */
  22065. while( e%22 ) { scale *= 1.0e+1; e -= 1; }
  22066. while( e>0 ) { scale *= 1.0e+22; e -= 22; }
  22067. if( esign<0 ){
  22068. result = s / scale;
  22069. }else{
  22070. result = s * scale;
  22071. }
  22072. }
  22073. } else {
  22074. result = (double)s;
  22075. }
  22076. }
  22077. /* store the result */
  22078. *pResult = result;
  22079. /* return true if number and no extra non-whitespace chracters after */
  22080. return z>=zEnd && nDigits>0 && eValid && nonNum==0;
  22081. #else
  22082. return !sqlite3Atoi64(z, pResult, length, enc);
  22083. #endif /* SQLITE_OMIT_FLOATING_POINT */
  22084. }
  22085. /*
  22086. ** Compare the 19-character string zNum against the text representation
  22087. ** value 2^63: 9223372036854775808. Return negative, zero, or positive
  22088. ** if zNum is less than, equal to, or greater than the string.
  22089. ** Note that zNum must contain exactly 19 characters.
  22090. **
  22091. ** Unlike memcmp() this routine is guaranteed to return the difference
  22092. ** in the values of the last digit if the only difference is in the
  22093. ** last digit. So, for example,
  22094. **
  22095. ** compare2pow63("9223372036854775800", 1)
  22096. **
  22097. ** will return -8.
  22098. */
  22099. static int compare2pow63(const char *zNum, int incr){
  22100. int c = 0;
  22101. int i;
  22102. /* 012345678901234567 */
  22103. const char *pow63 = "922337203685477580";
  22104. for(i=0; c==0 && i<18; i++){
  22105. c = (zNum[i*incr]-pow63[i])*10;
  22106. }
  22107. if( c==0 ){
  22108. c = zNum[18*incr] - '8';
  22109. testcase( c==(-1) );
  22110. testcase( c==0 );
  22111. testcase( c==(+1) );
  22112. }
  22113. return c;
  22114. }
  22115. /*
  22116. ** Convert zNum to a 64-bit signed integer. zNum must be decimal. This
  22117. ** routine does *not* accept hexadecimal notation.
  22118. **
  22119. ** If the zNum value is representable as a 64-bit twos-complement
  22120. ** integer, then write that value into *pNum and return 0.
  22121. **
  22122. ** If zNum is exactly 9223372036854775808, return 2. This special
  22123. ** case is broken out because while 9223372036854775808 cannot be a
  22124. ** signed 64-bit integer, its negative -9223372036854775808 can be.
  22125. **
  22126. ** If zNum is too big for a 64-bit integer and is not
  22127. ** 9223372036854775808 or if zNum contains any non-numeric text,
  22128. ** then return 1.
  22129. **
  22130. ** length is the number of bytes in the string (bytes, not characters).
  22131. ** The string is not necessarily zero-terminated. The encoding is
  22132. ** given by enc.
  22133. */
  22134. SQLITE_PRIVATE int sqlite3Atoi64(const char *zNum, i64 *pNum, int length, u8 enc){
  22135. int incr;
  22136. u64 u = 0;
  22137. int neg = 0; /* assume positive */
  22138. int i;
  22139. int c = 0;
  22140. int nonNum = 0;
  22141. const char *zStart;
  22142. const char *zEnd = zNum + length;
  22143. assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
  22144. if( enc==SQLITE_UTF8 ){
  22145. incr = 1;
  22146. }else{
  22147. incr = 2;
  22148. assert( SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
  22149. for(i=3-enc; i<length && zNum[i]==0; i+=2){}
  22150. nonNum = i<length;
  22151. zEnd = zNum+i+enc-3;
  22152. zNum += (enc&1);
  22153. }
  22154. while( zNum<zEnd && sqlite3Isspace(*zNum) ) zNum+=incr;
  22155. if( zNum<zEnd ){
  22156. if( *zNum=='-' ){
  22157. neg = 1;
  22158. zNum+=incr;
  22159. }else if( *zNum=='+' ){
  22160. zNum+=incr;
  22161. }
  22162. }
  22163. zStart = zNum;
  22164. while( zNum<zEnd && zNum[0]=='0' ){ zNum+=incr; } /* Skip leading zeros. */
  22165. for(i=0; &zNum[i]<zEnd && (c=zNum[i])>='0' && c<='9'; i+=incr){
  22166. u = u*10 + c - '0';
  22167. }
  22168. if( u>LARGEST_INT64 ){
  22169. *pNum = neg ? SMALLEST_INT64 : LARGEST_INT64;
  22170. }else if( neg ){
  22171. *pNum = -(i64)u;
  22172. }else{
  22173. *pNum = (i64)u;
  22174. }
  22175. testcase( i==18 );
  22176. testcase( i==19 );
  22177. testcase( i==20 );
  22178. if( (c!=0 && &zNum[i]<zEnd) || (i==0 && zStart==zNum) || i>19*incr || nonNum ){
  22179. /* zNum is empty or contains non-numeric text or is longer
  22180. ** than 19 digits (thus guaranteeing that it is too large) */
  22181. return 1;
  22182. }else if( i<19*incr ){
  22183. /* Less than 19 digits, so we know that it fits in 64 bits */
  22184. assert( u<=LARGEST_INT64 );
  22185. return 0;
  22186. }else{
  22187. /* zNum is a 19-digit numbers. Compare it against 9223372036854775808. */
  22188. c = compare2pow63(zNum, incr);
  22189. if( c<0 ){
  22190. /* zNum is less than 9223372036854775808 so it fits */
  22191. assert( u<=LARGEST_INT64 );
  22192. return 0;
  22193. }else if( c>0 ){
  22194. /* zNum is greater than 9223372036854775808 so it overflows */
  22195. return 1;
  22196. }else{
  22197. /* zNum is exactly 9223372036854775808. Fits if negative. The
  22198. ** special case 2 overflow if positive */
  22199. assert( u-1==LARGEST_INT64 );
  22200. return neg ? 0 : 2;
  22201. }
  22202. }
  22203. }
  22204. /*
  22205. ** Transform a UTF-8 integer literal, in either decimal or hexadecimal,
  22206. ** into a 64-bit signed integer. This routine accepts hexadecimal literals,
  22207. ** whereas sqlite3Atoi64() does not.
  22208. **
  22209. ** Returns:
  22210. **
  22211. ** 0 Successful transformation. Fits in a 64-bit signed integer.
  22212. ** 1 Integer too large for a 64-bit signed integer or is malformed
  22213. ** 2 Special case of 9223372036854775808
  22214. */
  22215. SQLITE_PRIVATE int sqlite3DecOrHexToI64(const char *z, i64 *pOut){
  22216. #ifndef SQLITE_OMIT_HEX_INTEGER
  22217. if( z[0]=='0'
  22218. && (z[1]=='x' || z[1]=='X')
  22219. && sqlite3Isxdigit(z[2])
  22220. ){
  22221. u64 u = 0;
  22222. int i, k;
  22223. for(i=2; z[i]=='0'; i++){}
  22224. for(k=i; sqlite3Isxdigit(z[k]); k++){
  22225. u = u*16 + sqlite3HexToInt(z[k]);
  22226. }
  22227. memcpy(pOut, &u, 8);
  22228. return (z[k]==0 && k-i<=16) ? 0 : 1;
  22229. }else
  22230. #endif /* SQLITE_OMIT_HEX_INTEGER */
  22231. {
  22232. return sqlite3Atoi64(z, pOut, sqlite3Strlen30(z), SQLITE_UTF8);
  22233. }
  22234. }
  22235. /*
  22236. ** If zNum represents an integer that will fit in 32-bits, then set
  22237. ** *pValue to that integer and return true. Otherwise return false.
  22238. **
  22239. ** This routine accepts both decimal and hexadecimal notation for integers.
  22240. **
  22241. ** Any non-numeric characters that following zNum are ignored.
  22242. ** This is different from sqlite3Atoi64() which requires the
  22243. ** input number to be zero-terminated.
  22244. */
  22245. SQLITE_PRIVATE int sqlite3GetInt32(const char *zNum, int *pValue){
  22246. sqlite_int64 v = 0;
  22247. int i, c;
  22248. int neg = 0;
  22249. if( zNum[0]=='-' ){
  22250. neg = 1;
  22251. zNum++;
  22252. }else if( zNum[0]=='+' ){
  22253. zNum++;
  22254. }
  22255. #ifndef SQLITE_OMIT_HEX_INTEGER
  22256. else if( zNum[0]=='0'
  22257. && (zNum[1]=='x' || zNum[1]=='X')
  22258. && sqlite3Isxdigit(zNum[2])
  22259. ){
  22260. u32 u = 0;
  22261. zNum += 2;
  22262. while( zNum[0]=='0' ) zNum++;
  22263. for(i=0; sqlite3Isxdigit(zNum[i]) && i<8; i++){
  22264. u = u*16 + sqlite3HexToInt(zNum[i]);
  22265. }
  22266. if( (u&0x80000000)==0 && sqlite3Isxdigit(zNum[i])==0 ){
  22267. memcpy(pValue, &u, 4);
  22268. return 1;
  22269. }else{
  22270. return 0;
  22271. }
  22272. }
  22273. #endif
  22274. for(i=0; i<11 && (c = zNum[i] - '0')>=0 && c<=9; i++){
  22275. v = v*10 + c;
  22276. }
  22277. /* The longest decimal representation of a 32 bit integer is 10 digits:
  22278. **
  22279. ** 1234567890
  22280. ** 2^31 -> 2147483648
  22281. */
  22282. testcase( i==10 );
  22283. if( i>10 ){
  22284. return 0;
  22285. }
  22286. testcase( v-neg==2147483647 );
  22287. if( v-neg>2147483647 ){
  22288. return 0;
  22289. }
  22290. if( neg ){
  22291. v = -v;
  22292. }
  22293. *pValue = (int)v;
  22294. return 1;
  22295. }
  22296. /*
  22297. ** Return a 32-bit integer value extracted from a string. If the
  22298. ** string is not an integer, just return 0.
  22299. */
  22300. SQLITE_PRIVATE int sqlite3Atoi(const char *z){
  22301. int x = 0;
  22302. if( z ) sqlite3GetInt32(z, &x);
  22303. return x;
  22304. }
  22305. /*
  22306. ** The variable-length integer encoding is as follows:
  22307. **
  22308. ** KEY:
  22309. ** A = 0xxxxxxx 7 bits of data and one flag bit
  22310. ** B = 1xxxxxxx 7 bits of data and one flag bit
  22311. ** C = xxxxxxxx 8 bits of data
  22312. **
  22313. ** 7 bits - A
  22314. ** 14 bits - BA
  22315. ** 21 bits - BBA
  22316. ** 28 bits - BBBA
  22317. ** 35 bits - BBBBA
  22318. ** 42 bits - BBBBBA
  22319. ** 49 bits - BBBBBBA
  22320. ** 56 bits - BBBBBBBA
  22321. ** 64 bits - BBBBBBBBC
  22322. */
  22323. /*
  22324. ** Write a 64-bit variable-length integer to memory starting at p[0].
  22325. ** The length of data write will be between 1 and 9 bytes. The number
  22326. ** of bytes written is returned.
  22327. **
  22328. ** A variable-length integer consists of the lower 7 bits of each byte
  22329. ** for all bytes that have the 8th bit set and one byte with the 8th
  22330. ** bit clear. Except, if we get to the 9th byte, it stores the full
  22331. ** 8 bits and is the last byte.
  22332. */
  22333. static int SQLITE_NOINLINE putVarint64(unsigned char *p, u64 v){
  22334. int i, j, n;
  22335. u8 buf[10];
  22336. if( v & (((u64)0xff000000)<<32) ){
  22337. p[8] = (u8)v;
  22338. v >>= 8;
  22339. for(i=7; i>=0; i--){
  22340. p[i] = (u8)((v & 0x7f) | 0x80);
  22341. v >>= 7;
  22342. }
  22343. return 9;
  22344. }
  22345. n = 0;
  22346. do{
  22347. buf[n++] = (u8)((v & 0x7f) | 0x80);
  22348. v >>= 7;
  22349. }while( v!=0 );
  22350. buf[0] &= 0x7f;
  22351. assert( n<=9 );
  22352. for(i=0, j=n-1; j>=0; j--, i++){
  22353. p[i] = buf[j];
  22354. }
  22355. return n;
  22356. }
  22357. SQLITE_PRIVATE int sqlite3PutVarint(unsigned char *p, u64 v){
  22358. if( v<=0x7f ){
  22359. p[0] = v&0x7f;
  22360. return 1;
  22361. }
  22362. if( v<=0x3fff ){
  22363. p[0] = ((v>>7)&0x7f)|0x80;
  22364. p[1] = v&0x7f;
  22365. return 2;
  22366. }
  22367. return putVarint64(p,v);
  22368. }
  22369. /*
  22370. ** Bitmasks used by sqlite3GetVarint(). These precomputed constants
  22371. ** are defined here rather than simply putting the constant expressions
  22372. ** inline in order to work around bugs in the RVT compiler.
  22373. **
  22374. ** SLOT_2_0 A mask for (0x7f<<14) | 0x7f
  22375. **
  22376. ** SLOT_4_2_0 A mask for (0x7f<<28) | SLOT_2_0
  22377. */
  22378. #define SLOT_2_0 0x001fc07f
  22379. #define SLOT_4_2_0 0xf01fc07f
  22380. /*
  22381. ** Read a 64-bit variable-length integer from memory starting at p[0].
  22382. ** Return the number of bytes read. The value is stored in *v.
  22383. */
  22384. SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *p, u64 *v){
  22385. u32 a,b,s;
  22386. a = *p;
  22387. /* a: p0 (unmasked) */
  22388. if (!(a&0x80))
  22389. {
  22390. *v = a;
  22391. return 1;
  22392. }
  22393. p++;
  22394. b = *p;
  22395. /* b: p1 (unmasked) */
  22396. if (!(b&0x80))
  22397. {
  22398. a &= 0x7f;
  22399. a = a<<7;
  22400. a |= b;
  22401. *v = a;
  22402. return 2;
  22403. }
  22404. /* Verify that constants are precomputed correctly */
  22405. assert( SLOT_2_0 == ((0x7f<<14) | (0x7f)) );
  22406. assert( SLOT_4_2_0 == ((0xfU<<28) | (0x7f<<14) | (0x7f)) );
  22407. p++;
  22408. a = a<<14;
  22409. a |= *p;
  22410. /* a: p0<<14 | p2 (unmasked) */
  22411. if (!(a&0x80))
  22412. {
  22413. a &= SLOT_2_0;
  22414. b &= 0x7f;
  22415. b = b<<7;
  22416. a |= b;
  22417. *v = a;
  22418. return 3;
  22419. }
  22420. /* CSE1 from below */
  22421. a &= SLOT_2_0;
  22422. p++;
  22423. b = b<<14;
  22424. b |= *p;
  22425. /* b: p1<<14 | p3 (unmasked) */
  22426. if (!(b&0x80))
  22427. {
  22428. b &= SLOT_2_0;
  22429. /* moved CSE1 up */
  22430. /* a &= (0x7f<<14)|(0x7f); */
  22431. a = a<<7;
  22432. a |= b;
  22433. *v = a;
  22434. return 4;
  22435. }
  22436. /* a: p0<<14 | p2 (masked) */
  22437. /* b: p1<<14 | p3 (unmasked) */
  22438. /* 1:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
  22439. /* moved CSE1 up */
  22440. /* a &= (0x7f<<14)|(0x7f); */
  22441. b &= SLOT_2_0;
  22442. s = a;
  22443. /* s: p0<<14 | p2 (masked) */
  22444. p++;
  22445. a = a<<14;
  22446. a |= *p;
  22447. /* a: p0<<28 | p2<<14 | p4 (unmasked) */
  22448. if (!(a&0x80))
  22449. {
  22450. /* we can skip these cause they were (effectively) done above in calc'ing s */
  22451. /* a &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
  22452. /* b &= (0x7f<<14)|(0x7f); */
  22453. b = b<<7;
  22454. a |= b;
  22455. s = s>>18;
  22456. *v = ((u64)s)<<32 | a;
  22457. return 5;
  22458. }
  22459. /* 2:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
  22460. s = s<<7;
  22461. s |= b;
  22462. /* s: p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
  22463. p++;
  22464. b = b<<14;
  22465. b |= *p;
  22466. /* b: p1<<28 | p3<<14 | p5 (unmasked) */
  22467. if (!(b&0x80))
  22468. {
  22469. /* we can skip this cause it was (effectively) done above in calc'ing s */
  22470. /* b &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
  22471. a &= SLOT_2_0;
  22472. a = a<<7;
  22473. a |= b;
  22474. s = s>>18;
  22475. *v = ((u64)s)<<32 | a;
  22476. return 6;
  22477. }
  22478. p++;
  22479. a = a<<14;
  22480. a |= *p;
  22481. /* a: p2<<28 | p4<<14 | p6 (unmasked) */
  22482. if (!(a&0x80))
  22483. {
  22484. a &= SLOT_4_2_0;
  22485. b &= SLOT_2_0;
  22486. b = b<<7;
  22487. a |= b;
  22488. s = s>>11;
  22489. *v = ((u64)s)<<32 | a;
  22490. return 7;
  22491. }
  22492. /* CSE2 from below */
  22493. a &= SLOT_2_0;
  22494. p++;
  22495. b = b<<14;
  22496. b |= *p;
  22497. /* b: p3<<28 | p5<<14 | p7 (unmasked) */
  22498. if (!(b&0x80))
  22499. {
  22500. b &= SLOT_4_2_0;
  22501. /* moved CSE2 up */
  22502. /* a &= (0x7f<<14)|(0x7f); */
  22503. a = a<<7;
  22504. a |= b;
  22505. s = s>>4;
  22506. *v = ((u64)s)<<32 | a;
  22507. return 8;
  22508. }
  22509. p++;
  22510. a = a<<15;
  22511. a |= *p;
  22512. /* a: p4<<29 | p6<<15 | p8 (unmasked) */
  22513. /* moved CSE2 up */
  22514. /* a &= (0x7f<<29)|(0x7f<<15)|(0xff); */
  22515. b &= SLOT_2_0;
  22516. b = b<<8;
  22517. a |= b;
  22518. s = s<<4;
  22519. b = p[-4];
  22520. b &= 0x7f;
  22521. b = b>>3;
  22522. s |= b;
  22523. *v = ((u64)s)<<32 | a;
  22524. return 9;
  22525. }
  22526. /*
  22527. ** Read a 32-bit variable-length integer from memory starting at p[0].
  22528. ** Return the number of bytes read. The value is stored in *v.
  22529. **
  22530. ** If the varint stored in p[0] is larger than can fit in a 32-bit unsigned
  22531. ** integer, then set *v to 0xffffffff.
  22532. **
  22533. ** A MACRO version, getVarint32, is provided which inlines the
  22534. ** single-byte case. All code should use the MACRO version as
  22535. ** this function assumes the single-byte case has already been handled.
  22536. */
  22537. SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *p, u32 *v){
  22538. u32 a,b;
  22539. /* The 1-byte case. Overwhelmingly the most common. Handled inline
  22540. ** by the getVarin32() macro */
  22541. a = *p;
  22542. /* a: p0 (unmasked) */
  22543. #ifndef getVarint32
  22544. if (!(a&0x80))
  22545. {
  22546. /* Values between 0 and 127 */
  22547. *v = a;
  22548. return 1;
  22549. }
  22550. #endif
  22551. /* The 2-byte case */
  22552. p++;
  22553. b = *p;
  22554. /* b: p1 (unmasked) */
  22555. if (!(b&0x80))
  22556. {
  22557. /* Values between 128 and 16383 */
  22558. a &= 0x7f;
  22559. a = a<<7;
  22560. *v = a | b;
  22561. return 2;
  22562. }
  22563. /* The 3-byte case */
  22564. p++;
  22565. a = a<<14;
  22566. a |= *p;
  22567. /* a: p0<<14 | p2 (unmasked) */
  22568. if (!(a&0x80))
  22569. {
  22570. /* Values between 16384 and 2097151 */
  22571. a &= (0x7f<<14)|(0x7f);
  22572. b &= 0x7f;
  22573. b = b<<7;
  22574. *v = a | b;
  22575. return 3;
  22576. }
  22577. /* A 32-bit varint is used to store size information in btrees.
  22578. ** Objects are rarely larger than 2MiB limit of a 3-byte varint.
  22579. ** A 3-byte varint is sufficient, for example, to record the size
  22580. ** of a 1048569-byte BLOB or string.
  22581. **
  22582. ** We only unroll the first 1-, 2-, and 3- byte cases. The very
  22583. ** rare larger cases can be handled by the slower 64-bit varint
  22584. ** routine.
  22585. */
  22586. #if 1
  22587. {
  22588. u64 v64;
  22589. u8 n;
  22590. p -= 2;
  22591. n = sqlite3GetVarint(p, &v64);
  22592. assert( n>3 && n<=9 );
  22593. if( (v64 & SQLITE_MAX_U32)!=v64 ){
  22594. *v = 0xffffffff;
  22595. }else{
  22596. *v = (u32)v64;
  22597. }
  22598. return n;
  22599. }
  22600. #else
  22601. /* For following code (kept for historical record only) shows an
  22602. ** unrolling for the 3- and 4-byte varint cases. This code is
  22603. ** slightly faster, but it is also larger and much harder to test.
  22604. */
  22605. p++;
  22606. b = b<<14;
  22607. b |= *p;
  22608. /* b: p1<<14 | p3 (unmasked) */
  22609. if (!(b&0x80))
  22610. {
  22611. /* Values between 2097152 and 268435455 */
  22612. b &= (0x7f<<14)|(0x7f);
  22613. a &= (0x7f<<14)|(0x7f);
  22614. a = a<<7;
  22615. *v = a | b;
  22616. return 4;
  22617. }
  22618. p++;
  22619. a = a<<14;
  22620. a |= *p;
  22621. /* a: p0<<28 | p2<<14 | p4 (unmasked) */
  22622. if (!(a&0x80))
  22623. {
  22624. /* Values between 268435456 and 34359738367 */
  22625. a &= SLOT_4_2_0;
  22626. b &= SLOT_4_2_0;
  22627. b = b<<7;
  22628. *v = a | b;
  22629. return 5;
  22630. }
  22631. /* We can only reach this point when reading a corrupt database
  22632. ** file. In that case we are not in any hurry. Use the (relatively
  22633. ** slow) general-purpose sqlite3GetVarint() routine to extract the
  22634. ** value. */
  22635. {
  22636. u64 v64;
  22637. u8 n;
  22638. p -= 4;
  22639. n = sqlite3GetVarint(p, &v64);
  22640. assert( n>5 && n<=9 );
  22641. *v = (u32)v64;
  22642. return n;
  22643. }
  22644. #endif
  22645. }
  22646. /*
  22647. ** Return the number of bytes that will be needed to store the given
  22648. ** 64-bit integer.
  22649. */
  22650. SQLITE_PRIVATE int sqlite3VarintLen(u64 v){
  22651. int i = 0;
  22652. do{
  22653. i++;
  22654. v >>= 7;
  22655. }while( v!=0 && ALWAYS(i<9) );
  22656. return i;
  22657. }
  22658. /*
  22659. ** Read or write a four-byte big-endian integer value.
  22660. */
  22661. SQLITE_PRIVATE u32 sqlite3Get4byte(const u8 *p){
  22662. testcase( p[0]&0x80 );
  22663. return ((unsigned)p[0]<<24) | (p[1]<<16) | (p[2]<<8) | p[3];
  22664. }
  22665. SQLITE_PRIVATE void sqlite3Put4byte(unsigned char *p, u32 v){
  22666. p[0] = (u8)(v>>24);
  22667. p[1] = (u8)(v>>16);
  22668. p[2] = (u8)(v>>8);
  22669. p[3] = (u8)v;
  22670. }
  22671. /*
  22672. ** Translate a single byte of Hex into an integer.
  22673. ** This routine only works if h really is a valid hexadecimal
  22674. ** character: 0..9a..fA..F
  22675. */
  22676. SQLITE_PRIVATE u8 sqlite3HexToInt(int h){
  22677. assert( (h>='0' && h<='9') || (h>='a' && h<='f') || (h>='A' && h<='F') );
  22678. #ifdef SQLITE_ASCII
  22679. h += 9*(1&(h>>6));
  22680. #endif
  22681. #ifdef SQLITE_EBCDIC
  22682. h += 9*(1&~(h>>4));
  22683. #endif
  22684. return (u8)(h & 0xf);
  22685. }
  22686. #if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC)
  22687. /*
  22688. ** Convert a BLOB literal of the form "x'hhhhhh'" into its binary
  22689. ** value. Return a pointer to its binary value. Space to hold the
  22690. ** binary value has been obtained from malloc and must be freed by
  22691. ** the calling routine.
  22692. */
  22693. SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3 *db, const char *z, int n){
  22694. char *zBlob;
  22695. int i;
  22696. zBlob = (char *)sqlite3DbMallocRaw(db, n/2 + 1);
  22697. n--;
  22698. if( zBlob ){
  22699. for(i=0; i<n; i+=2){
  22700. zBlob[i/2] = (sqlite3HexToInt(z[i])<<4) | sqlite3HexToInt(z[i+1]);
  22701. }
  22702. zBlob[i/2] = 0;
  22703. }
  22704. return zBlob;
  22705. }
  22706. #endif /* !SQLITE_OMIT_BLOB_LITERAL || SQLITE_HAS_CODEC */
  22707. /*
  22708. ** Log an error that is an API call on a connection pointer that should
  22709. ** not have been used. The "type" of connection pointer is given as the
  22710. ** argument. The zType is a word like "NULL" or "closed" or "invalid".
  22711. */
  22712. static void logBadConnection(const char *zType){
  22713. sqlite3_log(SQLITE_MISUSE,
  22714. "API call with %s database connection pointer",
  22715. zType
  22716. );
  22717. }
  22718. /*
  22719. ** Check to make sure we have a valid db pointer. This test is not
  22720. ** foolproof but it does provide some measure of protection against
  22721. ** misuse of the interface such as passing in db pointers that are
  22722. ** NULL or which have been previously closed. If this routine returns
  22723. ** 1 it means that the db pointer is valid and 0 if it should not be
  22724. ** dereferenced for any reason. The calling function should invoke
  22725. ** SQLITE_MISUSE immediately.
  22726. **
  22727. ** sqlite3SafetyCheckOk() requires that the db pointer be valid for
  22728. ** use. sqlite3SafetyCheckSickOrOk() allows a db pointer that failed to
  22729. ** open properly and is not fit for general use but which can be
  22730. ** used as an argument to sqlite3_errmsg() or sqlite3_close().
  22731. */
  22732. SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3 *db){
  22733. u32 magic;
  22734. if( db==0 ){
  22735. logBadConnection("NULL");
  22736. return 0;
  22737. }
  22738. magic = db->magic;
  22739. if( magic!=SQLITE_MAGIC_OPEN ){
  22740. if( sqlite3SafetyCheckSickOrOk(db) ){
  22741. testcase( sqlite3GlobalConfig.xLog!=0 );
  22742. logBadConnection("unopened");
  22743. }
  22744. return 0;
  22745. }else{
  22746. return 1;
  22747. }
  22748. }
  22749. SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3 *db){
  22750. u32 magic;
  22751. magic = db->magic;
  22752. if( magic!=SQLITE_MAGIC_SICK &&
  22753. magic!=SQLITE_MAGIC_OPEN &&
  22754. magic!=SQLITE_MAGIC_BUSY ){
  22755. testcase( sqlite3GlobalConfig.xLog!=0 );
  22756. logBadConnection("invalid");
  22757. return 0;
  22758. }else{
  22759. return 1;
  22760. }
  22761. }
  22762. /*
  22763. ** Attempt to add, substract, or multiply the 64-bit signed value iB against
  22764. ** the other 64-bit signed integer at *pA and store the result in *pA.
  22765. ** Return 0 on success. Or if the operation would have resulted in an
  22766. ** overflow, leave *pA unchanged and return 1.
  22767. */
  22768. SQLITE_PRIVATE int sqlite3AddInt64(i64 *pA, i64 iB){
  22769. i64 iA = *pA;
  22770. testcase( iA==0 ); testcase( iA==1 );
  22771. testcase( iB==-1 ); testcase( iB==0 );
  22772. if( iB>=0 ){
  22773. testcase( iA>0 && LARGEST_INT64 - iA == iB );
  22774. testcase( iA>0 && LARGEST_INT64 - iA == iB - 1 );
  22775. if( iA>0 && LARGEST_INT64 - iA < iB ) return 1;
  22776. }else{
  22777. testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 1 );
  22778. testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 2 );
  22779. if( iA<0 && -(iA + LARGEST_INT64) > iB + 1 ) return 1;
  22780. }
  22781. *pA += iB;
  22782. return 0;
  22783. }
  22784. SQLITE_PRIVATE int sqlite3SubInt64(i64 *pA, i64 iB){
  22785. testcase( iB==SMALLEST_INT64+1 );
  22786. if( iB==SMALLEST_INT64 ){
  22787. testcase( (*pA)==(-1) ); testcase( (*pA)==0 );
  22788. if( (*pA)>=0 ) return 1;
  22789. *pA -= iB;
  22790. return 0;
  22791. }else{
  22792. return sqlite3AddInt64(pA, -iB);
  22793. }
  22794. }
  22795. #define TWOPOWER32 (((i64)1)<<32)
  22796. #define TWOPOWER31 (((i64)1)<<31)
  22797. SQLITE_PRIVATE int sqlite3MulInt64(i64 *pA, i64 iB){
  22798. i64 iA = *pA;
  22799. i64 iA1, iA0, iB1, iB0, r;
  22800. iA1 = iA/TWOPOWER32;
  22801. iA0 = iA % TWOPOWER32;
  22802. iB1 = iB/TWOPOWER32;
  22803. iB0 = iB % TWOPOWER32;
  22804. if( iA1==0 ){
  22805. if( iB1==0 ){
  22806. *pA *= iB;
  22807. return 0;
  22808. }
  22809. r = iA0*iB1;
  22810. }else if( iB1==0 ){
  22811. r = iA1*iB0;
  22812. }else{
  22813. /* If both iA1 and iB1 are non-zero, overflow will result */
  22814. return 1;
  22815. }
  22816. testcase( r==(-TWOPOWER31)-1 );
  22817. testcase( r==(-TWOPOWER31) );
  22818. testcase( r==TWOPOWER31 );
  22819. testcase( r==TWOPOWER31-1 );
  22820. if( r<(-TWOPOWER31) || r>=TWOPOWER31 ) return 1;
  22821. r *= TWOPOWER32;
  22822. if( sqlite3AddInt64(&r, iA0*iB0) ) return 1;
  22823. *pA = r;
  22824. return 0;
  22825. }
  22826. /*
  22827. ** Compute the absolute value of a 32-bit signed integer, of possible. Or
  22828. ** if the integer has a value of -2147483648, return +2147483647
  22829. */
  22830. SQLITE_PRIVATE int sqlite3AbsInt32(int x){
  22831. if( x>=0 ) return x;
  22832. if( x==(int)0x80000000 ) return 0x7fffffff;
  22833. return -x;
  22834. }
  22835. #ifdef SQLITE_ENABLE_8_3_NAMES
  22836. /*
  22837. ** If SQLITE_ENABLE_8_3_NAMES is set at compile-time and if the database
  22838. ** filename in zBaseFilename is a URI with the "8_3_names=1" parameter and
  22839. ** if filename in z[] has a suffix (a.k.a. "extension") that is longer than
  22840. ** three characters, then shorten the suffix on z[] to be the last three
  22841. ** characters of the original suffix.
  22842. **
  22843. ** If SQLITE_ENABLE_8_3_NAMES is set to 2 at compile-time, then always
  22844. ** do the suffix shortening regardless of URI parameter.
  22845. **
  22846. ** Examples:
  22847. **
  22848. ** test.db-journal => test.nal
  22849. ** test.db-wal => test.wal
  22850. ** test.db-shm => test.shm
  22851. ** test.db-mj7f3319fa => test.9fa
  22852. */
  22853. SQLITE_PRIVATE void sqlite3FileSuffix3(const char *zBaseFilename, char *z){
  22854. #if SQLITE_ENABLE_8_3_NAMES<2
  22855. if( sqlite3_uri_boolean(zBaseFilename, "8_3_names", 0) )
  22856. #endif
  22857. {
  22858. int i, sz;
  22859. sz = sqlite3Strlen30(z);
  22860. for(i=sz-1; i>0 && z[i]!='/' && z[i]!='.'; i--){}
  22861. if( z[i]=='.' && ALWAYS(sz>i+4) ) memmove(&z[i+1], &z[sz-3], 4);
  22862. }
  22863. }
  22864. #endif
  22865. /*
  22866. ** Find (an approximate) sum of two LogEst values. This computation is
  22867. ** not a simple "+" operator because LogEst is stored as a logarithmic
  22868. ** value.
  22869. **
  22870. */
  22871. SQLITE_PRIVATE LogEst sqlite3LogEstAdd(LogEst a, LogEst b){
  22872. static const unsigned char x[] = {
  22873. 10, 10, /* 0,1 */
  22874. 9, 9, /* 2,3 */
  22875. 8, 8, /* 4,5 */
  22876. 7, 7, 7, /* 6,7,8 */
  22877. 6, 6, 6, /* 9,10,11 */
  22878. 5, 5, 5, /* 12-14 */
  22879. 4, 4, 4, 4, /* 15-18 */
  22880. 3, 3, 3, 3, 3, 3, /* 19-24 */
  22881. 2, 2, 2, 2, 2, 2, 2, /* 25-31 */
  22882. };
  22883. if( a>=b ){
  22884. if( a>b+49 ) return a;
  22885. if( a>b+31 ) return a+1;
  22886. return a+x[a-b];
  22887. }else{
  22888. if( b>a+49 ) return b;
  22889. if( b>a+31 ) return b+1;
  22890. return b+x[b-a];
  22891. }
  22892. }
  22893. /*
  22894. ** Convert an integer into a LogEst. In other words, compute an
  22895. ** approximation for 10*log2(x).
  22896. */
  22897. SQLITE_PRIVATE LogEst sqlite3LogEst(u64 x){
  22898. static LogEst a[] = { 0, 2, 3, 5, 6, 7, 8, 9 };
  22899. LogEst y = 40;
  22900. if( x<8 ){
  22901. if( x<2 ) return 0;
  22902. while( x<8 ){ y -= 10; x <<= 1; }
  22903. }else{
  22904. while( x>255 ){ y += 40; x >>= 4; }
  22905. while( x>15 ){ y += 10; x >>= 1; }
  22906. }
  22907. return a[x&7] + y - 10;
  22908. }
  22909. #ifndef SQLITE_OMIT_VIRTUALTABLE
  22910. /*
  22911. ** Convert a double into a LogEst
  22912. ** In other words, compute an approximation for 10*log2(x).
  22913. */
  22914. SQLITE_PRIVATE LogEst sqlite3LogEstFromDouble(double x){
  22915. u64 a;
  22916. LogEst e;
  22917. assert( sizeof(x)==8 && sizeof(a)==8 );
  22918. if( x<=1 ) return 0;
  22919. if( x<=2000000000 ) return sqlite3LogEst((u64)x);
  22920. memcpy(&a, &x, 8);
  22921. e = (a>>52) - 1022;
  22922. return e*10;
  22923. }
  22924. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  22925. /*
  22926. ** Convert a LogEst into an integer.
  22927. */
  22928. SQLITE_PRIVATE u64 sqlite3LogEstToInt(LogEst x){
  22929. u64 n;
  22930. if( x<10 ) return 1;
  22931. n = x%10;
  22932. x /= 10;
  22933. if( n>=5 ) n -= 2;
  22934. else if( n>=1 ) n -= 1;
  22935. if( x>=3 ){
  22936. return x>60 ? (u64)LARGEST_INT64 : (n+8)<<(x-3);
  22937. }
  22938. return (n+8)>>(3-x);
  22939. }
  22940. /************** End of util.c ************************************************/
  22941. /************** Begin file hash.c ********************************************/
  22942. /*
  22943. ** 2001 September 22
  22944. **
  22945. ** The author disclaims copyright to this source code. In place of
  22946. ** a legal notice, here is a blessing:
  22947. **
  22948. ** May you do good and not evil.
  22949. ** May you find forgiveness for yourself and forgive others.
  22950. ** May you share freely, never taking more than you give.
  22951. **
  22952. *************************************************************************
  22953. ** This is the implementation of generic hash-tables
  22954. ** used in SQLite.
  22955. */
  22956. /* #include <assert.h> */
  22957. /* Turn bulk memory into a hash table object by initializing the
  22958. ** fields of the Hash structure.
  22959. **
  22960. ** "pNew" is a pointer to the hash table that is to be initialized.
  22961. */
  22962. SQLITE_PRIVATE void sqlite3HashInit(Hash *pNew){
  22963. assert( pNew!=0 );
  22964. pNew->first = 0;
  22965. pNew->count = 0;
  22966. pNew->htsize = 0;
  22967. pNew->ht = 0;
  22968. }
  22969. /* Remove all entries from a hash table. Reclaim all memory.
  22970. ** Call this routine to delete a hash table or to reset a hash table
  22971. ** to the empty state.
  22972. */
  22973. SQLITE_PRIVATE void sqlite3HashClear(Hash *pH){
  22974. HashElem *elem; /* For looping over all elements of the table */
  22975. assert( pH!=0 );
  22976. elem = pH->first;
  22977. pH->first = 0;
  22978. sqlite3_free(pH->ht);
  22979. pH->ht = 0;
  22980. pH->htsize = 0;
  22981. while( elem ){
  22982. HashElem *next_elem = elem->next;
  22983. sqlite3_free(elem);
  22984. elem = next_elem;
  22985. }
  22986. pH->count = 0;
  22987. }
  22988. /*
  22989. ** The hashing function.
  22990. */
  22991. static unsigned int strHash(const char *z){
  22992. unsigned int h = 0;
  22993. unsigned char c;
  22994. while( (c = (unsigned char)*z++)!=0 ){
  22995. h = (h<<3) ^ h ^ sqlite3UpperToLower[c];
  22996. }
  22997. return h;
  22998. }
  22999. /* Link pNew element into the hash table pH. If pEntry!=0 then also
  23000. ** insert pNew into the pEntry hash bucket.
  23001. */
  23002. static void insertElement(
  23003. Hash *pH, /* The complete hash table */
  23004. struct _ht *pEntry, /* The entry into which pNew is inserted */
  23005. HashElem *pNew /* The element to be inserted */
  23006. ){
  23007. HashElem *pHead; /* First element already in pEntry */
  23008. if( pEntry ){
  23009. pHead = pEntry->count ? pEntry->chain : 0;
  23010. pEntry->count++;
  23011. pEntry->chain = pNew;
  23012. }else{
  23013. pHead = 0;
  23014. }
  23015. if( pHead ){
  23016. pNew->next = pHead;
  23017. pNew->prev = pHead->prev;
  23018. if( pHead->prev ){ pHead->prev->next = pNew; }
  23019. else { pH->first = pNew; }
  23020. pHead->prev = pNew;
  23021. }else{
  23022. pNew->next = pH->first;
  23023. if( pH->first ){ pH->first->prev = pNew; }
  23024. pNew->prev = 0;
  23025. pH->first = pNew;
  23026. }
  23027. }
  23028. /* Resize the hash table so that it cantains "new_size" buckets.
  23029. **
  23030. ** The hash table might fail to resize if sqlite3_malloc() fails or
  23031. ** if the new size is the same as the prior size.
  23032. ** Return TRUE if the resize occurs and false if not.
  23033. */
  23034. static int rehash(Hash *pH, unsigned int new_size){
  23035. struct _ht *new_ht; /* The new hash table */
  23036. HashElem *elem, *next_elem; /* For looping over existing elements */
  23037. #if SQLITE_MALLOC_SOFT_LIMIT>0
  23038. if( new_size*sizeof(struct _ht)>SQLITE_MALLOC_SOFT_LIMIT ){
  23039. new_size = SQLITE_MALLOC_SOFT_LIMIT/sizeof(struct _ht);
  23040. }
  23041. if( new_size==pH->htsize ) return 0;
  23042. #endif
  23043. /* The inability to allocates space for a larger hash table is
  23044. ** a performance hit but it is not a fatal error. So mark the
  23045. ** allocation as a benign. Use sqlite3Malloc()/memset(0) instead of
  23046. ** sqlite3MallocZero() to make the allocation, as sqlite3MallocZero()
  23047. ** only zeroes the requested number of bytes whereas this module will
  23048. ** use the actual amount of space allocated for the hash table (which
  23049. ** may be larger than the requested amount).
  23050. */
  23051. sqlite3BeginBenignMalloc();
  23052. new_ht = (struct _ht *)sqlite3Malloc( new_size*sizeof(struct _ht) );
  23053. sqlite3EndBenignMalloc();
  23054. if( new_ht==0 ) return 0;
  23055. sqlite3_free(pH->ht);
  23056. pH->ht = new_ht;
  23057. pH->htsize = new_size = sqlite3MallocSize(new_ht)/sizeof(struct _ht);
  23058. memset(new_ht, 0, new_size*sizeof(struct _ht));
  23059. for(elem=pH->first, pH->first=0; elem; elem = next_elem){
  23060. unsigned int h = strHash(elem->pKey) % new_size;
  23061. next_elem = elem->next;
  23062. insertElement(pH, &new_ht[h], elem);
  23063. }
  23064. return 1;
  23065. }
  23066. /* This function (for internal use only) locates an element in an
  23067. ** hash table that matches the given key. The hash for this key is
  23068. ** also computed and returned in the *pH parameter.
  23069. */
  23070. static HashElem *findElementWithHash(
  23071. const Hash *pH, /* The pH to be searched */
  23072. const char *pKey, /* The key we are searching for */
  23073. unsigned int *pHash /* Write the hash value here */
  23074. ){
  23075. HashElem *elem; /* Used to loop thru the element list */
  23076. int count; /* Number of elements left to test */
  23077. unsigned int h; /* The computed hash */
  23078. if( pH->ht ){
  23079. struct _ht *pEntry;
  23080. h = strHash(pKey) % pH->htsize;
  23081. pEntry = &pH->ht[h];
  23082. elem = pEntry->chain;
  23083. count = pEntry->count;
  23084. }else{
  23085. h = 0;
  23086. elem = pH->first;
  23087. count = pH->count;
  23088. }
  23089. *pHash = h;
  23090. while( count-- ){
  23091. assert( elem!=0 );
  23092. if( sqlite3StrICmp(elem->pKey,pKey)==0 ){
  23093. return elem;
  23094. }
  23095. elem = elem->next;
  23096. }
  23097. return 0;
  23098. }
  23099. /* Remove a single entry from the hash table given a pointer to that
  23100. ** element and a hash on the element's key.
  23101. */
  23102. static void removeElementGivenHash(
  23103. Hash *pH, /* The pH containing "elem" */
  23104. HashElem* elem, /* The element to be removed from the pH */
  23105. unsigned int h /* Hash value for the element */
  23106. ){
  23107. struct _ht *pEntry;
  23108. if( elem->prev ){
  23109. elem->prev->next = elem->next;
  23110. }else{
  23111. pH->first = elem->next;
  23112. }
  23113. if( elem->next ){
  23114. elem->next->prev = elem->prev;
  23115. }
  23116. if( pH->ht ){
  23117. pEntry = &pH->ht[h];
  23118. if( pEntry->chain==elem ){
  23119. pEntry->chain = elem->next;
  23120. }
  23121. pEntry->count--;
  23122. assert( pEntry->count>=0 );
  23123. }
  23124. sqlite3_free( elem );
  23125. pH->count--;
  23126. if( pH->count==0 ){
  23127. assert( pH->first==0 );
  23128. assert( pH->count==0 );
  23129. sqlite3HashClear(pH);
  23130. }
  23131. }
  23132. /* Attempt to locate an element of the hash table pH with a key
  23133. ** that matches pKey. Return the data for this element if it is
  23134. ** found, or NULL if there is no match.
  23135. */
  23136. SQLITE_PRIVATE void *sqlite3HashFind(const Hash *pH, const char *pKey){
  23137. HashElem *elem; /* The element that matches key */
  23138. unsigned int h; /* A hash on key */
  23139. assert( pH!=0 );
  23140. assert( pKey!=0 );
  23141. elem = findElementWithHash(pH, pKey, &h);
  23142. return elem ? elem->data : 0;
  23143. }
  23144. /* Insert an element into the hash table pH. The key is pKey
  23145. ** and the data is "data".
  23146. **
  23147. ** If no element exists with a matching key, then a new
  23148. ** element is created and NULL is returned.
  23149. **
  23150. ** If another element already exists with the same key, then the
  23151. ** new data replaces the old data and the old data is returned.
  23152. ** The key is not copied in this instance. If a malloc fails, then
  23153. ** the new data is returned and the hash table is unchanged.
  23154. **
  23155. ** If the "data" parameter to this function is NULL, then the
  23156. ** element corresponding to "key" is removed from the hash table.
  23157. */
  23158. SQLITE_PRIVATE void *sqlite3HashInsert(Hash *pH, const char *pKey, void *data){
  23159. unsigned int h; /* the hash of the key modulo hash table size */
  23160. HashElem *elem; /* Used to loop thru the element list */
  23161. HashElem *new_elem; /* New element added to the pH */
  23162. assert( pH!=0 );
  23163. assert( pKey!=0 );
  23164. elem = findElementWithHash(pH,pKey,&h);
  23165. if( elem ){
  23166. void *old_data = elem->data;
  23167. if( data==0 ){
  23168. removeElementGivenHash(pH,elem,h);
  23169. }else{
  23170. elem->data = data;
  23171. elem->pKey = pKey;
  23172. }
  23173. return old_data;
  23174. }
  23175. if( data==0 ) return 0;
  23176. new_elem = (HashElem*)sqlite3Malloc( sizeof(HashElem) );
  23177. if( new_elem==0 ) return data;
  23178. new_elem->pKey = pKey;
  23179. new_elem->data = data;
  23180. pH->count++;
  23181. if( pH->count>=10 && pH->count > 2*pH->htsize ){
  23182. if( rehash(pH, pH->count*2) ){
  23183. assert( pH->htsize>0 );
  23184. h = strHash(pKey) % pH->htsize;
  23185. }
  23186. }
  23187. insertElement(pH, pH->ht ? &pH->ht[h] : 0, new_elem);
  23188. return 0;
  23189. }
  23190. /************** End of hash.c ************************************************/
  23191. /************** Begin file opcodes.c *****************************************/
  23192. /* Automatically generated. Do not edit */
  23193. /* See the mkopcodec.awk script for details. */
  23194. #if !defined(SQLITE_OMIT_EXPLAIN) || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
  23195. #if defined(SQLITE_ENABLE_EXPLAIN_COMMENTS) || defined(SQLITE_DEBUG)
  23196. # define OpHelp(X) "\0" X
  23197. #else
  23198. # define OpHelp(X)
  23199. #endif
  23200. SQLITE_PRIVATE const char *sqlite3OpcodeName(int i){
  23201. static const char *const azName[] = { "?",
  23202. /* 1 */ "Function" OpHelp("r[P3]=func(r[P2@P5])"),
  23203. /* 2 */ "Savepoint" OpHelp(""),
  23204. /* 3 */ "AutoCommit" OpHelp(""),
  23205. /* 4 */ "Transaction" OpHelp(""),
  23206. /* 5 */ "SorterNext" OpHelp(""),
  23207. /* 6 */ "PrevIfOpen" OpHelp(""),
  23208. /* 7 */ "NextIfOpen" OpHelp(""),
  23209. /* 8 */ "Prev" OpHelp(""),
  23210. /* 9 */ "Next" OpHelp(""),
  23211. /* 10 */ "AggStep" OpHelp("accum=r[P3] step(r[P2@P5])"),
  23212. /* 11 */ "Checkpoint" OpHelp(""),
  23213. /* 12 */ "JournalMode" OpHelp(""),
  23214. /* 13 */ "Vacuum" OpHelp(""),
  23215. /* 14 */ "VFilter" OpHelp("iplan=r[P3] zplan='P4'"),
  23216. /* 15 */ "VUpdate" OpHelp("data=r[P3@P2]"),
  23217. /* 16 */ "Goto" OpHelp(""),
  23218. /* 17 */ "Gosub" OpHelp(""),
  23219. /* 18 */ "Return" OpHelp(""),
  23220. /* 19 */ "Not" OpHelp("r[P2]= !r[P1]"),
  23221. /* 20 */ "InitCoroutine" OpHelp(""),
  23222. /* 21 */ "EndCoroutine" OpHelp(""),
  23223. /* 22 */ "Yield" OpHelp(""),
  23224. /* 23 */ "HaltIfNull" OpHelp("if r[P3]=null halt"),
  23225. /* 24 */ "Halt" OpHelp(""),
  23226. /* 25 */ "Integer" OpHelp("r[P2]=P1"),
  23227. /* 26 */ "Int64" OpHelp("r[P2]=P4"),
  23228. /* 27 */ "String" OpHelp("r[P2]='P4' (len=P1)"),
  23229. /* 28 */ "Null" OpHelp("r[P2..P3]=NULL"),
  23230. /* 29 */ "SoftNull" OpHelp("r[P1]=NULL"),
  23231. /* 30 */ "Blob" OpHelp("r[P2]=P4 (len=P1)"),
  23232. /* 31 */ "Variable" OpHelp("r[P2]=parameter(P1,P4)"),
  23233. /* 32 */ "Move" OpHelp("r[P2@P3]=r[P1@P3]"),
  23234. /* 33 */ "Copy" OpHelp("r[P2@P3+1]=r[P1@P3+1]"),
  23235. /* 34 */ "SCopy" OpHelp("r[P2]=r[P1]"),
  23236. /* 35 */ "ResultRow" OpHelp("output=r[P1@P2]"),
  23237. /* 36 */ "CollSeq" OpHelp(""),
  23238. /* 37 */ "AddImm" OpHelp("r[P1]=r[P1]+P2"),
  23239. /* 38 */ "MustBeInt" OpHelp(""),
  23240. /* 39 */ "RealAffinity" OpHelp(""),
  23241. /* 40 */ "Cast" OpHelp("affinity(r[P1])"),
  23242. /* 41 */ "Permutation" OpHelp(""),
  23243. /* 42 */ "Compare" OpHelp("r[P1@P3] <-> r[P2@P3]"),
  23244. /* 43 */ "Jump" OpHelp(""),
  23245. /* 44 */ "Once" OpHelp(""),
  23246. /* 45 */ "If" OpHelp(""),
  23247. /* 46 */ "IfNot" OpHelp(""),
  23248. /* 47 */ "Column" OpHelp("r[P3]=PX"),
  23249. /* 48 */ "Affinity" OpHelp("affinity(r[P1@P2])"),
  23250. /* 49 */ "MakeRecord" OpHelp("r[P3]=mkrec(r[P1@P2])"),
  23251. /* 50 */ "Count" OpHelp("r[P2]=count()"),
  23252. /* 51 */ "ReadCookie" OpHelp(""),
  23253. /* 52 */ "SetCookie" OpHelp(""),
  23254. /* 53 */ "ReopenIdx" OpHelp("root=P2 iDb=P3"),
  23255. /* 54 */ "OpenRead" OpHelp("root=P2 iDb=P3"),
  23256. /* 55 */ "OpenWrite" OpHelp("root=P2 iDb=P3"),
  23257. /* 56 */ "OpenAutoindex" OpHelp("nColumn=P2"),
  23258. /* 57 */ "OpenEphemeral" OpHelp("nColumn=P2"),
  23259. /* 58 */ "SorterOpen" OpHelp(""),
  23260. /* 59 */ "SequenceTest" OpHelp("if( cursor[P1].ctr++ ) pc = P2"),
  23261. /* 60 */ "OpenPseudo" OpHelp("P3 columns in r[P2]"),
  23262. /* 61 */ "Close" OpHelp(""),
  23263. /* 62 */ "SeekLT" OpHelp("key=r[P3@P4]"),
  23264. /* 63 */ "SeekLE" OpHelp("key=r[P3@P4]"),
  23265. /* 64 */ "SeekGE" OpHelp("key=r[P3@P4]"),
  23266. /* 65 */ "SeekGT" OpHelp("key=r[P3@P4]"),
  23267. /* 66 */ "Seek" OpHelp("intkey=r[P2]"),
  23268. /* 67 */ "NoConflict" OpHelp("key=r[P3@P4]"),
  23269. /* 68 */ "NotFound" OpHelp("key=r[P3@P4]"),
  23270. /* 69 */ "Found" OpHelp("key=r[P3@P4]"),
  23271. /* 70 */ "NotExists" OpHelp("intkey=r[P3]"),
  23272. /* 71 */ "Or" OpHelp("r[P3]=(r[P1] || r[P2])"),
  23273. /* 72 */ "And" OpHelp("r[P3]=(r[P1] && r[P2])"),
  23274. /* 73 */ "Sequence" OpHelp("r[P2]=cursor[P1].ctr++"),
  23275. /* 74 */ "NewRowid" OpHelp("r[P2]=rowid"),
  23276. /* 75 */ "Insert" OpHelp("intkey=r[P3] data=r[P2]"),
  23277. /* 76 */ "IsNull" OpHelp("if r[P1]==NULL goto P2"),
  23278. /* 77 */ "NotNull" OpHelp("if r[P1]!=NULL goto P2"),
  23279. /* 78 */ "Ne" OpHelp("if r[P1]!=r[P3] goto P2"),
  23280. /* 79 */ "Eq" OpHelp("if r[P1]==r[P3] goto P2"),
  23281. /* 80 */ "Gt" OpHelp("if r[P1]>r[P3] goto P2"),
  23282. /* 81 */ "Le" OpHelp("if r[P1]<=r[P3] goto P2"),
  23283. /* 82 */ "Lt" OpHelp("if r[P1]<r[P3] goto P2"),
  23284. /* 83 */ "Ge" OpHelp("if r[P1]>=r[P3] goto P2"),
  23285. /* 84 */ "InsertInt" OpHelp("intkey=P3 data=r[P2]"),
  23286. /* 85 */ "BitAnd" OpHelp("r[P3]=r[P1]&r[P2]"),
  23287. /* 86 */ "BitOr" OpHelp("r[P3]=r[P1]|r[P2]"),
  23288. /* 87 */ "ShiftLeft" OpHelp("r[P3]=r[P2]<<r[P1]"),
  23289. /* 88 */ "ShiftRight" OpHelp("r[P3]=r[P2]>>r[P1]"),
  23290. /* 89 */ "Add" OpHelp("r[P3]=r[P1]+r[P2]"),
  23291. /* 90 */ "Subtract" OpHelp("r[P3]=r[P2]-r[P1]"),
  23292. /* 91 */ "Multiply" OpHelp("r[P3]=r[P1]*r[P2]"),
  23293. /* 92 */ "Divide" OpHelp("r[P3]=r[P2]/r[P1]"),
  23294. /* 93 */ "Remainder" OpHelp("r[P3]=r[P2]%r[P1]"),
  23295. /* 94 */ "Concat" OpHelp("r[P3]=r[P2]+r[P1]"),
  23296. /* 95 */ "Delete" OpHelp(""),
  23297. /* 96 */ "BitNot" OpHelp("r[P1]= ~r[P1]"),
  23298. /* 97 */ "String8" OpHelp("r[P2]='P4'"),
  23299. /* 98 */ "ResetCount" OpHelp(""),
  23300. /* 99 */ "SorterCompare" OpHelp("if key(P1)!=trim(r[P3],P4) goto P2"),
  23301. /* 100 */ "SorterData" OpHelp("r[P2]=data"),
  23302. /* 101 */ "RowKey" OpHelp("r[P2]=key"),
  23303. /* 102 */ "RowData" OpHelp("r[P2]=data"),
  23304. /* 103 */ "Rowid" OpHelp("r[P2]=rowid"),
  23305. /* 104 */ "NullRow" OpHelp(""),
  23306. /* 105 */ "Last" OpHelp(""),
  23307. /* 106 */ "SorterSort" OpHelp(""),
  23308. /* 107 */ "Sort" OpHelp(""),
  23309. /* 108 */ "Rewind" OpHelp(""),
  23310. /* 109 */ "SorterInsert" OpHelp(""),
  23311. /* 110 */ "IdxInsert" OpHelp("key=r[P2]"),
  23312. /* 111 */ "IdxDelete" OpHelp("key=r[P2@P3]"),
  23313. /* 112 */ "IdxRowid" OpHelp("r[P2]=rowid"),
  23314. /* 113 */ "IdxLE" OpHelp("key=r[P3@P4]"),
  23315. /* 114 */ "IdxGT" OpHelp("key=r[P3@P4]"),
  23316. /* 115 */ "IdxLT" OpHelp("key=r[P3@P4]"),
  23317. /* 116 */ "IdxGE" OpHelp("key=r[P3@P4]"),
  23318. /* 117 */ "Destroy" OpHelp(""),
  23319. /* 118 */ "Clear" OpHelp(""),
  23320. /* 119 */ "ResetSorter" OpHelp(""),
  23321. /* 120 */ "CreateIndex" OpHelp("r[P2]=root iDb=P1"),
  23322. /* 121 */ "CreateTable" OpHelp("r[P2]=root iDb=P1"),
  23323. /* 122 */ "ParseSchema" OpHelp(""),
  23324. /* 123 */ "LoadAnalysis" OpHelp(""),
  23325. /* 124 */ "DropTable" OpHelp(""),
  23326. /* 125 */ "DropIndex" OpHelp(""),
  23327. /* 126 */ "DropTrigger" OpHelp(""),
  23328. /* 127 */ "IntegrityCk" OpHelp(""),
  23329. /* 128 */ "RowSetAdd" OpHelp("rowset(P1)=r[P2]"),
  23330. /* 129 */ "RowSetRead" OpHelp("r[P3]=rowset(P1)"),
  23331. /* 130 */ "RowSetTest" OpHelp("if r[P3] in rowset(P1) goto P2"),
  23332. /* 131 */ "Program" OpHelp(""),
  23333. /* 132 */ "Param" OpHelp(""),
  23334. /* 133 */ "Real" OpHelp("r[P2]=P4"),
  23335. /* 134 */ "FkCounter" OpHelp("fkctr[P1]+=P2"),
  23336. /* 135 */ "FkIfZero" OpHelp("if fkctr[P1]==0 goto P2"),
  23337. /* 136 */ "MemMax" OpHelp("r[P1]=max(r[P1],r[P2])"),
  23338. /* 137 */ "IfPos" OpHelp("if r[P1]>0 goto P2"),
  23339. /* 138 */ "IfNeg" OpHelp("r[P1]+=P3, if r[P1]<0 goto P2"),
  23340. /* 139 */ "IfZero" OpHelp("r[P1]+=P3, if r[P1]==0 goto P2"),
  23341. /* 140 */ "AggFinal" OpHelp("accum=r[P1] N=P2"),
  23342. /* 141 */ "IncrVacuum" OpHelp(""),
  23343. /* 142 */ "Expire" OpHelp(""),
  23344. /* 143 */ "TableLock" OpHelp("iDb=P1 root=P2 write=P3"),
  23345. /* 144 */ "VBegin" OpHelp(""),
  23346. /* 145 */ "VCreate" OpHelp(""),
  23347. /* 146 */ "VDestroy" OpHelp(""),
  23348. /* 147 */ "VOpen" OpHelp(""),
  23349. /* 148 */ "VColumn" OpHelp("r[P3]=vcolumn(P2)"),
  23350. /* 149 */ "VNext" OpHelp(""),
  23351. /* 150 */ "VRename" OpHelp(""),
  23352. /* 151 */ "Pagecount" OpHelp(""),
  23353. /* 152 */ "MaxPgcnt" OpHelp(""),
  23354. /* 153 */ "Init" OpHelp("Start at P2"),
  23355. /* 154 */ "Noop" OpHelp(""),
  23356. /* 155 */ "Explain" OpHelp(""),
  23357. };
  23358. return azName[i];
  23359. }
  23360. #endif
  23361. /************** End of opcodes.c *********************************************/
  23362. /************** Begin file os_unix.c *****************************************/
  23363. /*
  23364. ** 2004 May 22
  23365. **
  23366. ** The author disclaims copyright to this source code. In place of
  23367. ** a legal notice, here is a blessing:
  23368. **
  23369. ** May you do good and not evil.
  23370. ** May you find forgiveness for yourself and forgive others.
  23371. ** May you share freely, never taking more than you give.
  23372. **
  23373. ******************************************************************************
  23374. **
  23375. ** This file contains the VFS implementation for unix-like operating systems
  23376. ** include Linux, MacOSX, *BSD, QNX, VxWorks, AIX, HPUX, and others.
  23377. **
  23378. ** There are actually several different VFS implementations in this file.
  23379. ** The differences are in the way that file locking is done. The default
  23380. ** implementation uses Posix Advisory Locks. Alternative implementations
  23381. ** use flock(), dot-files, various proprietary locking schemas, or simply
  23382. ** skip locking all together.
  23383. **
  23384. ** This source file is organized into divisions where the logic for various
  23385. ** subfunctions is contained within the appropriate division. PLEASE
  23386. ** KEEP THE STRUCTURE OF THIS FILE INTACT. New code should be placed
  23387. ** in the correct division and should be clearly labeled.
  23388. **
  23389. ** The layout of divisions is as follows:
  23390. **
  23391. ** * General-purpose declarations and utility functions.
  23392. ** * Unique file ID logic used by VxWorks.
  23393. ** * Various locking primitive implementations (all except proxy locking):
  23394. ** + for Posix Advisory Locks
  23395. ** + for no-op locks
  23396. ** + for dot-file locks
  23397. ** + for flock() locking
  23398. ** + for named semaphore locks (VxWorks only)
  23399. ** + for AFP filesystem locks (MacOSX only)
  23400. ** * sqlite3_file methods not associated with locking.
  23401. ** * Definitions of sqlite3_io_methods objects for all locking
  23402. ** methods plus "finder" functions for each locking method.
  23403. ** * sqlite3_vfs method implementations.
  23404. ** * Locking primitives for the proxy uber-locking-method. (MacOSX only)
  23405. ** * Definitions of sqlite3_vfs objects for all locking methods
  23406. ** plus implementations of sqlite3_os_init() and sqlite3_os_end().
  23407. */
  23408. #if SQLITE_OS_UNIX /* This file is used on unix only */
  23409. /*
  23410. ** There are various methods for file locking used for concurrency
  23411. ** control:
  23412. **
  23413. ** 1. POSIX locking (the default),
  23414. ** 2. No locking,
  23415. ** 3. Dot-file locking,
  23416. ** 4. flock() locking,
  23417. ** 5. AFP locking (OSX only),
  23418. ** 6. Named POSIX semaphores (VXWorks only),
  23419. ** 7. proxy locking. (OSX only)
  23420. **
  23421. ** Styles 4, 5, and 7 are only available of SQLITE_ENABLE_LOCKING_STYLE
  23422. ** is defined to 1. The SQLITE_ENABLE_LOCKING_STYLE also enables automatic
  23423. ** selection of the appropriate locking style based on the filesystem
  23424. ** where the database is located.
  23425. */
  23426. #if !defined(SQLITE_ENABLE_LOCKING_STYLE)
  23427. # if defined(__APPLE__)
  23428. # define SQLITE_ENABLE_LOCKING_STYLE 1
  23429. # else
  23430. # define SQLITE_ENABLE_LOCKING_STYLE 0
  23431. # endif
  23432. #endif
  23433. /*
  23434. ** Define the OS_VXWORKS pre-processor macro to 1 if building on
  23435. ** vxworks, or 0 otherwise.
  23436. */
  23437. #ifndef OS_VXWORKS
  23438. # if defined(__RTP__) || defined(_WRS_KERNEL)
  23439. # define OS_VXWORKS 1
  23440. # else
  23441. # define OS_VXWORKS 0
  23442. # endif
  23443. #endif
  23444. /*
  23445. ** standard include files.
  23446. */
  23447. #include <sys/types.h>
  23448. #include <sys/stat.h>
  23449. #include <fcntl.h>
  23450. #include <unistd.h>
  23451. /* #include <time.h> */
  23452. #include <sys/time.h>
  23453. #include <errno.h>
  23454. #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
  23455. # include <sys/mman.h>
  23456. #endif
  23457. #if SQLITE_ENABLE_LOCKING_STYLE || OS_VXWORKS
  23458. # include <sys/ioctl.h>
  23459. # if OS_VXWORKS
  23460. # include <semaphore.h>
  23461. # include <limits.h>
  23462. # else
  23463. # include <sys/file.h>
  23464. # include <sys/param.h>
  23465. # endif
  23466. #endif /* SQLITE_ENABLE_LOCKING_STYLE */
  23467. #if defined(__APPLE__) || (SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS)
  23468. # include <sys/mount.h>
  23469. #endif
  23470. #ifdef HAVE_UTIME
  23471. # include <utime.h>
  23472. #endif
  23473. /*
  23474. ** Allowed values of unixFile.fsFlags
  23475. */
  23476. #define SQLITE_FSFLAGS_IS_MSDOS 0x1
  23477. /*
  23478. ** If we are to be thread-safe, include the pthreads header and define
  23479. ** the SQLITE_UNIX_THREADS macro.
  23480. */
  23481. #if SQLITE_THREADSAFE
  23482. /* # include <pthread.h> */
  23483. # define SQLITE_UNIX_THREADS 1
  23484. #endif
  23485. /*
  23486. ** Default permissions when creating a new file
  23487. */
  23488. #ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
  23489. # define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
  23490. #endif
  23491. /*
  23492. ** Default permissions when creating auto proxy dir
  23493. */
  23494. #ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
  23495. # define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
  23496. #endif
  23497. /*
  23498. ** Maximum supported path-length.
  23499. */
  23500. #define MAX_PATHNAME 512
  23501. /*
  23502. ** Only set the lastErrno if the error code is a real error and not
  23503. ** a normal expected return code of SQLITE_BUSY or SQLITE_OK
  23504. */
  23505. #define IS_LOCK_ERROR(x) ((x != SQLITE_OK) && (x != SQLITE_BUSY))
  23506. /* Forward references */
  23507. typedef struct unixShm unixShm; /* Connection shared memory */
  23508. typedef struct unixShmNode unixShmNode; /* Shared memory instance */
  23509. typedef struct unixInodeInfo unixInodeInfo; /* An i-node */
  23510. typedef struct UnixUnusedFd UnixUnusedFd; /* An unused file descriptor */
  23511. /*
  23512. ** Sometimes, after a file handle is closed by SQLite, the file descriptor
  23513. ** cannot be closed immediately. In these cases, instances of the following
  23514. ** structure are used to store the file descriptor while waiting for an
  23515. ** opportunity to either close or reuse it.
  23516. */
  23517. struct UnixUnusedFd {
  23518. int fd; /* File descriptor to close */
  23519. int flags; /* Flags this file descriptor was opened with */
  23520. UnixUnusedFd *pNext; /* Next unused file descriptor on same file */
  23521. };
  23522. /*
  23523. ** The unixFile structure is subclass of sqlite3_file specific to the unix
  23524. ** VFS implementations.
  23525. */
  23526. typedef struct unixFile unixFile;
  23527. struct unixFile {
  23528. sqlite3_io_methods const *pMethod; /* Always the first entry */
  23529. sqlite3_vfs *pVfs; /* The VFS that created this unixFile */
  23530. unixInodeInfo *pInode; /* Info about locks on this inode */
  23531. int h; /* The file descriptor */
  23532. unsigned char eFileLock; /* The type of lock held on this fd */
  23533. unsigned short int ctrlFlags; /* Behavioral bits. UNIXFILE_* flags */
  23534. int lastErrno; /* The unix errno from last I/O error */
  23535. void *lockingContext; /* Locking style specific state */
  23536. UnixUnusedFd *pUnused; /* Pre-allocated UnixUnusedFd */
  23537. const char *zPath; /* Name of the file */
  23538. unixShm *pShm; /* Shared memory segment information */
  23539. int szChunk; /* Configured by FCNTL_CHUNK_SIZE */
  23540. #if SQLITE_MAX_MMAP_SIZE>0
  23541. int nFetchOut; /* Number of outstanding xFetch refs */
  23542. sqlite3_int64 mmapSize; /* Usable size of mapping at pMapRegion */
  23543. sqlite3_int64 mmapSizeActual; /* Actual size of mapping at pMapRegion */
  23544. sqlite3_int64 mmapSizeMax; /* Configured FCNTL_MMAP_SIZE value */
  23545. void *pMapRegion; /* Memory mapped region */
  23546. #endif
  23547. #ifdef __QNXNTO__
  23548. int sectorSize; /* Device sector size */
  23549. int deviceCharacteristics; /* Precomputed device characteristics */
  23550. #endif
  23551. #if SQLITE_ENABLE_LOCKING_STYLE
  23552. int openFlags; /* The flags specified at open() */
  23553. #endif
  23554. #if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__)
  23555. unsigned fsFlags; /* cached details from statfs() */
  23556. #endif
  23557. #if OS_VXWORKS
  23558. struct vxworksFileId *pId; /* Unique file ID */
  23559. #endif
  23560. #ifdef SQLITE_DEBUG
  23561. /* The next group of variables are used to track whether or not the
  23562. ** transaction counter in bytes 24-27 of database files are updated
  23563. ** whenever any part of the database changes. An assertion fault will
  23564. ** occur if a file is updated without also updating the transaction
  23565. ** counter. This test is made to avoid new problems similar to the
  23566. ** one described by ticket #3584.
  23567. */
  23568. unsigned char transCntrChng; /* True if the transaction counter changed */
  23569. unsigned char dbUpdate; /* True if any part of database file changed */
  23570. unsigned char inNormalWrite; /* True if in a normal write operation */
  23571. #endif
  23572. #ifdef SQLITE_TEST
  23573. /* In test mode, increase the size of this structure a bit so that
  23574. ** it is larger than the struct CrashFile defined in test6.c.
  23575. */
  23576. char aPadding[32];
  23577. #endif
  23578. };
  23579. /* This variable holds the process id (pid) from when the xRandomness()
  23580. ** method was called. If xOpen() is called from a different process id,
  23581. ** indicating that a fork() has occurred, the PRNG will be reset.
  23582. */
  23583. static int randomnessPid = 0;
  23584. /*
  23585. ** Allowed values for the unixFile.ctrlFlags bitmask:
  23586. */
  23587. #define UNIXFILE_EXCL 0x01 /* Connections from one process only */
  23588. #define UNIXFILE_RDONLY 0x02 /* Connection is read only */
  23589. #define UNIXFILE_PERSIST_WAL 0x04 /* Persistent WAL mode */
  23590. #ifndef SQLITE_DISABLE_DIRSYNC
  23591. # define UNIXFILE_DIRSYNC 0x08 /* Directory sync needed */
  23592. #else
  23593. # define UNIXFILE_DIRSYNC 0x00
  23594. #endif
  23595. #define UNIXFILE_PSOW 0x10 /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
  23596. #define UNIXFILE_DELETE 0x20 /* Delete on close */
  23597. #define UNIXFILE_URI 0x40 /* Filename might have query parameters */
  23598. #define UNIXFILE_NOLOCK 0x80 /* Do no file locking */
  23599. #define UNIXFILE_WARNED 0x0100 /* verifyDbFile() warnings have been issued */
  23600. /*
  23601. ** Include code that is common to all os_*.c files
  23602. */
  23603. /************** Include os_common.h in the middle of os_unix.c ***************/
  23604. /************** Begin file os_common.h ***************************************/
  23605. /*
  23606. ** 2004 May 22
  23607. **
  23608. ** The author disclaims copyright to this source code. In place of
  23609. ** a legal notice, here is a blessing:
  23610. **
  23611. ** May you do good and not evil.
  23612. ** May you find forgiveness for yourself and forgive others.
  23613. ** May you share freely, never taking more than you give.
  23614. **
  23615. ******************************************************************************
  23616. **
  23617. ** This file contains macros and a little bit of code that is common to
  23618. ** all of the platform-specific files (os_*.c) and is #included into those
  23619. ** files.
  23620. **
  23621. ** This file should be #included by the os_*.c files only. It is not a
  23622. ** general purpose header file.
  23623. */
  23624. #ifndef _OS_COMMON_H_
  23625. #define _OS_COMMON_H_
  23626. /*
  23627. ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
  23628. ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
  23629. ** switch. The following code should catch this problem at compile-time.
  23630. */
  23631. #ifdef MEMORY_DEBUG
  23632. # error "The MEMORY_DEBUG macro is obsolete. Use SQLITE_DEBUG instead."
  23633. #endif
  23634. #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
  23635. # ifndef SQLITE_DEBUG_OS_TRACE
  23636. # define SQLITE_DEBUG_OS_TRACE 0
  23637. # endif
  23638. int sqlite3OSTrace = SQLITE_DEBUG_OS_TRACE;
  23639. # define OSTRACE(X) if( sqlite3OSTrace ) sqlite3DebugPrintf X
  23640. #else
  23641. # define OSTRACE(X)
  23642. #endif
  23643. /*
  23644. ** Macros for performance tracing. Normally turned off. Only works
  23645. ** on i486 hardware.
  23646. */
  23647. #ifdef SQLITE_PERFORMANCE_TRACE
  23648. /*
  23649. ** hwtime.h contains inline assembler code for implementing
  23650. ** high-performance timing routines.
  23651. */
  23652. /************** Include hwtime.h in the middle of os_common.h ****************/
  23653. /************** Begin file hwtime.h ******************************************/
  23654. /*
  23655. ** 2008 May 27
  23656. **
  23657. ** The author disclaims copyright to this source code. In place of
  23658. ** a legal notice, here is a blessing:
  23659. **
  23660. ** May you do good and not evil.
  23661. ** May you find forgiveness for yourself and forgive others.
  23662. ** May you share freely, never taking more than you give.
  23663. **
  23664. ******************************************************************************
  23665. **
  23666. ** This file contains inline asm code for retrieving "high-performance"
  23667. ** counters for x86 class CPUs.
  23668. */
  23669. #ifndef _HWTIME_H_
  23670. #define _HWTIME_H_
  23671. /*
  23672. ** The following routine only works on pentium-class (or newer) processors.
  23673. ** It uses the RDTSC opcode to read the cycle count value out of the
  23674. ** processor and returns that value. This can be used for high-res
  23675. ** profiling.
  23676. */
  23677. #if (defined(__GNUC__) || defined(_MSC_VER)) && \
  23678. (defined(i386) || defined(__i386__) || defined(_M_IX86))
  23679. #if defined(__GNUC__)
  23680. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  23681. unsigned int lo, hi;
  23682. __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
  23683. return (sqlite_uint64)hi << 32 | lo;
  23684. }
  23685. #elif defined(_MSC_VER)
  23686. __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
  23687. __asm {
  23688. rdtsc
  23689. ret ; return value at EDX:EAX
  23690. }
  23691. }
  23692. #endif
  23693. #elif (defined(__GNUC__) && defined(__x86_64__))
  23694. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  23695. unsigned long val;
  23696. __asm__ __volatile__ ("rdtsc" : "=A" (val));
  23697. return val;
  23698. }
  23699. #elif (defined(__GNUC__) && defined(__ppc__))
  23700. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  23701. unsigned long long retval;
  23702. unsigned long junk;
  23703. __asm__ __volatile__ ("\n\
  23704. 1: mftbu %1\n\
  23705. mftb %L0\n\
  23706. mftbu %0\n\
  23707. cmpw %0,%1\n\
  23708. bne 1b"
  23709. : "=r" (retval), "=r" (junk));
  23710. return retval;
  23711. }
  23712. #else
  23713. #error Need implementation of sqlite3Hwtime() for your platform.
  23714. /*
  23715. ** To compile without implementing sqlite3Hwtime() for your platform,
  23716. ** you can remove the above #error and use the following
  23717. ** stub function. You will lose timing support for many
  23718. ** of the debugging and testing utilities, but it should at
  23719. ** least compile and run.
  23720. */
  23721. SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
  23722. #endif
  23723. #endif /* !defined(_HWTIME_H_) */
  23724. /************** End of hwtime.h **********************************************/
  23725. /************** Continuing where we left off in os_common.h ******************/
  23726. static sqlite_uint64 g_start;
  23727. static sqlite_uint64 g_elapsed;
  23728. #define TIMER_START g_start=sqlite3Hwtime()
  23729. #define TIMER_END g_elapsed=sqlite3Hwtime()-g_start
  23730. #define TIMER_ELAPSED g_elapsed
  23731. #else
  23732. #define TIMER_START
  23733. #define TIMER_END
  23734. #define TIMER_ELAPSED ((sqlite_uint64)0)
  23735. #endif
  23736. /*
  23737. ** If we compile with the SQLITE_TEST macro set, then the following block
  23738. ** of code will give us the ability to simulate a disk I/O error. This
  23739. ** is used for testing the I/O recovery logic.
  23740. */
  23741. #ifdef SQLITE_TEST
  23742. SQLITE_API int sqlite3_io_error_hit = 0; /* Total number of I/O Errors */
  23743. SQLITE_API int sqlite3_io_error_hardhit = 0; /* Number of non-benign errors */
  23744. SQLITE_API int sqlite3_io_error_pending = 0; /* Count down to first I/O error */
  23745. SQLITE_API int sqlite3_io_error_persist = 0; /* True if I/O errors persist */
  23746. SQLITE_API int sqlite3_io_error_benign = 0; /* True if errors are benign */
  23747. SQLITE_API int sqlite3_diskfull_pending = 0;
  23748. SQLITE_API int sqlite3_diskfull = 0;
  23749. #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
  23750. #define SimulateIOError(CODE) \
  23751. if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
  23752. || sqlite3_io_error_pending-- == 1 ) \
  23753. { local_ioerr(); CODE; }
  23754. static void local_ioerr(){
  23755. IOTRACE(("IOERR\n"));
  23756. sqlite3_io_error_hit++;
  23757. if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
  23758. }
  23759. #define SimulateDiskfullError(CODE) \
  23760. if( sqlite3_diskfull_pending ){ \
  23761. if( sqlite3_diskfull_pending == 1 ){ \
  23762. local_ioerr(); \
  23763. sqlite3_diskfull = 1; \
  23764. sqlite3_io_error_hit = 1; \
  23765. CODE; \
  23766. }else{ \
  23767. sqlite3_diskfull_pending--; \
  23768. } \
  23769. }
  23770. #else
  23771. #define SimulateIOErrorBenign(X)
  23772. #define SimulateIOError(A)
  23773. #define SimulateDiskfullError(A)
  23774. #endif
  23775. /*
  23776. ** When testing, keep a count of the number of open files.
  23777. */
  23778. #ifdef SQLITE_TEST
  23779. SQLITE_API int sqlite3_open_file_count = 0;
  23780. #define OpenCounter(X) sqlite3_open_file_count+=(X)
  23781. #else
  23782. #define OpenCounter(X)
  23783. #endif
  23784. #endif /* !defined(_OS_COMMON_H_) */
  23785. /************** End of os_common.h *******************************************/
  23786. /************** Continuing where we left off in os_unix.c ********************/
  23787. /*
  23788. ** Define various macros that are missing from some systems.
  23789. */
  23790. #ifndef O_LARGEFILE
  23791. # define O_LARGEFILE 0
  23792. #endif
  23793. #ifdef SQLITE_DISABLE_LFS
  23794. # undef O_LARGEFILE
  23795. # define O_LARGEFILE 0
  23796. #endif
  23797. #ifndef O_NOFOLLOW
  23798. # define O_NOFOLLOW 0
  23799. #endif
  23800. #ifndef O_BINARY
  23801. # define O_BINARY 0
  23802. #endif
  23803. /*
  23804. ** The threadid macro resolves to the thread-id or to 0. Used for
  23805. ** testing and debugging only.
  23806. */
  23807. #if SQLITE_THREADSAFE
  23808. #define threadid pthread_self()
  23809. #else
  23810. #define threadid 0
  23811. #endif
  23812. /*
  23813. ** HAVE_MREMAP defaults to true on Linux and false everywhere else.
  23814. */
  23815. #if !defined(HAVE_MREMAP)
  23816. # if defined(__linux__) && defined(_GNU_SOURCE)
  23817. # define HAVE_MREMAP 1
  23818. # else
  23819. # define HAVE_MREMAP 0
  23820. # endif
  23821. #endif
  23822. /*
  23823. ** Explicitly call the 64-bit version of lseek() on Android. Otherwise, lseek()
  23824. ** is the 32-bit version, even if _FILE_OFFSET_BITS=64 is defined.
  23825. */
  23826. #ifdef __ANDROID__
  23827. # define lseek lseek64
  23828. #endif
  23829. /*
  23830. ** Different Unix systems declare open() in different ways. Same use
  23831. ** open(const char*,int,mode_t). Others use open(const char*,int,...).
  23832. ** The difference is important when using a pointer to the function.
  23833. **
  23834. ** The safest way to deal with the problem is to always use this wrapper
  23835. ** which always has the same well-defined interface.
  23836. */
  23837. static int posixOpen(const char *zFile, int flags, int mode){
  23838. return open(zFile, flags, mode);
  23839. }
  23840. /*
  23841. ** On some systems, calls to fchown() will trigger a message in a security
  23842. ** log if they come from non-root processes. So avoid calling fchown() if
  23843. ** we are not running as root.
  23844. */
  23845. static int posixFchown(int fd, uid_t uid, gid_t gid){
  23846. #if OS_VXWORKS
  23847. return 0;
  23848. #else
  23849. return geteuid() ? 0 : fchown(fd,uid,gid);
  23850. #endif
  23851. }
  23852. /* Forward reference */
  23853. static int openDirectory(const char*, int*);
  23854. static int unixGetpagesize(void);
  23855. /*
  23856. ** Many system calls are accessed through pointer-to-functions so that
  23857. ** they may be overridden at runtime to facilitate fault injection during
  23858. ** testing and sandboxing. The following array holds the names and pointers
  23859. ** to all overrideable system calls.
  23860. */
  23861. static struct unix_syscall {
  23862. const char *zName; /* Name of the system call */
  23863. sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
  23864. sqlite3_syscall_ptr pDefault; /* Default value */
  23865. } aSyscall[] = {
  23866. { "open", (sqlite3_syscall_ptr)posixOpen, 0 },
  23867. #define osOpen ((int(*)(const char*,int,int))aSyscall[0].pCurrent)
  23868. { "close", (sqlite3_syscall_ptr)close, 0 },
  23869. #define osClose ((int(*)(int))aSyscall[1].pCurrent)
  23870. { "access", (sqlite3_syscall_ptr)access, 0 },
  23871. #define osAccess ((int(*)(const char*,int))aSyscall[2].pCurrent)
  23872. { "getcwd", (sqlite3_syscall_ptr)getcwd, 0 },
  23873. #define osGetcwd ((char*(*)(char*,size_t))aSyscall[3].pCurrent)
  23874. { "stat", (sqlite3_syscall_ptr)stat, 0 },
  23875. #define osStat ((int(*)(const char*,struct stat*))aSyscall[4].pCurrent)
  23876. /*
  23877. ** The DJGPP compiler environment looks mostly like Unix, but it
  23878. ** lacks the fcntl() system call. So redefine fcntl() to be something
  23879. ** that always succeeds. This means that locking does not occur under
  23880. ** DJGPP. But it is DOS - what did you expect?
  23881. */
  23882. #ifdef __DJGPP__
  23883. { "fstat", 0, 0 },
  23884. #define osFstat(a,b,c) 0
  23885. #else
  23886. { "fstat", (sqlite3_syscall_ptr)fstat, 0 },
  23887. #define osFstat ((int(*)(int,struct stat*))aSyscall[5].pCurrent)
  23888. #endif
  23889. { "ftruncate", (sqlite3_syscall_ptr)ftruncate, 0 },
  23890. #define osFtruncate ((int(*)(int,off_t))aSyscall[6].pCurrent)
  23891. { "fcntl", (sqlite3_syscall_ptr)fcntl, 0 },
  23892. #define osFcntl ((int(*)(int,int,...))aSyscall[7].pCurrent)
  23893. { "read", (sqlite3_syscall_ptr)read, 0 },
  23894. #define osRead ((ssize_t(*)(int,void*,size_t))aSyscall[8].pCurrent)
  23895. #if defined(USE_PREAD) || (SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS)
  23896. { "pread", (sqlite3_syscall_ptr)pread, 0 },
  23897. #else
  23898. { "pread", (sqlite3_syscall_ptr)0, 0 },
  23899. #endif
  23900. #define osPread ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[9].pCurrent)
  23901. #if defined(USE_PREAD64)
  23902. { "pread64", (sqlite3_syscall_ptr)pread64, 0 },
  23903. #else
  23904. { "pread64", (sqlite3_syscall_ptr)0, 0 },
  23905. #endif
  23906. #define osPread64 ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[10].pCurrent)
  23907. { "write", (sqlite3_syscall_ptr)write, 0 },
  23908. #define osWrite ((ssize_t(*)(int,const void*,size_t))aSyscall[11].pCurrent)
  23909. #if defined(USE_PREAD) || (SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS)
  23910. { "pwrite", (sqlite3_syscall_ptr)pwrite, 0 },
  23911. #else
  23912. { "pwrite", (sqlite3_syscall_ptr)0, 0 },
  23913. #endif
  23914. #define osPwrite ((ssize_t(*)(int,const void*,size_t,off_t))\
  23915. aSyscall[12].pCurrent)
  23916. #if defined(USE_PREAD64)
  23917. { "pwrite64", (sqlite3_syscall_ptr)pwrite64, 0 },
  23918. #else
  23919. { "pwrite64", (sqlite3_syscall_ptr)0, 0 },
  23920. #endif
  23921. #define osPwrite64 ((ssize_t(*)(int,const void*,size_t,off_t))\
  23922. aSyscall[13].pCurrent)
  23923. { "fchmod", (sqlite3_syscall_ptr)fchmod, 0 },
  23924. #define osFchmod ((int(*)(int,mode_t))aSyscall[14].pCurrent)
  23925. #if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
  23926. { "fallocate", (sqlite3_syscall_ptr)posix_fallocate, 0 },
  23927. #else
  23928. { "fallocate", (sqlite3_syscall_ptr)0, 0 },
  23929. #endif
  23930. #define osFallocate ((int(*)(int,off_t,off_t))aSyscall[15].pCurrent)
  23931. { "unlink", (sqlite3_syscall_ptr)unlink, 0 },
  23932. #define osUnlink ((int(*)(const char*))aSyscall[16].pCurrent)
  23933. { "openDirectory", (sqlite3_syscall_ptr)openDirectory, 0 },
  23934. #define osOpenDirectory ((int(*)(const char*,int*))aSyscall[17].pCurrent)
  23935. { "mkdir", (sqlite3_syscall_ptr)mkdir, 0 },
  23936. #define osMkdir ((int(*)(const char*,mode_t))aSyscall[18].pCurrent)
  23937. { "rmdir", (sqlite3_syscall_ptr)rmdir, 0 },
  23938. #define osRmdir ((int(*)(const char*))aSyscall[19].pCurrent)
  23939. { "fchown", (sqlite3_syscall_ptr)posixFchown, 0 },
  23940. #define osFchown ((int(*)(int,uid_t,gid_t))aSyscall[20].pCurrent)
  23941. #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
  23942. { "mmap", (sqlite3_syscall_ptr)mmap, 0 },
  23943. #define osMmap ((void*(*)(void*,size_t,int,int,int,off_t))aSyscall[21].pCurrent)
  23944. { "munmap", (sqlite3_syscall_ptr)munmap, 0 },
  23945. #define osMunmap ((void*(*)(void*,size_t))aSyscall[22].pCurrent)
  23946. #if HAVE_MREMAP
  23947. { "mremap", (sqlite3_syscall_ptr)mremap, 0 },
  23948. #else
  23949. { "mremap", (sqlite3_syscall_ptr)0, 0 },
  23950. #endif
  23951. #define osMremap ((void*(*)(void*,size_t,size_t,int,...))aSyscall[23].pCurrent)
  23952. { "getpagesize", (sqlite3_syscall_ptr)unixGetpagesize, 0 },
  23953. #define osGetpagesize ((int(*)(void))aSyscall[24].pCurrent)
  23954. #endif
  23955. }; /* End of the overrideable system calls */
  23956. /*
  23957. ** This is the xSetSystemCall() method of sqlite3_vfs for all of the
  23958. ** "unix" VFSes. Return SQLITE_OK opon successfully updating the
  23959. ** system call pointer, or SQLITE_NOTFOUND if there is no configurable
  23960. ** system call named zName.
  23961. */
  23962. static int unixSetSystemCall(
  23963. sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */
  23964. const char *zName, /* Name of system call to override */
  23965. sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */
  23966. ){
  23967. unsigned int i;
  23968. int rc = SQLITE_NOTFOUND;
  23969. UNUSED_PARAMETER(pNotUsed);
  23970. if( zName==0 ){
  23971. /* If no zName is given, restore all system calls to their default
  23972. ** settings and return NULL
  23973. */
  23974. rc = SQLITE_OK;
  23975. for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
  23976. if( aSyscall[i].pDefault ){
  23977. aSyscall[i].pCurrent = aSyscall[i].pDefault;
  23978. }
  23979. }
  23980. }else{
  23981. /* If zName is specified, operate on only the one system call
  23982. ** specified.
  23983. */
  23984. for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
  23985. if( strcmp(zName, aSyscall[i].zName)==0 ){
  23986. if( aSyscall[i].pDefault==0 ){
  23987. aSyscall[i].pDefault = aSyscall[i].pCurrent;
  23988. }
  23989. rc = SQLITE_OK;
  23990. if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
  23991. aSyscall[i].pCurrent = pNewFunc;
  23992. break;
  23993. }
  23994. }
  23995. }
  23996. return rc;
  23997. }
  23998. /*
  23999. ** Return the value of a system call. Return NULL if zName is not a
  24000. ** recognized system call name. NULL is also returned if the system call
  24001. ** is currently undefined.
  24002. */
  24003. static sqlite3_syscall_ptr unixGetSystemCall(
  24004. sqlite3_vfs *pNotUsed,
  24005. const char *zName
  24006. ){
  24007. unsigned int i;
  24008. UNUSED_PARAMETER(pNotUsed);
  24009. for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
  24010. if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
  24011. }
  24012. return 0;
  24013. }
  24014. /*
  24015. ** Return the name of the first system call after zName. If zName==NULL
  24016. ** then return the name of the first system call. Return NULL if zName
  24017. ** is the last system call or if zName is not the name of a valid
  24018. ** system call.
  24019. */
  24020. static const char *unixNextSystemCall(sqlite3_vfs *p, const char *zName){
  24021. int i = -1;
  24022. UNUSED_PARAMETER(p);
  24023. if( zName ){
  24024. for(i=0; i<ArraySize(aSyscall)-1; i++){
  24025. if( strcmp(zName, aSyscall[i].zName)==0 ) break;
  24026. }
  24027. }
  24028. for(i++; i<ArraySize(aSyscall); i++){
  24029. if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
  24030. }
  24031. return 0;
  24032. }
  24033. /*
  24034. ** Do not accept any file descriptor less than this value, in order to avoid
  24035. ** opening database file using file descriptors that are commonly used for
  24036. ** standard input, output, and error.
  24037. */
  24038. #ifndef SQLITE_MINIMUM_FILE_DESCRIPTOR
  24039. # define SQLITE_MINIMUM_FILE_DESCRIPTOR 3
  24040. #endif
  24041. /*
  24042. ** Invoke open(). Do so multiple times, until it either succeeds or
  24043. ** fails for some reason other than EINTR.
  24044. **
  24045. ** If the file creation mode "m" is 0 then set it to the default for
  24046. ** SQLite. The default is SQLITE_DEFAULT_FILE_PERMISSIONS (normally
  24047. ** 0644) as modified by the system umask. If m is not 0, then
  24048. ** make the file creation mode be exactly m ignoring the umask.
  24049. **
  24050. ** The m parameter will be non-zero only when creating -wal, -journal,
  24051. ** and -shm files. We want those files to have *exactly* the same
  24052. ** permissions as their original database, unadulterated by the umask.
  24053. ** In that way, if a database file is -rw-rw-rw or -rw-rw-r-, and a
  24054. ** transaction crashes and leaves behind hot journals, then any
  24055. ** process that is able to write to the database will also be able to
  24056. ** recover the hot journals.
  24057. */
  24058. static int robust_open(const char *z, int f, mode_t m){
  24059. int fd;
  24060. mode_t m2 = m ? m : SQLITE_DEFAULT_FILE_PERMISSIONS;
  24061. while(1){
  24062. #if defined(O_CLOEXEC)
  24063. fd = osOpen(z,f|O_CLOEXEC,m2);
  24064. #else
  24065. fd = osOpen(z,f,m2);
  24066. #endif
  24067. if( fd<0 ){
  24068. if( errno==EINTR ) continue;
  24069. break;
  24070. }
  24071. if( fd>=SQLITE_MINIMUM_FILE_DESCRIPTOR ) break;
  24072. osClose(fd);
  24073. sqlite3_log(SQLITE_WARNING,
  24074. "attempt to open \"%s\" as file descriptor %d", z, fd);
  24075. fd = -1;
  24076. if( osOpen("/dev/null", f, m)<0 ) break;
  24077. }
  24078. if( fd>=0 ){
  24079. if( m!=0 ){
  24080. struct stat statbuf;
  24081. if( osFstat(fd, &statbuf)==0
  24082. && statbuf.st_size==0
  24083. && (statbuf.st_mode&0777)!=m
  24084. ){
  24085. osFchmod(fd, m);
  24086. }
  24087. }
  24088. #if defined(FD_CLOEXEC) && (!defined(O_CLOEXEC) || O_CLOEXEC==0)
  24089. osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
  24090. #endif
  24091. }
  24092. return fd;
  24093. }
  24094. /*
  24095. ** Helper functions to obtain and relinquish the global mutex. The
  24096. ** global mutex is used to protect the unixInodeInfo and
  24097. ** vxworksFileId objects used by this file, all of which may be
  24098. ** shared by multiple threads.
  24099. **
  24100. ** Function unixMutexHeld() is used to assert() that the global mutex
  24101. ** is held when required. This function is only used as part of assert()
  24102. ** statements. e.g.
  24103. **
  24104. ** unixEnterMutex()
  24105. ** assert( unixMutexHeld() );
  24106. ** unixEnterLeave()
  24107. */
  24108. static void unixEnterMutex(void){
  24109. sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  24110. }
  24111. static void unixLeaveMutex(void){
  24112. sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  24113. }
  24114. #ifdef SQLITE_DEBUG
  24115. static int unixMutexHeld(void) {
  24116. return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  24117. }
  24118. #endif
  24119. #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
  24120. /*
  24121. ** Helper function for printing out trace information from debugging
  24122. ** binaries. This returns the string representation of the supplied
  24123. ** integer lock-type.
  24124. */
  24125. static const char *azFileLock(int eFileLock){
  24126. switch( eFileLock ){
  24127. case NO_LOCK: return "NONE";
  24128. case SHARED_LOCK: return "SHARED";
  24129. case RESERVED_LOCK: return "RESERVED";
  24130. case PENDING_LOCK: return "PENDING";
  24131. case EXCLUSIVE_LOCK: return "EXCLUSIVE";
  24132. }
  24133. return "ERROR";
  24134. }
  24135. #endif
  24136. #ifdef SQLITE_LOCK_TRACE
  24137. /*
  24138. ** Print out information about all locking operations.
  24139. **
  24140. ** This routine is used for troubleshooting locks on multithreaded
  24141. ** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
  24142. ** command-line option on the compiler. This code is normally
  24143. ** turned off.
  24144. */
  24145. static int lockTrace(int fd, int op, struct flock *p){
  24146. char *zOpName, *zType;
  24147. int s;
  24148. int savedErrno;
  24149. if( op==F_GETLK ){
  24150. zOpName = "GETLK";
  24151. }else if( op==F_SETLK ){
  24152. zOpName = "SETLK";
  24153. }else{
  24154. s = osFcntl(fd, op, p);
  24155. sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
  24156. return s;
  24157. }
  24158. if( p->l_type==F_RDLCK ){
  24159. zType = "RDLCK";
  24160. }else if( p->l_type==F_WRLCK ){
  24161. zType = "WRLCK";
  24162. }else if( p->l_type==F_UNLCK ){
  24163. zType = "UNLCK";
  24164. }else{
  24165. assert( 0 );
  24166. }
  24167. assert( p->l_whence==SEEK_SET );
  24168. s = osFcntl(fd, op, p);
  24169. savedErrno = errno;
  24170. sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
  24171. threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
  24172. (int)p->l_pid, s);
  24173. if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
  24174. struct flock l2;
  24175. l2 = *p;
  24176. osFcntl(fd, F_GETLK, &l2);
  24177. if( l2.l_type==F_RDLCK ){
  24178. zType = "RDLCK";
  24179. }else if( l2.l_type==F_WRLCK ){
  24180. zType = "WRLCK";
  24181. }else if( l2.l_type==F_UNLCK ){
  24182. zType = "UNLCK";
  24183. }else{
  24184. assert( 0 );
  24185. }
  24186. sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
  24187. zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
  24188. }
  24189. errno = savedErrno;
  24190. return s;
  24191. }
  24192. #undef osFcntl
  24193. #define osFcntl lockTrace
  24194. #endif /* SQLITE_LOCK_TRACE */
  24195. /*
  24196. ** Retry ftruncate() calls that fail due to EINTR
  24197. **
  24198. ** All calls to ftruncate() within this file should be made through this wrapper.
  24199. ** On the Android platform, bypassing the logic below could lead to a corrupt
  24200. ** database.
  24201. */
  24202. static int robust_ftruncate(int h, sqlite3_int64 sz){
  24203. int rc;
  24204. #ifdef __ANDROID__
  24205. /* On Android, ftruncate() always uses 32-bit offsets, even if
  24206. ** _FILE_OFFSET_BITS=64 is defined. This means it is unsafe to attempt to
  24207. ** truncate a file to any size larger than 2GiB. Silently ignore any
  24208. ** such attempts. */
  24209. if( sz>(sqlite3_int64)0x7FFFFFFF ){
  24210. rc = SQLITE_OK;
  24211. }else
  24212. #endif
  24213. do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );
  24214. return rc;
  24215. }
  24216. /*
  24217. ** This routine translates a standard POSIX errno code into something
  24218. ** useful to the clients of the sqlite3 functions. Specifically, it is
  24219. ** intended to translate a variety of "try again" errors into SQLITE_BUSY
  24220. ** and a variety of "please close the file descriptor NOW" errors into
  24221. ** SQLITE_IOERR
  24222. **
  24223. ** Errors during initialization of locks, or file system support for locks,
  24224. ** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
  24225. */
  24226. static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
  24227. switch (posixError) {
  24228. #if 0
  24229. /* At one point this code was not commented out. In theory, this branch
  24230. ** should never be hit, as this function should only be called after
  24231. ** a locking-related function (i.e. fcntl()) has returned non-zero with
  24232. ** the value of errno as the first argument. Since a system call has failed,
  24233. ** errno should be non-zero.
  24234. **
  24235. ** Despite this, if errno really is zero, we still don't want to return
  24236. ** SQLITE_OK. The system call failed, and *some* SQLite error should be
  24237. ** propagated back to the caller. Commenting this branch out means errno==0
  24238. ** will be handled by the "default:" case below.
  24239. */
  24240. case 0:
  24241. return SQLITE_OK;
  24242. #endif
  24243. case EAGAIN:
  24244. case ETIMEDOUT:
  24245. case EBUSY:
  24246. case EINTR:
  24247. case ENOLCK:
  24248. /* random NFS retry error, unless during file system support
  24249. * introspection, in which it actually means what it says */
  24250. return SQLITE_BUSY;
  24251. case EACCES:
  24252. /* EACCES is like EAGAIN during locking operations, but not any other time*/
  24253. if( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
  24254. (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
  24255. (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
  24256. (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) ){
  24257. return SQLITE_BUSY;
  24258. }
  24259. /* else fall through */
  24260. case EPERM:
  24261. return SQLITE_PERM;
  24262. #if EOPNOTSUPP!=ENOTSUP
  24263. case EOPNOTSUPP:
  24264. /* something went terribly awry, unless during file system support
  24265. * introspection, in which it actually means what it says */
  24266. #endif
  24267. #ifdef ENOTSUP
  24268. case ENOTSUP:
  24269. /* invalid fd, unless during file system support introspection, in which
  24270. * it actually means what it says */
  24271. #endif
  24272. case EIO:
  24273. case EBADF:
  24274. case EINVAL:
  24275. case ENOTCONN:
  24276. case ENODEV:
  24277. case ENXIO:
  24278. case ENOENT:
  24279. #ifdef ESTALE /* ESTALE is not defined on Interix systems */
  24280. case ESTALE:
  24281. #endif
  24282. case ENOSYS:
  24283. /* these should force the client to close the file and reconnect */
  24284. default:
  24285. return sqliteIOErr;
  24286. }
  24287. }
  24288. /******************************************************************************
  24289. ****************** Begin Unique File ID Utility Used By VxWorks ***************
  24290. **
  24291. ** On most versions of unix, we can get a unique ID for a file by concatenating
  24292. ** the device number and the inode number. But this does not work on VxWorks.
  24293. ** On VxWorks, a unique file id must be based on the canonical filename.
  24294. **
  24295. ** A pointer to an instance of the following structure can be used as a
  24296. ** unique file ID in VxWorks. Each instance of this structure contains
  24297. ** a copy of the canonical filename. There is also a reference count.
  24298. ** The structure is reclaimed when the number of pointers to it drops to
  24299. ** zero.
  24300. **
  24301. ** There are never very many files open at one time and lookups are not
  24302. ** a performance-critical path, so it is sufficient to put these
  24303. ** structures on a linked list.
  24304. */
  24305. struct vxworksFileId {
  24306. struct vxworksFileId *pNext; /* Next in a list of them all */
  24307. int nRef; /* Number of references to this one */
  24308. int nName; /* Length of the zCanonicalName[] string */
  24309. char *zCanonicalName; /* Canonical filename */
  24310. };
  24311. #if OS_VXWORKS
  24312. /*
  24313. ** All unique filenames are held on a linked list headed by this
  24314. ** variable:
  24315. */
  24316. static struct vxworksFileId *vxworksFileList = 0;
  24317. /*
  24318. ** Simplify a filename into its canonical form
  24319. ** by making the following changes:
  24320. **
  24321. ** * removing any trailing and duplicate /
  24322. ** * convert /./ into just /
  24323. ** * convert /A/../ where A is any simple name into just /
  24324. **
  24325. ** Changes are made in-place. Return the new name length.
  24326. **
  24327. ** The original filename is in z[0..n-1]. Return the number of
  24328. ** characters in the simplified name.
  24329. */
  24330. static int vxworksSimplifyName(char *z, int n){
  24331. int i, j;
  24332. while( n>1 && z[n-1]=='/' ){ n--; }
  24333. for(i=j=0; i<n; i++){
  24334. if( z[i]=='/' ){
  24335. if( z[i+1]=='/' ) continue;
  24336. if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
  24337. i += 1;
  24338. continue;
  24339. }
  24340. if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
  24341. while( j>0 && z[j-1]!='/' ){ j--; }
  24342. if( j>0 ){ j--; }
  24343. i += 2;
  24344. continue;
  24345. }
  24346. }
  24347. z[j++] = z[i];
  24348. }
  24349. z[j] = 0;
  24350. return j;
  24351. }
  24352. /*
  24353. ** Find a unique file ID for the given absolute pathname. Return
  24354. ** a pointer to the vxworksFileId object. This pointer is the unique
  24355. ** file ID.
  24356. **
  24357. ** The nRef field of the vxworksFileId object is incremented before
  24358. ** the object is returned. A new vxworksFileId object is created
  24359. ** and added to the global list if necessary.
  24360. **
  24361. ** If a memory allocation error occurs, return NULL.
  24362. */
  24363. static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
  24364. struct vxworksFileId *pNew; /* search key and new file ID */
  24365. struct vxworksFileId *pCandidate; /* For looping over existing file IDs */
  24366. int n; /* Length of zAbsoluteName string */
  24367. assert( zAbsoluteName[0]=='/' );
  24368. n = (int)strlen(zAbsoluteName);
  24369. pNew = sqlite3_malloc( sizeof(*pNew) + (n+1) );
  24370. if( pNew==0 ) return 0;
  24371. pNew->zCanonicalName = (char*)&pNew[1];
  24372. memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
  24373. n = vxworksSimplifyName(pNew->zCanonicalName, n);
  24374. /* Search for an existing entry that matching the canonical name.
  24375. ** If found, increment the reference count and return a pointer to
  24376. ** the existing file ID.
  24377. */
  24378. unixEnterMutex();
  24379. for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
  24380. if( pCandidate->nName==n
  24381. && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
  24382. ){
  24383. sqlite3_free(pNew);
  24384. pCandidate->nRef++;
  24385. unixLeaveMutex();
  24386. return pCandidate;
  24387. }
  24388. }
  24389. /* No match was found. We will make a new file ID */
  24390. pNew->nRef = 1;
  24391. pNew->nName = n;
  24392. pNew->pNext = vxworksFileList;
  24393. vxworksFileList = pNew;
  24394. unixLeaveMutex();
  24395. return pNew;
  24396. }
  24397. /*
  24398. ** Decrement the reference count on a vxworksFileId object. Free
  24399. ** the object when the reference count reaches zero.
  24400. */
  24401. static void vxworksReleaseFileId(struct vxworksFileId *pId){
  24402. unixEnterMutex();
  24403. assert( pId->nRef>0 );
  24404. pId->nRef--;
  24405. if( pId->nRef==0 ){
  24406. struct vxworksFileId **pp;
  24407. for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
  24408. assert( *pp==pId );
  24409. *pp = pId->pNext;
  24410. sqlite3_free(pId);
  24411. }
  24412. unixLeaveMutex();
  24413. }
  24414. #endif /* OS_VXWORKS */
  24415. /*************** End of Unique File ID Utility Used By VxWorks ****************
  24416. ******************************************************************************/
  24417. /******************************************************************************
  24418. *************************** Posix Advisory Locking ****************************
  24419. **
  24420. ** POSIX advisory locks are broken by design. ANSI STD 1003.1 (1996)
  24421. ** section 6.5.2.2 lines 483 through 490 specify that when a process
  24422. ** sets or clears a lock, that operation overrides any prior locks set
  24423. ** by the same process. It does not explicitly say so, but this implies
  24424. ** that it overrides locks set by the same process using a different
  24425. ** file descriptor. Consider this test case:
  24426. **
  24427. ** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
  24428. ** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
  24429. **
  24430. ** Suppose ./file1 and ./file2 are really the same file (because
  24431. ** one is a hard or symbolic link to the other) then if you set
  24432. ** an exclusive lock on fd1, then try to get an exclusive lock
  24433. ** on fd2, it works. I would have expected the second lock to
  24434. ** fail since there was already a lock on the file due to fd1.
  24435. ** But not so. Since both locks came from the same process, the
  24436. ** second overrides the first, even though they were on different
  24437. ** file descriptors opened on different file names.
  24438. **
  24439. ** This means that we cannot use POSIX locks to synchronize file access
  24440. ** among competing threads of the same process. POSIX locks will work fine
  24441. ** to synchronize access for threads in separate processes, but not
  24442. ** threads within the same process.
  24443. **
  24444. ** To work around the problem, SQLite has to manage file locks internally
  24445. ** on its own. Whenever a new database is opened, we have to find the
  24446. ** specific inode of the database file (the inode is determined by the
  24447. ** st_dev and st_ino fields of the stat structure that fstat() fills in)
  24448. ** and check for locks already existing on that inode. When locks are
  24449. ** created or removed, we have to look at our own internal record of the
  24450. ** locks to see if another thread has previously set a lock on that same
  24451. ** inode.
  24452. **
  24453. ** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
  24454. ** For VxWorks, we have to use the alternative unique ID system based on
  24455. ** canonical filename and implemented in the previous division.)
  24456. **
  24457. ** The sqlite3_file structure for POSIX is no longer just an integer file
  24458. ** descriptor. It is now a structure that holds the integer file
  24459. ** descriptor and a pointer to a structure that describes the internal
  24460. ** locks on the corresponding inode. There is one locking structure
  24461. ** per inode, so if the same inode is opened twice, both unixFile structures
  24462. ** point to the same locking structure. The locking structure keeps
  24463. ** a reference count (so we will know when to delete it) and a "cnt"
  24464. ** field that tells us its internal lock status. cnt==0 means the
  24465. ** file is unlocked. cnt==-1 means the file has an exclusive lock.
  24466. ** cnt>0 means there are cnt shared locks on the file.
  24467. **
  24468. ** Any attempt to lock or unlock a file first checks the locking
  24469. ** structure. The fcntl() system call is only invoked to set a
  24470. ** POSIX lock if the internal lock structure transitions between
  24471. ** a locked and an unlocked state.
  24472. **
  24473. ** But wait: there are yet more problems with POSIX advisory locks.
  24474. **
  24475. ** If you close a file descriptor that points to a file that has locks,
  24476. ** all locks on that file that are owned by the current process are
  24477. ** released. To work around this problem, each unixInodeInfo object
  24478. ** maintains a count of the number of pending locks on tha inode.
  24479. ** When an attempt is made to close an unixFile, if there are
  24480. ** other unixFile open on the same inode that are holding locks, the call
  24481. ** to close() the file descriptor is deferred until all of the locks clear.
  24482. ** The unixInodeInfo structure keeps a list of file descriptors that need to
  24483. ** be closed and that list is walked (and cleared) when the last lock
  24484. ** clears.
  24485. **
  24486. ** Yet another problem: LinuxThreads do not play well with posix locks.
  24487. **
  24488. ** Many older versions of linux use the LinuxThreads library which is
  24489. ** not posix compliant. Under LinuxThreads, a lock created by thread
  24490. ** A cannot be modified or overridden by a different thread B.
  24491. ** Only thread A can modify the lock. Locking behavior is correct
  24492. ** if the appliation uses the newer Native Posix Thread Library (NPTL)
  24493. ** on linux - with NPTL a lock created by thread A can override locks
  24494. ** in thread B. But there is no way to know at compile-time which
  24495. ** threading library is being used. So there is no way to know at
  24496. ** compile-time whether or not thread A can override locks on thread B.
  24497. ** One has to do a run-time check to discover the behavior of the
  24498. ** current process.
  24499. **
  24500. ** SQLite used to support LinuxThreads. But support for LinuxThreads
  24501. ** was dropped beginning with version 3.7.0. SQLite will still work with
  24502. ** LinuxThreads provided that (1) there is no more than one connection
  24503. ** per database file in the same process and (2) database connections
  24504. ** do not move across threads.
  24505. */
  24506. /*
  24507. ** An instance of the following structure serves as the key used
  24508. ** to locate a particular unixInodeInfo object.
  24509. */
  24510. struct unixFileId {
  24511. dev_t dev; /* Device number */
  24512. #if OS_VXWORKS
  24513. struct vxworksFileId *pId; /* Unique file ID for vxworks. */
  24514. #else
  24515. ino_t ino; /* Inode number */
  24516. #endif
  24517. };
  24518. /*
  24519. ** An instance of the following structure is allocated for each open
  24520. ** inode. Or, on LinuxThreads, there is one of these structures for
  24521. ** each inode opened by each thread.
  24522. **
  24523. ** A single inode can have multiple file descriptors, so each unixFile
  24524. ** structure contains a pointer to an instance of this object and this
  24525. ** object keeps a count of the number of unixFile pointing to it.
  24526. */
  24527. struct unixInodeInfo {
  24528. struct unixFileId fileId; /* The lookup key */
  24529. int nShared; /* Number of SHARED locks held */
  24530. unsigned char eFileLock; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
  24531. unsigned char bProcessLock; /* An exclusive process lock is held */
  24532. int nRef; /* Number of pointers to this structure */
  24533. unixShmNode *pShmNode; /* Shared memory associated with this inode */
  24534. int nLock; /* Number of outstanding file locks */
  24535. UnixUnusedFd *pUnused; /* Unused file descriptors to close */
  24536. unixInodeInfo *pNext; /* List of all unixInodeInfo objects */
  24537. unixInodeInfo *pPrev; /* .... doubly linked */
  24538. #if SQLITE_ENABLE_LOCKING_STYLE
  24539. unsigned long long sharedByte; /* for AFP simulated shared lock */
  24540. #endif
  24541. #if OS_VXWORKS
  24542. sem_t *pSem; /* Named POSIX semaphore */
  24543. char aSemName[MAX_PATHNAME+2]; /* Name of that semaphore */
  24544. #endif
  24545. };
  24546. /*
  24547. ** A lists of all unixInodeInfo objects.
  24548. */
  24549. static unixInodeInfo *inodeList = 0;
  24550. /*
  24551. **
  24552. ** This function - unixLogError_x(), is only ever called via the macro
  24553. ** unixLogError().
  24554. **
  24555. ** It is invoked after an error occurs in an OS function and errno has been
  24556. ** set. It logs a message using sqlite3_log() containing the current value of
  24557. ** errno and, if possible, the human-readable equivalent from strerror() or
  24558. ** strerror_r().
  24559. **
  24560. ** The first argument passed to the macro should be the error code that
  24561. ** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
  24562. ** The two subsequent arguments should be the name of the OS function that
  24563. ** failed (e.g. "unlink", "open") and the associated file-system path,
  24564. ** if any.
  24565. */
  24566. #define unixLogError(a,b,c) unixLogErrorAtLine(a,b,c,__LINE__)
  24567. static int unixLogErrorAtLine(
  24568. int errcode, /* SQLite error code */
  24569. const char *zFunc, /* Name of OS function that failed */
  24570. const char *zPath, /* File path associated with error */
  24571. int iLine /* Source line number where error occurred */
  24572. ){
  24573. char *zErr; /* Message from strerror() or equivalent */
  24574. int iErrno = errno; /* Saved syscall error number */
  24575. /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
  24576. ** the strerror() function to obtain the human-readable error message
  24577. ** equivalent to errno. Otherwise, use strerror_r().
  24578. */
  24579. #if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
  24580. char aErr[80];
  24581. memset(aErr, 0, sizeof(aErr));
  24582. zErr = aErr;
  24583. /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
  24584. ** assume that the system provides the GNU version of strerror_r() that
  24585. ** returns a pointer to a buffer containing the error message. That pointer
  24586. ** may point to aErr[], or it may point to some static storage somewhere.
  24587. ** Otherwise, assume that the system provides the POSIX version of
  24588. ** strerror_r(), which always writes an error message into aErr[].
  24589. **
  24590. ** If the code incorrectly assumes that it is the POSIX version that is
  24591. ** available, the error message will often be an empty string. Not a
  24592. ** huge problem. Incorrectly concluding that the GNU version is available
  24593. ** could lead to a segfault though.
  24594. */
  24595. #if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
  24596. zErr =
  24597. # endif
  24598. strerror_r(iErrno, aErr, sizeof(aErr)-1);
  24599. #elif SQLITE_THREADSAFE
  24600. /* This is a threadsafe build, but strerror_r() is not available. */
  24601. zErr = "";
  24602. #else
  24603. /* Non-threadsafe build, use strerror(). */
  24604. zErr = strerror(iErrno);
  24605. #endif
  24606. if( zPath==0 ) zPath = "";
  24607. sqlite3_log(errcode,
  24608. "os_unix.c:%d: (%d) %s(%s) - %s",
  24609. iLine, iErrno, zFunc, zPath, zErr
  24610. );
  24611. return errcode;
  24612. }
  24613. /*
  24614. ** Close a file descriptor.
  24615. **
  24616. ** We assume that close() almost always works, since it is only in a
  24617. ** very sick application or on a very sick platform that it might fail.
  24618. ** If it does fail, simply leak the file descriptor, but do log the
  24619. ** error.
  24620. **
  24621. ** Note that it is not safe to retry close() after EINTR since the
  24622. ** file descriptor might have already been reused by another thread.
  24623. ** So we don't even try to recover from an EINTR. Just log the error
  24624. ** and move on.
  24625. */
  24626. static void robust_close(unixFile *pFile, int h, int lineno){
  24627. if( osClose(h) ){
  24628. unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
  24629. pFile ? pFile->zPath : 0, lineno);
  24630. }
  24631. }
  24632. /*
  24633. ** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
  24634. */
  24635. static void closePendingFds(unixFile *pFile){
  24636. unixInodeInfo *pInode = pFile->pInode;
  24637. UnixUnusedFd *p;
  24638. UnixUnusedFd *pNext;
  24639. for(p=pInode->pUnused; p; p=pNext){
  24640. pNext = p->pNext;
  24641. robust_close(pFile, p->fd, __LINE__);
  24642. sqlite3_free(p);
  24643. }
  24644. pInode->pUnused = 0;
  24645. }
  24646. /*
  24647. ** Release a unixInodeInfo structure previously allocated by findInodeInfo().
  24648. **
  24649. ** The mutex entered using the unixEnterMutex() function must be held
  24650. ** when this function is called.
  24651. */
  24652. static void releaseInodeInfo(unixFile *pFile){
  24653. unixInodeInfo *pInode = pFile->pInode;
  24654. assert( unixMutexHeld() );
  24655. if( ALWAYS(pInode) ){
  24656. pInode->nRef--;
  24657. if( pInode->nRef==0 ){
  24658. assert( pInode->pShmNode==0 );
  24659. closePendingFds(pFile);
  24660. if( pInode->pPrev ){
  24661. assert( pInode->pPrev->pNext==pInode );
  24662. pInode->pPrev->pNext = pInode->pNext;
  24663. }else{
  24664. assert( inodeList==pInode );
  24665. inodeList = pInode->pNext;
  24666. }
  24667. if( pInode->pNext ){
  24668. assert( pInode->pNext->pPrev==pInode );
  24669. pInode->pNext->pPrev = pInode->pPrev;
  24670. }
  24671. sqlite3_free(pInode);
  24672. }
  24673. }
  24674. }
  24675. /*
  24676. ** Given a file descriptor, locate the unixInodeInfo object that
  24677. ** describes that file descriptor. Create a new one if necessary. The
  24678. ** return value might be uninitialized if an error occurs.
  24679. **
  24680. ** The mutex entered using the unixEnterMutex() function must be held
  24681. ** when this function is called.
  24682. **
  24683. ** Return an appropriate error code.
  24684. */
  24685. static int findInodeInfo(
  24686. unixFile *pFile, /* Unix file with file desc used in the key */
  24687. unixInodeInfo **ppInode /* Return the unixInodeInfo object here */
  24688. ){
  24689. int rc; /* System call return code */
  24690. int fd; /* The file descriptor for pFile */
  24691. struct unixFileId fileId; /* Lookup key for the unixInodeInfo */
  24692. struct stat statbuf; /* Low-level file information */
  24693. unixInodeInfo *pInode = 0; /* Candidate unixInodeInfo object */
  24694. assert( unixMutexHeld() );
  24695. /* Get low-level information about the file that we can used to
  24696. ** create a unique name for the file.
  24697. */
  24698. fd = pFile->h;
  24699. rc = osFstat(fd, &statbuf);
  24700. if( rc!=0 ){
  24701. pFile->lastErrno = errno;
  24702. #ifdef EOVERFLOW
  24703. if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
  24704. #endif
  24705. return SQLITE_IOERR;
  24706. }
  24707. #ifdef __APPLE__
  24708. /* On OS X on an msdos filesystem, the inode number is reported
  24709. ** incorrectly for zero-size files. See ticket #3260. To work
  24710. ** around this problem (we consider it a bug in OS X, not SQLite)
  24711. ** we always increase the file size to 1 by writing a single byte
  24712. ** prior to accessing the inode number. The one byte written is
  24713. ** an ASCII 'S' character which also happens to be the first byte
  24714. ** in the header of every SQLite database. In this way, if there
  24715. ** is a race condition such that another thread has already populated
  24716. ** the first page of the database, no damage is done.
  24717. */
  24718. if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
  24719. do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR );
  24720. if( rc!=1 ){
  24721. pFile->lastErrno = errno;
  24722. return SQLITE_IOERR;
  24723. }
  24724. rc = osFstat(fd, &statbuf);
  24725. if( rc!=0 ){
  24726. pFile->lastErrno = errno;
  24727. return SQLITE_IOERR;
  24728. }
  24729. }
  24730. #endif
  24731. memset(&fileId, 0, sizeof(fileId));
  24732. fileId.dev = statbuf.st_dev;
  24733. #if OS_VXWORKS
  24734. fileId.pId = pFile->pId;
  24735. #else
  24736. fileId.ino = statbuf.st_ino;
  24737. #endif
  24738. pInode = inodeList;
  24739. while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
  24740. pInode = pInode->pNext;
  24741. }
  24742. if( pInode==0 ){
  24743. pInode = sqlite3_malloc( sizeof(*pInode) );
  24744. if( pInode==0 ){
  24745. return SQLITE_NOMEM;
  24746. }
  24747. memset(pInode, 0, sizeof(*pInode));
  24748. memcpy(&pInode->fileId, &fileId, sizeof(fileId));
  24749. pInode->nRef = 1;
  24750. pInode->pNext = inodeList;
  24751. pInode->pPrev = 0;
  24752. if( inodeList ) inodeList->pPrev = pInode;
  24753. inodeList = pInode;
  24754. }else{
  24755. pInode->nRef++;
  24756. }
  24757. *ppInode = pInode;
  24758. return SQLITE_OK;
  24759. }
  24760. /*
  24761. ** Return TRUE if pFile has been renamed or unlinked since it was first opened.
  24762. */
  24763. static int fileHasMoved(unixFile *pFile){
  24764. #if OS_VXWORKS
  24765. return pFile->pInode!=0 && pFile->pId!=pFile->pInode->fileId.pId;
  24766. #else
  24767. struct stat buf;
  24768. return pFile->pInode!=0 &&
  24769. (osStat(pFile->zPath, &buf)!=0 || buf.st_ino!=pFile->pInode->fileId.ino);
  24770. #endif
  24771. }
  24772. /*
  24773. ** Check a unixFile that is a database. Verify the following:
  24774. **
  24775. ** (1) There is exactly one hard link on the file
  24776. ** (2) The file is not a symbolic link
  24777. ** (3) The file has not been renamed or unlinked
  24778. **
  24779. ** Issue sqlite3_log(SQLITE_WARNING,...) messages if anything is not right.
  24780. */
  24781. static void verifyDbFile(unixFile *pFile){
  24782. struct stat buf;
  24783. int rc;
  24784. if( pFile->ctrlFlags & UNIXFILE_WARNED ){
  24785. /* One or more of the following warnings have already been issued. Do not
  24786. ** repeat them so as not to clutter the error log */
  24787. return;
  24788. }
  24789. rc = osFstat(pFile->h, &buf);
  24790. if( rc!=0 ){
  24791. sqlite3_log(SQLITE_WARNING, "cannot fstat db file %s", pFile->zPath);
  24792. pFile->ctrlFlags |= UNIXFILE_WARNED;
  24793. return;
  24794. }
  24795. if( buf.st_nlink==0 && (pFile->ctrlFlags & UNIXFILE_DELETE)==0 ){
  24796. sqlite3_log(SQLITE_WARNING, "file unlinked while open: %s", pFile->zPath);
  24797. pFile->ctrlFlags |= UNIXFILE_WARNED;
  24798. return;
  24799. }
  24800. if( buf.st_nlink>1 ){
  24801. sqlite3_log(SQLITE_WARNING, "multiple links to file: %s", pFile->zPath);
  24802. pFile->ctrlFlags |= UNIXFILE_WARNED;
  24803. return;
  24804. }
  24805. if( fileHasMoved(pFile) ){
  24806. sqlite3_log(SQLITE_WARNING, "file renamed while open: %s", pFile->zPath);
  24807. pFile->ctrlFlags |= UNIXFILE_WARNED;
  24808. return;
  24809. }
  24810. }
  24811. /*
  24812. ** This routine checks if there is a RESERVED lock held on the specified
  24813. ** file by this or any other process. If such a lock is held, set *pResOut
  24814. ** to a non-zero value otherwise *pResOut is set to zero. The return value
  24815. ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
  24816. */
  24817. static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
  24818. int rc = SQLITE_OK;
  24819. int reserved = 0;
  24820. unixFile *pFile = (unixFile*)id;
  24821. SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
  24822. assert( pFile );
  24823. unixEnterMutex(); /* Because pFile->pInode is shared across threads */
  24824. /* Check if a thread in this process holds such a lock */
  24825. if( pFile->pInode->eFileLock>SHARED_LOCK ){
  24826. reserved = 1;
  24827. }
  24828. /* Otherwise see if some other process holds it.
  24829. */
  24830. #ifndef __DJGPP__
  24831. if( !reserved && !pFile->pInode->bProcessLock ){
  24832. struct flock lock;
  24833. lock.l_whence = SEEK_SET;
  24834. lock.l_start = RESERVED_BYTE;
  24835. lock.l_len = 1;
  24836. lock.l_type = F_WRLCK;
  24837. if( osFcntl(pFile->h, F_GETLK, &lock) ){
  24838. rc = SQLITE_IOERR_CHECKRESERVEDLOCK;
  24839. pFile->lastErrno = errno;
  24840. } else if( lock.l_type!=F_UNLCK ){
  24841. reserved = 1;
  24842. }
  24843. }
  24844. #endif
  24845. unixLeaveMutex();
  24846. OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
  24847. *pResOut = reserved;
  24848. return rc;
  24849. }
  24850. /*
  24851. ** Attempt to set a system-lock on the file pFile. The lock is
  24852. ** described by pLock.
  24853. **
  24854. ** If the pFile was opened read/write from unix-excl, then the only lock
  24855. ** ever obtained is an exclusive lock, and it is obtained exactly once
  24856. ** the first time any lock is attempted. All subsequent system locking
  24857. ** operations become no-ops. Locking operations still happen internally,
  24858. ** in order to coordinate access between separate database connections
  24859. ** within this process, but all of that is handled in memory and the
  24860. ** operating system does not participate.
  24861. **
  24862. ** This function is a pass-through to fcntl(F_SETLK) if pFile is using
  24863. ** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
  24864. ** and is read-only.
  24865. **
  24866. ** Zero is returned if the call completes successfully, or -1 if a call
  24867. ** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).
  24868. */
  24869. static int unixFileLock(unixFile *pFile, struct flock *pLock){
  24870. int rc;
  24871. unixInodeInfo *pInode = pFile->pInode;
  24872. assert( unixMutexHeld() );
  24873. assert( pInode!=0 );
  24874. if( ((pFile->ctrlFlags & UNIXFILE_EXCL)!=0 || pInode->bProcessLock)
  24875. && ((pFile->ctrlFlags & UNIXFILE_RDONLY)==0)
  24876. ){
  24877. if( pInode->bProcessLock==0 ){
  24878. struct flock lock;
  24879. assert( pInode->nLock==0 );
  24880. lock.l_whence = SEEK_SET;
  24881. lock.l_start = SHARED_FIRST;
  24882. lock.l_len = SHARED_SIZE;
  24883. lock.l_type = F_WRLCK;
  24884. rc = osFcntl(pFile->h, F_SETLK, &lock);
  24885. if( rc<0 ) return rc;
  24886. pInode->bProcessLock = 1;
  24887. pInode->nLock++;
  24888. }else{
  24889. rc = 0;
  24890. }
  24891. }else{
  24892. rc = osFcntl(pFile->h, F_SETLK, pLock);
  24893. }
  24894. return rc;
  24895. }
  24896. /*
  24897. ** Lock the file with the lock specified by parameter eFileLock - one
  24898. ** of the following:
  24899. **
  24900. ** (1) SHARED_LOCK
  24901. ** (2) RESERVED_LOCK
  24902. ** (3) PENDING_LOCK
  24903. ** (4) EXCLUSIVE_LOCK
  24904. **
  24905. ** Sometimes when requesting one lock state, additional lock states
  24906. ** are inserted in between. The locking might fail on one of the later
  24907. ** transitions leaving the lock state different from what it started but
  24908. ** still short of its goal. The following chart shows the allowed
  24909. ** transitions and the inserted intermediate states:
  24910. **
  24911. ** UNLOCKED -> SHARED
  24912. ** SHARED -> RESERVED
  24913. ** SHARED -> (PENDING) -> EXCLUSIVE
  24914. ** RESERVED -> (PENDING) -> EXCLUSIVE
  24915. ** PENDING -> EXCLUSIVE
  24916. **
  24917. ** This routine will only increase a lock. Use the sqlite3OsUnlock()
  24918. ** routine to lower a locking level.
  24919. */
  24920. static int unixLock(sqlite3_file *id, int eFileLock){
  24921. /* The following describes the implementation of the various locks and
  24922. ** lock transitions in terms of the POSIX advisory shared and exclusive
  24923. ** lock primitives (called read-locks and write-locks below, to avoid
  24924. ** confusion with SQLite lock names). The algorithms are complicated
  24925. ** slightly in order to be compatible with windows systems simultaneously
  24926. ** accessing the same database file, in case that is ever required.
  24927. **
  24928. ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
  24929. ** byte', each single bytes at well known offsets, and the 'shared byte
  24930. ** range', a range of 510 bytes at a well known offset.
  24931. **
  24932. ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
  24933. ** byte'. If this is successful, a random byte from the 'shared byte
  24934. ** range' is read-locked and the lock on the 'pending byte' released.
  24935. **
  24936. ** A process may only obtain a RESERVED lock after it has a SHARED lock.
  24937. ** A RESERVED lock is implemented by grabbing a write-lock on the
  24938. ** 'reserved byte'.
  24939. **
  24940. ** A process may only obtain a PENDING lock after it has obtained a
  24941. ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
  24942. ** on the 'pending byte'. This ensures that no new SHARED locks can be
  24943. ** obtained, but existing SHARED locks are allowed to persist. A process
  24944. ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
  24945. ** This property is used by the algorithm for rolling back a journal file
  24946. ** after a crash.
  24947. **
  24948. ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
  24949. ** implemented by obtaining a write-lock on the entire 'shared byte
  24950. ** range'. Since all other locks require a read-lock on one of the bytes
  24951. ** within this range, this ensures that no other locks are held on the
  24952. ** database.
  24953. **
  24954. ** The reason a single byte cannot be used instead of the 'shared byte
  24955. ** range' is that some versions of windows do not support read-locks. By
  24956. ** locking a random byte from a range, concurrent SHARED locks may exist
  24957. ** even if the locking primitive used is always a write-lock.
  24958. */
  24959. int rc = SQLITE_OK;
  24960. unixFile *pFile = (unixFile*)id;
  24961. unixInodeInfo *pInode;
  24962. struct flock lock;
  24963. int tErrno = 0;
  24964. assert( pFile );
  24965. OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
  24966. azFileLock(eFileLock), azFileLock(pFile->eFileLock),
  24967. azFileLock(pFile->pInode->eFileLock), pFile->pInode->nShared , getpid()));
  24968. /* If there is already a lock of this type or more restrictive on the
  24969. ** unixFile, do nothing. Don't use the end_lock: exit path, as
  24970. ** unixEnterMutex() hasn't been called yet.
  24971. */
  24972. if( pFile->eFileLock>=eFileLock ){
  24973. OSTRACE(("LOCK %d %s ok (already held) (unix)\n", pFile->h,
  24974. azFileLock(eFileLock)));
  24975. return SQLITE_OK;
  24976. }
  24977. /* Make sure the locking sequence is correct.
  24978. ** (1) We never move from unlocked to anything higher than shared lock.
  24979. ** (2) SQLite never explicitly requests a pendig lock.
  24980. ** (3) A shared lock is always held when a reserve lock is requested.
  24981. */
  24982. assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
  24983. assert( eFileLock!=PENDING_LOCK );
  24984. assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
  24985. /* This mutex is needed because pFile->pInode is shared across threads
  24986. */
  24987. unixEnterMutex();
  24988. pInode = pFile->pInode;
  24989. /* If some thread using this PID has a lock via a different unixFile*
  24990. ** handle that precludes the requested lock, return BUSY.
  24991. */
  24992. if( (pFile->eFileLock!=pInode->eFileLock &&
  24993. (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
  24994. ){
  24995. rc = SQLITE_BUSY;
  24996. goto end_lock;
  24997. }
  24998. /* If a SHARED lock is requested, and some thread using this PID already
  24999. ** has a SHARED or RESERVED lock, then increment reference counts and
  25000. ** return SQLITE_OK.
  25001. */
  25002. if( eFileLock==SHARED_LOCK &&
  25003. (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
  25004. assert( eFileLock==SHARED_LOCK );
  25005. assert( pFile->eFileLock==0 );
  25006. assert( pInode->nShared>0 );
  25007. pFile->eFileLock = SHARED_LOCK;
  25008. pInode->nShared++;
  25009. pInode->nLock++;
  25010. goto end_lock;
  25011. }
  25012. /* A PENDING lock is needed before acquiring a SHARED lock and before
  25013. ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
  25014. ** be released.
  25015. */
  25016. lock.l_len = 1L;
  25017. lock.l_whence = SEEK_SET;
  25018. if( eFileLock==SHARED_LOCK
  25019. || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
  25020. ){
  25021. lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
  25022. lock.l_start = PENDING_BYTE;
  25023. if( unixFileLock(pFile, &lock) ){
  25024. tErrno = errno;
  25025. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
  25026. if( rc!=SQLITE_BUSY ){
  25027. pFile->lastErrno = tErrno;
  25028. }
  25029. goto end_lock;
  25030. }
  25031. }
  25032. /* If control gets to this point, then actually go ahead and make
  25033. ** operating system calls for the specified lock.
  25034. */
  25035. if( eFileLock==SHARED_LOCK ){
  25036. assert( pInode->nShared==0 );
  25037. assert( pInode->eFileLock==0 );
  25038. assert( rc==SQLITE_OK );
  25039. /* Now get the read-lock */
  25040. lock.l_start = SHARED_FIRST;
  25041. lock.l_len = SHARED_SIZE;
  25042. if( unixFileLock(pFile, &lock) ){
  25043. tErrno = errno;
  25044. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
  25045. }
  25046. /* Drop the temporary PENDING lock */
  25047. lock.l_start = PENDING_BYTE;
  25048. lock.l_len = 1L;
  25049. lock.l_type = F_UNLCK;
  25050. if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){
  25051. /* This could happen with a network mount */
  25052. tErrno = errno;
  25053. rc = SQLITE_IOERR_UNLOCK;
  25054. }
  25055. if( rc ){
  25056. if( rc!=SQLITE_BUSY ){
  25057. pFile->lastErrno = tErrno;
  25058. }
  25059. goto end_lock;
  25060. }else{
  25061. pFile->eFileLock = SHARED_LOCK;
  25062. pInode->nLock++;
  25063. pInode->nShared = 1;
  25064. }
  25065. }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
  25066. /* We are trying for an exclusive lock but another thread in this
  25067. ** same process is still holding a shared lock. */
  25068. rc = SQLITE_BUSY;
  25069. }else{
  25070. /* The request was for a RESERVED or EXCLUSIVE lock. It is
  25071. ** assumed that there is a SHARED or greater lock on the file
  25072. ** already.
  25073. */
  25074. assert( 0!=pFile->eFileLock );
  25075. lock.l_type = F_WRLCK;
  25076. assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK );
  25077. if( eFileLock==RESERVED_LOCK ){
  25078. lock.l_start = RESERVED_BYTE;
  25079. lock.l_len = 1L;
  25080. }else{
  25081. lock.l_start = SHARED_FIRST;
  25082. lock.l_len = SHARED_SIZE;
  25083. }
  25084. if( unixFileLock(pFile, &lock) ){
  25085. tErrno = errno;
  25086. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
  25087. if( rc!=SQLITE_BUSY ){
  25088. pFile->lastErrno = tErrno;
  25089. }
  25090. }
  25091. }
  25092. #ifdef SQLITE_DEBUG
  25093. /* Set up the transaction-counter change checking flags when
  25094. ** transitioning from a SHARED to a RESERVED lock. The change
  25095. ** from SHARED to RESERVED marks the beginning of a normal
  25096. ** write operation (not a hot journal rollback).
  25097. */
  25098. if( rc==SQLITE_OK
  25099. && pFile->eFileLock<=SHARED_LOCK
  25100. && eFileLock==RESERVED_LOCK
  25101. ){
  25102. pFile->transCntrChng = 0;
  25103. pFile->dbUpdate = 0;
  25104. pFile->inNormalWrite = 1;
  25105. }
  25106. #endif
  25107. if( rc==SQLITE_OK ){
  25108. pFile->eFileLock = eFileLock;
  25109. pInode->eFileLock = eFileLock;
  25110. }else if( eFileLock==EXCLUSIVE_LOCK ){
  25111. pFile->eFileLock = PENDING_LOCK;
  25112. pInode->eFileLock = PENDING_LOCK;
  25113. }
  25114. end_lock:
  25115. unixLeaveMutex();
  25116. OSTRACE(("LOCK %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
  25117. rc==SQLITE_OK ? "ok" : "failed"));
  25118. return rc;
  25119. }
  25120. /*
  25121. ** Add the file descriptor used by file handle pFile to the corresponding
  25122. ** pUnused list.
  25123. */
  25124. static void setPendingFd(unixFile *pFile){
  25125. unixInodeInfo *pInode = pFile->pInode;
  25126. UnixUnusedFd *p = pFile->pUnused;
  25127. p->pNext = pInode->pUnused;
  25128. pInode->pUnused = p;
  25129. pFile->h = -1;
  25130. pFile->pUnused = 0;
  25131. }
  25132. /*
  25133. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  25134. ** must be either NO_LOCK or SHARED_LOCK.
  25135. **
  25136. ** If the locking level of the file descriptor is already at or below
  25137. ** the requested locking level, this routine is a no-op.
  25138. **
  25139. ** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
  25140. ** the byte range is divided into 2 parts and the first part is unlocked then
  25141. ** set to a read lock, then the other part is simply unlocked. This works
  25142. ** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
  25143. ** remove the write lock on a region when a read lock is set.
  25144. */
  25145. static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
  25146. unixFile *pFile = (unixFile*)id;
  25147. unixInodeInfo *pInode;
  25148. struct flock lock;
  25149. int rc = SQLITE_OK;
  25150. assert( pFile );
  25151. OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
  25152. pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
  25153. getpid()));
  25154. assert( eFileLock<=SHARED_LOCK );
  25155. if( pFile->eFileLock<=eFileLock ){
  25156. return SQLITE_OK;
  25157. }
  25158. unixEnterMutex();
  25159. pInode = pFile->pInode;
  25160. assert( pInode->nShared!=0 );
  25161. if( pFile->eFileLock>SHARED_LOCK ){
  25162. assert( pInode->eFileLock==pFile->eFileLock );
  25163. #ifdef SQLITE_DEBUG
  25164. /* When reducing a lock such that other processes can start
  25165. ** reading the database file again, make sure that the
  25166. ** transaction counter was updated if any part of the database
  25167. ** file changed. If the transaction counter is not updated,
  25168. ** other connections to the same file might not realize that
  25169. ** the file has changed and hence might not know to flush their
  25170. ** cache. The use of a stale cache can lead to database corruption.
  25171. */
  25172. pFile->inNormalWrite = 0;
  25173. #endif
  25174. /* downgrading to a shared lock on NFS involves clearing the write lock
  25175. ** before establishing the readlock - to avoid a race condition we downgrade
  25176. ** the lock in 2 blocks, so that part of the range will be covered by a
  25177. ** write lock until the rest is covered by a read lock:
  25178. ** 1: [WWWWW]
  25179. ** 2: [....W]
  25180. ** 3: [RRRRW]
  25181. ** 4: [RRRR.]
  25182. */
  25183. if( eFileLock==SHARED_LOCK ){
  25184. #if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
  25185. (void)handleNFSUnlock;
  25186. assert( handleNFSUnlock==0 );
  25187. #endif
  25188. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  25189. if( handleNFSUnlock ){
  25190. int tErrno; /* Error code from system call errors */
  25191. off_t divSize = SHARED_SIZE - 1;
  25192. lock.l_type = F_UNLCK;
  25193. lock.l_whence = SEEK_SET;
  25194. lock.l_start = SHARED_FIRST;
  25195. lock.l_len = divSize;
  25196. if( unixFileLock(pFile, &lock)==(-1) ){
  25197. tErrno = errno;
  25198. rc = SQLITE_IOERR_UNLOCK;
  25199. if( IS_LOCK_ERROR(rc) ){
  25200. pFile->lastErrno = tErrno;
  25201. }
  25202. goto end_unlock;
  25203. }
  25204. lock.l_type = F_RDLCK;
  25205. lock.l_whence = SEEK_SET;
  25206. lock.l_start = SHARED_FIRST;
  25207. lock.l_len = divSize;
  25208. if( unixFileLock(pFile, &lock)==(-1) ){
  25209. tErrno = errno;
  25210. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
  25211. if( IS_LOCK_ERROR(rc) ){
  25212. pFile->lastErrno = tErrno;
  25213. }
  25214. goto end_unlock;
  25215. }
  25216. lock.l_type = F_UNLCK;
  25217. lock.l_whence = SEEK_SET;
  25218. lock.l_start = SHARED_FIRST+divSize;
  25219. lock.l_len = SHARED_SIZE-divSize;
  25220. if( unixFileLock(pFile, &lock)==(-1) ){
  25221. tErrno = errno;
  25222. rc = SQLITE_IOERR_UNLOCK;
  25223. if( IS_LOCK_ERROR(rc) ){
  25224. pFile->lastErrno = tErrno;
  25225. }
  25226. goto end_unlock;
  25227. }
  25228. }else
  25229. #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
  25230. {
  25231. lock.l_type = F_RDLCK;
  25232. lock.l_whence = SEEK_SET;
  25233. lock.l_start = SHARED_FIRST;
  25234. lock.l_len = SHARED_SIZE;
  25235. if( unixFileLock(pFile, &lock) ){
  25236. /* In theory, the call to unixFileLock() cannot fail because another
  25237. ** process is holding an incompatible lock. If it does, this
  25238. ** indicates that the other process is not following the locking
  25239. ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning
  25240. ** SQLITE_BUSY would confuse the upper layer (in practice it causes
  25241. ** an assert to fail). */
  25242. rc = SQLITE_IOERR_RDLOCK;
  25243. pFile->lastErrno = errno;
  25244. goto end_unlock;
  25245. }
  25246. }
  25247. }
  25248. lock.l_type = F_UNLCK;
  25249. lock.l_whence = SEEK_SET;
  25250. lock.l_start = PENDING_BYTE;
  25251. lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
  25252. if( unixFileLock(pFile, &lock)==0 ){
  25253. pInode->eFileLock = SHARED_LOCK;
  25254. }else{
  25255. rc = SQLITE_IOERR_UNLOCK;
  25256. pFile->lastErrno = errno;
  25257. goto end_unlock;
  25258. }
  25259. }
  25260. if( eFileLock==NO_LOCK ){
  25261. /* Decrement the shared lock counter. Release the lock using an
  25262. ** OS call only when all threads in this same process have released
  25263. ** the lock.
  25264. */
  25265. pInode->nShared--;
  25266. if( pInode->nShared==0 ){
  25267. lock.l_type = F_UNLCK;
  25268. lock.l_whence = SEEK_SET;
  25269. lock.l_start = lock.l_len = 0L;
  25270. if( unixFileLock(pFile, &lock)==0 ){
  25271. pInode->eFileLock = NO_LOCK;
  25272. }else{
  25273. rc = SQLITE_IOERR_UNLOCK;
  25274. pFile->lastErrno = errno;
  25275. pInode->eFileLock = NO_LOCK;
  25276. pFile->eFileLock = NO_LOCK;
  25277. }
  25278. }
  25279. /* Decrement the count of locks against this same file. When the
  25280. ** count reaches zero, close any other file descriptors whose close
  25281. ** was deferred because of outstanding locks.
  25282. */
  25283. pInode->nLock--;
  25284. assert( pInode->nLock>=0 );
  25285. if( pInode->nLock==0 ){
  25286. closePendingFds(pFile);
  25287. }
  25288. }
  25289. end_unlock:
  25290. unixLeaveMutex();
  25291. if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
  25292. return rc;
  25293. }
  25294. /*
  25295. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  25296. ** must be either NO_LOCK or SHARED_LOCK.
  25297. **
  25298. ** If the locking level of the file descriptor is already at or below
  25299. ** the requested locking level, this routine is a no-op.
  25300. */
  25301. static int unixUnlock(sqlite3_file *id, int eFileLock){
  25302. #if SQLITE_MAX_MMAP_SIZE>0
  25303. assert( eFileLock==SHARED_LOCK || ((unixFile *)id)->nFetchOut==0 );
  25304. #endif
  25305. return posixUnlock(id, eFileLock, 0);
  25306. }
  25307. #if SQLITE_MAX_MMAP_SIZE>0
  25308. static int unixMapfile(unixFile *pFd, i64 nByte);
  25309. static void unixUnmapfile(unixFile *pFd);
  25310. #endif
  25311. /*
  25312. ** This function performs the parts of the "close file" operation
  25313. ** common to all locking schemes. It closes the directory and file
  25314. ** handles, if they are valid, and sets all fields of the unixFile
  25315. ** structure to 0.
  25316. **
  25317. ** It is *not* necessary to hold the mutex when this routine is called,
  25318. ** even on VxWorks. A mutex will be acquired on VxWorks by the
  25319. ** vxworksReleaseFileId() routine.
  25320. */
  25321. static int closeUnixFile(sqlite3_file *id){
  25322. unixFile *pFile = (unixFile*)id;
  25323. #if SQLITE_MAX_MMAP_SIZE>0
  25324. unixUnmapfile(pFile);
  25325. #endif
  25326. if( pFile->h>=0 ){
  25327. robust_close(pFile, pFile->h, __LINE__);
  25328. pFile->h = -1;
  25329. }
  25330. #if OS_VXWORKS
  25331. if( pFile->pId ){
  25332. if( pFile->ctrlFlags & UNIXFILE_DELETE ){
  25333. osUnlink(pFile->pId->zCanonicalName);
  25334. }
  25335. vxworksReleaseFileId(pFile->pId);
  25336. pFile->pId = 0;
  25337. }
  25338. #endif
  25339. #ifdef SQLITE_UNLINK_AFTER_CLOSE
  25340. if( pFile->ctrlFlags & UNIXFILE_DELETE ){
  25341. osUnlink(pFile->zPath);
  25342. sqlite3_free(*(char**)&pFile->zPath);
  25343. pFile->zPath = 0;
  25344. }
  25345. #endif
  25346. OSTRACE(("CLOSE %-3d\n", pFile->h));
  25347. OpenCounter(-1);
  25348. sqlite3_free(pFile->pUnused);
  25349. memset(pFile, 0, sizeof(unixFile));
  25350. return SQLITE_OK;
  25351. }
  25352. /*
  25353. ** Close a file.
  25354. */
  25355. static int unixClose(sqlite3_file *id){
  25356. int rc = SQLITE_OK;
  25357. unixFile *pFile = (unixFile *)id;
  25358. verifyDbFile(pFile);
  25359. unixUnlock(id, NO_LOCK);
  25360. unixEnterMutex();
  25361. /* unixFile.pInode is always valid here. Otherwise, a different close
  25362. ** routine (e.g. nolockClose()) would be called instead.
  25363. */
  25364. assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );
  25365. if( ALWAYS(pFile->pInode) && pFile->pInode->nLock ){
  25366. /* If there are outstanding locks, do not actually close the file just
  25367. ** yet because that would clear those locks. Instead, add the file
  25368. ** descriptor to pInode->pUnused list. It will be automatically closed
  25369. ** when the last lock is cleared.
  25370. */
  25371. setPendingFd(pFile);
  25372. }
  25373. releaseInodeInfo(pFile);
  25374. rc = closeUnixFile(id);
  25375. unixLeaveMutex();
  25376. return rc;
  25377. }
  25378. /************** End of the posix advisory lock implementation *****************
  25379. ******************************************************************************/
  25380. /******************************************************************************
  25381. ****************************** No-op Locking **********************************
  25382. **
  25383. ** Of the various locking implementations available, this is by far the
  25384. ** simplest: locking is ignored. No attempt is made to lock the database
  25385. ** file for reading or writing.
  25386. **
  25387. ** This locking mode is appropriate for use on read-only databases
  25388. ** (ex: databases that are burned into CD-ROM, for example.) It can
  25389. ** also be used if the application employs some external mechanism to
  25390. ** prevent simultaneous access of the same database by two or more
  25391. ** database connections. But there is a serious risk of database
  25392. ** corruption if this locking mode is used in situations where multiple
  25393. ** database connections are accessing the same database file at the same
  25394. ** time and one or more of those connections are writing.
  25395. */
  25396. static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
  25397. UNUSED_PARAMETER(NotUsed);
  25398. *pResOut = 0;
  25399. return SQLITE_OK;
  25400. }
  25401. static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
  25402. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  25403. return SQLITE_OK;
  25404. }
  25405. static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
  25406. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  25407. return SQLITE_OK;
  25408. }
  25409. /*
  25410. ** Close the file.
  25411. */
  25412. static int nolockClose(sqlite3_file *id) {
  25413. return closeUnixFile(id);
  25414. }
  25415. /******************* End of the no-op lock implementation *********************
  25416. ******************************************************************************/
  25417. /******************************************************************************
  25418. ************************* Begin dot-file Locking ******************************
  25419. **
  25420. ** The dotfile locking implementation uses the existence of separate lock
  25421. ** files (really a directory) to control access to the database. This works
  25422. ** on just about every filesystem imaginable. But there are serious downsides:
  25423. **
  25424. ** (1) There is zero concurrency. A single reader blocks all other
  25425. ** connections from reading or writing the database.
  25426. **
  25427. ** (2) An application crash or power loss can leave stale lock files
  25428. ** sitting around that need to be cleared manually.
  25429. **
  25430. ** Nevertheless, a dotlock is an appropriate locking mode for use if no
  25431. ** other locking strategy is available.
  25432. **
  25433. ** Dotfile locking works by creating a subdirectory in the same directory as
  25434. ** the database and with the same name but with a ".lock" extension added.
  25435. ** The existence of a lock directory implies an EXCLUSIVE lock. All other
  25436. ** lock types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
  25437. */
  25438. /*
  25439. ** The file suffix added to the data base filename in order to create the
  25440. ** lock directory.
  25441. */
  25442. #define DOTLOCK_SUFFIX ".lock"
  25443. /*
  25444. ** This routine checks if there is a RESERVED lock held on the specified
  25445. ** file by this or any other process. If such a lock is held, set *pResOut
  25446. ** to a non-zero value otherwise *pResOut is set to zero. The return value
  25447. ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
  25448. **
  25449. ** In dotfile locking, either a lock exists or it does not. So in this
  25450. ** variation of CheckReservedLock(), *pResOut is set to true if any lock
  25451. ** is held on the file and false if the file is unlocked.
  25452. */
  25453. static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
  25454. int rc = SQLITE_OK;
  25455. int reserved = 0;
  25456. unixFile *pFile = (unixFile*)id;
  25457. SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
  25458. assert( pFile );
  25459. /* Check if a thread in this process holds such a lock */
  25460. if( pFile->eFileLock>SHARED_LOCK ){
  25461. /* Either this connection or some other connection in the same process
  25462. ** holds a lock on the file. No need to check further. */
  25463. reserved = 1;
  25464. }else{
  25465. /* The lock is held if and only if the lockfile exists */
  25466. const char *zLockFile = (const char*)pFile->lockingContext;
  25467. reserved = osAccess(zLockFile, 0)==0;
  25468. }
  25469. OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
  25470. *pResOut = reserved;
  25471. return rc;
  25472. }
  25473. /*
  25474. ** Lock the file with the lock specified by parameter eFileLock - one
  25475. ** of the following:
  25476. **
  25477. ** (1) SHARED_LOCK
  25478. ** (2) RESERVED_LOCK
  25479. ** (3) PENDING_LOCK
  25480. ** (4) EXCLUSIVE_LOCK
  25481. **
  25482. ** Sometimes when requesting one lock state, additional lock states
  25483. ** are inserted in between. The locking might fail on one of the later
  25484. ** transitions leaving the lock state different from what it started but
  25485. ** still short of its goal. The following chart shows the allowed
  25486. ** transitions and the inserted intermediate states:
  25487. **
  25488. ** UNLOCKED -> SHARED
  25489. ** SHARED -> RESERVED
  25490. ** SHARED -> (PENDING) -> EXCLUSIVE
  25491. ** RESERVED -> (PENDING) -> EXCLUSIVE
  25492. ** PENDING -> EXCLUSIVE
  25493. **
  25494. ** This routine will only increase a lock. Use the sqlite3OsUnlock()
  25495. ** routine to lower a locking level.
  25496. **
  25497. ** With dotfile locking, we really only support state (4): EXCLUSIVE.
  25498. ** But we track the other locking levels internally.
  25499. */
  25500. static int dotlockLock(sqlite3_file *id, int eFileLock) {
  25501. unixFile *pFile = (unixFile*)id;
  25502. char *zLockFile = (char *)pFile->lockingContext;
  25503. int rc = SQLITE_OK;
  25504. /* If we have any lock, then the lock file already exists. All we have
  25505. ** to do is adjust our internal record of the lock level.
  25506. */
  25507. if( pFile->eFileLock > NO_LOCK ){
  25508. pFile->eFileLock = eFileLock;
  25509. /* Always update the timestamp on the old file */
  25510. #ifdef HAVE_UTIME
  25511. utime(zLockFile, NULL);
  25512. #else
  25513. utimes(zLockFile, NULL);
  25514. #endif
  25515. return SQLITE_OK;
  25516. }
  25517. /* grab an exclusive lock */
  25518. rc = osMkdir(zLockFile, 0777);
  25519. if( rc<0 ){
  25520. /* failed to open/create the lock directory */
  25521. int tErrno = errno;
  25522. if( EEXIST == tErrno ){
  25523. rc = SQLITE_BUSY;
  25524. } else {
  25525. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
  25526. if( IS_LOCK_ERROR(rc) ){
  25527. pFile->lastErrno = tErrno;
  25528. }
  25529. }
  25530. return rc;
  25531. }
  25532. /* got it, set the type and return ok */
  25533. pFile->eFileLock = eFileLock;
  25534. return rc;
  25535. }
  25536. /*
  25537. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  25538. ** must be either NO_LOCK or SHARED_LOCK.
  25539. **
  25540. ** If the locking level of the file descriptor is already at or below
  25541. ** the requested locking level, this routine is a no-op.
  25542. **
  25543. ** When the locking level reaches NO_LOCK, delete the lock file.
  25544. */
  25545. static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
  25546. unixFile *pFile = (unixFile*)id;
  25547. char *zLockFile = (char *)pFile->lockingContext;
  25548. int rc;
  25549. assert( pFile );
  25550. OSTRACE(("UNLOCK %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
  25551. pFile->eFileLock, getpid()));
  25552. assert( eFileLock<=SHARED_LOCK );
  25553. /* no-op if possible */
  25554. if( pFile->eFileLock==eFileLock ){
  25555. return SQLITE_OK;
  25556. }
  25557. /* To downgrade to shared, simply update our internal notion of the
  25558. ** lock state. No need to mess with the file on disk.
  25559. */
  25560. if( eFileLock==SHARED_LOCK ){
  25561. pFile->eFileLock = SHARED_LOCK;
  25562. return SQLITE_OK;
  25563. }
  25564. /* To fully unlock the database, delete the lock file */
  25565. assert( eFileLock==NO_LOCK );
  25566. rc = osRmdir(zLockFile);
  25567. if( rc<0 && errno==ENOTDIR ) rc = osUnlink(zLockFile);
  25568. if( rc<0 ){
  25569. int tErrno = errno;
  25570. rc = 0;
  25571. if( ENOENT != tErrno ){
  25572. rc = SQLITE_IOERR_UNLOCK;
  25573. }
  25574. if( IS_LOCK_ERROR(rc) ){
  25575. pFile->lastErrno = tErrno;
  25576. }
  25577. return rc;
  25578. }
  25579. pFile->eFileLock = NO_LOCK;
  25580. return SQLITE_OK;
  25581. }
  25582. /*
  25583. ** Close a file. Make sure the lock has been released before closing.
  25584. */
  25585. static int dotlockClose(sqlite3_file *id) {
  25586. int rc = SQLITE_OK;
  25587. if( id ){
  25588. unixFile *pFile = (unixFile*)id;
  25589. dotlockUnlock(id, NO_LOCK);
  25590. sqlite3_free(pFile->lockingContext);
  25591. rc = closeUnixFile(id);
  25592. }
  25593. return rc;
  25594. }
  25595. /****************** End of the dot-file lock implementation *******************
  25596. ******************************************************************************/
  25597. /******************************************************************************
  25598. ************************** Begin flock Locking ********************************
  25599. **
  25600. ** Use the flock() system call to do file locking.
  25601. **
  25602. ** flock() locking is like dot-file locking in that the various
  25603. ** fine-grain locking levels supported by SQLite are collapsed into
  25604. ** a single exclusive lock. In other words, SHARED, RESERVED, and
  25605. ** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite
  25606. ** still works when you do this, but concurrency is reduced since
  25607. ** only a single process can be reading the database at a time.
  25608. **
  25609. ** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off or if
  25610. ** compiling for VXWORKS.
  25611. */
  25612. #if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
  25613. /*
  25614. ** Retry flock() calls that fail with EINTR
  25615. */
  25616. #ifdef EINTR
  25617. static int robust_flock(int fd, int op){
  25618. int rc;
  25619. do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
  25620. return rc;
  25621. }
  25622. #else
  25623. # define robust_flock(a,b) flock(a,b)
  25624. #endif
  25625. /*
  25626. ** This routine checks if there is a RESERVED lock held on the specified
  25627. ** file by this or any other process. If such a lock is held, set *pResOut
  25628. ** to a non-zero value otherwise *pResOut is set to zero. The return value
  25629. ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
  25630. */
  25631. static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
  25632. int rc = SQLITE_OK;
  25633. int reserved = 0;
  25634. unixFile *pFile = (unixFile*)id;
  25635. SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
  25636. assert( pFile );
  25637. /* Check if a thread in this process holds such a lock */
  25638. if( pFile->eFileLock>SHARED_LOCK ){
  25639. reserved = 1;
  25640. }
  25641. /* Otherwise see if some other process holds it. */
  25642. if( !reserved ){
  25643. /* attempt to get the lock */
  25644. int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
  25645. if( !lrc ){
  25646. /* got the lock, unlock it */
  25647. lrc = robust_flock(pFile->h, LOCK_UN);
  25648. if ( lrc ) {
  25649. int tErrno = errno;
  25650. /* unlock failed with an error */
  25651. lrc = SQLITE_IOERR_UNLOCK;
  25652. if( IS_LOCK_ERROR(lrc) ){
  25653. pFile->lastErrno = tErrno;
  25654. rc = lrc;
  25655. }
  25656. }
  25657. } else {
  25658. int tErrno = errno;
  25659. reserved = 1;
  25660. /* someone else might have it reserved */
  25661. lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
  25662. if( IS_LOCK_ERROR(lrc) ){
  25663. pFile->lastErrno = tErrno;
  25664. rc = lrc;
  25665. }
  25666. }
  25667. }
  25668. OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
  25669. #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
  25670. if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
  25671. rc = SQLITE_OK;
  25672. reserved=1;
  25673. }
  25674. #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
  25675. *pResOut = reserved;
  25676. return rc;
  25677. }
  25678. /*
  25679. ** Lock the file with the lock specified by parameter eFileLock - one
  25680. ** of the following:
  25681. **
  25682. ** (1) SHARED_LOCK
  25683. ** (2) RESERVED_LOCK
  25684. ** (3) PENDING_LOCK
  25685. ** (4) EXCLUSIVE_LOCK
  25686. **
  25687. ** Sometimes when requesting one lock state, additional lock states
  25688. ** are inserted in between. The locking might fail on one of the later
  25689. ** transitions leaving the lock state different from what it started but
  25690. ** still short of its goal. The following chart shows the allowed
  25691. ** transitions and the inserted intermediate states:
  25692. **
  25693. ** UNLOCKED -> SHARED
  25694. ** SHARED -> RESERVED
  25695. ** SHARED -> (PENDING) -> EXCLUSIVE
  25696. ** RESERVED -> (PENDING) -> EXCLUSIVE
  25697. ** PENDING -> EXCLUSIVE
  25698. **
  25699. ** flock() only really support EXCLUSIVE locks. We track intermediate
  25700. ** lock states in the sqlite3_file structure, but all locks SHARED or
  25701. ** above are really EXCLUSIVE locks and exclude all other processes from
  25702. ** access the file.
  25703. **
  25704. ** This routine will only increase a lock. Use the sqlite3OsUnlock()
  25705. ** routine to lower a locking level.
  25706. */
  25707. static int flockLock(sqlite3_file *id, int eFileLock) {
  25708. int rc = SQLITE_OK;
  25709. unixFile *pFile = (unixFile*)id;
  25710. assert( pFile );
  25711. /* if we already have a lock, it is exclusive.
  25712. ** Just adjust level and punt on outta here. */
  25713. if (pFile->eFileLock > NO_LOCK) {
  25714. pFile->eFileLock = eFileLock;
  25715. return SQLITE_OK;
  25716. }
  25717. /* grab an exclusive lock */
  25718. if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
  25719. int tErrno = errno;
  25720. /* didn't get, must be busy */
  25721. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
  25722. if( IS_LOCK_ERROR(rc) ){
  25723. pFile->lastErrno = tErrno;
  25724. }
  25725. } else {
  25726. /* got it, set the type and return ok */
  25727. pFile->eFileLock = eFileLock;
  25728. }
  25729. OSTRACE(("LOCK %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
  25730. rc==SQLITE_OK ? "ok" : "failed"));
  25731. #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
  25732. if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
  25733. rc = SQLITE_BUSY;
  25734. }
  25735. #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
  25736. return rc;
  25737. }
  25738. /*
  25739. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  25740. ** must be either NO_LOCK or SHARED_LOCK.
  25741. **
  25742. ** If the locking level of the file descriptor is already at or below
  25743. ** the requested locking level, this routine is a no-op.
  25744. */
  25745. static int flockUnlock(sqlite3_file *id, int eFileLock) {
  25746. unixFile *pFile = (unixFile*)id;
  25747. assert( pFile );
  25748. OSTRACE(("UNLOCK %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
  25749. pFile->eFileLock, getpid()));
  25750. assert( eFileLock<=SHARED_LOCK );
  25751. /* no-op if possible */
  25752. if( pFile->eFileLock==eFileLock ){
  25753. return SQLITE_OK;
  25754. }
  25755. /* shared can just be set because we always have an exclusive */
  25756. if (eFileLock==SHARED_LOCK) {
  25757. pFile->eFileLock = eFileLock;
  25758. return SQLITE_OK;
  25759. }
  25760. /* no, really, unlock. */
  25761. if( robust_flock(pFile->h, LOCK_UN) ){
  25762. #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
  25763. return SQLITE_OK;
  25764. #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
  25765. return SQLITE_IOERR_UNLOCK;
  25766. }else{
  25767. pFile->eFileLock = NO_LOCK;
  25768. return SQLITE_OK;
  25769. }
  25770. }
  25771. /*
  25772. ** Close a file.
  25773. */
  25774. static int flockClose(sqlite3_file *id) {
  25775. int rc = SQLITE_OK;
  25776. if( id ){
  25777. flockUnlock(id, NO_LOCK);
  25778. rc = closeUnixFile(id);
  25779. }
  25780. return rc;
  25781. }
  25782. #endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
  25783. /******************* End of the flock lock implementation *********************
  25784. ******************************************************************************/
  25785. /******************************************************************************
  25786. ************************ Begin Named Semaphore Locking ************************
  25787. **
  25788. ** Named semaphore locking is only supported on VxWorks.
  25789. **
  25790. ** Semaphore locking is like dot-lock and flock in that it really only
  25791. ** supports EXCLUSIVE locking. Only a single process can read or write
  25792. ** the database file at a time. This reduces potential concurrency, but
  25793. ** makes the lock implementation much easier.
  25794. */
  25795. #if OS_VXWORKS
  25796. /*
  25797. ** This routine checks if there is a RESERVED lock held on the specified
  25798. ** file by this or any other process. If such a lock is held, set *pResOut
  25799. ** to a non-zero value otherwise *pResOut is set to zero. The return value
  25800. ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
  25801. */
  25802. static int semCheckReservedLock(sqlite3_file *id, int *pResOut) {
  25803. int rc = SQLITE_OK;
  25804. int reserved = 0;
  25805. unixFile *pFile = (unixFile*)id;
  25806. SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
  25807. assert( pFile );
  25808. /* Check if a thread in this process holds such a lock */
  25809. if( pFile->eFileLock>SHARED_LOCK ){
  25810. reserved = 1;
  25811. }
  25812. /* Otherwise see if some other process holds it. */
  25813. if( !reserved ){
  25814. sem_t *pSem = pFile->pInode->pSem;
  25815. if( sem_trywait(pSem)==-1 ){
  25816. int tErrno = errno;
  25817. if( EAGAIN != tErrno ){
  25818. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
  25819. pFile->lastErrno = tErrno;
  25820. } else {
  25821. /* someone else has the lock when we are in NO_LOCK */
  25822. reserved = (pFile->eFileLock < SHARED_LOCK);
  25823. }
  25824. }else{
  25825. /* we could have it if we want it */
  25826. sem_post(pSem);
  25827. }
  25828. }
  25829. OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
  25830. *pResOut = reserved;
  25831. return rc;
  25832. }
  25833. /*
  25834. ** Lock the file with the lock specified by parameter eFileLock - one
  25835. ** of the following:
  25836. **
  25837. ** (1) SHARED_LOCK
  25838. ** (2) RESERVED_LOCK
  25839. ** (3) PENDING_LOCK
  25840. ** (4) EXCLUSIVE_LOCK
  25841. **
  25842. ** Sometimes when requesting one lock state, additional lock states
  25843. ** are inserted in between. The locking might fail on one of the later
  25844. ** transitions leaving the lock state different from what it started but
  25845. ** still short of its goal. The following chart shows the allowed
  25846. ** transitions and the inserted intermediate states:
  25847. **
  25848. ** UNLOCKED -> SHARED
  25849. ** SHARED -> RESERVED
  25850. ** SHARED -> (PENDING) -> EXCLUSIVE
  25851. ** RESERVED -> (PENDING) -> EXCLUSIVE
  25852. ** PENDING -> EXCLUSIVE
  25853. **
  25854. ** Semaphore locks only really support EXCLUSIVE locks. We track intermediate
  25855. ** lock states in the sqlite3_file structure, but all locks SHARED or
  25856. ** above are really EXCLUSIVE locks and exclude all other processes from
  25857. ** access the file.
  25858. **
  25859. ** This routine will only increase a lock. Use the sqlite3OsUnlock()
  25860. ** routine to lower a locking level.
  25861. */
  25862. static int semLock(sqlite3_file *id, int eFileLock) {
  25863. unixFile *pFile = (unixFile*)id;
  25864. sem_t *pSem = pFile->pInode->pSem;
  25865. int rc = SQLITE_OK;
  25866. /* if we already have a lock, it is exclusive.
  25867. ** Just adjust level and punt on outta here. */
  25868. if (pFile->eFileLock > NO_LOCK) {
  25869. pFile->eFileLock = eFileLock;
  25870. rc = SQLITE_OK;
  25871. goto sem_end_lock;
  25872. }
  25873. /* lock semaphore now but bail out when already locked. */
  25874. if( sem_trywait(pSem)==-1 ){
  25875. rc = SQLITE_BUSY;
  25876. goto sem_end_lock;
  25877. }
  25878. /* got it, set the type and return ok */
  25879. pFile->eFileLock = eFileLock;
  25880. sem_end_lock:
  25881. return rc;
  25882. }
  25883. /*
  25884. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  25885. ** must be either NO_LOCK or SHARED_LOCK.
  25886. **
  25887. ** If the locking level of the file descriptor is already at or below
  25888. ** the requested locking level, this routine is a no-op.
  25889. */
  25890. static int semUnlock(sqlite3_file *id, int eFileLock) {
  25891. unixFile *pFile = (unixFile*)id;
  25892. sem_t *pSem = pFile->pInode->pSem;
  25893. assert( pFile );
  25894. assert( pSem );
  25895. OSTRACE(("UNLOCK %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
  25896. pFile->eFileLock, getpid()));
  25897. assert( eFileLock<=SHARED_LOCK );
  25898. /* no-op if possible */
  25899. if( pFile->eFileLock==eFileLock ){
  25900. return SQLITE_OK;
  25901. }
  25902. /* shared can just be set because we always have an exclusive */
  25903. if (eFileLock==SHARED_LOCK) {
  25904. pFile->eFileLock = eFileLock;
  25905. return SQLITE_OK;
  25906. }
  25907. /* no, really unlock. */
  25908. if ( sem_post(pSem)==-1 ) {
  25909. int rc, tErrno = errno;
  25910. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
  25911. if( IS_LOCK_ERROR(rc) ){
  25912. pFile->lastErrno = tErrno;
  25913. }
  25914. return rc;
  25915. }
  25916. pFile->eFileLock = NO_LOCK;
  25917. return SQLITE_OK;
  25918. }
  25919. /*
  25920. ** Close a file.
  25921. */
  25922. static int semClose(sqlite3_file *id) {
  25923. if( id ){
  25924. unixFile *pFile = (unixFile*)id;
  25925. semUnlock(id, NO_LOCK);
  25926. assert( pFile );
  25927. unixEnterMutex();
  25928. releaseInodeInfo(pFile);
  25929. unixLeaveMutex();
  25930. closeUnixFile(id);
  25931. }
  25932. return SQLITE_OK;
  25933. }
  25934. #endif /* OS_VXWORKS */
  25935. /*
  25936. ** Named semaphore locking is only available on VxWorks.
  25937. **
  25938. *************** End of the named semaphore lock implementation ****************
  25939. ******************************************************************************/
  25940. /******************************************************************************
  25941. *************************** Begin AFP Locking *********************************
  25942. **
  25943. ** AFP is the Apple Filing Protocol. AFP is a network filesystem found
  25944. ** on Apple Macintosh computers - both OS9 and OSX.
  25945. **
  25946. ** Third-party implementations of AFP are available. But this code here
  25947. ** only works on OSX.
  25948. */
  25949. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  25950. /*
  25951. ** The afpLockingContext structure contains all afp lock specific state
  25952. */
  25953. typedef struct afpLockingContext afpLockingContext;
  25954. struct afpLockingContext {
  25955. int reserved;
  25956. const char *dbPath; /* Name of the open file */
  25957. };
  25958. struct ByteRangeLockPB2
  25959. {
  25960. unsigned long long offset; /* offset to first byte to lock */
  25961. unsigned long long length; /* nbr of bytes to lock */
  25962. unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
  25963. unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
  25964. unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
  25965. int fd; /* file desc to assoc this lock with */
  25966. };
  25967. #define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
  25968. /*
  25969. ** This is a utility for setting or clearing a bit-range lock on an
  25970. ** AFP filesystem.
  25971. **
  25972. ** Return SQLITE_OK on success, SQLITE_BUSY on failure.
  25973. */
  25974. static int afpSetLock(
  25975. const char *path, /* Name of the file to be locked or unlocked */
  25976. unixFile *pFile, /* Open file descriptor on path */
  25977. unsigned long long offset, /* First byte to be locked */
  25978. unsigned long long length, /* Number of bytes to lock */
  25979. int setLockFlag /* True to set lock. False to clear lock */
  25980. ){
  25981. struct ByteRangeLockPB2 pb;
  25982. int err;
  25983. pb.unLockFlag = setLockFlag ? 0 : 1;
  25984. pb.startEndFlag = 0;
  25985. pb.offset = offset;
  25986. pb.length = length;
  25987. pb.fd = pFile->h;
  25988. OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
  25989. (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
  25990. offset, length));
  25991. err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
  25992. if ( err==-1 ) {
  25993. int rc;
  25994. int tErrno = errno;
  25995. OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
  25996. path, tErrno, strerror(tErrno)));
  25997. #ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
  25998. rc = SQLITE_BUSY;
  25999. #else
  26000. rc = sqliteErrorFromPosixError(tErrno,
  26001. setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
  26002. #endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
  26003. if( IS_LOCK_ERROR(rc) ){
  26004. pFile->lastErrno = tErrno;
  26005. }
  26006. return rc;
  26007. } else {
  26008. return SQLITE_OK;
  26009. }
  26010. }
  26011. /*
  26012. ** This routine checks if there is a RESERVED lock held on the specified
  26013. ** file by this or any other process. If such a lock is held, set *pResOut
  26014. ** to a non-zero value otherwise *pResOut is set to zero. The return value
  26015. ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
  26016. */
  26017. static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
  26018. int rc = SQLITE_OK;
  26019. int reserved = 0;
  26020. unixFile *pFile = (unixFile*)id;
  26021. afpLockingContext *context;
  26022. SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
  26023. assert( pFile );
  26024. context = (afpLockingContext *) pFile->lockingContext;
  26025. if( context->reserved ){
  26026. *pResOut = 1;
  26027. return SQLITE_OK;
  26028. }
  26029. unixEnterMutex(); /* Because pFile->pInode is shared across threads */
  26030. /* Check if a thread in this process holds such a lock */
  26031. if( pFile->pInode->eFileLock>SHARED_LOCK ){
  26032. reserved = 1;
  26033. }
  26034. /* Otherwise see if some other process holds it.
  26035. */
  26036. if( !reserved ){
  26037. /* lock the RESERVED byte */
  26038. int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
  26039. if( SQLITE_OK==lrc ){
  26040. /* if we succeeded in taking the reserved lock, unlock it to restore
  26041. ** the original state */
  26042. lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
  26043. } else {
  26044. /* if we failed to get the lock then someone else must have it */
  26045. reserved = 1;
  26046. }
  26047. if( IS_LOCK_ERROR(lrc) ){
  26048. rc=lrc;
  26049. }
  26050. }
  26051. unixLeaveMutex();
  26052. OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
  26053. *pResOut = reserved;
  26054. return rc;
  26055. }
  26056. /*
  26057. ** Lock the file with the lock specified by parameter eFileLock - one
  26058. ** of the following:
  26059. **
  26060. ** (1) SHARED_LOCK
  26061. ** (2) RESERVED_LOCK
  26062. ** (3) PENDING_LOCK
  26063. ** (4) EXCLUSIVE_LOCK
  26064. **
  26065. ** Sometimes when requesting one lock state, additional lock states
  26066. ** are inserted in between. The locking might fail on one of the later
  26067. ** transitions leaving the lock state different from what it started but
  26068. ** still short of its goal. The following chart shows the allowed
  26069. ** transitions and the inserted intermediate states:
  26070. **
  26071. ** UNLOCKED -> SHARED
  26072. ** SHARED -> RESERVED
  26073. ** SHARED -> (PENDING) -> EXCLUSIVE
  26074. ** RESERVED -> (PENDING) -> EXCLUSIVE
  26075. ** PENDING -> EXCLUSIVE
  26076. **
  26077. ** This routine will only increase a lock. Use the sqlite3OsUnlock()
  26078. ** routine to lower a locking level.
  26079. */
  26080. static int afpLock(sqlite3_file *id, int eFileLock){
  26081. int rc = SQLITE_OK;
  26082. unixFile *pFile = (unixFile*)id;
  26083. unixInodeInfo *pInode = pFile->pInode;
  26084. afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
  26085. assert( pFile );
  26086. OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
  26087. azFileLock(eFileLock), azFileLock(pFile->eFileLock),
  26088. azFileLock(pInode->eFileLock), pInode->nShared , getpid()));
  26089. /* If there is already a lock of this type or more restrictive on the
  26090. ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
  26091. ** unixEnterMutex() hasn't been called yet.
  26092. */
  26093. if( pFile->eFileLock>=eFileLock ){
  26094. OSTRACE(("LOCK %d %s ok (already held) (afp)\n", pFile->h,
  26095. azFileLock(eFileLock)));
  26096. return SQLITE_OK;
  26097. }
  26098. /* Make sure the locking sequence is correct
  26099. ** (1) We never move from unlocked to anything higher than shared lock.
  26100. ** (2) SQLite never explicitly requests a pendig lock.
  26101. ** (3) A shared lock is always held when a reserve lock is requested.
  26102. */
  26103. assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
  26104. assert( eFileLock!=PENDING_LOCK );
  26105. assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
  26106. /* This mutex is needed because pFile->pInode is shared across threads
  26107. */
  26108. unixEnterMutex();
  26109. pInode = pFile->pInode;
  26110. /* If some thread using this PID has a lock via a different unixFile*
  26111. ** handle that precludes the requested lock, return BUSY.
  26112. */
  26113. if( (pFile->eFileLock!=pInode->eFileLock &&
  26114. (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
  26115. ){
  26116. rc = SQLITE_BUSY;
  26117. goto afp_end_lock;
  26118. }
  26119. /* If a SHARED lock is requested, and some thread using this PID already
  26120. ** has a SHARED or RESERVED lock, then increment reference counts and
  26121. ** return SQLITE_OK.
  26122. */
  26123. if( eFileLock==SHARED_LOCK &&
  26124. (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
  26125. assert( eFileLock==SHARED_LOCK );
  26126. assert( pFile->eFileLock==0 );
  26127. assert( pInode->nShared>0 );
  26128. pFile->eFileLock = SHARED_LOCK;
  26129. pInode->nShared++;
  26130. pInode->nLock++;
  26131. goto afp_end_lock;
  26132. }
  26133. /* A PENDING lock is needed before acquiring a SHARED lock and before
  26134. ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
  26135. ** be released.
  26136. */
  26137. if( eFileLock==SHARED_LOCK
  26138. || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
  26139. ){
  26140. int failed;
  26141. failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
  26142. if (failed) {
  26143. rc = failed;
  26144. goto afp_end_lock;
  26145. }
  26146. }
  26147. /* If control gets to this point, then actually go ahead and make
  26148. ** operating system calls for the specified lock.
  26149. */
  26150. if( eFileLock==SHARED_LOCK ){
  26151. int lrc1, lrc2, lrc1Errno = 0;
  26152. long lk, mask;
  26153. assert( pInode->nShared==0 );
  26154. assert( pInode->eFileLock==0 );
  26155. mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
  26156. /* Now get the read-lock SHARED_LOCK */
  26157. /* note that the quality of the randomness doesn't matter that much */
  26158. lk = random();
  26159. pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
  26160. lrc1 = afpSetLock(context->dbPath, pFile,
  26161. SHARED_FIRST+pInode->sharedByte, 1, 1);
  26162. if( IS_LOCK_ERROR(lrc1) ){
  26163. lrc1Errno = pFile->lastErrno;
  26164. }
  26165. /* Drop the temporary PENDING lock */
  26166. lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
  26167. if( IS_LOCK_ERROR(lrc1) ) {
  26168. pFile->lastErrno = lrc1Errno;
  26169. rc = lrc1;
  26170. goto afp_end_lock;
  26171. } else if( IS_LOCK_ERROR(lrc2) ){
  26172. rc = lrc2;
  26173. goto afp_end_lock;
  26174. } else if( lrc1 != SQLITE_OK ) {
  26175. rc = lrc1;
  26176. } else {
  26177. pFile->eFileLock = SHARED_LOCK;
  26178. pInode->nLock++;
  26179. pInode->nShared = 1;
  26180. }
  26181. }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
  26182. /* We are trying for an exclusive lock but another thread in this
  26183. ** same process is still holding a shared lock. */
  26184. rc = SQLITE_BUSY;
  26185. }else{
  26186. /* The request was for a RESERVED or EXCLUSIVE lock. It is
  26187. ** assumed that there is a SHARED or greater lock on the file
  26188. ** already.
  26189. */
  26190. int failed = 0;
  26191. assert( 0!=pFile->eFileLock );
  26192. if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
  26193. /* Acquire a RESERVED lock */
  26194. failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
  26195. if( !failed ){
  26196. context->reserved = 1;
  26197. }
  26198. }
  26199. if (!failed && eFileLock == EXCLUSIVE_LOCK) {
  26200. /* Acquire an EXCLUSIVE lock */
  26201. /* Remove the shared lock before trying the range. we'll need to
  26202. ** reestablish the shared lock if we can't get the afpUnlock
  26203. */
  26204. if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
  26205. pInode->sharedByte, 1, 0)) ){
  26206. int failed2 = SQLITE_OK;
  26207. /* now attemmpt to get the exclusive lock range */
  26208. failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
  26209. SHARED_SIZE, 1);
  26210. if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
  26211. SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
  26212. /* Can't reestablish the shared lock. Sqlite can't deal, this is
  26213. ** a critical I/O error
  26214. */
  26215. rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 :
  26216. SQLITE_IOERR_LOCK;
  26217. goto afp_end_lock;
  26218. }
  26219. }else{
  26220. rc = failed;
  26221. }
  26222. }
  26223. if( failed ){
  26224. rc = failed;
  26225. }
  26226. }
  26227. if( rc==SQLITE_OK ){
  26228. pFile->eFileLock = eFileLock;
  26229. pInode->eFileLock = eFileLock;
  26230. }else if( eFileLock==EXCLUSIVE_LOCK ){
  26231. pFile->eFileLock = PENDING_LOCK;
  26232. pInode->eFileLock = PENDING_LOCK;
  26233. }
  26234. afp_end_lock:
  26235. unixLeaveMutex();
  26236. OSTRACE(("LOCK %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
  26237. rc==SQLITE_OK ? "ok" : "failed"));
  26238. return rc;
  26239. }
  26240. /*
  26241. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  26242. ** must be either NO_LOCK or SHARED_LOCK.
  26243. **
  26244. ** If the locking level of the file descriptor is already at or below
  26245. ** the requested locking level, this routine is a no-op.
  26246. */
  26247. static int afpUnlock(sqlite3_file *id, int eFileLock) {
  26248. int rc = SQLITE_OK;
  26249. unixFile *pFile = (unixFile*)id;
  26250. unixInodeInfo *pInode;
  26251. afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
  26252. int skipShared = 0;
  26253. #ifdef SQLITE_TEST
  26254. int h = pFile->h;
  26255. #endif
  26256. assert( pFile );
  26257. OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
  26258. pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
  26259. getpid()));
  26260. assert( eFileLock<=SHARED_LOCK );
  26261. if( pFile->eFileLock<=eFileLock ){
  26262. return SQLITE_OK;
  26263. }
  26264. unixEnterMutex();
  26265. pInode = pFile->pInode;
  26266. assert( pInode->nShared!=0 );
  26267. if( pFile->eFileLock>SHARED_LOCK ){
  26268. assert( pInode->eFileLock==pFile->eFileLock );
  26269. SimulateIOErrorBenign(1);
  26270. SimulateIOError( h=(-1) )
  26271. SimulateIOErrorBenign(0);
  26272. #ifdef SQLITE_DEBUG
  26273. /* When reducing a lock such that other processes can start
  26274. ** reading the database file again, make sure that the
  26275. ** transaction counter was updated if any part of the database
  26276. ** file changed. If the transaction counter is not updated,
  26277. ** other connections to the same file might not realize that
  26278. ** the file has changed and hence might not know to flush their
  26279. ** cache. The use of a stale cache can lead to database corruption.
  26280. */
  26281. assert( pFile->inNormalWrite==0
  26282. || pFile->dbUpdate==0
  26283. || pFile->transCntrChng==1 );
  26284. pFile->inNormalWrite = 0;
  26285. #endif
  26286. if( pFile->eFileLock==EXCLUSIVE_LOCK ){
  26287. rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
  26288. if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
  26289. /* only re-establish the shared lock if necessary */
  26290. int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
  26291. rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
  26292. } else {
  26293. skipShared = 1;
  26294. }
  26295. }
  26296. if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
  26297. rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
  26298. }
  26299. if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
  26300. rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
  26301. if( !rc ){
  26302. context->reserved = 0;
  26303. }
  26304. }
  26305. if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
  26306. pInode->eFileLock = SHARED_LOCK;
  26307. }
  26308. }
  26309. if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
  26310. /* Decrement the shared lock counter. Release the lock using an
  26311. ** OS call only when all threads in this same process have released
  26312. ** the lock.
  26313. */
  26314. unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
  26315. pInode->nShared--;
  26316. if( pInode->nShared==0 ){
  26317. SimulateIOErrorBenign(1);
  26318. SimulateIOError( h=(-1) )
  26319. SimulateIOErrorBenign(0);
  26320. if( !skipShared ){
  26321. rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
  26322. }
  26323. if( !rc ){
  26324. pInode->eFileLock = NO_LOCK;
  26325. pFile->eFileLock = NO_LOCK;
  26326. }
  26327. }
  26328. if( rc==SQLITE_OK ){
  26329. pInode->nLock--;
  26330. assert( pInode->nLock>=0 );
  26331. if( pInode->nLock==0 ){
  26332. closePendingFds(pFile);
  26333. }
  26334. }
  26335. }
  26336. unixLeaveMutex();
  26337. if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
  26338. return rc;
  26339. }
  26340. /*
  26341. ** Close a file & cleanup AFP specific locking context
  26342. */
  26343. static int afpClose(sqlite3_file *id) {
  26344. int rc = SQLITE_OK;
  26345. if( id ){
  26346. unixFile *pFile = (unixFile*)id;
  26347. afpUnlock(id, NO_LOCK);
  26348. unixEnterMutex();
  26349. if( pFile->pInode && pFile->pInode->nLock ){
  26350. /* If there are outstanding locks, do not actually close the file just
  26351. ** yet because that would clear those locks. Instead, add the file
  26352. ** descriptor to pInode->aPending. It will be automatically closed when
  26353. ** the last lock is cleared.
  26354. */
  26355. setPendingFd(pFile);
  26356. }
  26357. releaseInodeInfo(pFile);
  26358. sqlite3_free(pFile->lockingContext);
  26359. rc = closeUnixFile(id);
  26360. unixLeaveMutex();
  26361. }
  26362. return rc;
  26363. }
  26364. #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
  26365. /*
  26366. ** The code above is the AFP lock implementation. The code is specific
  26367. ** to MacOSX and does not work on other unix platforms. No alternative
  26368. ** is available. If you don't compile for a mac, then the "unix-afp"
  26369. ** VFS is not available.
  26370. **
  26371. ********************* End of the AFP lock implementation **********************
  26372. ******************************************************************************/
  26373. /******************************************************************************
  26374. *************************** Begin NFS Locking ********************************/
  26375. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  26376. /*
  26377. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  26378. ** must be either NO_LOCK or SHARED_LOCK.
  26379. **
  26380. ** If the locking level of the file descriptor is already at or below
  26381. ** the requested locking level, this routine is a no-op.
  26382. */
  26383. static int nfsUnlock(sqlite3_file *id, int eFileLock){
  26384. return posixUnlock(id, eFileLock, 1);
  26385. }
  26386. #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
  26387. /*
  26388. ** The code above is the NFS lock implementation. The code is specific
  26389. ** to MacOSX and does not work on other unix platforms. No alternative
  26390. ** is available.
  26391. **
  26392. ********************* End of the NFS lock implementation **********************
  26393. ******************************************************************************/
  26394. /******************************************************************************
  26395. **************** Non-locking sqlite3_file methods *****************************
  26396. **
  26397. ** The next division contains implementations for all methods of the
  26398. ** sqlite3_file object other than the locking methods. The locking
  26399. ** methods were defined in divisions above (one locking method per
  26400. ** division). Those methods that are common to all locking modes
  26401. ** are gather together into this division.
  26402. */
  26403. /*
  26404. ** Seek to the offset passed as the second argument, then read cnt
  26405. ** bytes into pBuf. Return the number of bytes actually read.
  26406. **
  26407. ** NB: If you define USE_PREAD or USE_PREAD64, then it might also
  26408. ** be necessary to define _XOPEN_SOURCE to be 500. This varies from
  26409. ** one system to another. Since SQLite does not define USE_PREAD
  26410. ** in any form by default, we will not attempt to define _XOPEN_SOURCE.
  26411. ** See tickets #2741 and #2681.
  26412. **
  26413. ** To avoid stomping the errno value on a failed read the lastErrno value
  26414. ** is set before returning.
  26415. */
  26416. static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
  26417. int got;
  26418. int prior = 0;
  26419. #if (!defined(USE_PREAD) && !defined(USE_PREAD64))
  26420. i64 newOffset;
  26421. #endif
  26422. TIMER_START;
  26423. assert( cnt==(cnt&0x1ffff) );
  26424. assert( id->h>2 );
  26425. cnt &= 0x1ffff;
  26426. do{
  26427. #if defined(USE_PREAD)
  26428. got = osPread(id->h, pBuf, cnt, offset);
  26429. SimulateIOError( got = -1 );
  26430. #elif defined(USE_PREAD64)
  26431. got = osPread64(id->h, pBuf, cnt, offset);
  26432. SimulateIOError( got = -1 );
  26433. #else
  26434. newOffset = lseek(id->h, offset, SEEK_SET);
  26435. SimulateIOError( newOffset-- );
  26436. if( newOffset!=offset ){
  26437. if( newOffset == -1 ){
  26438. ((unixFile*)id)->lastErrno = errno;
  26439. }else{
  26440. ((unixFile*)id)->lastErrno = 0;
  26441. }
  26442. return -1;
  26443. }
  26444. got = osRead(id->h, pBuf, cnt);
  26445. #endif
  26446. if( got==cnt ) break;
  26447. if( got<0 ){
  26448. if( errno==EINTR ){ got = 1; continue; }
  26449. prior = 0;
  26450. ((unixFile*)id)->lastErrno = errno;
  26451. break;
  26452. }else if( got>0 ){
  26453. cnt -= got;
  26454. offset += got;
  26455. prior += got;
  26456. pBuf = (void*)(got + (char*)pBuf);
  26457. }
  26458. }while( got>0 );
  26459. TIMER_END;
  26460. OSTRACE(("READ %-3d %5d %7lld %llu\n",
  26461. id->h, got+prior, offset-prior, TIMER_ELAPSED));
  26462. return got+prior;
  26463. }
  26464. /*
  26465. ** Read data from a file into a buffer. Return SQLITE_OK if all
  26466. ** bytes were read successfully and SQLITE_IOERR if anything goes
  26467. ** wrong.
  26468. */
  26469. static int unixRead(
  26470. sqlite3_file *id,
  26471. void *pBuf,
  26472. int amt,
  26473. sqlite3_int64 offset
  26474. ){
  26475. unixFile *pFile = (unixFile *)id;
  26476. int got;
  26477. assert( id );
  26478. assert( offset>=0 );
  26479. assert( amt>0 );
  26480. /* If this is a database file (not a journal, master-journal or temp
  26481. ** file), the bytes in the locking range should never be read or written. */
  26482. #if 0
  26483. assert( pFile->pUnused==0
  26484. || offset>=PENDING_BYTE+512
  26485. || offset+amt<=PENDING_BYTE
  26486. );
  26487. #endif
  26488. #if SQLITE_MAX_MMAP_SIZE>0
  26489. /* Deal with as much of this read request as possible by transfering
  26490. ** data from the memory mapping using memcpy(). */
  26491. if( offset<pFile->mmapSize ){
  26492. if( offset+amt <= pFile->mmapSize ){
  26493. memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
  26494. return SQLITE_OK;
  26495. }else{
  26496. int nCopy = pFile->mmapSize - offset;
  26497. memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
  26498. pBuf = &((u8 *)pBuf)[nCopy];
  26499. amt -= nCopy;
  26500. offset += nCopy;
  26501. }
  26502. }
  26503. #endif
  26504. got = seekAndRead(pFile, offset, pBuf, amt);
  26505. if( got==amt ){
  26506. return SQLITE_OK;
  26507. }else if( got<0 ){
  26508. /* lastErrno set by seekAndRead */
  26509. return SQLITE_IOERR_READ;
  26510. }else{
  26511. pFile->lastErrno = 0; /* not a system error */
  26512. /* Unread parts of the buffer must be zero-filled */
  26513. memset(&((char*)pBuf)[got], 0, amt-got);
  26514. return SQLITE_IOERR_SHORT_READ;
  26515. }
  26516. }
  26517. /*
  26518. ** Attempt to seek the file-descriptor passed as the first argument to
  26519. ** absolute offset iOff, then attempt to write nBuf bytes of data from
  26520. ** pBuf to it. If an error occurs, return -1 and set *piErrno. Otherwise,
  26521. ** return the actual number of bytes written (which may be less than
  26522. ** nBuf).
  26523. */
  26524. static int seekAndWriteFd(
  26525. int fd, /* File descriptor to write to */
  26526. i64 iOff, /* File offset to begin writing at */
  26527. const void *pBuf, /* Copy data from this buffer to the file */
  26528. int nBuf, /* Size of buffer pBuf in bytes */
  26529. int *piErrno /* OUT: Error number if error occurs */
  26530. ){
  26531. int rc = 0; /* Value returned by system call */
  26532. assert( nBuf==(nBuf&0x1ffff) );
  26533. assert( fd>2 );
  26534. nBuf &= 0x1ffff;
  26535. TIMER_START;
  26536. #if defined(USE_PREAD)
  26537. do{ rc = osPwrite(fd, pBuf, nBuf, iOff); }while( rc<0 && errno==EINTR );
  26538. #elif defined(USE_PREAD64)
  26539. do{ rc = osPwrite64(fd, pBuf, nBuf, iOff);}while( rc<0 && errno==EINTR);
  26540. #else
  26541. do{
  26542. i64 iSeek = lseek(fd, iOff, SEEK_SET);
  26543. SimulateIOError( iSeek-- );
  26544. if( iSeek!=iOff ){
  26545. if( piErrno ) *piErrno = (iSeek==-1 ? errno : 0);
  26546. return -1;
  26547. }
  26548. rc = osWrite(fd, pBuf, nBuf);
  26549. }while( rc<0 && errno==EINTR );
  26550. #endif
  26551. TIMER_END;
  26552. OSTRACE(("WRITE %-3d %5d %7lld %llu\n", fd, rc, iOff, TIMER_ELAPSED));
  26553. if( rc<0 && piErrno ) *piErrno = errno;
  26554. return rc;
  26555. }
  26556. /*
  26557. ** Seek to the offset in id->offset then read cnt bytes into pBuf.
  26558. ** Return the number of bytes actually read. Update the offset.
  26559. **
  26560. ** To avoid stomping the errno value on a failed write the lastErrno value
  26561. ** is set before returning.
  26562. */
  26563. static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
  26564. return seekAndWriteFd(id->h, offset, pBuf, cnt, &id->lastErrno);
  26565. }
  26566. /*
  26567. ** Write data from a buffer into a file. Return SQLITE_OK on success
  26568. ** or some other error code on failure.
  26569. */
  26570. static int unixWrite(
  26571. sqlite3_file *id,
  26572. const void *pBuf,
  26573. int amt,
  26574. sqlite3_int64 offset
  26575. ){
  26576. unixFile *pFile = (unixFile*)id;
  26577. int wrote = 0;
  26578. assert( id );
  26579. assert( amt>0 );
  26580. /* If this is a database file (not a journal, master-journal or temp
  26581. ** file), the bytes in the locking range should never be read or written. */
  26582. #if 0
  26583. assert( pFile->pUnused==0
  26584. || offset>=PENDING_BYTE+512
  26585. || offset+amt<=PENDING_BYTE
  26586. );
  26587. #endif
  26588. #ifdef SQLITE_DEBUG
  26589. /* If we are doing a normal write to a database file (as opposed to
  26590. ** doing a hot-journal rollback or a write to some file other than a
  26591. ** normal database file) then record the fact that the database
  26592. ** has changed. If the transaction counter is modified, record that
  26593. ** fact too.
  26594. */
  26595. if( pFile->inNormalWrite ){
  26596. pFile->dbUpdate = 1; /* The database has been modified */
  26597. if( offset<=24 && offset+amt>=27 ){
  26598. int rc;
  26599. char oldCntr[4];
  26600. SimulateIOErrorBenign(1);
  26601. rc = seekAndRead(pFile, 24, oldCntr, 4);
  26602. SimulateIOErrorBenign(0);
  26603. if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
  26604. pFile->transCntrChng = 1; /* The transaction counter has changed */
  26605. }
  26606. }
  26607. }
  26608. #endif
  26609. #if SQLITE_MAX_MMAP_SIZE>0
  26610. /* Deal with as much of this write request as possible by transfering
  26611. ** data from the memory mapping using memcpy(). */
  26612. if( offset<pFile->mmapSize ){
  26613. if( offset+amt <= pFile->mmapSize ){
  26614. memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
  26615. return SQLITE_OK;
  26616. }else{
  26617. int nCopy = pFile->mmapSize - offset;
  26618. memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
  26619. pBuf = &((u8 *)pBuf)[nCopy];
  26620. amt -= nCopy;
  26621. offset += nCopy;
  26622. }
  26623. }
  26624. #endif
  26625. while( amt>0 && (wrote = seekAndWrite(pFile, offset, pBuf, amt))>0 ){
  26626. amt -= wrote;
  26627. offset += wrote;
  26628. pBuf = &((char*)pBuf)[wrote];
  26629. }
  26630. SimulateIOError(( wrote=(-1), amt=1 ));
  26631. SimulateDiskfullError(( wrote=0, amt=1 ));
  26632. if( amt>0 ){
  26633. if( wrote<0 && pFile->lastErrno!=ENOSPC ){
  26634. /* lastErrno set by seekAndWrite */
  26635. return SQLITE_IOERR_WRITE;
  26636. }else{
  26637. pFile->lastErrno = 0; /* not a system error */
  26638. return SQLITE_FULL;
  26639. }
  26640. }
  26641. return SQLITE_OK;
  26642. }
  26643. #ifdef SQLITE_TEST
  26644. /*
  26645. ** Count the number of fullsyncs and normal syncs. This is used to test
  26646. ** that syncs and fullsyncs are occurring at the right times.
  26647. */
  26648. SQLITE_API int sqlite3_sync_count = 0;
  26649. SQLITE_API int sqlite3_fullsync_count = 0;
  26650. #endif
  26651. /*
  26652. ** We do not trust systems to provide a working fdatasync(). Some do.
  26653. ** Others do no. To be safe, we will stick with the (slightly slower)
  26654. ** fsync(). If you know that your system does support fdatasync() correctly,
  26655. ** then simply compile with -Dfdatasync=fdatasync
  26656. */
  26657. #if !defined(fdatasync)
  26658. # define fdatasync fsync
  26659. #endif
  26660. /*
  26661. ** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
  26662. ** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
  26663. ** only available on Mac OS X. But that could change.
  26664. */
  26665. #ifdef F_FULLFSYNC
  26666. # define HAVE_FULLFSYNC 1
  26667. #else
  26668. # define HAVE_FULLFSYNC 0
  26669. #endif
  26670. /*
  26671. ** The fsync() system call does not work as advertised on many
  26672. ** unix systems. The following procedure is an attempt to make
  26673. ** it work better.
  26674. **
  26675. ** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
  26676. ** for testing when we want to run through the test suite quickly.
  26677. ** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
  26678. ** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
  26679. ** or power failure will likely corrupt the database file.
  26680. **
  26681. ** SQLite sets the dataOnly flag if the size of the file is unchanged.
  26682. ** The idea behind dataOnly is that it should only write the file content
  26683. ** to disk, not the inode. We only set dataOnly if the file size is
  26684. ** unchanged since the file size is part of the inode. However,
  26685. ** Ted Ts'o tells us that fdatasync() will also write the inode if the
  26686. ** file size has changed. The only real difference between fdatasync()
  26687. ** and fsync(), Ted tells us, is that fdatasync() will not flush the
  26688. ** inode if the mtime or owner or other inode attributes have changed.
  26689. ** We only care about the file size, not the other file attributes, so
  26690. ** as far as SQLite is concerned, an fdatasync() is always adequate.
  26691. ** So, we always use fdatasync() if it is available, regardless of
  26692. ** the value of the dataOnly flag.
  26693. */
  26694. static int full_fsync(int fd, int fullSync, int dataOnly){
  26695. int rc;
  26696. /* The following "ifdef/elif/else/" block has the same structure as
  26697. ** the one below. It is replicated here solely to avoid cluttering
  26698. ** up the real code with the UNUSED_PARAMETER() macros.
  26699. */
  26700. #ifdef SQLITE_NO_SYNC
  26701. UNUSED_PARAMETER(fd);
  26702. UNUSED_PARAMETER(fullSync);
  26703. UNUSED_PARAMETER(dataOnly);
  26704. #elif HAVE_FULLFSYNC
  26705. UNUSED_PARAMETER(dataOnly);
  26706. #else
  26707. UNUSED_PARAMETER(fullSync);
  26708. UNUSED_PARAMETER(dataOnly);
  26709. #endif
  26710. /* Record the number of times that we do a normal fsync() and
  26711. ** FULLSYNC. This is used during testing to verify that this procedure
  26712. ** gets called with the correct arguments.
  26713. */
  26714. #ifdef SQLITE_TEST
  26715. if( fullSync ) sqlite3_fullsync_count++;
  26716. sqlite3_sync_count++;
  26717. #endif
  26718. /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
  26719. ** no-op
  26720. */
  26721. #ifdef SQLITE_NO_SYNC
  26722. rc = SQLITE_OK;
  26723. #elif HAVE_FULLFSYNC
  26724. if( fullSync ){
  26725. rc = osFcntl(fd, F_FULLFSYNC, 0);
  26726. }else{
  26727. rc = 1;
  26728. }
  26729. /* If the FULLFSYNC failed, fall back to attempting an fsync().
  26730. ** It shouldn't be possible for fullfsync to fail on the local
  26731. ** file system (on OSX), so failure indicates that FULLFSYNC
  26732. ** isn't supported for this file system. So, attempt an fsync
  26733. ** and (for now) ignore the overhead of a superfluous fcntl call.
  26734. ** It'd be better to detect fullfsync support once and avoid
  26735. ** the fcntl call every time sync is called.
  26736. */
  26737. if( rc ) rc = fsync(fd);
  26738. #elif defined(__APPLE__)
  26739. /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
  26740. ** so currently we default to the macro that redefines fdatasync to fsync
  26741. */
  26742. rc = fsync(fd);
  26743. #else
  26744. rc = fdatasync(fd);
  26745. #if OS_VXWORKS
  26746. if( rc==-1 && errno==ENOTSUP ){
  26747. rc = fsync(fd);
  26748. }
  26749. #endif /* OS_VXWORKS */
  26750. #endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
  26751. if( OS_VXWORKS && rc!= -1 ){
  26752. rc = 0;
  26753. }
  26754. return rc;
  26755. }
  26756. /*
  26757. ** Open a file descriptor to the directory containing file zFilename.
  26758. ** If successful, *pFd is set to the opened file descriptor and
  26759. ** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
  26760. ** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
  26761. ** value.
  26762. **
  26763. ** The directory file descriptor is used for only one thing - to
  26764. ** fsync() a directory to make sure file creation and deletion events
  26765. ** are flushed to disk. Such fsyncs are not needed on newer
  26766. ** journaling filesystems, but are required on older filesystems.
  26767. **
  26768. ** This routine can be overridden using the xSetSysCall interface.
  26769. ** The ability to override this routine was added in support of the
  26770. ** chromium sandbox. Opening a directory is a security risk (we are
  26771. ** told) so making it overrideable allows the chromium sandbox to
  26772. ** replace this routine with a harmless no-op. To make this routine
  26773. ** a no-op, replace it with a stub that returns SQLITE_OK but leaves
  26774. ** *pFd set to a negative number.
  26775. **
  26776. ** If SQLITE_OK is returned, the caller is responsible for closing
  26777. ** the file descriptor *pFd using close().
  26778. */
  26779. static int openDirectory(const char *zFilename, int *pFd){
  26780. int ii;
  26781. int fd = -1;
  26782. char zDirname[MAX_PATHNAME+1];
  26783. sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
  26784. for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
  26785. if( ii>0 ){
  26786. zDirname[ii] = '\0';
  26787. fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
  26788. if( fd>=0 ){
  26789. OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
  26790. }
  26791. }
  26792. *pFd = fd;
  26793. return (fd>=0?SQLITE_OK:unixLogError(SQLITE_CANTOPEN_BKPT, "open", zDirname));
  26794. }
  26795. /*
  26796. ** Make sure all writes to a particular file are committed to disk.
  26797. **
  26798. ** If dataOnly==0 then both the file itself and its metadata (file
  26799. ** size, access time, etc) are synced. If dataOnly!=0 then only the
  26800. ** file data is synced.
  26801. **
  26802. ** Under Unix, also make sure that the directory entry for the file
  26803. ** has been created by fsync-ing the directory that contains the file.
  26804. ** If we do not do this and we encounter a power failure, the directory
  26805. ** entry for the journal might not exist after we reboot. The next
  26806. ** SQLite to access the file will not know that the journal exists (because
  26807. ** the directory entry for the journal was never created) and the transaction
  26808. ** will not roll back - possibly leading to database corruption.
  26809. */
  26810. static int unixSync(sqlite3_file *id, int flags){
  26811. int rc;
  26812. unixFile *pFile = (unixFile*)id;
  26813. int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
  26814. int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
  26815. /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
  26816. assert((flags&0x0F)==SQLITE_SYNC_NORMAL
  26817. || (flags&0x0F)==SQLITE_SYNC_FULL
  26818. );
  26819. /* Unix cannot, but some systems may return SQLITE_FULL from here. This
  26820. ** line is to test that doing so does not cause any problems.
  26821. */
  26822. SimulateDiskfullError( return SQLITE_FULL );
  26823. assert( pFile );
  26824. OSTRACE(("SYNC %-3d\n", pFile->h));
  26825. rc = full_fsync(pFile->h, isFullsync, isDataOnly);
  26826. SimulateIOError( rc=1 );
  26827. if( rc ){
  26828. pFile->lastErrno = errno;
  26829. return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
  26830. }
  26831. /* Also fsync the directory containing the file if the DIRSYNC flag
  26832. ** is set. This is a one-time occurrence. Many systems (examples: AIX)
  26833. ** are unable to fsync a directory, so ignore errors on the fsync.
  26834. */
  26835. if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){
  26836. int dirfd;
  26837. OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath,
  26838. HAVE_FULLFSYNC, isFullsync));
  26839. rc = osOpenDirectory(pFile->zPath, &dirfd);
  26840. if( rc==SQLITE_OK && dirfd>=0 ){
  26841. full_fsync(dirfd, 0, 0);
  26842. robust_close(pFile, dirfd, __LINE__);
  26843. }else if( rc==SQLITE_CANTOPEN ){
  26844. rc = SQLITE_OK;
  26845. }
  26846. pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC;
  26847. }
  26848. return rc;
  26849. }
  26850. /*
  26851. ** Truncate an open file to a specified size
  26852. */
  26853. static int unixTruncate(sqlite3_file *id, i64 nByte){
  26854. unixFile *pFile = (unixFile *)id;
  26855. int rc;
  26856. assert( pFile );
  26857. SimulateIOError( return SQLITE_IOERR_TRUNCATE );
  26858. /* If the user has configured a chunk-size for this file, truncate the
  26859. ** file so that it consists of an integer number of chunks (i.e. the
  26860. ** actual file size after the operation may be larger than the requested
  26861. ** size).
  26862. */
  26863. if( pFile->szChunk>0 ){
  26864. nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
  26865. }
  26866. rc = robust_ftruncate(pFile->h, nByte);
  26867. if( rc ){
  26868. pFile->lastErrno = errno;
  26869. return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
  26870. }else{
  26871. #ifdef SQLITE_DEBUG
  26872. /* If we are doing a normal write to a database file (as opposed to
  26873. ** doing a hot-journal rollback or a write to some file other than a
  26874. ** normal database file) and we truncate the file to zero length,
  26875. ** that effectively updates the change counter. This might happen
  26876. ** when restoring a database using the backup API from a zero-length
  26877. ** source.
  26878. */
  26879. if( pFile->inNormalWrite && nByte==0 ){
  26880. pFile->transCntrChng = 1;
  26881. }
  26882. #endif
  26883. #if SQLITE_MAX_MMAP_SIZE>0
  26884. /* If the file was just truncated to a size smaller than the currently
  26885. ** mapped region, reduce the effective mapping size as well. SQLite will
  26886. ** use read() and write() to access data beyond this point from now on.
  26887. */
  26888. if( nByte<pFile->mmapSize ){
  26889. pFile->mmapSize = nByte;
  26890. }
  26891. #endif
  26892. return SQLITE_OK;
  26893. }
  26894. }
  26895. /*
  26896. ** Determine the current size of a file in bytes
  26897. */
  26898. static int unixFileSize(sqlite3_file *id, i64 *pSize){
  26899. int rc;
  26900. struct stat buf;
  26901. assert( id );
  26902. rc = osFstat(((unixFile*)id)->h, &buf);
  26903. SimulateIOError( rc=1 );
  26904. if( rc!=0 ){
  26905. ((unixFile*)id)->lastErrno = errno;
  26906. return SQLITE_IOERR_FSTAT;
  26907. }
  26908. *pSize = buf.st_size;
  26909. /* When opening a zero-size database, the findInodeInfo() procedure
  26910. ** writes a single byte into that file in order to work around a bug
  26911. ** in the OS-X msdos filesystem. In order to avoid problems with upper
  26912. ** layers, we need to report this file size as zero even though it is
  26913. ** really 1. Ticket #3260.
  26914. */
  26915. if( *pSize==1 ) *pSize = 0;
  26916. return SQLITE_OK;
  26917. }
  26918. #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
  26919. /*
  26920. ** Handler for proxy-locking file-control verbs. Defined below in the
  26921. ** proxying locking division.
  26922. */
  26923. static int proxyFileControl(sqlite3_file*,int,void*);
  26924. #endif
  26925. /*
  26926. ** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
  26927. ** file-control operation. Enlarge the database to nBytes in size
  26928. ** (rounded up to the next chunk-size). If the database is already
  26929. ** nBytes or larger, this routine is a no-op.
  26930. */
  26931. static int fcntlSizeHint(unixFile *pFile, i64 nByte){
  26932. if( pFile->szChunk>0 ){
  26933. i64 nSize; /* Required file size */
  26934. struct stat buf; /* Used to hold return values of fstat() */
  26935. if( osFstat(pFile->h, &buf) ) return SQLITE_IOERR_FSTAT;
  26936. nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
  26937. if( nSize>(i64)buf.st_size ){
  26938. #if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
  26939. /* The code below is handling the return value of osFallocate()
  26940. ** correctly. posix_fallocate() is defined to "returns zero on success,
  26941. ** or an error number on failure". See the manpage for details. */
  26942. int err;
  26943. do{
  26944. err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
  26945. }while( err==EINTR );
  26946. if( err ) return SQLITE_IOERR_WRITE;
  26947. #else
  26948. /* If the OS does not have posix_fallocate(), fake it. First use
  26949. ** ftruncate() to set the file size, then write a single byte to
  26950. ** the last byte in each block within the extended region. This
  26951. ** is the same technique used by glibc to implement posix_fallocate()
  26952. ** on systems that do not have a real fallocate() system call.
  26953. */
  26954. int nBlk = buf.st_blksize; /* File-system block size */
  26955. i64 iWrite; /* Next offset to write to */
  26956. if( robust_ftruncate(pFile->h, nSize) ){
  26957. pFile->lastErrno = errno;
  26958. return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
  26959. }
  26960. iWrite = ((buf.st_size + 2*nBlk - 1)/nBlk)*nBlk-1;
  26961. while( iWrite<nSize ){
  26962. int nWrite = seekAndWrite(pFile, iWrite, "", 1);
  26963. if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
  26964. iWrite += nBlk;
  26965. }
  26966. #endif
  26967. }
  26968. }
  26969. #if SQLITE_MAX_MMAP_SIZE>0
  26970. if( pFile->mmapSizeMax>0 && nByte>pFile->mmapSize ){
  26971. int rc;
  26972. if( pFile->szChunk<=0 ){
  26973. if( robust_ftruncate(pFile->h, nByte) ){
  26974. pFile->lastErrno = errno;
  26975. return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
  26976. }
  26977. }
  26978. rc = unixMapfile(pFile, nByte);
  26979. return rc;
  26980. }
  26981. #endif
  26982. return SQLITE_OK;
  26983. }
  26984. /*
  26985. ** If *pArg is initially negative then this is a query. Set *pArg to
  26986. ** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
  26987. **
  26988. ** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
  26989. */
  26990. static void unixModeBit(unixFile *pFile, unsigned char mask, int *pArg){
  26991. if( *pArg<0 ){
  26992. *pArg = (pFile->ctrlFlags & mask)!=0;
  26993. }else if( (*pArg)==0 ){
  26994. pFile->ctrlFlags &= ~mask;
  26995. }else{
  26996. pFile->ctrlFlags |= mask;
  26997. }
  26998. }
  26999. /* Forward declaration */
  27000. static int unixGetTempname(int nBuf, char *zBuf);
  27001. /*
  27002. ** Information and control of an open file handle.
  27003. */
  27004. static int unixFileControl(sqlite3_file *id, int op, void *pArg){
  27005. unixFile *pFile = (unixFile*)id;
  27006. switch( op ){
  27007. case SQLITE_FCNTL_LOCKSTATE: {
  27008. *(int*)pArg = pFile->eFileLock;
  27009. return SQLITE_OK;
  27010. }
  27011. case SQLITE_LAST_ERRNO: {
  27012. *(int*)pArg = pFile->lastErrno;
  27013. return SQLITE_OK;
  27014. }
  27015. case SQLITE_FCNTL_CHUNK_SIZE: {
  27016. pFile->szChunk = *(int *)pArg;
  27017. return SQLITE_OK;
  27018. }
  27019. case SQLITE_FCNTL_SIZE_HINT: {
  27020. int rc;
  27021. SimulateIOErrorBenign(1);
  27022. rc = fcntlSizeHint(pFile, *(i64 *)pArg);
  27023. SimulateIOErrorBenign(0);
  27024. return rc;
  27025. }
  27026. case SQLITE_FCNTL_PERSIST_WAL: {
  27027. unixModeBit(pFile, UNIXFILE_PERSIST_WAL, (int*)pArg);
  27028. return SQLITE_OK;
  27029. }
  27030. case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
  27031. unixModeBit(pFile, UNIXFILE_PSOW, (int*)pArg);
  27032. return SQLITE_OK;
  27033. }
  27034. case SQLITE_FCNTL_VFSNAME: {
  27035. *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
  27036. return SQLITE_OK;
  27037. }
  27038. case SQLITE_FCNTL_TEMPFILENAME: {
  27039. char *zTFile = sqlite3_malloc( pFile->pVfs->mxPathname );
  27040. if( zTFile ){
  27041. unixGetTempname(pFile->pVfs->mxPathname, zTFile);
  27042. *(char**)pArg = zTFile;
  27043. }
  27044. return SQLITE_OK;
  27045. }
  27046. case SQLITE_FCNTL_HAS_MOVED: {
  27047. *(int*)pArg = fileHasMoved(pFile);
  27048. return SQLITE_OK;
  27049. }
  27050. #if SQLITE_MAX_MMAP_SIZE>0
  27051. case SQLITE_FCNTL_MMAP_SIZE: {
  27052. i64 newLimit = *(i64*)pArg;
  27053. int rc = SQLITE_OK;
  27054. if( newLimit>sqlite3GlobalConfig.mxMmap ){
  27055. newLimit = sqlite3GlobalConfig.mxMmap;
  27056. }
  27057. *(i64*)pArg = pFile->mmapSizeMax;
  27058. if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
  27059. pFile->mmapSizeMax = newLimit;
  27060. if( pFile->mmapSize>0 ){
  27061. unixUnmapfile(pFile);
  27062. rc = unixMapfile(pFile, -1);
  27063. }
  27064. }
  27065. return rc;
  27066. }
  27067. #endif
  27068. #ifdef SQLITE_DEBUG
  27069. /* The pager calls this method to signal that it has done
  27070. ** a rollback and that the database is therefore unchanged and
  27071. ** it hence it is OK for the transaction change counter to be
  27072. ** unchanged.
  27073. */
  27074. case SQLITE_FCNTL_DB_UNCHANGED: {
  27075. ((unixFile*)id)->dbUpdate = 0;
  27076. return SQLITE_OK;
  27077. }
  27078. #endif
  27079. #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
  27080. case SQLITE_SET_LOCKPROXYFILE:
  27081. case SQLITE_GET_LOCKPROXYFILE: {
  27082. return proxyFileControl(id,op,pArg);
  27083. }
  27084. #endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
  27085. }
  27086. return SQLITE_NOTFOUND;
  27087. }
  27088. /*
  27089. ** Return the sector size in bytes of the underlying block device for
  27090. ** the specified file. This is almost always 512 bytes, but may be
  27091. ** larger for some devices.
  27092. **
  27093. ** SQLite code assumes this function cannot fail. It also assumes that
  27094. ** if two files are created in the same file-system directory (i.e.
  27095. ** a database and its journal file) that the sector size will be the
  27096. ** same for both.
  27097. */
  27098. #ifndef __QNXNTO__
  27099. static int unixSectorSize(sqlite3_file *NotUsed){
  27100. UNUSED_PARAMETER(NotUsed);
  27101. return SQLITE_DEFAULT_SECTOR_SIZE;
  27102. }
  27103. #endif
  27104. /*
  27105. ** The following version of unixSectorSize() is optimized for QNX.
  27106. */
  27107. #ifdef __QNXNTO__
  27108. #include <sys/dcmd_blk.h>
  27109. #include <sys/statvfs.h>
  27110. static int unixSectorSize(sqlite3_file *id){
  27111. unixFile *pFile = (unixFile*)id;
  27112. if( pFile->sectorSize == 0 ){
  27113. struct statvfs fsInfo;
  27114. /* Set defaults for non-supported filesystems */
  27115. pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
  27116. pFile->deviceCharacteristics = 0;
  27117. if( fstatvfs(pFile->h, &fsInfo) == -1 ) {
  27118. return pFile->sectorSize;
  27119. }
  27120. if( !strcmp(fsInfo.f_basetype, "tmp") ) {
  27121. pFile->sectorSize = fsInfo.f_bsize;
  27122. pFile->deviceCharacteristics =
  27123. SQLITE_IOCAP_ATOMIC4K | /* All ram filesystem writes are atomic */
  27124. SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
  27125. ** the write succeeds */
  27126. SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
  27127. ** so it is ordered */
  27128. 0;
  27129. }else if( strstr(fsInfo.f_basetype, "etfs") ){
  27130. pFile->sectorSize = fsInfo.f_bsize;
  27131. pFile->deviceCharacteristics =
  27132. /* etfs cluster size writes are atomic */
  27133. (pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) |
  27134. SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
  27135. ** the write succeeds */
  27136. SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
  27137. ** so it is ordered */
  27138. 0;
  27139. }else if( !strcmp(fsInfo.f_basetype, "qnx6") ){
  27140. pFile->sectorSize = fsInfo.f_bsize;
  27141. pFile->deviceCharacteristics =
  27142. SQLITE_IOCAP_ATOMIC | /* All filesystem writes are atomic */
  27143. SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
  27144. ** the write succeeds */
  27145. SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
  27146. ** so it is ordered */
  27147. 0;
  27148. }else if( !strcmp(fsInfo.f_basetype, "qnx4") ){
  27149. pFile->sectorSize = fsInfo.f_bsize;
  27150. pFile->deviceCharacteristics =
  27151. /* full bitset of atomics from max sector size and smaller */
  27152. ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
  27153. SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
  27154. ** so it is ordered */
  27155. 0;
  27156. }else if( strstr(fsInfo.f_basetype, "dos") ){
  27157. pFile->sectorSize = fsInfo.f_bsize;
  27158. pFile->deviceCharacteristics =
  27159. /* full bitset of atomics from max sector size and smaller */
  27160. ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
  27161. SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
  27162. ** so it is ordered */
  27163. 0;
  27164. }else{
  27165. pFile->deviceCharacteristics =
  27166. SQLITE_IOCAP_ATOMIC512 | /* blocks are atomic */
  27167. SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
  27168. ** the write succeeds */
  27169. 0;
  27170. }
  27171. }
  27172. /* Last chance verification. If the sector size isn't a multiple of 512
  27173. ** then it isn't valid.*/
  27174. if( pFile->sectorSize % 512 != 0 ){
  27175. pFile->deviceCharacteristics = 0;
  27176. pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
  27177. }
  27178. return pFile->sectorSize;
  27179. }
  27180. #endif /* __QNXNTO__ */
  27181. /*
  27182. ** Return the device characteristics for the file.
  27183. **
  27184. ** This VFS is set up to return SQLITE_IOCAP_POWERSAFE_OVERWRITE by default.
  27185. ** However, that choice is controversial since technically the underlying
  27186. ** file system does not always provide powersafe overwrites. (In other
  27187. ** words, after a power-loss event, parts of the file that were never
  27188. ** written might end up being altered.) However, non-PSOW behavior is very,
  27189. ** very rare. And asserting PSOW makes a large reduction in the amount
  27190. ** of required I/O for journaling, since a lot of padding is eliminated.
  27191. ** Hence, while POWERSAFE_OVERWRITE is on by default, there is a file-control
  27192. ** available to turn it off and URI query parameter available to turn it off.
  27193. */
  27194. static int unixDeviceCharacteristics(sqlite3_file *id){
  27195. unixFile *p = (unixFile*)id;
  27196. int rc = 0;
  27197. #ifdef __QNXNTO__
  27198. if( p->sectorSize==0 ) unixSectorSize(id);
  27199. rc = p->deviceCharacteristics;
  27200. #endif
  27201. if( p->ctrlFlags & UNIXFILE_PSOW ){
  27202. rc |= SQLITE_IOCAP_POWERSAFE_OVERWRITE;
  27203. }
  27204. return rc;
  27205. }
  27206. #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
  27207. /*
  27208. ** Return the system page size.
  27209. **
  27210. ** This function should not be called directly by other code in this file.
  27211. ** Instead, it should be called via macro osGetpagesize().
  27212. */
  27213. static int unixGetpagesize(void){
  27214. #if defined(_BSD_SOURCE)
  27215. return getpagesize();
  27216. #else
  27217. return (int)sysconf(_SC_PAGESIZE);
  27218. #endif
  27219. }
  27220. #endif /* !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0 */
  27221. #ifndef SQLITE_OMIT_WAL
  27222. /*
  27223. ** Object used to represent an shared memory buffer.
  27224. **
  27225. ** When multiple threads all reference the same wal-index, each thread
  27226. ** has its own unixShm object, but they all point to a single instance
  27227. ** of this unixShmNode object. In other words, each wal-index is opened
  27228. ** only once per process.
  27229. **
  27230. ** Each unixShmNode object is connected to a single unixInodeInfo object.
  27231. ** We could coalesce this object into unixInodeInfo, but that would mean
  27232. ** every open file that does not use shared memory (in other words, most
  27233. ** open files) would have to carry around this extra information. So
  27234. ** the unixInodeInfo object contains a pointer to this unixShmNode object
  27235. ** and the unixShmNode object is created only when needed.
  27236. **
  27237. ** unixMutexHeld() must be true when creating or destroying
  27238. ** this object or while reading or writing the following fields:
  27239. **
  27240. ** nRef
  27241. **
  27242. ** The following fields are read-only after the object is created:
  27243. **
  27244. ** fid
  27245. ** zFilename
  27246. **
  27247. ** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
  27248. ** unixMutexHeld() is true when reading or writing any other field
  27249. ** in this structure.
  27250. */
  27251. struct unixShmNode {
  27252. unixInodeInfo *pInode; /* unixInodeInfo that owns this SHM node */
  27253. sqlite3_mutex *mutex; /* Mutex to access this object */
  27254. char *zFilename; /* Name of the mmapped file */
  27255. int h; /* Open file descriptor */
  27256. int szRegion; /* Size of shared-memory regions */
  27257. u16 nRegion; /* Size of array apRegion */
  27258. u8 isReadonly; /* True if read-only */
  27259. char **apRegion; /* Array of mapped shared-memory regions */
  27260. int nRef; /* Number of unixShm objects pointing to this */
  27261. unixShm *pFirst; /* All unixShm objects pointing to this */
  27262. #ifdef SQLITE_DEBUG
  27263. u8 exclMask; /* Mask of exclusive locks held */
  27264. u8 sharedMask; /* Mask of shared locks held */
  27265. u8 nextShmId; /* Next available unixShm.id value */
  27266. #endif
  27267. };
  27268. /*
  27269. ** Structure used internally by this VFS to record the state of an
  27270. ** open shared memory connection.
  27271. **
  27272. ** The following fields are initialized when this object is created and
  27273. ** are read-only thereafter:
  27274. **
  27275. ** unixShm.pFile
  27276. ** unixShm.id
  27277. **
  27278. ** All other fields are read/write. The unixShm.pFile->mutex must be held
  27279. ** while accessing any read/write fields.
  27280. */
  27281. struct unixShm {
  27282. unixShmNode *pShmNode; /* The underlying unixShmNode object */
  27283. unixShm *pNext; /* Next unixShm with the same unixShmNode */
  27284. u8 hasMutex; /* True if holding the unixShmNode mutex */
  27285. u8 id; /* Id of this connection within its unixShmNode */
  27286. u16 sharedMask; /* Mask of shared locks held */
  27287. u16 exclMask; /* Mask of exclusive locks held */
  27288. };
  27289. /*
  27290. ** Constants used for locking
  27291. */
  27292. #define UNIX_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
  27293. #define UNIX_SHM_DMS (UNIX_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
  27294. /*
  27295. ** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
  27296. **
  27297. ** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
  27298. ** otherwise.
  27299. */
  27300. static int unixShmSystemLock(
  27301. unixShmNode *pShmNode, /* Apply locks to this open shared-memory segment */
  27302. int lockType, /* F_UNLCK, F_RDLCK, or F_WRLCK */
  27303. int ofst, /* First byte of the locking range */
  27304. int n /* Number of bytes to lock */
  27305. ){
  27306. struct flock f; /* The posix advisory locking structure */
  27307. int rc = SQLITE_OK; /* Result code form fcntl() */
  27308. /* Access to the unixShmNode object is serialized by the caller */
  27309. assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
  27310. /* Shared locks never span more than one byte */
  27311. assert( n==1 || lockType!=F_RDLCK );
  27312. /* Locks are within range */
  27313. assert( n>=1 && n<SQLITE_SHM_NLOCK );
  27314. if( pShmNode->h>=0 ){
  27315. /* Initialize the locking parameters */
  27316. memset(&f, 0, sizeof(f));
  27317. f.l_type = lockType;
  27318. f.l_whence = SEEK_SET;
  27319. f.l_start = ofst;
  27320. f.l_len = n;
  27321. rc = osFcntl(pShmNode->h, F_SETLK, &f);
  27322. rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
  27323. }
  27324. /* Update the global lock state and do debug tracing */
  27325. #ifdef SQLITE_DEBUG
  27326. { u16 mask;
  27327. OSTRACE(("SHM-LOCK "));
  27328. mask = ofst>31 ? 0xffff : (1<<(ofst+n)) - (1<<ofst);
  27329. if( rc==SQLITE_OK ){
  27330. if( lockType==F_UNLCK ){
  27331. OSTRACE(("unlock %d ok", ofst));
  27332. pShmNode->exclMask &= ~mask;
  27333. pShmNode->sharedMask &= ~mask;
  27334. }else if( lockType==F_RDLCK ){
  27335. OSTRACE(("read-lock %d ok", ofst));
  27336. pShmNode->exclMask &= ~mask;
  27337. pShmNode->sharedMask |= mask;
  27338. }else{
  27339. assert( lockType==F_WRLCK );
  27340. OSTRACE(("write-lock %d ok", ofst));
  27341. pShmNode->exclMask |= mask;
  27342. pShmNode->sharedMask &= ~mask;
  27343. }
  27344. }else{
  27345. if( lockType==F_UNLCK ){
  27346. OSTRACE(("unlock %d failed", ofst));
  27347. }else if( lockType==F_RDLCK ){
  27348. OSTRACE(("read-lock failed"));
  27349. }else{
  27350. assert( lockType==F_WRLCK );
  27351. OSTRACE(("write-lock %d failed", ofst));
  27352. }
  27353. }
  27354. OSTRACE((" - afterwards %03x,%03x\n",
  27355. pShmNode->sharedMask, pShmNode->exclMask));
  27356. }
  27357. #endif
  27358. return rc;
  27359. }
  27360. /*
  27361. ** Return the minimum number of 32KB shm regions that should be mapped at
  27362. ** a time, assuming that each mapping must be an integer multiple of the
  27363. ** current system page-size.
  27364. **
  27365. ** Usually, this is 1. The exception seems to be systems that are configured
  27366. ** to use 64KB pages - in this case each mapping must cover at least two
  27367. ** shm regions.
  27368. */
  27369. static int unixShmRegionPerMap(void){
  27370. int shmsz = 32*1024; /* SHM region size */
  27371. int pgsz = osGetpagesize(); /* System page size */
  27372. assert( ((pgsz-1)&pgsz)==0 ); /* Page size must be a power of 2 */
  27373. if( pgsz<shmsz ) return 1;
  27374. return pgsz/shmsz;
  27375. }
  27376. /*
  27377. ** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
  27378. **
  27379. ** This is not a VFS shared-memory method; it is a utility function called
  27380. ** by VFS shared-memory methods.
  27381. */
  27382. static void unixShmPurge(unixFile *pFd){
  27383. unixShmNode *p = pFd->pInode->pShmNode;
  27384. assert( unixMutexHeld() );
  27385. if( p && p->nRef==0 ){
  27386. int nShmPerMap = unixShmRegionPerMap();
  27387. int i;
  27388. assert( p->pInode==pFd->pInode );
  27389. sqlite3_mutex_free(p->mutex);
  27390. for(i=0; i<p->nRegion; i+=nShmPerMap){
  27391. if( p->h>=0 ){
  27392. osMunmap(p->apRegion[i], p->szRegion);
  27393. }else{
  27394. sqlite3_free(p->apRegion[i]);
  27395. }
  27396. }
  27397. sqlite3_free(p->apRegion);
  27398. if( p->h>=0 ){
  27399. robust_close(pFd, p->h, __LINE__);
  27400. p->h = -1;
  27401. }
  27402. p->pInode->pShmNode = 0;
  27403. sqlite3_free(p);
  27404. }
  27405. }
  27406. /*
  27407. ** Open a shared-memory area associated with open database file pDbFd.
  27408. ** This particular implementation uses mmapped files.
  27409. **
  27410. ** The file used to implement shared-memory is in the same directory
  27411. ** as the open database file and has the same name as the open database
  27412. ** file with the "-shm" suffix added. For example, if the database file
  27413. ** is "/home/user1/config.db" then the file that is created and mmapped
  27414. ** for shared memory will be called "/home/user1/config.db-shm".
  27415. **
  27416. ** Another approach to is to use files in /dev/shm or /dev/tmp or an
  27417. ** some other tmpfs mount. But if a file in a different directory
  27418. ** from the database file is used, then differing access permissions
  27419. ** or a chroot() might cause two different processes on the same
  27420. ** database to end up using different files for shared memory -
  27421. ** meaning that their memory would not really be shared - resulting
  27422. ** in database corruption. Nevertheless, this tmpfs file usage
  27423. ** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
  27424. ** or the equivalent. The use of the SQLITE_SHM_DIRECTORY compile-time
  27425. ** option results in an incompatible build of SQLite; builds of SQLite
  27426. ** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
  27427. ** same database file at the same time, database corruption will likely
  27428. ** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
  27429. ** "unsupported" and may go away in a future SQLite release.
  27430. **
  27431. ** When opening a new shared-memory file, if no other instances of that
  27432. ** file are currently open, in this process or in other processes, then
  27433. ** the file must be truncated to zero length or have its header cleared.
  27434. **
  27435. ** If the original database file (pDbFd) is using the "unix-excl" VFS
  27436. ** that means that an exclusive lock is held on the database file and
  27437. ** that no other processes are able to read or write the database. In
  27438. ** that case, we do not really need shared memory. No shared memory
  27439. ** file is created. The shared memory will be simulated with heap memory.
  27440. */
  27441. static int unixOpenSharedMemory(unixFile *pDbFd){
  27442. struct unixShm *p = 0; /* The connection to be opened */
  27443. struct unixShmNode *pShmNode; /* The underlying mmapped file */
  27444. int rc; /* Result code */
  27445. unixInodeInfo *pInode; /* The inode of fd */
  27446. char *zShmFilename; /* Name of the file used for SHM */
  27447. int nShmFilename; /* Size of the SHM filename in bytes */
  27448. /* Allocate space for the new unixShm object. */
  27449. p = sqlite3_malloc( sizeof(*p) );
  27450. if( p==0 ) return SQLITE_NOMEM;
  27451. memset(p, 0, sizeof(*p));
  27452. assert( pDbFd->pShm==0 );
  27453. /* Check to see if a unixShmNode object already exists. Reuse an existing
  27454. ** one if present. Create a new one if necessary.
  27455. */
  27456. unixEnterMutex();
  27457. pInode = pDbFd->pInode;
  27458. pShmNode = pInode->pShmNode;
  27459. if( pShmNode==0 ){
  27460. struct stat sStat; /* fstat() info for database file */
  27461. /* Call fstat() to figure out the permissions on the database file. If
  27462. ** a new *-shm file is created, an attempt will be made to create it
  27463. ** with the same permissions.
  27464. */
  27465. if( osFstat(pDbFd->h, &sStat) && pInode->bProcessLock==0 ){
  27466. rc = SQLITE_IOERR_FSTAT;
  27467. goto shm_open_err;
  27468. }
  27469. #ifdef SQLITE_SHM_DIRECTORY
  27470. nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 31;
  27471. #else
  27472. nShmFilename = 6 + (int)strlen(pDbFd->zPath);
  27473. #endif
  27474. pShmNode = sqlite3_malloc( sizeof(*pShmNode) + nShmFilename );
  27475. if( pShmNode==0 ){
  27476. rc = SQLITE_NOMEM;
  27477. goto shm_open_err;
  27478. }
  27479. memset(pShmNode, 0, sizeof(*pShmNode)+nShmFilename);
  27480. zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
  27481. #ifdef SQLITE_SHM_DIRECTORY
  27482. sqlite3_snprintf(nShmFilename, zShmFilename,
  27483. SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
  27484. (u32)sStat.st_ino, (u32)sStat.st_dev);
  27485. #else
  27486. sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", pDbFd->zPath);
  27487. sqlite3FileSuffix3(pDbFd->zPath, zShmFilename);
  27488. #endif
  27489. pShmNode->h = -1;
  27490. pDbFd->pInode->pShmNode = pShmNode;
  27491. pShmNode->pInode = pDbFd->pInode;
  27492. pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
  27493. if( pShmNode->mutex==0 ){
  27494. rc = SQLITE_NOMEM;
  27495. goto shm_open_err;
  27496. }
  27497. if( pInode->bProcessLock==0 ){
  27498. int openFlags = O_RDWR | O_CREAT;
  27499. if( sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
  27500. openFlags = O_RDONLY;
  27501. pShmNode->isReadonly = 1;
  27502. }
  27503. pShmNode->h = robust_open(zShmFilename, openFlags, (sStat.st_mode&0777));
  27504. if( pShmNode->h<0 ){
  27505. rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShmFilename);
  27506. goto shm_open_err;
  27507. }
  27508. /* If this process is running as root, make sure that the SHM file
  27509. ** is owned by the same user that owns the original database. Otherwise,
  27510. ** the original owner will not be able to connect.
  27511. */
  27512. osFchown(pShmNode->h, sStat.st_uid, sStat.st_gid);
  27513. /* Check to see if another process is holding the dead-man switch.
  27514. ** If not, truncate the file to zero length.
  27515. */
  27516. rc = SQLITE_OK;
  27517. if( unixShmSystemLock(pShmNode, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
  27518. if( robust_ftruncate(pShmNode->h, 0) ){
  27519. rc = unixLogError(SQLITE_IOERR_SHMOPEN, "ftruncate", zShmFilename);
  27520. }
  27521. }
  27522. if( rc==SQLITE_OK ){
  27523. rc = unixShmSystemLock(pShmNode, F_RDLCK, UNIX_SHM_DMS, 1);
  27524. }
  27525. if( rc ) goto shm_open_err;
  27526. }
  27527. }
  27528. /* Make the new connection a child of the unixShmNode */
  27529. p->pShmNode = pShmNode;
  27530. #ifdef SQLITE_DEBUG
  27531. p->id = pShmNode->nextShmId++;
  27532. #endif
  27533. pShmNode->nRef++;
  27534. pDbFd->pShm = p;
  27535. unixLeaveMutex();
  27536. /* The reference count on pShmNode has already been incremented under
  27537. ** the cover of the unixEnterMutex() mutex and the pointer from the
  27538. ** new (struct unixShm) object to the pShmNode has been set. All that is
  27539. ** left to do is to link the new object into the linked list starting
  27540. ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
  27541. ** mutex.
  27542. */
  27543. sqlite3_mutex_enter(pShmNode->mutex);
  27544. p->pNext = pShmNode->pFirst;
  27545. pShmNode->pFirst = p;
  27546. sqlite3_mutex_leave(pShmNode->mutex);
  27547. return SQLITE_OK;
  27548. /* Jump here on any error */
  27549. shm_open_err:
  27550. unixShmPurge(pDbFd); /* This call frees pShmNode if required */
  27551. sqlite3_free(p);
  27552. unixLeaveMutex();
  27553. return rc;
  27554. }
  27555. /*
  27556. ** This function is called to obtain a pointer to region iRegion of the
  27557. ** shared-memory associated with the database file fd. Shared-memory regions
  27558. ** are numbered starting from zero. Each shared-memory region is szRegion
  27559. ** bytes in size.
  27560. **
  27561. ** If an error occurs, an error code is returned and *pp is set to NULL.
  27562. **
  27563. ** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
  27564. ** region has not been allocated (by any client, including one running in a
  27565. ** separate process), then *pp is set to NULL and SQLITE_OK returned. If
  27566. ** bExtend is non-zero and the requested shared-memory region has not yet
  27567. ** been allocated, it is allocated by this function.
  27568. **
  27569. ** If the shared-memory region has already been allocated or is allocated by
  27570. ** this call as described above, then it is mapped into this processes
  27571. ** address space (if it is not already), *pp is set to point to the mapped
  27572. ** memory and SQLITE_OK returned.
  27573. */
  27574. static int unixShmMap(
  27575. sqlite3_file *fd, /* Handle open on database file */
  27576. int iRegion, /* Region to retrieve */
  27577. int szRegion, /* Size of regions */
  27578. int bExtend, /* True to extend file if necessary */
  27579. void volatile **pp /* OUT: Mapped memory */
  27580. ){
  27581. unixFile *pDbFd = (unixFile*)fd;
  27582. unixShm *p;
  27583. unixShmNode *pShmNode;
  27584. int rc = SQLITE_OK;
  27585. int nShmPerMap = unixShmRegionPerMap();
  27586. int nReqRegion;
  27587. /* If the shared-memory file has not yet been opened, open it now. */
  27588. if( pDbFd->pShm==0 ){
  27589. rc = unixOpenSharedMemory(pDbFd);
  27590. if( rc!=SQLITE_OK ) return rc;
  27591. }
  27592. p = pDbFd->pShm;
  27593. pShmNode = p->pShmNode;
  27594. sqlite3_mutex_enter(pShmNode->mutex);
  27595. assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
  27596. assert( pShmNode->pInode==pDbFd->pInode );
  27597. assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
  27598. assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
  27599. /* Minimum number of regions required to be mapped. */
  27600. nReqRegion = ((iRegion+nShmPerMap) / nShmPerMap) * nShmPerMap;
  27601. if( pShmNode->nRegion<nReqRegion ){
  27602. char **apNew; /* New apRegion[] array */
  27603. int nByte = nReqRegion*szRegion; /* Minimum required file size */
  27604. struct stat sStat; /* Used by fstat() */
  27605. pShmNode->szRegion = szRegion;
  27606. if( pShmNode->h>=0 ){
  27607. /* The requested region is not mapped into this processes address space.
  27608. ** Check to see if it has been allocated (i.e. if the wal-index file is
  27609. ** large enough to contain the requested region).
  27610. */
  27611. if( osFstat(pShmNode->h, &sStat) ){
  27612. rc = SQLITE_IOERR_SHMSIZE;
  27613. goto shmpage_out;
  27614. }
  27615. if( sStat.st_size<nByte ){
  27616. /* The requested memory region does not exist. If bExtend is set to
  27617. ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
  27618. */
  27619. if( !bExtend ){
  27620. goto shmpage_out;
  27621. }
  27622. /* Alternatively, if bExtend is true, extend the file. Do this by
  27623. ** writing a single byte to the end of each (OS) page being
  27624. ** allocated or extended. Technically, we need only write to the
  27625. ** last page in order to extend the file. But writing to all new
  27626. ** pages forces the OS to allocate them immediately, which reduces
  27627. ** the chances of SIGBUS while accessing the mapped region later on.
  27628. */
  27629. else{
  27630. static const int pgsz = 4096;
  27631. int iPg;
  27632. /* Write to the last byte of each newly allocated or extended page */
  27633. assert( (nByte % pgsz)==0 );
  27634. for(iPg=(sStat.st_size/pgsz); iPg<(nByte/pgsz); iPg++){
  27635. if( seekAndWriteFd(pShmNode->h, iPg*pgsz + pgsz-1, "", 1, 0)!=1 ){
  27636. const char *zFile = pShmNode->zFilename;
  27637. rc = unixLogError(SQLITE_IOERR_SHMSIZE, "write", zFile);
  27638. goto shmpage_out;
  27639. }
  27640. }
  27641. }
  27642. }
  27643. }
  27644. /* Map the requested memory region into this processes address space. */
  27645. apNew = (char **)sqlite3_realloc(
  27646. pShmNode->apRegion, nReqRegion*sizeof(char *)
  27647. );
  27648. if( !apNew ){
  27649. rc = SQLITE_IOERR_NOMEM;
  27650. goto shmpage_out;
  27651. }
  27652. pShmNode->apRegion = apNew;
  27653. while( pShmNode->nRegion<nReqRegion ){
  27654. int nMap = szRegion*nShmPerMap;
  27655. int i;
  27656. void *pMem;
  27657. if( pShmNode->h>=0 ){
  27658. pMem = osMmap(0, nMap,
  27659. pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE,
  27660. MAP_SHARED, pShmNode->h, szRegion*(i64)pShmNode->nRegion
  27661. );
  27662. if( pMem==MAP_FAILED ){
  27663. rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
  27664. goto shmpage_out;
  27665. }
  27666. }else{
  27667. pMem = sqlite3_malloc(szRegion);
  27668. if( pMem==0 ){
  27669. rc = SQLITE_NOMEM;
  27670. goto shmpage_out;
  27671. }
  27672. memset(pMem, 0, szRegion);
  27673. }
  27674. for(i=0; i<nShmPerMap; i++){
  27675. pShmNode->apRegion[pShmNode->nRegion+i] = &((char*)pMem)[szRegion*i];
  27676. }
  27677. pShmNode->nRegion += nShmPerMap;
  27678. }
  27679. }
  27680. shmpage_out:
  27681. if( pShmNode->nRegion>iRegion ){
  27682. *pp = pShmNode->apRegion[iRegion];
  27683. }else{
  27684. *pp = 0;
  27685. }
  27686. if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
  27687. sqlite3_mutex_leave(pShmNode->mutex);
  27688. return rc;
  27689. }
  27690. /*
  27691. ** Change the lock state for a shared-memory segment.
  27692. **
  27693. ** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
  27694. ** different here than in posix. In xShmLock(), one can go from unlocked
  27695. ** to shared and back or from unlocked to exclusive and back. But one may
  27696. ** not go from shared to exclusive or from exclusive to shared.
  27697. */
  27698. static int unixShmLock(
  27699. sqlite3_file *fd, /* Database file holding the shared memory */
  27700. int ofst, /* First lock to acquire or release */
  27701. int n, /* Number of locks to acquire or release */
  27702. int flags /* What to do with the lock */
  27703. ){
  27704. unixFile *pDbFd = (unixFile*)fd; /* Connection holding shared memory */
  27705. unixShm *p = pDbFd->pShm; /* The shared memory being locked */
  27706. unixShm *pX; /* For looping over all siblings */
  27707. unixShmNode *pShmNode = p->pShmNode; /* The underlying file iNode */
  27708. int rc = SQLITE_OK; /* Result code */
  27709. u16 mask; /* Mask of locks to take or release */
  27710. assert( pShmNode==pDbFd->pInode->pShmNode );
  27711. assert( pShmNode->pInode==pDbFd->pInode );
  27712. assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
  27713. assert( n>=1 );
  27714. assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
  27715. || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
  27716. || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
  27717. || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
  27718. assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
  27719. assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
  27720. assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
  27721. mask = (1<<(ofst+n)) - (1<<ofst);
  27722. assert( n>1 || mask==(1<<ofst) );
  27723. sqlite3_mutex_enter(pShmNode->mutex);
  27724. if( flags & SQLITE_SHM_UNLOCK ){
  27725. u16 allMask = 0; /* Mask of locks held by siblings */
  27726. /* See if any siblings hold this same lock */
  27727. for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
  27728. if( pX==p ) continue;
  27729. assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
  27730. allMask |= pX->sharedMask;
  27731. }
  27732. /* Unlock the system-level locks */
  27733. if( (mask & allMask)==0 ){
  27734. rc = unixShmSystemLock(pShmNode, F_UNLCK, ofst+UNIX_SHM_BASE, n);
  27735. }else{
  27736. rc = SQLITE_OK;
  27737. }
  27738. /* Undo the local locks */
  27739. if( rc==SQLITE_OK ){
  27740. p->exclMask &= ~mask;
  27741. p->sharedMask &= ~mask;
  27742. }
  27743. }else if( flags & SQLITE_SHM_SHARED ){
  27744. u16 allShared = 0; /* Union of locks held by connections other than "p" */
  27745. /* Find out which shared locks are already held by sibling connections.
  27746. ** If any sibling already holds an exclusive lock, go ahead and return
  27747. ** SQLITE_BUSY.
  27748. */
  27749. for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
  27750. if( (pX->exclMask & mask)!=0 ){
  27751. rc = SQLITE_BUSY;
  27752. break;
  27753. }
  27754. allShared |= pX->sharedMask;
  27755. }
  27756. /* Get shared locks at the system level, if necessary */
  27757. if( rc==SQLITE_OK ){
  27758. if( (allShared & mask)==0 ){
  27759. rc = unixShmSystemLock(pShmNode, F_RDLCK, ofst+UNIX_SHM_BASE, n);
  27760. }else{
  27761. rc = SQLITE_OK;
  27762. }
  27763. }
  27764. /* Get the local shared locks */
  27765. if( rc==SQLITE_OK ){
  27766. p->sharedMask |= mask;
  27767. }
  27768. }else{
  27769. /* Make sure no sibling connections hold locks that will block this
  27770. ** lock. If any do, return SQLITE_BUSY right away.
  27771. */
  27772. for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
  27773. if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
  27774. rc = SQLITE_BUSY;
  27775. break;
  27776. }
  27777. }
  27778. /* Get the exclusive locks at the system level. Then if successful
  27779. ** also mark the local connection as being locked.
  27780. */
  27781. if( rc==SQLITE_OK ){
  27782. rc = unixShmSystemLock(pShmNode, F_WRLCK, ofst+UNIX_SHM_BASE, n);
  27783. if( rc==SQLITE_OK ){
  27784. assert( (p->sharedMask & mask)==0 );
  27785. p->exclMask |= mask;
  27786. }
  27787. }
  27788. }
  27789. sqlite3_mutex_leave(pShmNode->mutex);
  27790. OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
  27791. p->id, getpid(), p->sharedMask, p->exclMask));
  27792. return rc;
  27793. }
  27794. /*
  27795. ** Implement a memory barrier or memory fence on shared memory.
  27796. **
  27797. ** All loads and stores begun before the barrier must complete before
  27798. ** any load or store begun after the barrier.
  27799. */
  27800. static void unixShmBarrier(
  27801. sqlite3_file *fd /* Database file holding the shared memory */
  27802. ){
  27803. UNUSED_PARAMETER(fd);
  27804. unixEnterMutex();
  27805. unixLeaveMutex();
  27806. }
  27807. /*
  27808. ** Close a connection to shared-memory. Delete the underlying
  27809. ** storage if deleteFlag is true.
  27810. **
  27811. ** If there is no shared memory associated with the connection then this
  27812. ** routine is a harmless no-op.
  27813. */
  27814. static int unixShmUnmap(
  27815. sqlite3_file *fd, /* The underlying database file */
  27816. int deleteFlag /* Delete shared-memory if true */
  27817. ){
  27818. unixShm *p; /* The connection to be closed */
  27819. unixShmNode *pShmNode; /* The underlying shared-memory file */
  27820. unixShm **pp; /* For looping over sibling connections */
  27821. unixFile *pDbFd; /* The underlying database file */
  27822. pDbFd = (unixFile*)fd;
  27823. p = pDbFd->pShm;
  27824. if( p==0 ) return SQLITE_OK;
  27825. pShmNode = p->pShmNode;
  27826. assert( pShmNode==pDbFd->pInode->pShmNode );
  27827. assert( pShmNode->pInode==pDbFd->pInode );
  27828. /* Remove connection p from the set of connections associated
  27829. ** with pShmNode */
  27830. sqlite3_mutex_enter(pShmNode->mutex);
  27831. for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
  27832. *pp = p->pNext;
  27833. /* Free the connection p */
  27834. sqlite3_free(p);
  27835. pDbFd->pShm = 0;
  27836. sqlite3_mutex_leave(pShmNode->mutex);
  27837. /* If pShmNode->nRef has reached 0, then close the underlying
  27838. ** shared-memory file, too */
  27839. unixEnterMutex();
  27840. assert( pShmNode->nRef>0 );
  27841. pShmNode->nRef--;
  27842. if( pShmNode->nRef==0 ){
  27843. if( deleteFlag && pShmNode->h>=0 ) osUnlink(pShmNode->zFilename);
  27844. unixShmPurge(pDbFd);
  27845. }
  27846. unixLeaveMutex();
  27847. return SQLITE_OK;
  27848. }
  27849. #else
  27850. # define unixShmMap 0
  27851. # define unixShmLock 0
  27852. # define unixShmBarrier 0
  27853. # define unixShmUnmap 0
  27854. #endif /* #ifndef SQLITE_OMIT_WAL */
  27855. #if SQLITE_MAX_MMAP_SIZE>0
  27856. /*
  27857. ** If it is currently memory mapped, unmap file pFd.
  27858. */
  27859. static void unixUnmapfile(unixFile *pFd){
  27860. assert( pFd->nFetchOut==0 );
  27861. if( pFd->pMapRegion ){
  27862. osMunmap(pFd->pMapRegion, pFd->mmapSizeActual);
  27863. pFd->pMapRegion = 0;
  27864. pFd->mmapSize = 0;
  27865. pFd->mmapSizeActual = 0;
  27866. }
  27867. }
  27868. /*
  27869. ** Attempt to set the size of the memory mapping maintained by file
  27870. ** descriptor pFd to nNew bytes. Any existing mapping is discarded.
  27871. **
  27872. ** If successful, this function sets the following variables:
  27873. **
  27874. ** unixFile.pMapRegion
  27875. ** unixFile.mmapSize
  27876. ** unixFile.mmapSizeActual
  27877. **
  27878. ** If unsuccessful, an error message is logged via sqlite3_log() and
  27879. ** the three variables above are zeroed. In this case SQLite should
  27880. ** continue accessing the database using the xRead() and xWrite()
  27881. ** methods.
  27882. */
  27883. static void unixRemapfile(
  27884. unixFile *pFd, /* File descriptor object */
  27885. i64 nNew /* Required mapping size */
  27886. ){
  27887. const char *zErr = "mmap";
  27888. int h = pFd->h; /* File descriptor open on db file */
  27889. u8 *pOrig = (u8 *)pFd->pMapRegion; /* Pointer to current file mapping */
  27890. i64 nOrig = pFd->mmapSizeActual; /* Size of pOrig region in bytes */
  27891. u8 *pNew = 0; /* Location of new mapping */
  27892. int flags = PROT_READ; /* Flags to pass to mmap() */
  27893. assert( pFd->nFetchOut==0 );
  27894. assert( nNew>pFd->mmapSize );
  27895. assert( nNew<=pFd->mmapSizeMax );
  27896. assert( nNew>0 );
  27897. assert( pFd->mmapSizeActual>=pFd->mmapSize );
  27898. assert( MAP_FAILED!=0 );
  27899. if( (pFd->ctrlFlags & UNIXFILE_RDONLY)==0 ) flags |= PROT_WRITE;
  27900. if( pOrig ){
  27901. #if HAVE_MREMAP
  27902. i64 nReuse = pFd->mmapSize;
  27903. #else
  27904. const int szSyspage = osGetpagesize();
  27905. i64 nReuse = (pFd->mmapSize & ~(szSyspage-1));
  27906. #endif
  27907. u8 *pReq = &pOrig[nReuse];
  27908. /* Unmap any pages of the existing mapping that cannot be reused. */
  27909. if( nReuse!=nOrig ){
  27910. osMunmap(pReq, nOrig-nReuse);
  27911. }
  27912. #if HAVE_MREMAP
  27913. pNew = osMremap(pOrig, nReuse, nNew, MREMAP_MAYMOVE);
  27914. zErr = "mremap";
  27915. #else
  27916. pNew = osMmap(pReq, nNew-nReuse, flags, MAP_SHARED, h, nReuse);
  27917. if( pNew!=MAP_FAILED ){
  27918. if( pNew!=pReq ){
  27919. osMunmap(pNew, nNew - nReuse);
  27920. pNew = 0;
  27921. }else{
  27922. pNew = pOrig;
  27923. }
  27924. }
  27925. #endif
  27926. /* The attempt to extend the existing mapping failed. Free it. */
  27927. if( pNew==MAP_FAILED || pNew==0 ){
  27928. osMunmap(pOrig, nReuse);
  27929. }
  27930. }
  27931. /* If pNew is still NULL, try to create an entirely new mapping. */
  27932. if( pNew==0 ){
  27933. pNew = osMmap(0, nNew, flags, MAP_SHARED, h, 0);
  27934. }
  27935. if( pNew==MAP_FAILED ){
  27936. pNew = 0;
  27937. nNew = 0;
  27938. unixLogError(SQLITE_OK, zErr, pFd->zPath);
  27939. /* If the mmap() above failed, assume that all subsequent mmap() calls
  27940. ** will probably fail too. Fall back to using xRead/xWrite exclusively
  27941. ** in this case. */
  27942. pFd->mmapSizeMax = 0;
  27943. }
  27944. pFd->pMapRegion = (void *)pNew;
  27945. pFd->mmapSize = pFd->mmapSizeActual = nNew;
  27946. }
  27947. /*
  27948. ** Memory map or remap the file opened by file-descriptor pFd (if the file
  27949. ** is already mapped, the existing mapping is replaced by the new). Or, if
  27950. ** there already exists a mapping for this file, and there are still
  27951. ** outstanding xFetch() references to it, this function is a no-op.
  27952. **
  27953. ** If parameter nByte is non-negative, then it is the requested size of
  27954. ** the mapping to create. Otherwise, if nByte is less than zero, then the
  27955. ** requested size is the size of the file on disk. The actual size of the
  27956. ** created mapping is either the requested size or the value configured
  27957. ** using SQLITE_FCNTL_MMAP_LIMIT, whichever is smaller.
  27958. **
  27959. ** SQLITE_OK is returned if no error occurs (even if the mapping is not
  27960. ** recreated as a result of outstanding references) or an SQLite error
  27961. ** code otherwise.
  27962. */
  27963. static int unixMapfile(unixFile *pFd, i64 nByte){
  27964. i64 nMap = nByte;
  27965. int rc;
  27966. assert( nMap>=0 || pFd->nFetchOut==0 );
  27967. if( pFd->nFetchOut>0 ) return SQLITE_OK;
  27968. if( nMap<0 ){
  27969. struct stat statbuf; /* Low-level file information */
  27970. rc = osFstat(pFd->h, &statbuf);
  27971. if( rc!=SQLITE_OK ){
  27972. return SQLITE_IOERR_FSTAT;
  27973. }
  27974. nMap = statbuf.st_size;
  27975. }
  27976. if( nMap>pFd->mmapSizeMax ){
  27977. nMap = pFd->mmapSizeMax;
  27978. }
  27979. if( nMap!=pFd->mmapSize ){
  27980. if( nMap>0 ){
  27981. unixRemapfile(pFd, nMap);
  27982. }else{
  27983. unixUnmapfile(pFd);
  27984. }
  27985. }
  27986. return SQLITE_OK;
  27987. }
  27988. #endif /* SQLITE_MAX_MMAP_SIZE>0 */
  27989. /*
  27990. ** If possible, return a pointer to a mapping of file fd starting at offset
  27991. ** iOff. The mapping must be valid for at least nAmt bytes.
  27992. **
  27993. ** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
  27994. ** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
  27995. ** Finally, if an error does occur, return an SQLite error code. The final
  27996. ** value of *pp is undefined in this case.
  27997. **
  27998. ** If this function does return a pointer, the caller must eventually
  27999. ** release the reference by calling unixUnfetch().
  28000. */
  28001. static int unixFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
  28002. #if SQLITE_MAX_MMAP_SIZE>0
  28003. unixFile *pFd = (unixFile *)fd; /* The underlying database file */
  28004. #endif
  28005. *pp = 0;
  28006. #if SQLITE_MAX_MMAP_SIZE>0
  28007. if( pFd->mmapSizeMax>0 ){
  28008. if( pFd->pMapRegion==0 ){
  28009. int rc = unixMapfile(pFd, -1);
  28010. if( rc!=SQLITE_OK ) return rc;
  28011. }
  28012. if( pFd->mmapSize >= iOff+nAmt ){
  28013. *pp = &((u8 *)pFd->pMapRegion)[iOff];
  28014. pFd->nFetchOut++;
  28015. }
  28016. }
  28017. #endif
  28018. return SQLITE_OK;
  28019. }
  28020. /*
  28021. ** If the third argument is non-NULL, then this function releases a
  28022. ** reference obtained by an earlier call to unixFetch(). The second
  28023. ** argument passed to this function must be the same as the corresponding
  28024. ** argument that was passed to the unixFetch() invocation.
  28025. **
  28026. ** Or, if the third argument is NULL, then this function is being called
  28027. ** to inform the VFS layer that, according to POSIX, any existing mapping
  28028. ** may now be invalid and should be unmapped.
  28029. */
  28030. static int unixUnfetch(sqlite3_file *fd, i64 iOff, void *p){
  28031. #if SQLITE_MAX_MMAP_SIZE>0
  28032. unixFile *pFd = (unixFile *)fd; /* The underlying database file */
  28033. UNUSED_PARAMETER(iOff);
  28034. /* If p==0 (unmap the entire file) then there must be no outstanding
  28035. ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
  28036. ** then there must be at least one outstanding. */
  28037. assert( (p==0)==(pFd->nFetchOut==0) );
  28038. /* If p!=0, it must match the iOff value. */
  28039. assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
  28040. if( p ){
  28041. pFd->nFetchOut--;
  28042. }else{
  28043. unixUnmapfile(pFd);
  28044. }
  28045. assert( pFd->nFetchOut>=0 );
  28046. #else
  28047. UNUSED_PARAMETER(fd);
  28048. UNUSED_PARAMETER(p);
  28049. UNUSED_PARAMETER(iOff);
  28050. #endif
  28051. return SQLITE_OK;
  28052. }
  28053. /*
  28054. ** Here ends the implementation of all sqlite3_file methods.
  28055. **
  28056. ********************** End sqlite3_file Methods *******************************
  28057. ******************************************************************************/
  28058. /*
  28059. ** This division contains definitions of sqlite3_io_methods objects that
  28060. ** implement various file locking strategies. It also contains definitions
  28061. ** of "finder" functions. A finder-function is used to locate the appropriate
  28062. ** sqlite3_io_methods object for a particular database file. The pAppData
  28063. ** field of the sqlite3_vfs VFS objects are initialized to be pointers to
  28064. ** the correct finder-function for that VFS.
  28065. **
  28066. ** Most finder functions return a pointer to a fixed sqlite3_io_methods
  28067. ** object. The only interesting finder-function is autolockIoFinder, which
  28068. ** looks at the filesystem type and tries to guess the best locking
  28069. ** strategy from that.
  28070. **
  28071. ** For finder-function F, two objects are created:
  28072. **
  28073. ** (1) The real finder-function named "FImpt()".
  28074. **
  28075. ** (2) A constant pointer to this function named just "F".
  28076. **
  28077. **
  28078. ** A pointer to the F pointer is used as the pAppData value for VFS
  28079. ** objects. We have to do this instead of letting pAppData point
  28080. ** directly at the finder-function since C90 rules prevent a void*
  28081. ** from be cast into a function pointer.
  28082. **
  28083. **
  28084. ** Each instance of this macro generates two objects:
  28085. **
  28086. ** * A constant sqlite3_io_methods object call METHOD that has locking
  28087. ** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
  28088. **
  28089. ** * An I/O method finder function called FINDER that returns a pointer
  28090. ** to the METHOD object in the previous bullet.
  28091. */
  28092. #define IOMETHODS(FINDER, METHOD, VERSION, CLOSE, LOCK, UNLOCK, CKLOCK, SHMMAP) \
  28093. static const sqlite3_io_methods METHOD = { \
  28094. VERSION, /* iVersion */ \
  28095. CLOSE, /* xClose */ \
  28096. unixRead, /* xRead */ \
  28097. unixWrite, /* xWrite */ \
  28098. unixTruncate, /* xTruncate */ \
  28099. unixSync, /* xSync */ \
  28100. unixFileSize, /* xFileSize */ \
  28101. LOCK, /* xLock */ \
  28102. UNLOCK, /* xUnlock */ \
  28103. CKLOCK, /* xCheckReservedLock */ \
  28104. unixFileControl, /* xFileControl */ \
  28105. unixSectorSize, /* xSectorSize */ \
  28106. unixDeviceCharacteristics, /* xDeviceCapabilities */ \
  28107. SHMMAP, /* xShmMap */ \
  28108. unixShmLock, /* xShmLock */ \
  28109. unixShmBarrier, /* xShmBarrier */ \
  28110. unixShmUnmap, /* xShmUnmap */ \
  28111. unixFetch, /* xFetch */ \
  28112. unixUnfetch, /* xUnfetch */ \
  28113. }; \
  28114. static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \
  28115. UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \
  28116. return &METHOD; \
  28117. } \
  28118. static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \
  28119. = FINDER##Impl;
  28120. /*
  28121. ** Here are all of the sqlite3_io_methods objects for each of the
  28122. ** locking strategies. Functions that return pointers to these methods
  28123. ** are also created.
  28124. */
  28125. IOMETHODS(
  28126. posixIoFinder, /* Finder function name */
  28127. posixIoMethods, /* sqlite3_io_methods object name */
  28128. 3, /* shared memory and mmap are enabled */
  28129. unixClose, /* xClose method */
  28130. unixLock, /* xLock method */
  28131. unixUnlock, /* xUnlock method */
  28132. unixCheckReservedLock, /* xCheckReservedLock method */
  28133. unixShmMap /* xShmMap method */
  28134. )
  28135. IOMETHODS(
  28136. nolockIoFinder, /* Finder function name */
  28137. nolockIoMethods, /* sqlite3_io_methods object name */
  28138. 3, /* shared memory is disabled */
  28139. nolockClose, /* xClose method */
  28140. nolockLock, /* xLock method */
  28141. nolockUnlock, /* xUnlock method */
  28142. nolockCheckReservedLock, /* xCheckReservedLock method */
  28143. 0 /* xShmMap method */
  28144. )
  28145. IOMETHODS(
  28146. dotlockIoFinder, /* Finder function name */
  28147. dotlockIoMethods, /* sqlite3_io_methods object name */
  28148. 1, /* shared memory is disabled */
  28149. dotlockClose, /* xClose method */
  28150. dotlockLock, /* xLock method */
  28151. dotlockUnlock, /* xUnlock method */
  28152. dotlockCheckReservedLock, /* xCheckReservedLock method */
  28153. 0 /* xShmMap method */
  28154. )
  28155. #if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
  28156. IOMETHODS(
  28157. flockIoFinder, /* Finder function name */
  28158. flockIoMethods, /* sqlite3_io_methods object name */
  28159. 1, /* shared memory is disabled */
  28160. flockClose, /* xClose method */
  28161. flockLock, /* xLock method */
  28162. flockUnlock, /* xUnlock method */
  28163. flockCheckReservedLock, /* xCheckReservedLock method */
  28164. 0 /* xShmMap method */
  28165. )
  28166. #endif
  28167. #if OS_VXWORKS
  28168. IOMETHODS(
  28169. semIoFinder, /* Finder function name */
  28170. semIoMethods, /* sqlite3_io_methods object name */
  28171. 1, /* shared memory is disabled */
  28172. semClose, /* xClose method */
  28173. semLock, /* xLock method */
  28174. semUnlock, /* xUnlock method */
  28175. semCheckReservedLock, /* xCheckReservedLock method */
  28176. 0 /* xShmMap method */
  28177. )
  28178. #endif
  28179. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  28180. IOMETHODS(
  28181. afpIoFinder, /* Finder function name */
  28182. afpIoMethods, /* sqlite3_io_methods object name */
  28183. 1, /* shared memory is disabled */
  28184. afpClose, /* xClose method */
  28185. afpLock, /* xLock method */
  28186. afpUnlock, /* xUnlock method */
  28187. afpCheckReservedLock, /* xCheckReservedLock method */
  28188. 0 /* xShmMap method */
  28189. )
  28190. #endif
  28191. /*
  28192. ** The proxy locking method is a "super-method" in the sense that it
  28193. ** opens secondary file descriptors for the conch and lock files and
  28194. ** it uses proxy, dot-file, AFP, and flock() locking methods on those
  28195. ** secondary files. For this reason, the division that implements
  28196. ** proxy locking is located much further down in the file. But we need
  28197. ** to go ahead and define the sqlite3_io_methods and finder function
  28198. ** for proxy locking here. So we forward declare the I/O methods.
  28199. */
  28200. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  28201. static int proxyClose(sqlite3_file*);
  28202. static int proxyLock(sqlite3_file*, int);
  28203. static int proxyUnlock(sqlite3_file*, int);
  28204. static int proxyCheckReservedLock(sqlite3_file*, int*);
  28205. IOMETHODS(
  28206. proxyIoFinder, /* Finder function name */
  28207. proxyIoMethods, /* sqlite3_io_methods object name */
  28208. 1, /* shared memory is disabled */
  28209. proxyClose, /* xClose method */
  28210. proxyLock, /* xLock method */
  28211. proxyUnlock, /* xUnlock method */
  28212. proxyCheckReservedLock, /* xCheckReservedLock method */
  28213. 0 /* xShmMap method */
  28214. )
  28215. #endif
  28216. /* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
  28217. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  28218. IOMETHODS(
  28219. nfsIoFinder, /* Finder function name */
  28220. nfsIoMethods, /* sqlite3_io_methods object name */
  28221. 1, /* shared memory is disabled */
  28222. unixClose, /* xClose method */
  28223. unixLock, /* xLock method */
  28224. nfsUnlock, /* xUnlock method */
  28225. unixCheckReservedLock, /* xCheckReservedLock method */
  28226. 0 /* xShmMap method */
  28227. )
  28228. #endif
  28229. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  28230. /*
  28231. ** This "finder" function attempts to determine the best locking strategy
  28232. ** for the database file "filePath". It then returns the sqlite3_io_methods
  28233. ** object that implements that strategy.
  28234. **
  28235. ** This is for MacOSX only.
  28236. */
  28237. static const sqlite3_io_methods *autolockIoFinderImpl(
  28238. const char *filePath, /* name of the database file */
  28239. unixFile *pNew /* open file object for the database file */
  28240. ){
  28241. static const struct Mapping {
  28242. const char *zFilesystem; /* Filesystem type name */
  28243. const sqlite3_io_methods *pMethods; /* Appropriate locking method */
  28244. } aMap[] = {
  28245. { "hfs", &posixIoMethods },
  28246. { "ufs", &posixIoMethods },
  28247. { "afpfs", &afpIoMethods },
  28248. { "smbfs", &afpIoMethods },
  28249. { "webdav", &nolockIoMethods },
  28250. { 0, 0 }
  28251. };
  28252. int i;
  28253. struct statfs fsInfo;
  28254. struct flock lockInfo;
  28255. if( !filePath ){
  28256. /* If filePath==NULL that means we are dealing with a transient file
  28257. ** that does not need to be locked. */
  28258. return &nolockIoMethods;
  28259. }
  28260. if( statfs(filePath, &fsInfo) != -1 ){
  28261. if( fsInfo.f_flags & MNT_RDONLY ){
  28262. return &nolockIoMethods;
  28263. }
  28264. for(i=0; aMap[i].zFilesystem; i++){
  28265. if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
  28266. return aMap[i].pMethods;
  28267. }
  28268. }
  28269. }
  28270. /* Default case. Handles, amongst others, "nfs".
  28271. ** Test byte-range lock using fcntl(). If the call succeeds,
  28272. ** assume that the file-system supports POSIX style locks.
  28273. */
  28274. lockInfo.l_len = 1;
  28275. lockInfo.l_start = 0;
  28276. lockInfo.l_whence = SEEK_SET;
  28277. lockInfo.l_type = F_RDLCK;
  28278. if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
  28279. if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
  28280. return &nfsIoMethods;
  28281. } else {
  28282. return &posixIoMethods;
  28283. }
  28284. }else{
  28285. return &dotlockIoMethods;
  28286. }
  28287. }
  28288. static const sqlite3_io_methods
  28289. *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
  28290. #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
  28291. #if OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE
  28292. /*
  28293. ** This "finder" function attempts to determine the best locking strategy
  28294. ** for the database file "filePath". It then returns the sqlite3_io_methods
  28295. ** object that implements that strategy.
  28296. **
  28297. ** This is for VXWorks only.
  28298. */
  28299. static const sqlite3_io_methods *autolockIoFinderImpl(
  28300. const char *filePath, /* name of the database file */
  28301. unixFile *pNew /* the open file object */
  28302. ){
  28303. struct flock lockInfo;
  28304. if( !filePath ){
  28305. /* If filePath==NULL that means we are dealing with a transient file
  28306. ** that does not need to be locked. */
  28307. return &nolockIoMethods;
  28308. }
  28309. /* Test if fcntl() is supported and use POSIX style locks.
  28310. ** Otherwise fall back to the named semaphore method.
  28311. */
  28312. lockInfo.l_len = 1;
  28313. lockInfo.l_start = 0;
  28314. lockInfo.l_whence = SEEK_SET;
  28315. lockInfo.l_type = F_RDLCK;
  28316. if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
  28317. return &posixIoMethods;
  28318. }else{
  28319. return &semIoMethods;
  28320. }
  28321. }
  28322. static const sqlite3_io_methods
  28323. *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
  28324. #endif /* OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE */
  28325. /*
  28326. ** An abstract type for a pointer to an IO method finder function:
  28327. */
  28328. typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
  28329. /****************************************************************************
  28330. **************************** sqlite3_vfs methods ****************************
  28331. **
  28332. ** This division contains the implementation of methods on the
  28333. ** sqlite3_vfs object.
  28334. */
  28335. /*
  28336. ** Initialize the contents of the unixFile structure pointed to by pId.
  28337. */
  28338. static int fillInUnixFile(
  28339. sqlite3_vfs *pVfs, /* Pointer to vfs object */
  28340. int h, /* Open file descriptor of file being opened */
  28341. sqlite3_file *pId, /* Write to the unixFile structure here */
  28342. const char *zFilename, /* Name of the file being opened */
  28343. int ctrlFlags /* Zero or more UNIXFILE_* values */
  28344. ){
  28345. const sqlite3_io_methods *pLockingStyle;
  28346. unixFile *pNew = (unixFile *)pId;
  28347. int rc = SQLITE_OK;
  28348. assert( pNew->pInode==NULL );
  28349. /* Usually the path zFilename should not be a relative pathname. The
  28350. ** exception is when opening the proxy "conch" file in builds that
  28351. ** include the special Apple locking styles.
  28352. */
  28353. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  28354. assert( zFilename==0 || zFilename[0]=='/'
  28355. || pVfs->pAppData==(void*)&autolockIoFinder );
  28356. #else
  28357. assert( zFilename==0 || zFilename[0]=='/' );
  28358. #endif
  28359. /* No locking occurs in temporary files */
  28360. assert( zFilename!=0 || (ctrlFlags & UNIXFILE_NOLOCK)!=0 );
  28361. OSTRACE(("OPEN %-3d %s\n", h, zFilename));
  28362. pNew->h = h;
  28363. pNew->pVfs = pVfs;
  28364. pNew->zPath = zFilename;
  28365. pNew->ctrlFlags = (u8)ctrlFlags;
  28366. #if SQLITE_MAX_MMAP_SIZE>0
  28367. pNew->mmapSizeMax = sqlite3GlobalConfig.szMmap;
  28368. #endif
  28369. if( sqlite3_uri_boolean(((ctrlFlags & UNIXFILE_URI) ? zFilename : 0),
  28370. "psow", SQLITE_POWERSAFE_OVERWRITE) ){
  28371. pNew->ctrlFlags |= UNIXFILE_PSOW;
  28372. }
  28373. if( strcmp(pVfs->zName,"unix-excl")==0 ){
  28374. pNew->ctrlFlags |= UNIXFILE_EXCL;
  28375. }
  28376. #if OS_VXWORKS
  28377. pNew->pId = vxworksFindFileId(zFilename);
  28378. if( pNew->pId==0 ){
  28379. ctrlFlags |= UNIXFILE_NOLOCK;
  28380. rc = SQLITE_NOMEM;
  28381. }
  28382. #endif
  28383. if( ctrlFlags & UNIXFILE_NOLOCK ){
  28384. pLockingStyle = &nolockIoMethods;
  28385. }else{
  28386. pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
  28387. #if SQLITE_ENABLE_LOCKING_STYLE
  28388. /* Cache zFilename in the locking context (AFP and dotlock override) for
  28389. ** proxyLock activation is possible (remote proxy is based on db name)
  28390. ** zFilename remains valid until file is closed, to support */
  28391. pNew->lockingContext = (void*)zFilename;
  28392. #endif
  28393. }
  28394. if( pLockingStyle == &posixIoMethods
  28395. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  28396. || pLockingStyle == &nfsIoMethods
  28397. #endif
  28398. ){
  28399. unixEnterMutex();
  28400. rc = findInodeInfo(pNew, &pNew->pInode);
  28401. if( rc!=SQLITE_OK ){
  28402. /* If an error occurred in findInodeInfo(), close the file descriptor
  28403. ** immediately, before releasing the mutex. findInodeInfo() may fail
  28404. ** in two scenarios:
  28405. **
  28406. ** (a) A call to fstat() failed.
  28407. ** (b) A malloc failed.
  28408. **
  28409. ** Scenario (b) may only occur if the process is holding no other
  28410. ** file descriptors open on the same file. If there were other file
  28411. ** descriptors on this file, then no malloc would be required by
  28412. ** findInodeInfo(). If this is the case, it is quite safe to close
  28413. ** handle h - as it is guaranteed that no posix locks will be released
  28414. ** by doing so.
  28415. **
  28416. ** If scenario (a) caused the error then things are not so safe. The
  28417. ** implicit assumption here is that if fstat() fails, things are in
  28418. ** such bad shape that dropping a lock or two doesn't matter much.
  28419. */
  28420. robust_close(pNew, h, __LINE__);
  28421. h = -1;
  28422. }
  28423. unixLeaveMutex();
  28424. }
  28425. #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
  28426. else if( pLockingStyle == &afpIoMethods ){
  28427. /* AFP locking uses the file path so it needs to be included in
  28428. ** the afpLockingContext.
  28429. */
  28430. afpLockingContext *pCtx;
  28431. pNew->lockingContext = pCtx = sqlite3_malloc( sizeof(*pCtx) );
  28432. if( pCtx==0 ){
  28433. rc = SQLITE_NOMEM;
  28434. }else{
  28435. /* NB: zFilename exists and remains valid until the file is closed
  28436. ** according to requirement F11141. So we do not need to make a
  28437. ** copy of the filename. */
  28438. pCtx->dbPath = zFilename;
  28439. pCtx->reserved = 0;
  28440. srandomdev();
  28441. unixEnterMutex();
  28442. rc = findInodeInfo(pNew, &pNew->pInode);
  28443. if( rc!=SQLITE_OK ){
  28444. sqlite3_free(pNew->lockingContext);
  28445. robust_close(pNew, h, __LINE__);
  28446. h = -1;
  28447. }
  28448. unixLeaveMutex();
  28449. }
  28450. }
  28451. #endif
  28452. else if( pLockingStyle == &dotlockIoMethods ){
  28453. /* Dotfile locking uses the file path so it needs to be included in
  28454. ** the dotlockLockingContext
  28455. */
  28456. char *zLockFile;
  28457. int nFilename;
  28458. assert( zFilename!=0 );
  28459. nFilename = (int)strlen(zFilename) + 6;
  28460. zLockFile = (char *)sqlite3_malloc(nFilename);
  28461. if( zLockFile==0 ){
  28462. rc = SQLITE_NOMEM;
  28463. }else{
  28464. sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
  28465. }
  28466. pNew->lockingContext = zLockFile;
  28467. }
  28468. #if OS_VXWORKS
  28469. else if( pLockingStyle == &semIoMethods ){
  28470. /* Named semaphore locking uses the file path so it needs to be
  28471. ** included in the semLockingContext
  28472. */
  28473. unixEnterMutex();
  28474. rc = findInodeInfo(pNew, &pNew->pInode);
  28475. if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
  28476. char *zSemName = pNew->pInode->aSemName;
  28477. int n;
  28478. sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
  28479. pNew->pId->zCanonicalName);
  28480. for( n=1; zSemName[n]; n++ )
  28481. if( zSemName[n]=='/' ) zSemName[n] = '_';
  28482. pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
  28483. if( pNew->pInode->pSem == SEM_FAILED ){
  28484. rc = SQLITE_NOMEM;
  28485. pNew->pInode->aSemName[0] = '\0';
  28486. }
  28487. }
  28488. unixLeaveMutex();
  28489. }
  28490. #endif
  28491. pNew->lastErrno = 0;
  28492. #if OS_VXWORKS
  28493. if( rc!=SQLITE_OK ){
  28494. if( h>=0 ) robust_close(pNew, h, __LINE__);
  28495. h = -1;
  28496. osUnlink(zFilename);
  28497. pNew->ctrlFlags |= UNIXFILE_DELETE;
  28498. }
  28499. #endif
  28500. if( rc!=SQLITE_OK ){
  28501. if( h>=0 ) robust_close(pNew, h, __LINE__);
  28502. }else{
  28503. pNew->pMethod = pLockingStyle;
  28504. OpenCounter(+1);
  28505. verifyDbFile(pNew);
  28506. }
  28507. return rc;
  28508. }
  28509. /*
  28510. ** Return the name of a directory in which to put temporary files.
  28511. ** If no suitable temporary file directory can be found, return NULL.
  28512. */
  28513. static const char *unixTempFileDir(void){
  28514. static const char *azDirs[] = {
  28515. 0,
  28516. 0,
  28517. 0,
  28518. "/var/tmp",
  28519. "/usr/tmp",
  28520. "/tmp",
  28521. 0 /* List terminator */
  28522. };
  28523. unsigned int i;
  28524. struct stat buf;
  28525. const char *zDir = 0;
  28526. azDirs[0] = sqlite3_temp_directory;
  28527. if( !azDirs[1] ) azDirs[1] = getenv("SQLITE_TMPDIR");
  28528. if( !azDirs[2] ) azDirs[2] = getenv("TMPDIR");
  28529. for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
  28530. if( zDir==0 ) continue;
  28531. if( osStat(zDir, &buf) ) continue;
  28532. if( !S_ISDIR(buf.st_mode) ) continue;
  28533. if( osAccess(zDir, 07) ) continue;
  28534. break;
  28535. }
  28536. return zDir;
  28537. }
  28538. /*
  28539. ** Create a temporary file name in zBuf. zBuf must be allocated
  28540. ** by the calling process and must be big enough to hold at least
  28541. ** pVfs->mxPathname bytes.
  28542. */
  28543. static int unixGetTempname(int nBuf, char *zBuf){
  28544. static const unsigned char zChars[] =
  28545. "abcdefghijklmnopqrstuvwxyz"
  28546. "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  28547. "0123456789";
  28548. unsigned int i, j;
  28549. const char *zDir;
  28550. /* It's odd to simulate an io-error here, but really this is just
  28551. ** using the io-error infrastructure to test that SQLite handles this
  28552. ** function failing.
  28553. */
  28554. SimulateIOError( return SQLITE_IOERR );
  28555. zDir = unixTempFileDir();
  28556. if( zDir==0 ) zDir = ".";
  28557. /* Check that the output buffer is large enough for the temporary file
  28558. ** name. If it is not, return SQLITE_ERROR.
  28559. */
  28560. if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 18) >= (size_t)nBuf ){
  28561. return SQLITE_ERROR;
  28562. }
  28563. do{
  28564. sqlite3_snprintf(nBuf-18, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
  28565. j = (int)strlen(zBuf);
  28566. sqlite3_randomness(15, &zBuf[j]);
  28567. for(i=0; i<15; i++, j++){
  28568. zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
  28569. }
  28570. zBuf[j] = 0;
  28571. zBuf[j+1] = 0;
  28572. }while( osAccess(zBuf,0)==0 );
  28573. return SQLITE_OK;
  28574. }
  28575. #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
  28576. /*
  28577. ** Routine to transform a unixFile into a proxy-locking unixFile.
  28578. ** Implementation in the proxy-lock division, but used by unixOpen()
  28579. ** if SQLITE_PREFER_PROXY_LOCKING is defined.
  28580. */
  28581. static int proxyTransformUnixFile(unixFile*, const char*);
  28582. #endif
  28583. /*
  28584. ** Search for an unused file descriptor that was opened on the database
  28585. ** file (not a journal or master-journal file) identified by pathname
  28586. ** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
  28587. ** argument to this function.
  28588. **
  28589. ** Such a file descriptor may exist if a database connection was closed
  28590. ** but the associated file descriptor could not be closed because some
  28591. ** other file descriptor open on the same file is holding a file-lock.
  28592. ** Refer to comments in the unixClose() function and the lengthy comment
  28593. ** describing "Posix Advisory Locking" at the start of this file for
  28594. ** further details. Also, ticket #4018.
  28595. **
  28596. ** If a suitable file descriptor is found, then it is returned. If no
  28597. ** such file descriptor is located, -1 is returned.
  28598. */
  28599. static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
  28600. UnixUnusedFd *pUnused = 0;
  28601. /* Do not search for an unused file descriptor on vxworks. Not because
  28602. ** vxworks would not benefit from the change (it might, we're not sure),
  28603. ** but because no way to test it is currently available. It is better
  28604. ** not to risk breaking vxworks support for the sake of such an obscure
  28605. ** feature. */
  28606. #if !OS_VXWORKS
  28607. struct stat sStat; /* Results of stat() call */
  28608. /* A stat() call may fail for various reasons. If this happens, it is
  28609. ** almost certain that an open() call on the same path will also fail.
  28610. ** For this reason, if an error occurs in the stat() call here, it is
  28611. ** ignored and -1 is returned. The caller will try to open a new file
  28612. ** descriptor on the same path, fail, and return an error to SQLite.
  28613. **
  28614. ** Even if a subsequent open() call does succeed, the consequences of
  28615. ** not searching for a reusable file descriptor are not dire. */
  28616. if( 0==osStat(zPath, &sStat) ){
  28617. unixInodeInfo *pInode;
  28618. unixEnterMutex();
  28619. pInode = inodeList;
  28620. while( pInode && (pInode->fileId.dev!=sStat.st_dev
  28621. || pInode->fileId.ino!=sStat.st_ino) ){
  28622. pInode = pInode->pNext;
  28623. }
  28624. if( pInode ){
  28625. UnixUnusedFd **pp;
  28626. for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
  28627. pUnused = *pp;
  28628. if( pUnused ){
  28629. *pp = pUnused->pNext;
  28630. }
  28631. }
  28632. unixLeaveMutex();
  28633. }
  28634. #endif /* if !OS_VXWORKS */
  28635. return pUnused;
  28636. }
  28637. /*
  28638. ** This function is called by unixOpen() to determine the unix permissions
  28639. ** to create new files with. If no error occurs, then SQLITE_OK is returned
  28640. ** and a value suitable for passing as the third argument to open(2) is
  28641. ** written to *pMode. If an IO error occurs, an SQLite error code is
  28642. ** returned and the value of *pMode is not modified.
  28643. **
  28644. ** In most cases, this routine sets *pMode to 0, which will become
  28645. ** an indication to robust_open() to create the file using
  28646. ** SQLITE_DEFAULT_FILE_PERMISSIONS adjusted by the umask.
  28647. ** But if the file being opened is a WAL or regular journal file, then
  28648. ** this function queries the file-system for the permissions on the
  28649. ** corresponding database file and sets *pMode to this value. Whenever
  28650. ** possible, WAL and journal files are created using the same permissions
  28651. ** as the associated database file.
  28652. **
  28653. ** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the
  28654. ** original filename is unavailable. But 8_3_NAMES is only used for
  28655. ** FAT filesystems and permissions do not matter there, so just use
  28656. ** the default permissions.
  28657. */
  28658. static int findCreateFileMode(
  28659. const char *zPath, /* Path of file (possibly) being created */
  28660. int flags, /* Flags passed as 4th argument to xOpen() */
  28661. mode_t *pMode, /* OUT: Permissions to open file with */
  28662. uid_t *pUid, /* OUT: uid to set on the file */
  28663. gid_t *pGid /* OUT: gid to set on the file */
  28664. ){
  28665. int rc = SQLITE_OK; /* Return Code */
  28666. *pMode = 0;
  28667. *pUid = 0;
  28668. *pGid = 0;
  28669. if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
  28670. char zDb[MAX_PATHNAME+1]; /* Database file path */
  28671. int nDb; /* Number of valid bytes in zDb */
  28672. struct stat sStat; /* Output of stat() on database file */
  28673. /* zPath is a path to a WAL or journal file. The following block derives
  28674. ** the path to the associated database file from zPath. This block handles
  28675. ** the following naming conventions:
  28676. **
  28677. ** "<path to db>-journal"
  28678. ** "<path to db>-wal"
  28679. ** "<path to db>-journalNN"
  28680. ** "<path to db>-walNN"
  28681. **
  28682. ** where NN is a decimal number. The NN naming schemes are
  28683. ** used by the test_multiplex.c module.
  28684. */
  28685. nDb = sqlite3Strlen30(zPath) - 1;
  28686. #ifdef SQLITE_ENABLE_8_3_NAMES
  28687. while( nDb>0 && sqlite3Isalnum(zPath[nDb]) ) nDb--;
  28688. if( nDb==0 || zPath[nDb]!='-' ) return SQLITE_OK;
  28689. #else
  28690. while( zPath[nDb]!='-' ){
  28691. assert( nDb>0 );
  28692. assert( zPath[nDb]!='\n' );
  28693. nDb--;
  28694. }
  28695. #endif
  28696. memcpy(zDb, zPath, nDb);
  28697. zDb[nDb] = '\0';
  28698. if( 0==osStat(zDb, &sStat) ){
  28699. *pMode = sStat.st_mode & 0777;
  28700. *pUid = sStat.st_uid;
  28701. *pGid = sStat.st_gid;
  28702. }else{
  28703. rc = SQLITE_IOERR_FSTAT;
  28704. }
  28705. }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
  28706. *pMode = 0600;
  28707. }
  28708. return rc;
  28709. }
  28710. /*
  28711. ** Open the file zPath.
  28712. **
  28713. ** Previously, the SQLite OS layer used three functions in place of this
  28714. ** one:
  28715. **
  28716. ** sqlite3OsOpenReadWrite();
  28717. ** sqlite3OsOpenReadOnly();
  28718. ** sqlite3OsOpenExclusive();
  28719. **
  28720. ** These calls correspond to the following combinations of flags:
  28721. **
  28722. ** ReadWrite() -> (READWRITE | CREATE)
  28723. ** ReadOnly() -> (READONLY)
  28724. ** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
  28725. **
  28726. ** The old OpenExclusive() accepted a boolean argument - "delFlag". If
  28727. ** true, the file was configured to be automatically deleted when the
  28728. ** file handle closed. To achieve the same effect using this new
  28729. ** interface, add the DELETEONCLOSE flag to those specified above for
  28730. ** OpenExclusive().
  28731. */
  28732. static int unixOpen(
  28733. sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
  28734. const char *zPath, /* Pathname of file to be opened */
  28735. sqlite3_file *pFile, /* The file descriptor to be filled in */
  28736. int flags, /* Input flags to control the opening */
  28737. int *pOutFlags /* Output flags returned to SQLite core */
  28738. ){
  28739. unixFile *p = (unixFile *)pFile;
  28740. int fd = -1; /* File descriptor returned by open() */
  28741. int openFlags = 0; /* Flags to pass to open() */
  28742. int eType = flags&0xFFFFFF00; /* Type of file to open */
  28743. int noLock; /* True to omit locking primitives */
  28744. int rc = SQLITE_OK; /* Function Return Code */
  28745. int ctrlFlags = 0; /* UNIXFILE_* flags */
  28746. int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
  28747. int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
  28748. int isCreate = (flags & SQLITE_OPEN_CREATE);
  28749. int isReadonly = (flags & SQLITE_OPEN_READONLY);
  28750. int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
  28751. #if SQLITE_ENABLE_LOCKING_STYLE
  28752. int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY);
  28753. #endif
  28754. #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
  28755. struct statfs fsInfo;
  28756. #endif
  28757. /* If creating a master or main-file journal, this function will open
  28758. ** a file-descriptor on the directory too. The first time unixSync()
  28759. ** is called the directory file descriptor will be fsync()ed and close()d.
  28760. */
  28761. int syncDir = (isCreate && (
  28762. eType==SQLITE_OPEN_MASTER_JOURNAL
  28763. || eType==SQLITE_OPEN_MAIN_JOURNAL
  28764. || eType==SQLITE_OPEN_WAL
  28765. ));
  28766. /* If argument zPath is a NULL pointer, this function is required to open
  28767. ** a temporary file. Use this buffer to store the file name in.
  28768. */
  28769. char zTmpname[MAX_PATHNAME+2];
  28770. const char *zName = zPath;
  28771. /* Check the following statements are true:
  28772. **
  28773. ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
  28774. ** (b) if CREATE is set, then READWRITE must also be set, and
  28775. ** (c) if EXCLUSIVE is set, then CREATE must also be set.
  28776. ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
  28777. */
  28778. assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
  28779. assert(isCreate==0 || isReadWrite);
  28780. assert(isExclusive==0 || isCreate);
  28781. assert(isDelete==0 || isCreate);
  28782. /* The main DB, main journal, WAL file and master journal are never
  28783. ** automatically deleted. Nor are they ever temporary files. */
  28784. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
  28785. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
  28786. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
  28787. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
  28788. /* Assert that the upper layer has set one of the "file-type" flags. */
  28789. assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
  28790. || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
  28791. || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
  28792. || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
  28793. );
  28794. /* Detect a pid change and reset the PRNG. There is a race condition
  28795. ** here such that two or more threads all trying to open databases at
  28796. ** the same instant might all reset the PRNG. But multiple resets
  28797. ** are harmless.
  28798. */
  28799. if( randomnessPid!=getpid() ){
  28800. randomnessPid = getpid();
  28801. sqlite3_randomness(0,0);
  28802. }
  28803. memset(p, 0, sizeof(unixFile));
  28804. if( eType==SQLITE_OPEN_MAIN_DB ){
  28805. UnixUnusedFd *pUnused;
  28806. pUnused = findReusableFd(zName, flags);
  28807. if( pUnused ){
  28808. fd = pUnused->fd;
  28809. }else{
  28810. pUnused = sqlite3_malloc(sizeof(*pUnused));
  28811. if( !pUnused ){
  28812. return SQLITE_NOMEM;
  28813. }
  28814. }
  28815. p->pUnused = pUnused;
  28816. /* Database filenames are double-zero terminated if they are not
  28817. ** URIs with parameters. Hence, they can always be passed into
  28818. ** sqlite3_uri_parameter(). */
  28819. assert( (flags & SQLITE_OPEN_URI) || zName[strlen(zName)+1]==0 );
  28820. }else if( !zName ){
  28821. /* If zName is NULL, the upper layer is requesting a temp file. */
  28822. assert(isDelete && !syncDir);
  28823. rc = unixGetTempname(MAX_PATHNAME+2, zTmpname);
  28824. if( rc!=SQLITE_OK ){
  28825. return rc;
  28826. }
  28827. zName = zTmpname;
  28828. /* Generated temporary filenames are always double-zero terminated
  28829. ** for use by sqlite3_uri_parameter(). */
  28830. assert( zName[strlen(zName)+1]==0 );
  28831. }
  28832. /* Determine the value of the flags parameter passed to POSIX function
  28833. ** open(). These must be calculated even if open() is not called, as
  28834. ** they may be stored as part of the file handle and used by the
  28835. ** 'conch file' locking functions later on. */
  28836. if( isReadonly ) openFlags |= O_RDONLY;
  28837. if( isReadWrite ) openFlags |= O_RDWR;
  28838. if( isCreate ) openFlags |= O_CREAT;
  28839. if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
  28840. openFlags |= (O_LARGEFILE|O_BINARY);
  28841. if( fd<0 ){
  28842. mode_t openMode; /* Permissions to create file with */
  28843. uid_t uid; /* Userid for the file */
  28844. gid_t gid; /* Groupid for the file */
  28845. rc = findCreateFileMode(zName, flags, &openMode, &uid, &gid);
  28846. if( rc!=SQLITE_OK ){
  28847. assert( !p->pUnused );
  28848. assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
  28849. return rc;
  28850. }
  28851. fd = robust_open(zName, openFlags, openMode);
  28852. OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags));
  28853. if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
  28854. /* Failed to open the file for read/write access. Try read-only. */
  28855. flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
  28856. openFlags &= ~(O_RDWR|O_CREAT);
  28857. flags |= SQLITE_OPEN_READONLY;
  28858. openFlags |= O_RDONLY;
  28859. isReadonly = 1;
  28860. fd = robust_open(zName, openFlags, openMode);
  28861. }
  28862. if( fd<0 ){
  28863. rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
  28864. goto open_finished;
  28865. }
  28866. /* If this process is running as root and if creating a new rollback
  28867. ** journal or WAL file, set the ownership of the journal or WAL to be
  28868. ** the same as the original database.
  28869. */
  28870. if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
  28871. osFchown(fd, uid, gid);
  28872. }
  28873. }
  28874. assert( fd>=0 );
  28875. if( pOutFlags ){
  28876. *pOutFlags = flags;
  28877. }
  28878. if( p->pUnused ){
  28879. p->pUnused->fd = fd;
  28880. p->pUnused->flags = flags;
  28881. }
  28882. if( isDelete ){
  28883. #if OS_VXWORKS
  28884. zPath = zName;
  28885. #elif defined(SQLITE_UNLINK_AFTER_CLOSE)
  28886. zPath = sqlite3_mprintf("%s", zName);
  28887. if( zPath==0 ){
  28888. robust_close(p, fd, __LINE__);
  28889. return SQLITE_NOMEM;
  28890. }
  28891. #else
  28892. osUnlink(zName);
  28893. #endif
  28894. }
  28895. #if SQLITE_ENABLE_LOCKING_STYLE
  28896. else{
  28897. p->openFlags = openFlags;
  28898. }
  28899. #endif
  28900. noLock = eType!=SQLITE_OPEN_MAIN_DB;
  28901. #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
  28902. if( fstatfs(fd, &fsInfo) == -1 ){
  28903. ((unixFile*)pFile)->lastErrno = errno;
  28904. robust_close(p, fd, __LINE__);
  28905. return SQLITE_IOERR_ACCESS;
  28906. }
  28907. if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
  28908. ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
  28909. }
  28910. #endif
  28911. /* Set up appropriate ctrlFlags */
  28912. if( isDelete ) ctrlFlags |= UNIXFILE_DELETE;
  28913. if( isReadonly ) ctrlFlags |= UNIXFILE_RDONLY;
  28914. if( noLock ) ctrlFlags |= UNIXFILE_NOLOCK;
  28915. if( syncDir ) ctrlFlags |= UNIXFILE_DIRSYNC;
  28916. if( flags & SQLITE_OPEN_URI ) ctrlFlags |= UNIXFILE_URI;
  28917. #if SQLITE_ENABLE_LOCKING_STYLE
  28918. #if SQLITE_PREFER_PROXY_LOCKING
  28919. isAutoProxy = 1;
  28920. #endif
  28921. if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
  28922. char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
  28923. int useProxy = 0;
  28924. /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
  28925. ** never use proxy, NULL means use proxy for non-local files only. */
  28926. if( envforce!=NULL ){
  28927. useProxy = atoi(envforce)>0;
  28928. }else{
  28929. if( statfs(zPath, &fsInfo) == -1 ){
  28930. /* In theory, the close(fd) call is sub-optimal. If the file opened
  28931. ** with fd is a database file, and there are other connections open
  28932. ** on that file that are currently holding advisory locks on it,
  28933. ** then the call to close() will cancel those locks. In practice,
  28934. ** we're assuming that statfs() doesn't fail very often. At least
  28935. ** not while other file descriptors opened by the same process on
  28936. ** the same file are working. */
  28937. p->lastErrno = errno;
  28938. robust_close(p, fd, __LINE__);
  28939. rc = SQLITE_IOERR_ACCESS;
  28940. goto open_finished;
  28941. }
  28942. useProxy = !(fsInfo.f_flags&MNT_LOCAL);
  28943. }
  28944. if( useProxy ){
  28945. rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
  28946. if( rc==SQLITE_OK ){
  28947. rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
  28948. if( rc!=SQLITE_OK ){
  28949. /* Use unixClose to clean up the resources added in fillInUnixFile
  28950. ** and clear all the structure's references. Specifically,
  28951. ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
  28952. */
  28953. unixClose(pFile);
  28954. return rc;
  28955. }
  28956. }
  28957. goto open_finished;
  28958. }
  28959. }
  28960. #endif
  28961. rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
  28962. open_finished:
  28963. if( rc!=SQLITE_OK ){
  28964. sqlite3_free(p->pUnused);
  28965. }
  28966. return rc;
  28967. }
  28968. /*
  28969. ** Delete the file at zPath. If the dirSync argument is true, fsync()
  28970. ** the directory after deleting the file.
  28971. */
  28972. static int unixDelete(
  28973. sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
  28974. const char *zPath, /* Name of file to be deleted */
  28975. int dirSync /* If true, fsync() directory after deleting file */
  28976. ){
  28977. int rc = SQLITE_OK;
  28978. UNUSED_PARAMETER(NotUsed);
  28979. SimulateIOError(return SQLITE_IOERR_DELETE);
  28980. if( osUnlink(zPath)==(-1) ){
  28981. if( errno==ENOENT
  28982. #if OS_VXWORKS
  28983. || osAccess(zPath,0)!=0
  28984. #endif
  28985. ){
  28986. rc = SQLITE_IOERR_DELETE_NOENT;
  28987. }else{
  28988. rc = unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
  28989. }
  28990. return rc;
  28991. }
  28992. #ifndef SQLITE_DISABLE_DIRSYNC
  28993. if( (dirSync & 1)!=0 ){
  28994. int fd;
  28995. rc = osOpenDirectory(zPath, &fd);
  28996. if( rc==SQLITE_OK ){
  28997. #if OS_VXWORKS
  28998. if( fsync(fd)==-1 )
  28999. #else
  29000. if( fsync(fd) )
  29001. #endif
  29002. {
  29003. rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
  29004. }
  29005. robust_close(0, fd, __LINE__);
  29006. }else if( rc==SQLITE_CANTOPEN ){
  29007. rc = SQLITE_OK;
  29008. }
  29009. }
  29010. #endif
  29011. return rc;
  29012. }
  29013. /*
  29014. ** Test the existence of or access permissions of file zPath. The
  29015. ** test performed depends on the value of flags:
  29016. **
  29017. ** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
  29018. ** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
  29019. ** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
  29020. **
  29021. ** Otherwise return 0.
  29022. */
  29023. static int unixAccess(
  29024. sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
  29025. const char *zPath, /* Path of the file to examine */
  29026. int flags, /* What do we want to learn about the zPath file? */
  29027. int *pResOut /* Write result boolean here */
  29028. ){
  29029. int amode = 0;
  29030. UNUSED_PARAMETER(NotUsed);
  29031. SimulateIOError( return SQLITE_IOERR_ACCESS; );
  29032. switch( flags ){
  29033. case SQLITE_ACCESS_EXISTS:
  29034. amode = F_OK;
  29035. break;
  29036. case SQLITE_ACCESS_READWRITE:
  29037. amode = W_OK|R_OK;
  29038. break;
  29039. case SQLITE_ACCESS_READ:
  29040. amode = R_OK;
  29041. break;
  29042. default:
  29043. assert(!"Invalid flags argument");
  29044. }
  29045. *pResOut = (osAccess(zPath, amode)==0);
  29046. if( flags==SQLITE_ACCESS_EXISTS && *pResOut ){
  29047. struct stat buf;
  29048. if( 0==osStat(zPath, &buf) && buf.st_size==0 ){
  29049. *pResOut = 0;
  29050. }
  29051. }
  29052. return SQLITE_OK;
  29053. }
  29054. /*
  29055. ** Turn a relative pathname into a full pathname. The relative path
  29056. ** is stored as a nul-terminated string in the buffer pointed to by
  29057. ** zPath.
  29058. **
  29059. ** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
  29060. ** (in this case, MAX_PATHNAME bytes). The full-path is written to
  29061. ** this buffer before returning.
  29062. */
  29063. static int unixFullPathname(
  29064. sqlite3_vfs *pVfs, /* Pointer to vfs object */
  29065. const char *zPath, /* Possibly relative input path */
  29066. int nOut, /* Size of output buffer in bytes */
  29067. char *zOut /* Output buffer */
  29068. ){
  29069. /* It's odd to simulate an io-error here, but really this is just
  29070. ** using the io-error infrastructure to test that SQLite handles this
  29071. ** function failing. This function could fail if, for example, the
  29072. ** current working directory has been unlinked.
  29073. */
  29074. SimulateIOError( return SQLITE_ERROR );
  29075. assert( pVfs->mxPathname==MAX_PATHNAME );
  29076. UNUSED_PARAMETER(pVfs);
  29077. zOut[nOut-1] = '\0';
  29078. if( zPath[0]=='/' ){
  29079. sqlite3_snprintf(nOut, zOut, "%s", zPath);
  29080. }else{
  29081. int nCwd;
  29082. if( osGetcwd(zOut, nOut-1)==0 ){
  29083. return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
  29084. }
  29085. nCwd = (int)strlen(zOut);
  29086. sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
  29087. }
  29088. return SQLITE_OK;
  29089. }
  29090. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  29091. /*
  29092. ** Interfaces for opening a shared library, finding entry points
  29093. ** within the shared library, and closing the shared library.
  29094. */
  29095. #include <dlfcn.h>
  29096. static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
  29097. UNUSED_PARAMETER(NotUsed);
  29098. return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
  29099. }
  29100. /*
  29101. ** SQLite calls this function immediately after a call to unixDlSym() or
  29102. ** unixDlOpen() fails (returns a null pointer). If a more detailed error
  29103. ** message is available, it is written to zBufOut. If no error message
  29104. ** is available, zBufOut is left unmodified and SQLite uses a default
  29105. ** error message.
  29106. */
  29107. static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
  29108. const char *zErr;
  29109. UNUSED_PARAMETER(NotUsed);
  29110. unixEnterMutex();
  29111. zErr = dlerror();
  29112. if( zErr ){
  29113. sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
  29114. }
  29115. unixLeaveMutex();
  29116. }
  29117. static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
  29118. /*
  29119. ** GCC with -pedantic-errors says that C90 does not allow a void* to be
  29120. ** cast into a pointer to a function. And yet the library dlsym() routine
  29121. ** returns a void* which is really a pointer to a function. So how do we
  29122. ** use dlsym() with -pedantic-errors?
  29123. **
  29124. ** Variable x below is defined to be a pointer to a function taking
  29125. ** parameters void* and const char* and returning a pointer to a function.
  29126. ** We initialize x by assigning it a pointer to the dlsym() function.
  29127. ** (That assignment requires a cast.) Then we call the function that
  29128. ** x points to.
  29129. **
  29130. ** This work-around is unlikely to work correctly on any system where
  29131. ** you really cannot cast a function pointer into void*. But then, on the
  29132. ** other hand, dlsym() will not work on such a system either, so we have
  29133. ** not really lost anything.
  29134. */
  29135. void (*(*x)(void*,const char*))(void);
  29136. UNUSED_PARAMETER(NotUsed);
  29137. x = (void(*(*)(void*,const char*))(void))dlsym;
  29138. return (*x)(p, zSym);
  29139. }
  29140. static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
  29141. UNUSED_PARAMETER(NotUsed);
  29142. dlclose(pHandle);
  29143. }
  29144. #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
  29145. #define unixDlOpen 0
  29146. #define unixDlError 0
  29147. #define unixDlSym 0
  29148. #define unixDlClose 0
  29149. #endif
  29150. /*
  29151. ** Write nBuf bytes of random data to the supplied buffer zBuf.
  29152. */
  29153. static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
  29154. UNUSED_PARAMETER(NotUsed);
  29155. assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
  29156. /* We have to initialize zBuf to prevent valgrind from reporting
  29157. ** errors. The reports issued by valgrind are incorrect - we would
  29158. ** prefer that the randomness be increased by making use of the
  29159. ** uninitialized space in zBuf - but valgrind errors tend to worry
  29160. ** some users. Rather than argue, it seems easier just to initialize
  29161. ** the whole array and silence valgrind, even if that means less randomness
  29162. ** in the random seed.
  29163. **
  29164. ** When testing, initializing zBuf[] to zero is all we do. That means
  29165. ** that we always use the same random number sequence. This makes the
  29166. ** tests repeatable.
  29167. */
  29168. memset(zBuf, 0, nBuf);
  29169. randomnessPid = getpid();
  29170. #if !defined(SQLITE_TEST)
  29171. {
  29172. int fd, got;
  29173. fd = robust_open("/dev/urandom", O_RDONLY, 0);
  29174. if( fd<0 ){
  29175. time_t t;
  29176. time(&t);
  29177. memcpy(zBuf, &t, sizeof(t));
  29178. memcpy(&zBuf[sizeof(t)], &randomnessPid, sizeof(randomnessPid));
  29179. assert( sizeof(t)+sizeof(randomnessPid)<=(size_t)nBuf );
  29180. nBuf = sizeof(t) + sizeof(randomnessPid);
  29181. }else{
  29182. do{ got = osRead(fd, zBuf, nBuf); }while( got<0 && errno==EINTR );
  29183. robust_close(0, fd, __LINE__);
  29184. }
  29185. }
  29186. #endif
  29187. return nBuf;
  29188. }
  29189. /*
  29190. ** Sleep for a little while. Return the amount of time slept.
  29191. ** The argument is the number of microseconds we want to sleep.
  29192. ** The return value is the number of microseconds of sleep actually
  29193. ** requested from the underlying operating system, a number which
  29194. ** might be greater than or equal to the argument, but not less
  29195. ** than the argument.
  29196. */
  29197. static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
  29198. #if OS_VXWORKS
  29199. struct timespec sp;
  29200. sp.tv_sec = microseconds / 1000000;
  29201. sp.tv_nsec = (microseconds % 1000000) * 1000;
  29202. nanosleep(&sp, NULL);
  29203. UNUSED_PARAMETER(NotUsed);
  29204. return microseconds;
  29205. #elif defined(HAVE_USLEEP) && HAVE_USLEEP
  29206. usleep(microseconds);
  29207. UNUSED_PARAMETER(NotUsed);
  29208. return microseconds;
  29209. #else
  29210. int seconds = (microseconds+999999)/1000000;
  29211. sleep(seconds);
  29212. UNUSED_PARAMETER(NotUsed);
  29213. return seconds*1000000;
  29214. #endif
  29215. }
  29216. /*
  29217. ** The following variable, if set to a non-zero value, is interpreted as
  29218. ** the number of seconds since 1970 and is used to set the result of
  29219. ** sqlite3OsCurrentTime() during testing.
  29220. */
  29221. #ifdef SQLITE_TEST
  29222. SQLITE_API int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
  29223. #endif
  29224. /*
  29225. ** Find the current time (in Universal Coordinated Time). Write into *piNow
  29226. ** the current time and date as a Julian Day number times 86_400_000. In
  29227. ** other words, write into *piNow the number of milliseconds since the Julian
  29228. ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
  29229. ** proleptic Gregorian calendar.
  29230. **
  29231. ** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date
  29232. ** cannot be found.
  29233. */
  29234. static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
  29235. static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
  29236. int rc = SQLITE_OK;
  29237. #if defined(NO_GETTOD)
  29238. time_t t;
  29239. time(&t);
  29240. *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
  29241. #elif OS_VXWORKS
  29242. struct timespec sNow;
  29243. clock_gettime(CLOCK_REALTIME, &sNow);
  29244. *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
  29245. #else
  29246. struct timeval sNow;
  29247. if( gettimeofday(&sNow, 0)==0 ){
  29248. *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
  29249. }else{
  29250. rc = SQLITE_ERROR;
  29251. }
  29252. #endif
  29253. #ifdef SQLITE_TEST
  29254. if( sqlite3_current_time ){
  29255. *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
  29256. }
  29257. #endif
  29258. UNUSED_PARAMETER(NotUsed);
  29259. return rc;
  29260. }
  29261. /*
  29262. ** Find the current time (in Universal Coordinated Time). Write the
  29263. ** current time and date as a Julian Day number into *prNow and
  29264. ** return 0. Return 1 if the time and date cannot be found.
  29265. */
  29266. static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
  29267. sqlite3_int64 i = 0;
  29268. int rc;
  29269. UNUSED_PARAMETER(NotUsed);
  29270. rc = unixCurrentTimeInt64(0, &i);
  29271. *prNow = i/86400000.0;
  29272. return rc;
  29273. }
  29274. /*
  29275. ** We added the xGetLastError() method with the intention of providing
  29276. ** better low-level error messages when operating-system problems come up
  29277. ** during SQLite operation. But so far, none of that has been implemented
  29278. ** in the core. So this routine is never called. For now, it is merely
  29279. ** a place-holder.
  29280. */
  29281. static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
  29282. UNUSED_PARAMETER(NotUsed);
  29283. UNUSED_PARAMETER(NotUsed2);
  29284. UNUSED_PARAMETER(NotUsed3);
  29285. return 0;
  29286. }
  29287. /*
  29288. ************************ End of sqlite3_vfs methods ***************************
  29289. ******************************************************************************/
  29290. /******************************************************************************
  29291. ************************** Begin Proxy Locking ********************************
  29292. **
  29293. ** Proxy locking is a "uber-locking-method" in this sense: It uses the
  29294. ** other locking methods on secondary lock files. Proxy locking is a
  29295. ** meta-layer over top of the primitive locking implemented above. For
  29296. ** this reason, the division that implements of proxy locking is deferred
  29297. ** until late in the file (here) after all of the other I/O methods have
  29298. ** been defined - so that the primitive locking methods are available
  29299. ** as services to help with the implementation of proxy locking.
  29300. **
  29301. ****
  29302. **
  29303. ** The default locking schemes in SQLite use byte-range locks on the
  29304. ** database file to coordinate safe, concurrent access by multiple readers
  29305. ** and writers [http://sqlite.org/lockingv3.html]. The five file locking
  29306. ** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
  29307. ** as POSIX read & write locks over fixed set of locations (via fsctl),
  29308. ** on AFP and SMB only exclusive byte-range locks are available via fsctl
  29309. ** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
  29310. ** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
  29311. ** address in the shared range is taken for a SHARED lock, the entire
  29312. ** shared range is taken for an EXCLUSIVE lock):
  29313. **
  29314. ** PENDING_BYTE 0x40000000
  29315. ** RESERVED_BYTE 0x40000001
  29316. ** SHARED_RANGE 0x40000002 -> 0x40000200
  29317. **
  29318. ** This works well on the local file system, but shows a nearly 100x
  29319. ** slowdown in read performance on AFP because the AFP client disables
  29320. ** the read cache when byte-range locks are present. Enabling the read
  29321. ** cache exposes a cache coherency problem that is present on all OS X
  29322. ** supported network file systems. NFS and AFP both observe the
  29323. ** close-to-open semantics for ensuring cache coherency
  29324. ** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
  29325. ** address the requirements for concurrent database access by multiple
  29326. ** readers and writers
  29327. ** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
  29328. **
  29329. ** To address the performance and cache coherency issues, proxy file locking
  29330. ** changes the way database access is controlled by limiting access to a
  29331. ** single host at a time and moving file locks off of the database file
  29332. ** and onto a proxy file on the local file system.
  29333. **
  29334. **
  29335. ** Using proxy locks
  29336. ** -----------------
  29337. **
  29338. ** C APIs
  29339. **
  29340. ** sqlite3_file_control(db, dbname, SQLITE_SET_LOCKPROXYFILE,
  29341. ** <proxy_path> | ":auto:");
  29342. ** sqlite3_file_control(db, dbname, SQLITE_GET_LOCKPROXYFILE, &<proxy_path>);
  29343. **
  29344. **
  29345. ** SQL pragmas
  29346. **
  29347. ** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
  29348. ** PRAGMA [database.]lock_proxy_file
  29349. **
  29350. ** Specifying ":auto:" means that if there is a conch file with a matching
  29351. ** host ID in it, the proxy path in the conch file will be used, otherwise
  29352. ** a proxy path based on the user's temp dir
  29353. ** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
  29354. ** actual proxy file name is generated from the name and path of the
  29355. ** database file. For example:
  29356. **
  29357. ** For database path "/Users/me/foo.db"
  29358. ** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
  29359. **
  29360. ** Once a lock proxy is configured for a database connection, it can not
  29361. ** be removed, however it may be switched to a different proxy path via
  29362. ** the above APIs (assuming the conch file is not being held by another
  29363. ** connection or process).
  29364. **
  29365. **
  29366. ** How proxy locking works
  29367. ** -----------------------
  29368. **
  29369. ** Proxy file locking relies primarily on two new supporting files:
  29370. **
  29371. ** * conch file to limit access to the database file to a single host
  29372. ** at a time
  29373. **
  29374. ** * proxy file to act as a proxy for the advisory locks normally
  29375. ** taken on the database
  29376. **
  29377. ** The conch file - to use a proxy file, sqlite must first "hold the conch"
  29378. ** by taking an sqlite-style shared lock on the conch file, reading the
  29379. ** contents and comparing the host's unique host ID (see below) and lock
  29380. ** proxy path against the values stored in the conch. The conch file is
  29381. ** stored in the same directory as the database file and the file name
  29382. ** is patterned after the database file name as ".<databasename>-conch".
  29383. ** If the conch file does not exist, or its contents do not match the
  29384. ** host ID and/or proxy path, then the lock is escalated to an exclusive
  29385. ** lock and the conch file contents is updated with the host ID and proxy
  29386. ** path and the lock is downgraded to a shared lock again. If the conch
  29387. ** is held by another process (with a shared lock), the exclusive lock
  29388. ** will fail and SQLITE_BUSY is returned.
  29389. **
  29390. ** The proxy file - a single-byte file used for all advisory file locks
  29391. ** normally taken on the database file. This allows for safe sharing
  29392. ** of the database file for multiple readers and writers on the same
  29393. ** host (the conch ensures that they all use the same local lock file).
  29394. **
  29395. ** Requesting the lock proxy does not immediately take the conch, it is
  29396. ** only taken when the first request to lock database file is made.
  29397. ** This matches the semantics of the traditional locking behavior, where
  29398. ** opening a connection to a database file does not take a lock on it.
  29399. ** The shared lock and an open file descriptor are maintained until
  29400. ** the connection to the database is closed.
  29401. **
  29402. ** The proxy file and the lock file are never deleted so they only need
  29403. ** to be created the first time they are used.
  29404. **
  29405. ** Configuration options
  29406. ** ---------------------
  29407. **
  29408. ** SQLITE_PREFER_PROXY_LOCKING
  29409. **
  29410. ** Database files accessed on non-local file systems are
  29411. ** automatically configured for proxy locking, lock files are
  29412. ** named automatically using the same logic as
  29413. ** PRAGMA lock_proxy_file=":auto:"
  29414. **
  29415. ** SQLITE_PROXY_DEBUG
  29416. **
  29417. ** Enables the logging of error messages during host id file
  29418. ** retrieval and creation
  29419. **
  29420. ** LOCKPROXYDIR
  29421. **
  29422. ** Overrides the default directory used for lock proxy files that
  29423. ** are named automatically via the ":auto:" setting
  29424. **
  29425. ** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
  29426. **
  29427. ** Permissions to use when creating a directory for storing the
  29428. ** lock proxy files, only used when LOCKPROXYDIR is not set.
  29429. **
  29430. **
  29431. ** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
  29432. ** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
  29433. ** force proxy locking to be used for every database file opened, and 0
  29434. ** will force automatic proxy locking to be disabled for all database
  29435. ** files (explicitly calling the SQLITE_SET_LOCKPROXYFILE pragma or
  29436. ** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
  29437. */
  29438. /*
  29439. ** Proxy locking is only available on MacOSX
  29440. */
  29441. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  29442. /*
  29443. ** The proxyLockingContext has the path and file structures for the remote
  29444. ** and local proxy files in it
  29445. */
  29446. typedef struct proxyLockingContext proxyLockingContext;
  29447. struct proxyLockingContext {
  29448. unixFile *conchFile; /* Open conch file */
  29449. char *conchFilePath; /* Name of the conch file */
  29450. unixFile *lockProxy; /* Open proxy lock file */
  29451. char *lockProxyPath; /* Name of the proxy lock file */
  29452. char *dbPath; /* Name of the open file */
  29453. int conchHeld; /* 1 if the conch is held, -1 if lockless */
  29454. void *oldLockingContext; /* Original lockingcontext to restore on close */
  29455. sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
  29456. };
  29457. /*
  29458. ** The proxy lock file path for the database at dbPath is written into lPath,
  29459. ** which must point to valid, writable memory large enough for a maxLen length
  29460. ** file path.
  29461. */
  29462. static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
  29463. int len;
  29464. int dbLen;
  29465. int i;
  29466. #ifdef LOCKPROXYDIR
  29467. len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
  29468. #else
  29469. # ifdef _CS_DARWIN_USER_TEMP_DIR
  29470. {
  29471. if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
  29472. OSTRACE(("GETLOCKPATH failed %s errno=%d pid=%d\n",
  29473. lPath, errno, getpid()));
  29474. return SQLITE_IOERR_LOCK;
  29475. }
  29476. len = strlcat(lPath, "sqliteplocks", maxLen);
  29477. }
  29478. # else
  29479. len = strlcpy(lPath, "/tmp/", maxLen);
  29480. # endif
  29481. #endif
  29482. if( lPath[len-1]!='/' ){
  29483. len = strlcat(lPath, "/", maxLen);
  29484. }
  29485. /* transform the db path to a unique cache name */
  29486. dbLen = (int)strlen(dbPath);
  29487. for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
  29488. char c = dbPath[i];
  29489. lPath[i+len] = (c=='/')?'_':c;
  29490. }
  29491. lPath[i+len]='\0';
  29492. strlcat(lPath, ":auto:", maxLen);
  29493. OSTRACE(("GETLOCKPATH proxy lock path=%s pid=%d\n", lPath, getpid()));
  29494. return SQLITE_OK;
  29495. }
  29496. /*
  29497. ** Creates the lock file and any missing directories in lockPath
  29498. */
  29499. static int proxyCreateLockPath(const char *lockPath){
  29500. int i, len;
  29501. char buf[MAXPATHLEN];
  29502. int start = 0;
  29503. assert(lockPath!=NULL);
  29504. /* try to create all the intermediate directories */
  29505. len = (int)strlen(lockPath);
  29506. buf[0] = lockPath[0];
  29507. for( i=1; i<len; i++ ){
  29508. if( lockPath[i] == '/' && (i - start > 0) ){
  29509. /* only mkdir if leaf dir != "." or "/" or ".." */
  29510. if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
  29511. || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
  29512. buf[i]='\0';
  29513. if( osMkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
  29514. int err=errno;
  29515. if( err!=EEXIST ) {
  29516. OSTRACE(("CREATELOCKPATH FAILED creating %s, "
  29517. "'%s' proxy lock path=%s pid=%d\n",
  29518. buf, strerror(err), lockPath, getpid()));
  29519. return err;
  29520. }
  29521. }
  29522. }
  29523. start=i+1;
  29524. }
  29525. buf[i] = lockPath[i];
  29526. }
  29527. OSTRACE(("CREATELOCKPATH proxy lock path=%s pid=%d\n", lockPath, getpid()));
  29528. return 0;
  29529. }
  29530. /*
  29531. ** Create a new VFS file descriptor (stored in memory obtained from
  29532. ** sqlite3_malloc) and open the file named "path" in the file descriptor.
  29533. **
  29534. ** The caller is responsible not only for closing the file descriptor
  29535. ** but also for freeing the memory associated with the file descriptor.
  29536. */
  29537. static int proxyCreateUnixFile(
  29538. const char *path, /* path for the new unixFile */
  29539. unixFile **ppFile, /* unixFile created and returned by ref */
  29540. int islockfile /* if non zero missing dirs will be created */
  29541. ) {
  29542. int fd = -1;
  29543. unixFile *pNew;
  29544. int rc = SQLITE_OK;
  29545. int openFlags = O_RDWR | O_CREAT;
  29546. sqlite3_vfs dummyVfs;
  29547. int terrno = 0;
  29548. UnixUnusedFd *pUnused = NULL;
  29549. /* 1. first try to open/create the file
  29550. ** 2. if that fails, and this is a lock file (not-conch), try creating
  29551. ** the parent directories and then try again.
  29552. ** 3. if that fails, try to open the file read-only
  29553. ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
  29554. */
  29555. pUnused = findReusableFd(path, openFlags);
  29556. if( pUnused ){
  29557. fd = pUnused->fd;
  29558. }else{
  29559. pUnused = sqlite3_malloc(sizeof(*pUnused));
  29560. if( !pUnused ){
  29561. return SQLITE_NOMEM;
  29562. }
  29563. }
  29564. if( fd<0 ){
  29565. fd = robust_open(path, openFlags, 0);
  29566. terrno = errno;
  29567. if( fd<0 && errno==ENOENT && islockfile ){
  29568. if( proxyCreateLockPath(path) == SQLITE_OK ){
  29569. fd = robust_open(path, openFlags, 0);
  29570. }
  29571. }
  29572. }
  29573. if( fd<0 ){
  29574. openFlags = O_RDONLY;
  29575. fd = robust_open(path, openFlags, 0);
  29576. terrno = errno;
  29577. }
  29578. if( fd<0 ){
  29579. if( islockfile ){
  29580. return SQLITE_BUSY;
  29581. }
  29582. switch (terrno) {
  29583. case EACCES:
  29584. return SQLITE_PERM;
  29585. case EIO:
  29586. return SQLITE_IOERR_LOCK; /* even though it is the conch */
  29587. default:
  29588. return SQLITE_CANTOPEN_BKPT;
  29589. }
  29590. }
  29591. pNew = (unixFile *)sqlite3_malloc(sizeof(*pNew));
  29592. if( pNew==NULL ){
  29593. rc = SQLITE_NOMEM;
  29594. goto end_create_proxy;
  29595. }
  29596. memset(pNew, 0, sizeof(unixFile));
  29597. pNew->openFlags = openFlags;
  29598. memset(&dummyVfs, 0, sizeof(dummyVfs));
  29599. dummyVfs.pAppData = (void*)&autolockIoFinder;
  29600. dummyVfs.zName = "dummy";
  29601. pUnused->fd = fd;
  29602. pUnused->flags = openFlags;
  29603. pNew->pUnused = pUnused;
  29604. rc = fillInUnixFile(&dummyVfs, fd, (sqlite3_file*)pNew, path, 0);
  29605. if( rc==SQLITE_OK ){
  29606. *ppFile = pNew;
  29607. return SQLITE_OK;
  29608. }
  29609. end_create_proxy:
  29610. robust_close(pNew, fd, __LINE__);
  29611. sqlite3_free(pNew);
  29612. sqlite3_free(pUnused);
  29613. return rc;
  29614. }
  29615. #ifdef SQLITE_TEST
  29616. /* simulate multiple hosts by creating unique hostid file paths */
  29617. SQLITE_API int sqlite3_hostid_num = 0;
  29618. #endif
  29619. #define PROXY_HOSTIDLEN 16 /* conch file host id length */
  29620. /* Not always defined in the headers as it ought to be */
  29621. extern int gethostuuid(uuid_t id, const struct timespec *wait);
  29622. /* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
  29623. ** bytes of writable memory.
  29624. */
  29625. static int proxyGetHostID(unsigned char *pHostID, int *pError){
  29626. assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
  29627. memset(pHostID, 0, PROXY_HOSTIDLEN);
  29628. #if defined(__MAX_OS_X_VERSION_MIN_REQUIRED)\
  29629. && __MAC_OS_X_VERSION_MIN_REQUIRED<1050
  29630. {
  29631. static const struct timespec timeout = {1, 0}; /* 1 sec timeout */
  29632. if( gethostuuid(pHostID, &timeout) ){
  29633. int err = errno;
  29634. if( pError ){
  29635. *pError = err;
  29636. }
  29637. return SQLITE_IOERR;
  29638. }
  29639. }
  29640. #else
  29641. UNUSED_PARAMETER(pError);
  29642. #endif
  29643. #ifdef SQLITE_TEST
  29644. /* simulate multiple hosts by creating unique hostid file paths */
  29645. if( sqlite3_hostid_num != 0){
  29646. pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
  29647. }
  29648. #endif
  29649. return SQLITE_OK;
  29650. }
  29651. /* The conch file contains the header, host id and lock file path
  29652. */
  29653. #define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */
  29654. #define PROXY_HEADERLEN 1 /* conch file header length */
  29655. #define PROXY_PATHINDEX (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
  29656. #define PROXY_MAXCONCHLEN (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
  29657. /*
  29658. ** Takes an open conch file, copies the contents to a new path and then moves
  29659. ** it back. The newly created file's file descriptor is assigned to the
  29660. ** conch file structure and finally the original conch file descriptor is
  29661. ** closed. Returns zero if successful.
  29662. */
  29663. static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
  29664. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  29665. unixFile *conchFile = pCtx->conchFile;
  29666. char tPath[MAXPATHLEN];
  29667. char buf[PROXY_MAXCONCHLEN];
  29668. char *cPath = pCtx->conchFilePath;
  29669. size_t readLen = 0;
  29670. size_t pathLen = 0;
  29671. char errmsg[64] = "";
  29672. int fd = -1;
  29673. int rc = -1;
  29674. UNUSED_PARAMETER(myHostID);
  29675. /* create a new path by replace the trailing '-conch' with '-break' */
  29676. pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
  29677. if( pathLen>MAXPATHLEN || pathLen<6 ||
  29678. (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
  29679. sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
  29680. goto end_breaklock;
  29681. }
  29682. /* read the conch content */
  29683. readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
  29684. if( readLen<PROXY_PATHINDEX ){
  29685. sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
  29686. goto end_breaklock;
  29687. }
  29688. /* write it out to the temporary break file */
  29689. fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL), 0);
  29690. if( fd<0 ){
  29691. sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
  29692. goto end_breaklock;
  29693. }
  29694. if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
  29695. sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
  29696. goto end_breaklock;
  29697. }
  29698. if( rename(tPath, cPath) ){
  29699. sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
  29700. goto end_breaklock;
  29701. }
  29702. rc = 0;
  29703. fprintf(stderr, "broke stale lock on %s\n", cPath);
  29704. robust_close(pFile, conchFile->h, __LINE__);
  29705. conchFile->h = fd;
  29706. conchFile->openFlags = O_RDWR | O_CREAT;
  29707. end_breaklock:
  29708. if( rc ){
  29709. if( fd>=0 ){
  29710. osUnlink(tPath);
  29711. robust_close(pFile, fd, __LINE__);
  29712. }
  29713. fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
  29714. }
  29715. return rc;
  29716. }
  29717. /* Take the requested lock on the conch file and break a stale lock if the
  29718. ** host id matches.
  29719. */
  29720. static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
  29721. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  29722. unixFile *conchFile = pCtx->conchFile;
  29723. int rc = SQLITE_OK;
  29724. int nTries = 0;
  29725. struct timespec conchModTime;
  29726. memset(&conchModTime, 0, sizeof(conchModTime));
  29727. do {
  29728. rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
  29729. nTries ++;
  29730. if( rc==SQLITE_BUSY ){
  29731. /* If the lock failed (busy):
  29732. * 1st try: get the mod time of the conch, wait 0.5s and try again.
  29733. * 2nd try: fail if the mod time changed or host id is different, wait
  29734. * 10 sec and try again
  29735. * 3rd try: break the lock unless the mod time has changed.
  29736. */
  29737. struct stat buf;
  29738. if( osFstat(conchFile->h, &buf) ){
  29739. pFile->lastErrno = errno;
  29740. return SQLITE_IOERR_LOCK;
  29741. }
  29742. if( nTries==1 ){
  29743. conchModTime = buf.st_mtimespec;
  29744. usleep(500000); /* wait 0.5 sec and try the lock again*/
  29745. continue;
  29746. }
  29747. assert( nTries>1 );
  29748. if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
  29749. conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
  29750. return SQLITE_BUSY;
  29751. }
  29752. if( nTries==2 ){
  29753. char tBuf[PROXY_MAXCONCHLEN];
  29754. int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
  29755. if( len<0 ){
  29756. pFile->lastErrno = errno;
  29757. return SQLITE_IOERR_LOCK;
  29758. }
  29759. if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
  29760. /* don't break the lock if the host id doesn't match */
  29761. if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
  29762. return SQLITE_BUSY;
  29763. }
  29764. }else{
  29765. /* don't break the lock on short read or a version mismatch */
  29766. return SQLITE_BUSY;
  29767. }
  29768. usleep(10000000); /* wait 10 sec and try the lock again */
  29769. continue;
  29770. }
  29771. assert( nTries==3 );
  29772. if( 0==proxyBreakConchLock(pFile, myHostID) ){
  29773. rc = SQLITE_OK;
  29774. if( lockType==EXCLUSIVE_LOCK ){
  29775. rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
  29776. }
  29777. if( !rc ){
  29778. rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
  29779. }
  29780. }
  29781. }
  29782. } while( rc==SQLITE_BUSY && nTries<3 );
  29783. return rc;
  29784. }
  29785. /* Takes the conch by taking a shared lock and read the contents conch, if
  29786. ** lockPath is non-NULL, the host ID and lock file path must match. A NULL
  29787. ** lockPath means that the lockPath in the conch file will be used if the
  29788. ** host IDs match, or a new lock path will be generated automatically
  29789. ** and written to the conch file.
  29790. */
  29791. static int proxyTakeConch(unixFile *pFile){
  29792. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  29793. if( pCtx->conchHeld!=0 ){
  29794. return SQLITE_OK;
  29795. }else{
  29796. unixFile *conchFile = pCtx->conchFile;
  29797. uuid_t myHostID;
  29798. int pError = 0;
  29799. char readBuf[PROXY_MAXCONCHLEN];
  29800. char lockPath[MAXPATHLEN];
  29801. char *tempLockPath = NULL;
  29802. int rc = SQLITE_OK;
  29803. int createConch = 0;
  29804. int hostIdMatch = 0;
  29805. int readLen = 0;
  29806. int tryOldLockPath = 0;
  29807. int forceNewLockPath = 0;
  29808. OSTRACE(("TAKECONCH %d for %s pid=%d\n", conchFile->h,
  29809. (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), getpid()));
  29810. rc = proxyGetHostID(myHostID, &pError);
  29811. if( (rc&0xff)==SQLITE_IOERR ){
  29812. pFile->lastErrno = pError;
  29813. goto end_takeconch;
  29814. }
  29815. rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
  29816. if( rc!=SQLITE_OK ){
  29817. goto end_takeconch;
  29818. }
  29819. /* read the existing conch file */
  29820. readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
  29821. if( readLen<0 ){
  29822. /* I/O error: lastErrno set by seekAndRead */
  29823. pFile->lastErrno = conchFile->lastErrno;
  29824. rc = SQLITE_IOERR_READ;
  29825. goto end_takeconch;
  29826. }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
  29827. readBuf[0]!=(char)PROXY_CONCHVERSION ){
  29828. /* a short read or version format mismatch means we need to create a new
  29829. ** conch file.
  29830. */
  29831. createConch = 1;
  29832. }
  29833. /* if the host id matches and the lock path already exists in the conch
  29834. ** we'll try to use the path there, if we can't open that path, we'll
  29835. ** retry with a new auto-generated path
  29836. */
  29837. do { /* in case we need to try again for an :auto: named lock file */
  29838. if( !createConch && !forceNewLockPath ){
  29839. hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
  29840. PROXY_HOSTIDLEN);
  29841. /* if the conch has data compare the contents */
  29842. if( !pCtx->lockProxyPath ){
  29843. /* for auto-named local lock file, just check the host ID and we'll
  29844. ** use the local lock file path that's already in there
  29845. */
  29846. if( hostIdMatch ){
  29847. size_t pathLen = (readLen - PROXY_PATHINDEX);
  29848. if( pathLen>=MAXPATHLEN ){
  29849. pathLen=MAXPATHLEN-1;
  29850. }
  29851. memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
  29852. lockPath[pathLen] = 0;
  29853. tempLockPath = lockPath;
  29854. tryOldLockPath = 1;
  29855. /* create a copy of the lock path if the conch is taken */
  29856. goto end_takeconch;
  29857. }
  29858. }else if( hostIdMatch
  29859. && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
  29860. readLen-PROXY_PATHINDEX)
  29861. ){
  29862. /* conch host and lock path match */
  29863. goto end_takeconch;
  29864. }
  29865. }
  29866. /* if the conch isn't writable and doesn't match, we can't take it */
  29867. if( (conchFile->openFlags&O_RDWR) == 0 ){
  29868. rc = SQLITE_BUSY;
  29869. goto end_takeconch;
  29870. }
  29871. /* either the conch didn't match or we need to create a new one */
  29872. if( !pCtx->lockProxyPath ){
  29873. proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
  29874. tempLockPath = lockPath;
  29875. /* create a copy of the lock path _only_ if the conch is taken */
  29876. }
  29877. /* update conch with host and path (this will fail if other process
  29878. ** has a shared lock already), if the host id matches, use the big
  29879. ** stick.
  29880. */
  29881. futimes(conchFile->h, NULL);
  29882. if( hostIdMatch && !createConch ){
  29883. if( conchFile->pInode && conchFile->pInode->nShared>1 ){
  29884. /* We are trying for an exclusive lock but another thread in this
  29885. ** same process is still holding a shared lock. */
  29886. rc = SQLITE_BUSY;
  29887. } else {
  29888. rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
  29889. }
  29890. }else{
  29891. rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, EXCLUSIVE_LOCK);
  29892. }
  29893. if( rc==SQLITE_OK ){
  29894. char writeBuffer[PROXY_MAXCONCHLEN];
  29895. int writeSize = 0;
  29896. writeBuffer[0] = (char)PROXY_CONCHVERSION;
  29897. memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
  29898. if( pCtx->lockProxyPath!=NULL ){
  29899. strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath, MAXPATHLEN);
  29900. }else{
  29901. strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
  29902. }
  29903. writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
  29904. robust_ftruncate(conchFile->h, writeSize);
  29905. rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
  29906. fsync(conchFile->h);
  29907. /* If we created a new conch file (not just updated the contents of a
  29908. ** valid conch file), try to match the permissions of the database
  29909. */
  29910. if( rc==SQLITE_OK && createConch ){
  29911. struct stat buf;
  29912. int err = osFstat(pFile->h, &buf);
  29913. if( err==0 ){
  29914. mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
  29915. S_IROTH|S_IWOTH);
  29916. /* try to match the database file R/W permissions, ignore failure */
  29917. #ifndef SQLITE_PROXY_DEBUG
  29918. osFchmod(conchFile->h, cmode);
  29919. #else
  29920. do{
  29921. rc = osFchmod(conchFile->h, cmode);
  29922. }while( rc==(-1) && errno==EINTR );
  29923. if( rc!=0 ){
  29924. int code = errno;
  29925. fprintf(stderr, "fchmod %o FAILED with %d %s\n",
  29926. cmode, code, strerror(code));
  29927. } else {
  29928. fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
  29929. }
  29930. }else{
  29931. int code = errno;
  29932. fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
  29933. err, code, strerror(code));
  29934. #endif
  29935. }
  29936. }
  29937. }
  29938. conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
  29939. end_takeconch:
  29940. OSTRACE(("TRANSPROXY: CLOSE %d\n", pFile->h));
  29941. if( rc==SQLITE_OK && pFile->openFlags ){
  29942. int fd;
  29943. if( pFile->h>=0 ){
  29944. robust_close(pFile, pFile->h, __LINE__);
  29945. }
  29946. pFile->h = -1;
  29947. fd = robust_open(pCtx->dbPath, pFile->openFlags, 0);
  29948. OSTRACE(("TRANSPROXY: OPEN %d\n", fd));
  29949. if( fd>=0 ){
  29950. pFile->h = fd;
  29951. }else{
  29952. rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
  29953. during locking */
  29954. }
  29955. }
  29956. if( rc==SQLITE_OK && !pCtx->lockProxy ){
  29957. char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
  29958. rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
  29959. if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
  29960. /* we couldn't create the proxy lock file with the old lock file path
  29961. ** so try again via auto-naming
  29962. */
  29963. forceNewLockPath = 1;
  29964. tryOldLockPath = 0;
  29965. continue; /* go back to the do {} while start point, try again */
  29966. }
  29967. }
  29968. if( rc==SQLITE_OK ){
  29969. /* Need to make a copy of path if we extracted the value
  29970. ** from the conch file or the path was allocated on the stack
  29971. */
  29972. if( tempLockPath ){
  29973. pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
  29974. if( !pCtx->lockProxyPath ){
  29975. rc = SQLITE_NOMEM;
  29976. }
  29977. }
  29978. }
  29979. if( rc==SQLITE_OK ){
  29980. pCtx->conchHeld = 1;
  29981. if( pCtx->lockProxy->pMethod == &afpIoMethods ){
  29982. afpLockingContext *afpCtx;
  29983. afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
  29984. afpCtx->dbPath = pCtx->lockProxyPath;
  29985. }
  29986. } else {
  29987. conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
  29988. }
  29989. OSTRACE(("TAKECONCH %d %s\n", conchFile->h,
  29990. rc==SQLITE_OK?"ok":"failed"));
  29991. return rc;
  29992. } while (1); /* in case we need to retry the :auto: lock file -
  29993. ** we should never get here except via the 'continue' call. */
  29994. }
  29995. }
  29996. /*
  29997. ** If pFile holds a lock on a conch file, then release that lock.
  29998. */
  29999. static int proxyReleaseConch(unixFile *pFile){
  30000. int rc = SQLITE_OK; /* Subroutine return code */
  30001. proxyLockingContext *pCtx; /* The locking context for the proxy lock */
  30002. unixFile *conchFile; /* Name of the conch file */
  30003. pCtx = (proxyLockingContext *)pFile->lockingContext;
  30004. conchFile = pCtx->conchFile;
  30005. OSTRACE(("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
  30006. (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
  30007. getpid()));
  30008. if( pCtx->conchHeld>0 ){
  30009. rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
  30010. }
  30011. pCtx->conchHeld = 0;
  30012. OSTRACE(("RELEASECONCH %d %s\n", conchFile->h,
  30013. (rc==SQLITE_OK ? "ok" : "failed")));
  30014. return rc;
  30015. }
  30016. /*
  30017. ** Given the name of a database file, compute the name of its conch file.
  30018. ** Store the conch filename in memory obtained from sqlite3_malloc().
  30019. ** Make *pConchPath point to the new name. Return SQLITE_OK on success
  30020. ** or SQLITE_NOMEM if unable to obtain memory.
  30021. **
  30022. ** The caller is responsible for ensuring that the allocated memory
  30023. ** space is eventually freed.
  30024. **
  30025. ** *pConchPath is set to NULL if a memory allocation error occurs.
  30026. */
  30027. static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
  30028. int i; /* Loop counter */
  30029. int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
  30030. char *conchPath; /* buffer in which to construct conch name */
  30031. /* Allocate space for the conch filename and initialize the name to
  30032. ** the name of the original database file. */
  30033. *pConchPath = conchPath = (char *)sqlite3_malloc(len + 8);
  30034. if( conchPath==0 ){
  30035. return SQLITE_NOMEM;
  30036. }
  30037. memcpy(conchPath, dbPath, len+1);
  30038. /* now insert a "." before the last / character */
  30039. for( i=(len-1); i>=0; i-- ){
  30040. if( conchPath[i]=='/' ){
  30041. i++;
  30042. break;
  30043. }
  30044. }
  30045. conchPath[i]='.';
  30046. while ( i<len ){
  30047. conchPath[i+1]=dbPath[i];
  30048. i++;
  30049. }
  30050. /* append the "-conch" suffix to the file */
  30051. memcpy(&conchPath[i+1], "-conch", 7);
  30052. assert( (int)strlen(conchPath) == len+7 );
  30053. return SQLITE_OK;
  30054. }
  30055. /* Takes a fully configured proxy locking-style unix file and switches
  30056. ** the local lock file path
  30057. */
  30058. static int switchLockProxyPath(unixFile *pFile, const char *path) {
  30059. proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
  30060. char *oldPath = pCtx->lockProxyPath;
  30061. int rc = SQLITE_OK;
  30062. if( pFile->eFileLock!=NO_LOCK ){
  30063. return SQLITE_BUSY;
  30064. }
  30065. /* nothing to do if the path is NULL, :auto: or matches the existing path */
  30066. if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
  30067. (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
  30068. return SQLITE_OK;
  30069. }else{
  30070. unixFile *lockProxy = pCtx->lockProxy;
  30071. pCtx->lockProxy=NULL;
  30072. pCtx->conchHeld = 0;
  30073. if( lockProxy!=NULL ){
  30074. rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
  30075. if( rc ) return rc;
  30076. sqlite3_free(lockProxy);
  30077. }
  30078. sqlite3_free(oldPath);
  30079. pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
  30080. }
  30081. return rc;
  30082. }
  30083. /*
  30084. ** pFile is a file that has been opened by a prior xOpen call. dbPath
  30085. ** is a string buffer at least MAXPATHLEN+1 characters in size.
  30086. **
  30087. ** This routine find the filename associated with pFile and writes it
  30088. ** int dbPath.
  30089. */
  30090. static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
  30091. #if defined(__APPLE__)
  30092. if( pFile->pMethod == &afpIoMethods ){
  30093. /* afp style keeps a reference to the db path in the filePath field
  30094. ** of the struct */
  30095. assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
  30096. strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath, MAXPATHLEN);
  30097. } else
  30098. #endif
  30099. if( pFile->pMethod == &dotlockIoMethods ){
  30100. /* dot lock style uses the locking context to store the dot lock
  30101. ** file path */
  30102. int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
  30103. memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
  30104. }else{
  30105. /* all other styles use the locking context to store the db file path */
  30106. assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
  30107. strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
  30108. }
  30109. return SQLITE_OK;
  30110. }
  30111. /*
  30112. ** Takes an already filled in unix file and alters it so all file locking
  30113. ** will be performed on the local proxy lock file. The following fields
  30114. ** are preserved in the locking context so that they can be restored and
  30115. ** the unix structure properly cleaned up at close time:
  30116. ** ->lockingContext
  30117. ** ->pMethod
  30118. */
  30119. static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
  30120. proxyLockingContext *pCtx;
  30121. char dbPath[MAXPATHLEN+1]; /* Name of the database file */
  30122. char *lockPath=NULL;
  30123. int rc = SQLITE_OK;
  30124. if( pFile->eFileLock!=NO_LOCK ){
  30125. return SQLITE_BUSY;
  30126. }
  30127. proxyGetDbPathForUnixFile(pFile, dbPath);
  30128. if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
  30129. lockPath=NULL;
  30130. }else{
  30131. lockPath=(char *)path;
  30132. }
  30133. OSTRACE(("TRANSPROXY %d for %s pid=%d\n", pFile->h,
  30134. (lockPath ? lockPath : ":auto:"), getpid()));
  30135. pCtx = sqlite3_malloc( sizeof(*pCtx) );
  30136. if( pCtx==0 ){
  30137. return SQLITE_NOMEM;
  30138. }
  30139. memset(pCtx, 0, sizeof(*pCtx));
  30140. rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
  30141. if( rc==SQLITE_OK ){
  30142. rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
  30143. if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
  30144. /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
  30145. ** (c) the file system is read-only, then enable no-locking access.
  30146. ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
  30147. ** that openFlags will have only one of O_RDONLY or O_RDWR.
  30148. */
  30149. struct statfs fsInfo;
  30150. struct stat conchInfo;
  30151. int goLockless = 0;
  30152. if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
  30153. int err = errno;
  30154. if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
  30155. goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
  30156. }
  30157. }
  30158. if( goLockless ){
  30159. pCtx->conchHeld = -1; /* read only FS/ lockless */
  30160. rc = SQLITE_OK;
  30161. }
  30162. }
  30163. }
  30164. if( rc==SQLITE_OK && lockPath ){
  30165. pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
  30166. }
  30167. if( rc==SQLITE_OK ){
  30168. pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
  30169. if( pCtx->dbPath==NULL ){
  30170. rc = SQLITE_NOMEM;
  30171. }
  30172. }
  30173. if( rc==SQLITE_OK ){
  30174. /* all memory is allocated, proxys are created and assigned,
  30175. ** switch the locking context and pMethod then return.
  30176. */
  30177. pCtx->oldLockingContext = pFile->lockingContext;
  30178. pFile->lockingContext = pCtx;
  30179. pCtx->pOldMethod = pFile->pMethod;
  30180. pFile->pMethod = &proxyIoMethods;
  30181. }else{
  30182. if( pCtx->conchFile ){
  30183. pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
  30184. sqlite3_free(pCtx->conchFile);
  30185. }
  30186. sqlite3DbFree(0, pCtx->lockProxyPath);
  30187. sqlite3_free(pCtx->conchFilePath);
  30188. sqlite3_free(pCtx);
  30189. }
  30190. OSTRACE(("TRANSPROXY %d %s\n", pFile->h,
  30191. (rc==SQLITE_OK ? "ok" : "failed")));
  30192. return rc;
  30193. }
  30194. /*
  30195. ** This routine handles sqlite3_file_control() calls that are specific
  30196. ** to proxy locking.
  30197. */
  30198. static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
  30199. switch( op ){
  30200. case SQLITE_GET_LOCKPROXYFILE: {
  30201. unixFile *pFile = (unixFile*)id;
  30202. if( pFile->pMethod == &proxyIoMethods ){
  30203. proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
  30204. proxyTakeConch(pFile);
  30205. if( pCtx->lockProxyPath ){
  30206. *(const char **)pArg = pCtx->lockProxyPath;
  30207. }else{
  30208. *(const char **)pArg = ":auto: (not held)";
  30209. }
  30210. } else {
  30211. *(const char **)pArg = NULL;
  30212. }
  30213. return SQLITE_OK;
  30214. }
  30215. case SQLITE_SET_LOCKPROXYFILE: {
  30216. unixFile *pFile = (unixFile*)id;
  30217. int rc = SQLITE_OK;
  30218. int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
  30219. if( pArg==NULL || (const char *)pArg==0 ){
  30220. if( isProxyStyle ){
  30221. /* turn off proxy locking - not supported */
  30222. rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
  30223. }else{
  30224. /* turn off proxy locking - already off - NOOP */
  30225. rc = SQLITE_OK;
  30226. }
  30227. }else{
  30228. const char *proxyPath = (const char *)pArg;
  30229. if( isProxyStyle ){
  30230. proxyLockingContext *pCtx =
  30231. (proxyLockingContext*)pFile->lockingContext;
  30232. if( !strcmp(pArg, ":auto:")
  30233. || (pCtx->lockProxyPath &&
  30234. !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
  30235. ){
  30236. rc = SQLITE_OK;
  30237. }else{
  30238. rc = switchLockProxyPath(pFile, proxyPath);
  30239. }
  30240. }else{
  30241. /* turn on proxy file locking */
  30242. rc = proxyTransformUnixFile(pFile, proxyPath);
  30243. }
  30244. }
  30245. return rc;
  30246. }
  30247. default: {
  30248. assert( 0 ); /* The call assures that only valid opcodes are sent */
  30249. }
  30250. }
  30251. /*NOTREACHED*/
  30252. return SQLITE_ERROR;
  30253. }
  30254. /*
  30255. ** Within this division (the proxying locking implementation) the procedures
  30256. ** above this point are all utilities. The lock-related methods of the
  30257. ** proxy-locking sqlite3_io_method object follow.
  30258. */
  30259. /*
  30260. ** This routine checks if there is a RESERVED lock held on the specified
  30261. ** file by this or any other process. If such a lock is held, set *pResOut
  30262. ** to a non-zero value otherwise *pResOut is set to zero. The return value
  30263. ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
  30264. */
  30265. static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
  30266. unixFile *pFile = (unixFile*)id;
  30267. int rc = proxyTakeConch(pFile);
  30268. if( rc==SQLITE_OK ){
  30269. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  30270. if( pCtx->conchHeld>0 ){
  30271. unixFile *proxy = pCtx->lockProxy;
  30272. return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
  30273. }else{ /* conchHeld < 0 is lockless */
  30274. pResOut=0;
  30275. }
  30276. }
  30277. return rc;
  30278. }
  30279. /*
  30280. ** Lock the file with the lock specified by parameter eFileLock - one
  30281. ** of the following:
  30282. **
  30283. ** (1) SHARED_LOCK
  30284. ** (2) RESERVED_LOCK
  30285. ** (3) PENDING_LOCK
  30286. ** (4) EXCLUSIVE_LOCK
  30287. **
  30288. ** Sometimes when requesting one lock state, additional lock states
  30289. ** are inserted in between. The locking might fail on one of the later
  30290. ** transitions leaving the lock state different from what it started but
  30291. ** still short of its goal. The following chart shows the allowed
  30292. ** transitions and the inserted intermediate states:
  30293. **
  30294. ** UNLOCKED -> SHARED
  30295. ** SHARED -> RESERVED
  30296. ** SHARED -> (PENDING) -> EXCLUSIVE
  30297. ** RESERVED -> (PENDING) -> EXCLUSIVE
  30298. ** PENDING -> EXCLUSIVE
  30299. **
  30300. ** This routine will only increase a lock. Use the sqlite3OsUnlock()
  30301. ** routine to lower a locking level.
  30302. */
  30303. static int proxyLock(sqlite3_file *id, int eFileLock) {
  30304. unixFile *pFile = (unixFile*)id;
  30305. int rc = proxyTakeConch(pFile);
  30306. if( rc==SQLITE_OK ){
  30307. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  30308. if( pCtx->conchHeld>0 ){
  30309. unixFile *proxy = pCtx->lockProxy;
  30310. rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
  30311. pFile->eFileLock = proxy->eFileLock;
  30312. }else{
  30313. /* conchHeld < 0 is lockless */
  30314. }
  30315. }
  30316. return rc;
  30317. }
  30318. /*
  30319. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  30320. ** must be either NO_LOCK or SHARED_LOCK.
  30321. **
  30322. ** If the locking level of the file descriptor is already at or below
  30323. ** the requested locking level, this routine is a no-op.
  30324. */
  30325. static int proxyUnlock(sqlite3_file *id, int eFileLock) {
  30326. unixFile *pFile = (unixFile*)id;
  30327. int rc = proxyTakeConch(pFile);
  30328. if( rc==SQLITE_OK ){
  30329. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  30330. if( pCtx->conchHeld>0 ){
  30331. unixFile *proxy = pCtx->lockProxy;
  30332. rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
  30333. pFile->eFileLock = proxy->eFileLock;
  30334. }else{
  30335. /* conchHeld < 0 is lockless */
  30336. }
  30337. }
  30338. return rc;
  30339. }
  30340. /*
  30341. ** Close a file that uses proxy locks.
  30342. */
  30343. static int proxyClose(sqlite3_file *id) {
  30344. if( id ){
  30345. unixFile *pFile = (unixFile*)id;
  30346. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  30347. unixFile *lockProxy = pCtx->lockProxy;
  30348. unixFile *conchFile = pCtx->conchFile;
  30349. int rc = SQLITE_OK;
  30350. if( lockProxy ){
  30351. rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
  30352. if( rc ) return rc;
  30353. rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
  30354. if( rc ) return rc;
  30355. sqlite3_free(lockProxy);
  30356. pCtx->lockProxy = 0;
  30357. }
  30358. if( conchFile ){
  30359. if( pCtx->conchHeld ){
  30360. rc = proxyReleaseConch(pFile);
  30361. if( rc ) return rc;
  30362. }
  30363. rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
  30364. if( rc ) return rc;
  30365. sqlite3_free(conchFile);
  30366. }
  30367. sqlite3DbFree(0, pCtx->lockProxyPath);
  30368. sqlite3_free(pCtx->conchFilePath);
  30369. sqlite3DbFree(0, pCtx->dbPath);
  30370. /* restore the original locking context and pMethod then close it */
  30371. pFile->lockingContext = pCtx->oldLockingContext;
  30372. pFile->pMethod = pCtx->pOldMethod;
  30373. sqlite3_free(pCtx);
  30374. return pFile->pMethod->xClose(id);
  30375. }
  30376. return SQLITE_OK;
  30377. }
  30378. #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
  30379. /*
  30380. ** The proxy locking style is intended for use with AFP filesystems.
  30381. ** And since AFP is only supported on MacOSX, the proxy locking is also
  30382. ** restricted to MacOSX.
  30383. **
  30384. **
  30385. ******************* End of the proxy lock implementation **********************
  30386. ******************************************************************************/
  30387. /*
  30388. ** Initialize the operating system interface.
  30389. **
  30390. ** This routine registers all VFS implementations for unix-like operating
  30391. ** systems. This routine, and the sqlite3_os_end() routine that follows,
  30392. ** should be the only routines in this file that are visible from other
  30393. ** files.
  30394. **
  30395. ** This routine is called once during SQLite initialization and by a
  30396. ** single thread. The memory allocation and mutex subsystems have not
  30397. ** necessarily been initialized when this routine is called, and so they
  30398. ** should not be used.
  30399. */
  30400. SQLITE_API int sqlite3_os_init(void){
  30401. /*
  30402. ** The following macro defines an initializer for an sqlite3_vfs object.
  30403. ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
  30404. ** to the "finder" function. (pAppData is a pointer to a pointer because
  30405. ** silly C90 rules prohibit a void* from being cast to a function pointer
  30406. ** and so we have to go through the intermediate pointer to avoid problems
  30407. ** when compiling with -pedantic-errors on GCC.)
  30408. **
  30409. ** The FINDER parameter to this macro is the name of the pointer to the
  30410. ** finder-function. The finder-function returns a pointer to the
  30411. ** sqlite_io_methods object that implements the desired locking
  30412. ** behaviors. See the division above that contains the IOMETHODS
  30413. ** macro for addition information on finder-functions.
  30414. **
  30415. ** Most finders simply return a pointer to a fixed sqlite3_io_methods
  30416. ** object. But the "autolockIoFinder" available on MacOSX does a little
  30417. ** more than that; it looks at the filesystem type that hosts the
  30418. ** database file and tries to choose an locking method appropriate for
  30419. ** that filesystem time.
  30420. */
  30421. #define UNIXVFS(VFSNAME, FINDER) { \
  30422. 3, /* iVersion */ \
  30423. sizeof(unixFile), /* szOsFile */ \
  30424. MAX_PATHNAME, /* mxPathname */ \
  30425. 0, /* pNext */ \
  30426. VFSNAME, /* zName */ \
  30427. (void*)&FINDER, /* pAppData */ \
  30428. unixOpen, /* xOpen */ \
  30429. unixDelete, /* xDelete */ \
  30430. unixAccess, /* xAccess */ \
  30431. unixFullPathname, /* xFullPathname */ \
  30432. unixDlOpen, /* xDlOpen */ \
  30433. unixDlError, /* xDlError */ \
  30434. unixDlSym, /* xDlSym */ \
  30435. unixDlClose, /* xDlClose */ \
  30436. unixRandomness, /* xRandomness */ \
  30437. unixSleep, /* xSleep */ \
  30438. unixCurrentTime, /* xCurrentTime */ \
  30439. unixGetLastError, /* xGetLastError */ \
  30440. unixCurrentTimeInt64, /* xCurrentTimeInt64 */ \
  30441. unixSetSystemCall, /* xSetSystemCall */ \
  30442. unixGetSystemCall, /* xGetSystemCall */ \
  30443. unixNextSystemCall, /* xNextSystemCall */ \
  30444. }
  30445. /*
  30446. ** All default VFSes for unix are contained in the following array.
  30447. **
  30448. ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
  30449. ** by the SQLite core when the VFS is registered. So the following
  30450. ** array cannot be const.
  30451. */
  30452. static sqlite3_vfs aVfs[] = {
  30453. #if SQLITE_ENABLE_LOCKING_STYLE && (OS_VXWORKS || defined(__APPLE__))
  30454. UNIXVFS("unix", autolockIoFinder ),
  30455. #else
  30456. UNIXVFS("unix", posixIoFinder ),
  30457. #endif
  30458. UNIXVFS("unix-none", nolockIoFinder ),
  30459. UNIXVFS("unix-dotfile", dotlockIoFinder ),
  30460. UNIXVFS("unix-excl", posixIoFinder ),
  30461. #if OS_VXWORKS
  30462. UNIXVFS("unix-namedsem", semIoFinder ),
  30463. #endif
  30464. #if SQLITE_ENABLE_LOCKING_STYLE
  30465. UNIXVFS("unix-posix", posixIoFinder ),
  30466. #if !OS_VXWORKS
  30467. UNIXVFS("unix-flock", flockIoFinder ),
  30468. #endif
  30469. #endif
  30470. #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
  30471. UNIXVFS("unix-afp", afpIoFinder ),
  30472. UNIXVFS("unix-nfs", nfsIoFinder ),
  30473. UNIXVFS("unix-proxy", proxyIoFinder ),
  30474. #endif
  30475. };
  30476. unsigned int i; /* Loop counter */
  30477. /* Double-check that the aSyscall[] array has been constructed
  30478. ** correctly. See ticket [bb3a86e890c8e96ab] */
  30479. assert( ArraySize(aSyscall)==25 );
  30480. /* Register all VFSes defined in the aVfs[] array */
  30481. for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
  30482. sqlite3_vfs_register(&aVfs[i], i==0);
  30483. }
  30484. return SQLITE_OK;
  30485. }
  30486. /*
  30487. ** Shutdown the operating system interface.
  30488. **
  30489. ** Some operating systems might need to do some cleanup in this routine,
  30490. ** to release dynamically allocated objects. But not on unix.
  30491. ** This routine is a no-op for unix.
  30492. */
  30493. SQLITE_API int sqlite3_os_end(void){
  30494. return SQLITE_OK;
  30495. }
  30496. #endif /* SQLITE_OS_UNIX */
  30497. /************** End of os_unix.c *********************************************/
  30498. /************** Begin file os_win.c ******************************************/
  30499. /*
  30500. ** 2004 May 22
  30501. **
  30502. ** The author disclaims copyright to this source code. In place of
  30503. ** a legal notice, here is a blessing:
  30504. **
  30505. ** May you do good and not evil.
  30506. ** May you find forgiveness for yourself and forgive others.
  30507. ** May you share freely, never taking more than you give.
  30508. **
  30509. ******************************************************************************
  30510. **
  30511. ** This file contains code that is specific to Windows.
  30512. */
  30513. #if SQLITE_OS_WIN /* This file is used for Windows only */
  30514. /*
  30515. ** Include code that is common to all os_*.c files
  30516. */
  30517. /************** Include os_common.h in the middle of os_win.c ****************/
  30518. /************** Begin file os_common.h ***************************************/
  30519. /*
  30520. ** 2004 May 22
  30521. **
  30522. ** The author disclaims copyright to this source code. In place of
  30523. ** a legal notice, here is a blessing:
  30524. **
  30525. ** May you do good and not evil.
  30526. ** May you find forgiveness for yourself and forgive others.
  30527. ** May you share freely, never taking more than you give.
  30528. **
  30529. ******************************************************************************
  30530. **
  30531. ** This file contains macros and a little bit of code that is common to
  30532. ** all of the platform-specific files (os_*.c) and is #included into those
  30533. ** files.
  30534. **
  30535. ** This file should be #included by the os_*.c files only. It is not a
  30536. ** general purpose header file.
  30537. */
  30538. #ifndef _OS_COMMON_H_
  30539. #define _OS_COMMON_H_
  30540. /*
  30541. ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
  30542. ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
  30543. ** switch. The following code should catch this problem at compile-time.
  30544. */
  30545. #ifdef MEMORY_DEBUG
  30546. # error "The MEMORY_DEBUG macro is obsolete. Use SQLITE_DEBUG instead."
  30547. #endif
  30548. #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
  30549. # ifndef SQLITE_DEBUG_OS_TRACE
  30550. # define SQLITE_DEBUG_OS_TRACE 0
  30551. # endif
  30552. int sqlite3OSTrace = SQLITE_DEBUG_OS_TRACE;
  30553. # define OSTRACE(X) if( sqlite3OSTrace ) sqlite3DebugPrintf X
  30554. #else
  30555. # define OSTRACE(X)
  30556. #endif
  30557. /*
  30558. ** Macros for performance tracing. Normally turned off. Only works
  30559. ** on i486 hardware.
  30560. */
  30561. #ifdef SQLITE_PERFORMANCE_TRACE
  30562. /*
  30563. ** hwtime.h contains inline assembler code for implementing
  30564. ** high-performance timing routines.
  30565. */
  30566. /************** Include hwtime.h in the middle of os_common.h ****************/
  30567. /************** Begin file hwtime.h ******************************************/
  30568. /*
  30569. ** 2008 May 27
  30570. **
  30571. ** The author disclaims copyright to this source code. In place of
  30572. ** a legal notice, here is a blessing:
  30573. **
  30574. ** May you do good and not evil.
  30575. ** May you find forgiveness for yourself and forgive others.
  30576. ** May you share freely, never taking more than you give.
  30577. **
  30578. ******************************************************************************
  30579. **
  30580. ** This file contains inline asm code for retrieving "high-performance"
  30581. ** counters for x86 class CPUs.
  30582. */
  30583. #ifndef _HWTIME_H_
  30584. #define _HWTIME_H_
  30585. /*
  30586. ** The following routine only works on pentium-class (or newer) processors.
  30587. ** It uses the RDTSC opcode to read the cycle count value out of the
  30588. ** processor and returns that value. This can be used for high-res
  30589. ** profiling.
  30590. */
  30591. #if (defined(__GNUC__) || defined(_MSC_VER)) && \
  30592. (defined(i386) || defined(__i386__) || defined(_M_IX86))
  30593. #if defined(__GNUC__)
  30594. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  30595. unsigned int lo, hi;
  30596. __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
  30597. return (sqlite_uint64)hi << 32 | lo;
  30598. }
  30599. #elif defined(_MSC_VER)
  30600. __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
  30601. __asm {
  30602. rdtsc
  30603. ret ; return value at EDX:EAX
  30604. }
  30605. }
  30606. #endif
  30607. #elif (defined(__GNUC__) && defined(__x86_64__))
  30608. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  30609. unsigned long val;
  30610. __asm__ __volatile__ ("rdtsc" : "=A" (val));
  30611. return val;
  30612. }
  30613. #elif (defined(__GNUC__) && defined(__ppc__))
  30614. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  30615. unsigned long long retval;
  30616. unsigned long junk;
  30617. __asm__ __volatile__ ("\n\
  30618. 1: mftbu %1\n\
  30619. mftb %L0\n\
  30620. mftbu %0\n\
  30621. cmpw %0,%1\n\
  30622. bne 1b"
  30623. : "=r" (retval), "=r" (junk));
  30624. return retval;
  30625. }
  30626. #else
  30627. #error Need implementation of sqlite3Hwtime() for your platform.
  30628. /*
  30629. ** To compile without implementing sqlite3Hwtime() for your platform,
  30630. ** you can remove the above #error and use the following
  30631. ** stub function. You will lose timing support for many
  30632. ** of the debugging and testing utilities, but it should at
  30633. ** least compile and run.
  30634. */
  30635. SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
  30636. #endif
  30637. #endif /* !defined(_HWTIME_H_) */
  30638. /************** End of hwtime.h **********************************************/
  30639. /************** Continuing where we left off in os_common.h ******************/
  30640. static sqlite_uint64 g_start;
  30641. static sqlite_uint64 g_elapsed;
  30642. #define TIMER_START g_start=sqlite3Hwtime()
  30643. #define TIMER_END g_elapsed=sqlite3Hwtime()-g_start
  30644. #define TIMER_ELAPSED g_elapsed
  30645. #else
  30646. #define TIMER_START
  30647. #define TIMER_END
  30648. #define TIMER_ELAPSED ((sqlite_uint64)0)
  30649. #endif
  30650. /*
  30651. ** If we compile with the SQLITE_TEST macro set, then the following block
  30652. ** of code will give us the ability to simulate a disk I/O error. This
  30653. ** is used for testing the I/O recovery logic.
  30654. */
  30655. #ifdef SQLITE_TEST
  30656. SQLITE_API int sqlite3_io_error_hit = 0; /* Total number of I/O Errors */
  30657. SQLITE_API int sqlite3_io_error_hardhit = 0; /* Number of non-benign errors */
  30658. SQLITE_API int sqlite3_io_error_pending = 0; /* Count down to first I/O error */
  30659. SQLITE_API int sqlite3_io_error_persist = 0; /* True if I/O errors persist */
  30660. SQLITE_API int sqlite3_io_error_benign = 0; /* True if errors are benign */
  30661. SQLITE_API int sqlite3_diskfull_pending = 0;
  30662. SQLITE_API int sqlite3_diskfull = 0;
  30663. #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
  30664. #define SimulateIOError(CODE) \
  30665. if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
  30666. || sqlite3_io_error_pending-- == 1 ) \
  30667. { local_ioerr(); CODE; }
  30668. static void local_ioerr(){
  30669. IOTRACE(("IOERR\n"));
  30670. sqlite3_io_error_hit++;
  30671. if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
  30672. }
  30673. #define SimulateDiskfullError(CODE) \
  30674. if( sqlite3_diskfull_pending ){ \
  30675. if( sqlite3_diskfull_pending == 1 ){ \
  30676. local_ioerr(); \
  30677. sqlite3_diskfull = 1; \
  30678. sqlite3_io_error_hit = 1; \
  30679. CODE; \
  30680. }else{ \
  30681. sqlite3_diskfull_pending--; \
  30682. } \
  30683. }
  30684. #else
  30685. #define SimulateIOErrorBenign(X)
  30686. #define SimulateIOError(A)
  30687. #define SimulateDiskfullError(A)
  30688. #endif
  30689. /*
  30690. ** When testing, keep a count of the number of open files.
  30691. */
  30692. #ifdef SQLITE_TEST
  30693. SQLITE_API int sqlite3_open_file_count = 0;
  30694. #define OpenCounter(X) sqlite3_open_file_count+=(X)
  30695. #else
  30696. #define OpenCounter(X)
  30697. #endif
  30698. #endif /* !defined(_OS_COMMON_H_) */
  30699. /************** End of os_common.h *******************************************/
  30700. /************** Continuing where we left off in os_win.c *********************/
  30701. /*
  30702. ** Include the header file for the Windows VFS.
  30703. */
  30704. /*
  30705. ** Compiling and using WAL mode requires several APIs that are only
  30706. ** available in Windows platforms based on the NT kernel.
  30707. */
  30708. #if !SQLITE_OS_WINNT && !defined(SQLITE_OMIT_WAL)
  30709. # error "WAL mode requires support from the Windows NT kernel, compile\
  30710. with SQLITE_OMIT_WAL."
  30711. #endif
  30712. /*
  30713. ** Are most of the Win32 ANSI APIs available (i.e. with certain exceptions
  30714. ** based on the sub-platform)?
  30715. */
  30716. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && !defined(SQLITE_WIN32_NO_ANSI)
  30717. # define SQLITE_WIN32_HAS_ANSI
  30718. #endif
  30719. /*
  30720. ** Are most of the Win32 Unicode APIs available (i.e. with certain exceptions
  30721. ** based on the sub-platform)?
  30722. */
  30723. #if (SQLITE_OS_WINCE || SQLITE_OS_WINNT || SQLITE_OS_WINRT) && \
  30724. !defined(SQLITE_WIN32_NO_WIDE)
  30725. # define SQLITE_WIN32_HAS_WIDE
  30726. #endif
  30727. /*
  30728. ** Make sure at least one set of Win32 APIs is available.
  30729. */
  30730. #if !defined(SQLITE_WIN32_HAS_ANSI) && !defined(SQLITE_WIN32_HAS_WIDE)
  30731. # error "At least one of SQLITE_WIN32_HAS_ANSI and SQLITE_WIN32_HAS_WIDE\
  30732. must be defined."
  30733. #endif
  30734. /*
  30735. ** Define the required Windows SDK version constants if they are not
  30736. ** already available.
  30737. */
  30738. #ifndef NTDDI_WIN8
  30739. # define NTDDI_WIN8 0x06020000
  30740. #endif
  30741. #ifndef NTDDI_WINBLUE
  30742. # define NTDDI_WINBLUE 0x06030000
  30743. #endif
  30744. /*
  30745. ** Check to see if the GetVersionEx[AW] functions are deprecated on the
  30746. ** target system. GetVersionEx was first deprecated in Win8.1.
  30747. */
  30748. #ifndef SQLITE_WIN32_GETVERSIONEX
  30749. # if defined(NTDDI_VERSION) && NTDDI_VERSION >= NTDDI_WINBLUE
  30750. # define SQLITE_WIN32_GETVERSIONEX 0 /* GetVersionEx() is deprecated */
  30751. # else
  30752. # define SQLITE_WIN32_GETVERSIONEX 1 /* GetVersionEx() is current */
  30753. # endif
  30754. #endif
  30755. /*
  30756. ** This constant should already be defined (in the "WinDef.h" SDK file).
  30757. */
  30758. #ifndef MAX_PATH
  30759. # define MAX_PATH (260)
  30760. #endif
  30761. /*
  30762. ** Maximum pathname length (in chars) for Win32. This should normally be
  30763. ** MAX_PATH.
  30764. */
  30765. #ifndef SQLITE_WIN32_MAX_PATH_CHARS
  30766. # define SQLITE_WIN32_MAX_PATH_CHARS (MAX_PATH)
  30767. #endif
  30768. /*
  30769. ** This constant should already be defined (in the "WinNT.h" SDK file).
  30770. */
  30771. #ifndef UNICODE_STRING_MAX_CHARS
  30772. # define UNICODE_STRING_MAX_CHARS (32767)
  30773. #endif
  30774. /*
  30775. ** Maximum pathname length (in chars) for WinNT. This should normally be
  30776. ** UNICODE_STRING_MAX_CHARS.
  30777. */
  30778. #ifndef SQLITE_WINNT_MAX_PATH_CHARS
  30779. # define SQLITE_WINNT_MAX_PATH_CHARS (UNICODE_STRING_MAX_CHARS)
  30780. #endif
  30781. /*
  30782. ** Maximum pathname length (in bytes) for Win32. The MAX_PATH macro is in
  30783. ** characters, so we allocate 4 bytes per character assuming worst-case of
  30784. ** 4-bytes-per-character for UTF8.
  30785. */
  30786. #ifndef SQLITE_WIN32_MAX_PATH_BYTES
  30787. # define SQLITE_WIN32_MAX_PATH_BYTES (SQLITE_WIN32_MAX_PATH_CHARS*4)
  30788. #endif
  30789. /*
  30790. ** Maximum pathname length (in bytes) for WinNT. This should normally be
  30791. ** UNICODE_STRING_MAX_CHARS * sizeof(WCHAR).
  30792. */
  30793. #ifndef SQLITE_WINNT_MAX_PATH_BYTES
  30794. # define SQLITE_WINNT_MAX_PATH_BYTES \
  30795. (sizeof(WCHAR) * SQLITE_WINNT_MAX_PATH_CHARS)
  30796. #endif
  30797. /*
  30798. ** Maximum error message length (in chars) for WinRT.
  30799. */
  30800. #ifndef SQLITE_WIN32_MAX_ERRMSG_CHARS
  30801. # define SQLITE_WIN32_MAX_ERRMSG_CHARS (1024)
  30802. #endif
  30803. /*
  30804. ** Returns non-zero if the character should be treated as a directory
  30805. ** separator.
  30806. */
  30807. #ifndef winIsDirSep
  30808. # define winIsDirSep(a) (((a) == '/') || ((a) == '\\'))
  30809. #endif
  30810. /*
  30811. ** This macro is used when a local variable is set to a value that is
  30812. ** [sometimes] not used by the code (e.g. via conditional compilation).
  30813. */
  30814. #ifndef UNUSED_VARIABLE_VALUE
  30815. # define UNUSED_VARIABLE_VALUE(x) (void)(x)
  30816. #endif
  30817. /*
  30818. ** Returns the character that should be used as the directory separator.
  30819. */
  30820. #ifndef winGetDirSep
  30821. # define winGetDirSep() '\\'
  30822. #endif
  30823. /*
  30824. ** Do we need to manually define the Win32 file mapping APIs for use with WAL
  30825. ** mode (e.g. these APIs are available in the Windows CE SDK; however, they
  30826. ** are not present in the header file)?
  30827. */
  30828. #if SQLITE_WIN32_FILEMAPPING_API && !defined(SQLITE_OMIT_WAL)
  30829. /*
  30830. ** Two of the file mapping APIs are different under WinRT. Figure out which
  30831. ** set we need.
  30832. */
  30833. #if SQLITE_OS_WINRT
  30834. WINBASEAPI HANDLE WINAPI CreateFileMappingFromApp(HANDLE, \
  30835. LPSECURITY_ATTRIBUTES, ULONG, ULONG64, LPCWSTR);
  30836. WINBASEAPI LPVOID WINAPI MapViewOfFileFromApp(HANDLE, ULONG, ULONG64, SIZE_T);
  30837. #else
  30838. #if defined(SQLITE_WIN32_HAS_ANSI)
  30839. WINBASEAPI HANDLE WINAPI CreateFileMappingA(HANDLE, LPSECURITY_ATTRIBUTES, \
  30840. DWORD, DWORD, DWORD, LPCSTR);
  30841. #endif /* defined(SQLITE_WIN32_HAS_ANSI) */
  30842. #if defined(SQLITE_WIN32_HAS_WIDE)
  30843. WINBASEAPI HANDLE WINAPI CreateFileMappingW(HANDLE, LPSECURITY_ATTRIBUTES, \
  30844. DWORD, DWORD, DWORD, LPCWSTR);
  30845. #endif /* defined(SQLITE_WIN32_HAS_WIDE) */
  30846. WINBASEAPI LPVOID WINAPI MapViewOfFile(HANDLE, DWORD, DWORD, DWORD, SIZE_T);
  30847. #endif /* SQLITE_OS_WINRT */
  30848. /*
  30849. ** This file mapping API is common to both Win32 and WinRT.
  30850. */
  30851. WINBASEAPI BOOL WINAPI UnmapViewOfFile(LPCVOID);
  30852. #endif /* SQLITE_WIN32_FILEMAPPING_API && !defined(SQLITE_OMIT_WAL) */
  30853. /*
  30854. ** Some Microsoft compilers lack this definition.
  30855. */
  30856. #ifndef INVALID_FILE_ATTRIBUTES
  30857. # define INVALID_FILE_ATTRIBUTES ((DWORD)-1)
  30858. #endif
  30859. #ifndef FILE_FLAG_MASK
  30860. # define FILE_FLAG_MASK (0xFF3C0000)
  30861. #endif
  30862. #ifndef FILE_ATTRIBUTE_MASK
  30863. # define FILE_ATTRIBUTE_MASK (0x0003FFF7)
  30864. #endif
  30865. #ifndef SQLITE_OMIT_WAL
  30866. /* Forward references to structures used for WAL */
  30867. typedef struct winShm winShm; /* A connection to shared-memory */
  30868. typedef struct winShmNode winShmNode; /* A region of shared-memory */
  30869. #endif
  30870. /*
  30871. ** WinCE lacks native support for file locking so we have to fake it
  30872. ** with some code of our own.
  30873. */
  30874. #if SQLITE_OS_WINCE
  30875. typedef struct winceLock {
  30876. int nReaders; /* Number of reader locks obtained */
  30877. BOOL bPending; /* Indicates a pending lock has been obtained */
  30878. BOOL bReserved; /* Indicates a reserved lock has been obtained */
  30879. BOOL bExclusive; /* Indicates an exclusive lock has been obtained */
  30880. } winceLock;
  30881. #endif
  30882. /*
  30883. ** The winFile structure is a subclass of sqlite3_file* specific to the win32
  30884. ** portability layer.
  30885. */
  30886. typedef struct winFile winFile;
  30887. struct winFile {
  30888. const sqlite3_io_methods *pMethod; /*** Must be first ***/
  30889. sqlite3_vfs *pVfs; /* The VFS used to open this file */
  30890. HANDLE h; /* Handle for accessing the file */
  30891. u8 locktype; /* Type of lock currently held on this file */
  30892. short sharedLockByte; /* Randomly chosen byte used as a shared lock */
  30893. u8 ctrlFlags; /* Flags. See WINFILE_* below */
  30894. DWORD lastErrno; /* The Windows errno from the last I/O error */
  30895. #ifndef SQLITE_OMIT_WAL
  30896. winShm *pShm; /* Instance of shared memory on this file */
  30897. #endif
  30898. const char *zPath; /* Full pathname of this file */
  30899. int szChunk; /* Chunk size configured by FCNTL_CHUNK_SIZE */
  30900. #if SQLITE_OS_WINCE
  30901. LPWSTR zDeleteOnClose; /* Name of file to delete when closing */
  30902. HANDLE hMutex; /* Mutex used to control access to shared lock */
  30903. HANDLE hShared; /* Shared memory segment used for locking */
  30904. winceLock local; /* Locks obtained by this instance of winFile */
  30905. winceLock *shared; /* Global shared lock memory for the file */
  30906. #endif
  30907. #if SQLITE_MAX_MMAP_SIZE>0
  30908. int nFetchOut; /* Number of outstanding xFetch references */
  30909. HANDLE hMap; /* Handle for accessing memory mapping */
  30910. void *pMapRegion; /* Area memory mapped */
  30911. sqlite3_int64 mmapSize; /* Usable size of mapped region */
  30912. sqlite3_int64 mmapSizeActual; /* Actual size of mapped region */
  30913. sqlite3_int64 mmapSizeMax; /* Configured FCNTL_MMAP_SIZE value */
  30914. #endif
  30915. };
  30916. /*
  30917. ** Allowed values for winFile.ctrlFlags
  30918. */
  30919. #define WINFILE_RDONLY 0x02 /* Connection is read only */
  30920. #define WINFILE_PERSIST_WAL 0x04 /* Persistent WAL mode */
  30921. #define WINFILE_PSOW 0x10 /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
  30922. /*
  30923. * The size of the buffer used by sqlite3_win32_write_debug().
  30924. */
  30925. #ifndef SQLITE_WIN32_DBG_BUF_SIZE
  30926. # define SQLITE_WIN32_DBG_BUF_SIZE ((int)(4096-sizeof(DWORD)))
  30927. #endif
  30928. /*
  30929. * The value used with sqlite3_win32_set_directory() to specify that
  30930. * the data directory should be changed.
  30931. */
  30932. #ifndef SQLITE_WIN32_DATA_DIRECTORY_TYPE
  30933. # define SQLITE_WIN32_DATA_DIRECTORY_TYPE (1)
  30934. #endif
  30935. /*
  30936. * The value used with sqlite3_win32_set_directory() to specify that
  30937. * the temporary directory should be changed.
  30938. */
  30939. #ifndef SQLITE_WIN32_TEMP_DIRECTORY_TYPE
  30940. # define SQLITE_WIN32_TEMP_DIRECTORY_TYPE (2)
  30941. #endif
  30942. /*
  30943. * If compiled with SQLITE_WIN32_MALLOC on Windows, we will use the
  30944. * various Win32 API heap functions instead of our own.
  30945. */
  30946. #ifdef SQLITE_WIN32_MALLOC
  30947. /*
  30948. * If this is non-zero, an isolated heap will be created by the native Win32
  30949. * allocator subsystem; otherwise, the default process heap will be used. This
  30950. * setting has no effect when compiling for WinRT. By default, this is enabled
  30951. * and an isolated heap will be created to store all allocated data.
  30952. *
  30953. ******************************************************************************
  30954. * WARNING: It is important to note that when this setting is non-zero and the
  30955. * winMemShutdown function is called (e.g. by the sqlite3_shutdown
  30956. * function), all data that was allocated using the isolated heap will
  30957. * be freed immediately and any attempt to access any of that freed
  30958. * data will almost certainly result in an immediate access violation.
  30959. ******************************************************************************
  30960. */
  30961. #ifndef SQLITE_WIN32_HEAP_CREATE
  30962. # define SQLITE_WIN32_HEAP_CREATE (TRUE)
  30963. #endif
  30964. /*
  30965. * The initial size of the Win32-specific heap. This value may be zero.
  30966. */
  30967. #ifndef SQLITE_WIN32_HEAP_INIT_SIZE
  30968. # define SQLITE_WIN32_HEAP_INIT_SIZE ((SQLITE_DEFAULT_CACHE_SIZE) * \
  30969. (SQLITE_DEFAULT_PAGE_SIZE) + 4194304)
  30970. #endif
  30971. /*
  30972. * The maximum size of the Win32-specific heap. This value may be zero.
  30973. */
  30974. #ifndef SQLITE_WIN32_HEAP_MAX_SIZE
  30975. # define SQLITE_WIN32_HEAP_MAX_SIZE (0)
  30976. #endif
  30977. /*
  30978. * The extra flags to use in calls to the Win32 heap APIs. This value may be
  30979. * zero for the default behavior.
  30980. */
  30981. #ifndef SQLITE_WIN32_HEAP_FLAGS
  30982. # define SQLITE_WIN32_HEAP_FLAGS (0)
  30983. #endif
  30984. /*
  30985. ** The winMemData structure stores information required by the Win32-specific
  30986. ** sqlite3_mem_methods implementation.
  30987. */
  30988. typedef struct winMemData winMemData;
  30989. struct winMemData {
  30990. #ifndef NDEBUG
  30991. u32 magic1; /* Magic number to detect structure corruption. */
  30992. #endif
  30993. HANDLE hHeap; /* The handle to our heap. */
  30994. BOOL bOwned; /* Do we own the heap (i.e. destroy it on shutdown)? */
  30995. #ifndef NDEBUG
  30996. u32 magic2; /* Magic number to detect structure corruption. */
  30997. #endif
  30998. };
  30999. #ifndef NDEBUG
  31000. #define WINMEM_MAGIC1 0x42b2830b
  31001. #define WINMEM_MAGIC2 0xbd4d7cf4
  31002. #endif
  31003. static struct winMemData win_mem_data = {
  31004. #ifndef NDEBUG
  31005. WINMEM_MAGIC1,
  31006. #endif
  31007. NULL, FALSE
  31008. #ifndef NDEBUG
  31009. ,WINMEM_MAGIC2
  31010. #endif
  31011. };
  31012. #ifndef NDEBUG
  31013. #define winMemAssertMagic1() assert( win_mem_data.magic1==WINMEM_MAGIC1 )
  31014. #define winMemAssertMagic2() assert( win_mem_data.magic2==WINMEM_MAGIC2 )
  31015. #define winMemAssertMagic() winMemAssertMagic1(); winMemAssertMagic2();
  31016. #else
  31017. #define winMemAssertMagic()
  31018. #endif
  31019. #define winMemGetDataPtr() &win_mem_data
  31020. #define winMemGetHeap() win_mem_data.hHeap
  31021. #define winMemGetOwned() win_mem_data.bOwned
  31022. static void *winMemMalloc(int nBytes);
  31023. static void winMemFree(void *pPrior);
  31024. static void *winMemRealloc(void *pPrior, int nBytes);
  31025. static int winMemSize(void *p);
  31026. static int winMemRoundup(int n);
  31027. static int winMemInit(void *pAppData);
  31028. static void winMemShutdown(void *pAppData);
  31029. SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetWin32(void);
  31030. #endif /* SQLITE_WIN32_MALLOC */
  31031. /*
  31032. ** The following variable is (normally) set once and never changes
  31033. ** thereafter. It records whether the operating system is Win9x
  31034. ** or WinNT.
  31035. **
  31036. ** 0: Operating system unknown.
  31037. ** 1: Operating system is Win9x.
  31038. ** 2: Operating system is WinNT.
  31039. **
  31040. ** In order to facilitate testing on a WinNT system, the test fixture
  31041. ** can manually set this value to 1 to emulate Win98 behavior.
  31042. */
  31043. #ifdef SQLITE_TEST
  31044. SQLITE_API LONG SQLITE_WIN32_VOLATILE sqlite3_os_type = 0;
  31045. #else
  31046. static LONG SQLITE_WIN32_VOLATILE sqlite3_os_type = 0;
  31047. #endif
  31048. #ifndef SYSCALL
  31049. # define SYSCALL sqlite3_syscall_ptr
  31050. #endif
  31051. /*
  31052. ** This function is not available on Windows CE or WinRT.
  31053. */
  31054. #if SQLITE_OS_WINCE || SQLITE_OS_WINRT
  31055. # define osAreFileApisANSI() 1
  31056. #endif
  31057. /*
  31058. ** Many system calls are accessed through pointer-to-functions so that
  31059. ** they may be overridden at runtime to facilitate fault injection during
  31060. ** testing and sandboxing. The following array holds the names and pointers
  31061. ** to all overrideable system calls.
  31062. */
  31063. static struct win_syscall {
  31064. const char *zName; /* Name of the system call */
  31065. sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
  31066. sqlite3_syscall_ptr pDefault; /* Default value */
  31067. } aSyscall[] = {
  31068. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
  31069. { "AreFileApisANSI", (SYSCALL)AreFileApisANSI, 0 },
  31070. #else
  31071. { "AreFileApisANSI", (SYSCALL)0, 0 },
  31072. #endif
  31073. #ifndef osAreFileApisANSI
  31074. #define osAreFileApisANSI ((BOOL(WINAPI*)(VOID))aSyscall[0].pCurrent)
  31075. #endif
  31076. #if SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE)
  31077. { "CharLowerW", (SYSCALL)CharLowerW, 0 },
  31078. #else
  31079. { "CharLowerW", (SYSCALL)0, 0 },
  31080. #endif
  31081. #define osCharLowerW ((LPWSTR(WINAPI*)(LPWSTR))aSyscall[1].pCurrent)
  31082. #if SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE)
  31083. { "CharUpperW", (SYSCALL)CharUpperW, 0 },
  31084. #else
  31085. { "CharUpperW", (SYSCALL)0, 0 },
  31086. #endif
  31087. #define osCharUpperW ((LPWSTR(WINAPI*)(LPWSTR))aSyscall[2].pCurrent)
  31088. { "CloseHandle", (SYSCALL)CloseHandle, 0 },
  31089. #define osCloseHandle ((BOOL(WINAPI*)(HANDLE))aSyscall[3].pCurrent)
  31090. #if defined(SQLITE_WIN32_HAS_ANSI)
  31091. { "CreateFileA", (SYSCALL)CreateFileA, 0 },
  31092. #else
  31093. { "CreateFileA", (SYSCALL)0, 0 },
  31094. #endif
  31095. #define osCreateFileA ((HANDLE(WINAPI*)(LPCSTR,DWORD,DWORD, \
  31096. LPSECURITY_ATTRIBUTES,DWORD,DWORD,HANDLE))aSyscall[4].pCurrent)
  31097. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
  31098. { "CreateFileW", (SYSCALL)CreateFileW, 0 },
  31099. #else
  31100. { "CreateFileW", (SYSCALL)0, 0 },
  31101. #endif
  31102. #define osCreateFileW ((HANDLE(WINAPI*)(LPCWSTR,DWORD,DWORD, \
  31103. LPSECURITY_ATTRIBUTES,DWORD,DWORD,HANDLE))aSyscall[5].pCurrent)
  31104. #if (!SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_ANSI) && \
  31105. !defined(SQLITE_OMIT_WAL))
  31106. { "CreateFileMappingA", (SYSCALL)CreateFileMappingA, 0 },
  31107. #else
  31108. { "CreateFileMappingA", (SYSCALL)0, 0 },
  31109. #endif
  31110. #define osCreateFileMappingA ((HANDLE(WINAPI*)(HANDLE,LPSECURITY_ATTRIBUTES, \
  31111. DWORD,DWORD,DWORD,LPCSTR))aSyscall[6].pCurrent)
  31112. #if SQLITE_OS_WINCE || (!SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
  31113. !defined(SQLITE_OMIT_WAL))
  31114. { "CreateFileMappingW", (SYSCALL)CreateFileMappingW, 0 },
  31115. #else
  31116. { "CreateFileMappingW", (SYSCALL)0, 0 },
  31117. #endif
  31118. #define osCreateFileMappingW ((HANDLE(WINAPI*)(HANDLE,LPSECURITY_ATTRIBUTES, \
  31119. DWORD,DWORD,DWORD,LPCWSTR))aSyscall[7].pCurrent)
  31120. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
  31121. { "CreateMutexW", (SYSCALL)CreateMutexW, 0 },
  31122. #else
  31123. { "CreateMutexW", (SYSCALL)0, 0 },
  31124. #endif
  31125. #define osCreateMutexW ((HANDLE(WINAPI*)(LPSECURITY_ATTRIBUTES,BOOL, \
  31126. LPCWSTR))aSyscall[8].pCurrent)
  31127. #if defined(SQLITE_WIN32_HAS_ANSI)
  31128. { "DeleteFileA", (SYSCALL)DeleteFileA, 0 },
  31129. #else
  31130. { "DeleteFileA", (SYSCALL)0, 0 },
  31131. #endif
  31132. #define osDeleteFileA ((BOOL(WINAPI*)(LPCSTR))aSyscall[9].pCurrent)
  31133. #if defined(SQLITE_WIN32_HAS_WIDE)
  31134. { "DeleteFileW", (SYSCALL)DeleteFileW, 0 },
  31135. #else
  31136. { "DeleteFileW", (SYSCALL)0, 0 },
  31137. #endif
  31138. #define osDeleteFileW ((BOOL(WINAPI*)(LPCWSTR))aSyscall[10].pCurrent)
  31139. #if SQLITE_OS_WINCE
  31140. { "FileTimeToLocalFileTime", (SYSCALL)FileTimeToLocalFileTime, 0 },
  31141. #else
  31142. { "FileTimeToLocalFileTime", (SYSCALL)0, 0 },
  31143. #endif
  31144. #define osFileTimeToLocalFileTime ((BOOL(WINAPI*)(CONST FILETIME*, \
  31145. LPFILETIME))aSyscall[11].pCurrent)
  31146. #if SQLITE_OS_WINCE
  31147. { "FileTimeToSystemTime", (SYSCALL)FileTimeToSystemTime, 0 },
  31148. #else
  31149. { "FileTimeToSystemTime", (SYSCALL)0, 0 },
  31150. #endif
  31151. #define osFileTimeToSystemTime ((BOOL(WINAPI*)(CONST FILETIME*, \
  31152. LPSYSTEMTIME))aSyscall[12].pCurrent)
  31153. { "FlushFileBuffers", (SYSCALL)FlushFileBuffers, 0 },
  31154. #define osFlushFileBuffers ((BOOL(WINAPI*)(HANDLE))aSyscall[13].pCurrent)
  31155. #if defined(SQLITE_WIN32_HAS_ANSI)
  31156. { "FormatMessageA", (SYSCALL)FormatMessageA, 0 },
  31157. #else
  31158. { "FormatMessageA", (SYSCALL)0, 0 },
  31159. #endif
  31160. #define osFormatMessageA ((DWORD(WINAPI*)(DWORD,LPCVOID,DWORD,DWORD,LPSTR, \
  31161. DWORD,va_list*))aSyscall[14].pCurrent)
  31162. #if defined(SQLITE_WIN32_HAS_WIDE)
  31163. { "FormatMessageW", (SYSCALL)FormatMessageW, 0 },
  31164. #else
  31165. { "FormatMessageW", (SYSCALL)0, 0 },
  31166. #endif
  31167. #define osFormatMessageW ((DWORD(WINAPI*)(DWORD,LPCVOID,DWORD,DWORD,LPWSTR, \
  31168. DWORD,va_list*))aSyscall[15].pCurrent)
  31169. #if !defined(SQLITE_OMIT_LOAD_EXTENSION)
  31170. { "FreeLibrary", (SYSCALL)FreeLibrary, 0 },
  31171. #else
  31172. { "FreeLibrary", (SYSCALL)0, 0 },
  31173. #endif
  31174. #define osFreeLibrary ((BOOL(WINAPI*)(HMODULE))aSyscall[16].pCurrent)
  31175. { "GetCurrentProcessId", (SYSCALL)GetCurrentProcessId, 0 },
  31176. #define osGetCurrentProcessId ((DWORD(WINAPI*)(VOID))aSyscall[17].pCurrent)
  31177. #if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_ANSI)
  31178. { "GetDiskFreeSpaceA", (SYSCALL)GetDiskFreeSpaceA, 0 },
  31179. #else
  31180. { "GetDiskFreeSpaceA", (SYSCALL)0, 0 },
  31181. #endif
  31182. #define osGetDiskFreeSpaceA ((BOOL(WINAPI*)(LPCSTR,LPDWORD,LPDWORD,LPDWORD, \
  31183. LPDWORD))aSyscall[18].pCurrent)
  31184. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
  31185. { "GetDiskFreeSpaceW", (SYSCALL)GetDiskFreeSpaceW, 0 },
  31186. #else
  31187. { "GetDiskFreeSpaceW", (SYSCALL)0, 0 },
  31188. #endif
  31189. #define osGetDiskFreeSpaceW ((BOOL(WINAPI*)(LPCWSTR,LPDWORD,LPDWORD,LPDWORD, \
  31190. LPDWORD))aSyscall[19].pCurrent)
  31191. #if defined(SQLITE_WIN32_HAS_ANSI)
  31192. { "GetFileAttributesA", (SYSCALL)GetFileAttributesA, 0 },
  31193. #else
  31194. { "GetFileAttributesA", (SYSCALL)0, 0 },
  31195. #endif
  31196. #define osGetFileAttributesA ((DWORD(WINAPI*)(LPCSTR))aSyscall[20].pCurrent)
  31197. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
  31198. { "GetFileAttributesW", (SYSCALL)GetFileAttributesW, 0 },
  31199. #else
  31200. { "GetFileAttributesW", (SYSCALL)0, 0 },
  31201. #endif
  31202. #define osGetFileAttributesW ((DWORD(WINAPI*)(LPCWSTR))aSyscall[21].pCurrent)
  31203. #if defined(SQLITE_WIN32_HAS_WIDE)
  31204. { "GetFileAttributesExW", (SYSCALL)GetFileAttributesExW, 0 },
  31205. #else
  31206. { "GetFileAttributesExW", (SYSCALL)0, 0 },
  31207. #endif
  31208. #define osGetFileAttributesExW ((BOOL(WINAPI*)(LPCWSTR,GET_FILEEX_INFO_LEVELS, \
  31209. LPVOID))aSyscall[22].pCurrent)
  31210. #if !SQLITE_OS_WINRT
  31211. { "GetFileSize", (SYSCALL)GetFileSize, 0 },
  31212. #else
  31213. { "GetFileSize", (SYSCALL)0, 0 },
  31214. #endif
  31215. #define osGetFileSize ((DWORD(WINAPI*)(HANDLE,LPDWORD))aSyscall[23].pCurrent)
  31216. #if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_ANSI)
  31217. { "GetFullPathNameA", (SYSCALL)GetFullPathNameA, 0 },
  31218. #else
  31219. { "GetFullPathNameA", (SYSCALL)0, 0 },
  31220. #endif
  31221. #define osGetFullPathNameA ((DWORD(WINAPI*)(LPCSTR,DWORD,LPSTR, \
  31222. LPSTR*))aSyscall[24].pCurrent)
  31223. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
  31224. { "GetFullPathNameW", (SYSCALL)GetFullPathNameW, 0 },
  31225. #else
  31226. { "GetFullPathNameW", (SYSCALL)0, 0 },
  31227. #endif
  31228. #define osGetFullPathNameW ((DWORD(WINAPI*)(LPCWSTR,DWORD,LPWSTR, \
  31229. LPWSTR*))aSyscall[25].pCurrent)
  31230. { "GetLastError", (SYSCALL)GetLastError, 0 },
  31231. #define osGetLastError ((DWORD(WINAPI*)(VOID))aSyscall[26].pCurrent)
  31232. #if !defined(SQLITE_OMIT_LOAD_EXTENSION)
  31233. #if SQLITE_OS_WINCE
  31234. /* The GetProcAddressA() routine is only available on Windows CE. */
  31235. { "GetProcAddressA", (SYSCALL)GetProcAddressA, 0 },
  31236. #else
  31237. /* All other Windows platforms expect GetProcAddress() to take
  31238. ** an ANSI string regardless of the _UNICODE setting */
  31239. { "GetProcAddressA", (SYSCALL)GetProcAddress, 0 },
  31240. #endif
  31241. #else
  31242. { "GetProcAddressA", (SYSCALL)0, 0 },
  31243. #endif
  31244. #define osGetProcAddressA ((FARPROC(WINAPI*)(HMODULE, \
  31245. LPCSTR))aSyscall[27].pCurrent)
  31246. #if !SQLITE_OS_WINRT
  31247. { "GetSystemInfo", (SYSCALL)GetSystemInfo, 0 },
  31248. #else
  31249. { "GetSystemInfo", (SYSCALL)0, 0 },
  31250. #endif
  31251. #define osGetSystemInfo ((VOID(WINAPI*)(LPSYSTEM_INFO))aSyscall[28].pCurrent)
  31252. { "GetSystemTime", (SYSCALL)GetSystemTime, 0 },
  31253. #define osGetSystemTime ((VOID(WINAPI*)(LPSYSTEMTIME))aSyscall[29].pCurrent)
  31254. #if !SQLITE_OS_WINCE
  31255. { "GetSystemTimeAsFileTime", (SYSCALL)GetSystemTimeAsFileTime, 0 },
  31256. #else
  31257. { "GetSystemTimeAsFileTime", (SYSCALL)0, 0 },
  31258. #endif
  31259. #define osGetSystemTimeAsFileTime ((VOID(WINAPI*)( \
  31260. LPFILETIME))aSyscall[30].pCurrent)
  31261. #if defined(SQLITE_WIN32_HAS_ANSI)
  31262. { "GetTempPathA", (SYSCALL)GetTempPathA, 0 },
  31263. #else
  31264. { "GetTempPathA", (SYSCALL)0, 0 },
  31265. #endif
  31266. #define osGetTempPathA ((DWORD(WINAPI*)(DWORD,LPSTR))aSyscall[31].pCurrent)
  31267. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
  31268. { "GetTempPathW", (SYSCALL)GetTempPathW, 0 },
  31269. #else
  31270. { "GetTempPathW", (SYSCALL)0, 0 },
  31271. #endif
  31272. #define osGetTempPathW ((DWORD(WINAPI*)(DWORD,LPWSTR))aSyscall[32].pCurrent)
  31273. #if !SQLITE_OS_WINRT
  31274. { "GetTickCount", (SYSCALL)GetTickCount, 0 },
  31275. #else
  31276. { "GetTickCount", (SYSCALL)0, 0 },
  31277. #endif
  31278. #define osGetTickCount ((DWORD(WINAPI*)(VOID))aSyscall[33].pCurrent)
  31279. #if defined(SQLITE_WIN32_HAS_ANSI) && defined(SQLITE_WIN32_GETVERSIONEX) && \
  31280. SQLITE_WIN32_GETVERSIONEX
  31281. { "GetVersionExA", (SYSCALL)GetVersionExA, 0 },
  31282. #else
  31283. { "GetVersionExA", (SYSCALL)0, 0 },
  31284. #endif
  31285. #define osGetVersionExA ((BOOL(WINAPI*)( \
  31286. LPOSVERSIONINFOA))aSyscall[34].pCurrent)
  31287. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
  31288. defined(SQLITE_WIN32_GETVERSIONEX) && SQLITE_WIN32_GETVERSIONEX
  31289. { "GetVersionExW", (SYSCALL)GetVersionExW, 0 },
  31290. #else
  31291. { "GetVersionExW", (SYSCALL)0, 0 },
  31292. #endif
  31293. #define osGetVersionExW ((BOOL(WINAPI*)( \
  31294. LPOSVERSIONINFOW))aSyscall[35].pCurrent)
  31295. { "HeapAlloc", (SYSCALL)HeapAlloc, 0 },
  31296. #define osHeapAlloc ((LPVOID(WINAPI*)(HANDLE,DWORD, \
  31297. SIZE_T))aSyscall[36].pCurrent)
  31298. #if !SQLITE_OS_WINRT
  31299. { "HeapCreate", (SYSCALL)HeapCreate, 0 },
  31300. #else
  31301. { "HeapCreate", (SYSCALL)0, 0 },
  31302. #endif
  31303. #define osHeapCreate ((HANDLE(WINAPI*)(DWORD,SIZE_T, \
  31304. SIZE_T))aSyscall[37].pCurrent)
  31305. #if !SQLITE_OS_WINRT
  31306. { "HeapDestroy", (SYSCALL)HeapDestroy, 0 },
  31307. #else
  31308. { "HeapDestroy", (SYSCALL)0, 0 },
  31309. #endif
  31310. #define osHeapDestroy ((BOOL(WINAPI*)(HANDLE))aSyscall[38].pCurrent)
  31311. { "HeapFree", (SYSCALL)HeapFree, 0 },
  31312. #define osHeapFree ((BOOL(WINAPI*)(HANDLE,DWORD,LPVOID))aSyscall[39].pCurrent)
  31313. { "HeapReAlloc", (SYSCALL)HeapReAlloc, 0 },
  31314. #define osHeapReAlloc ((LPVOID(WINAPI*)(HANDLE,DWORD,LPVOID, \
  31315. SIZE_T))aSyscall[40].pCurrent)
  31316. { "HeapSize", (SYSCALL)HeapSize, 0 },
  31317. #define osHeapSize ((SIZE_T(WINAPI*)(HANDLE,DWORD, \
  31318. LPCVOID))aSyscall[41].pCurrent)
  31319. #if !SQLITE_OS_WINRT
  31320. { "HeapValidate", (SYSCALL)HeapValidate, 0 },
  31321. #else
  31322. { "HeapValidate", (SYSCALL)0, 0 },
  31323. #endif
  31324. #define osHeapValidate ((BOOL(WINAPI*)(HANDLE,DWORD, \
  31325. LPCVOID))aSyscall[42].pCurrent)
  31326. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
  31327. { "HeapCompact", (SYSCALL)HeapCompact, 0 },
  31328. #else
  31329. { "HeapCompact", (SYSCALL)0, 0 },
  31330. #endif
  31331. #define osHeapCompact ((UINT(WINAPI*)(HANDLE,DWORD))aSyscall[43].pCurrent)
  31332. #if defined(SQLITE_WIN32_HAS_ANSI) && !defined(SQLITE_OMIT_LOAD_EXTENSION)
  31333. { "LoadLibraryA", (SYSCALL)LoadLibraryA, 0 },
  31334. #else
  31335. { "LoadLibraryA", (SYSCALL)0, 0 },
  31336. #endif
  31337. #define osLoadLibraryA ((HMODULE(WINAPI*)(LPCSTR))aSyscall[44].pCurrent)
  31338. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
  31339. !defined(SQLITE_OMIT_LOAD_EXTENSION)
  31340. { "LoadLibraryW", (SYSCALL)LoadLibraryW, 0 },
  31341. #else
  31342. { "LoadLibraryW", (SYSCALL)0, 0 },
  31343. #endif
  31344. #define osLoadLibraryW ((HMODULE(WINAPI*)(LPCWSTR))aSyscall[45].pCurrent)
  31345. #if !SQLITE_OS_WINRT
  31346. { "LocalFree", (SYSCALL)LocalFree, 0 },
  31347. #else
  31348. { "LocalFree", (SYSCALL)0, 0 },
  31349. #endif
  31350. #define osLocalFree ((HLOCAL(WINAPI*)(HLOCAL))aSyscall[46].pCurrent)
  31351. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
  31352. { "LockFile", (SYSCALL)LockFile, 0 },
  31353. #else
  31354. { "LockFile", (SYSCALL)0, 0 },
  31355. #endif
  31356. #ifndef osLockFile
  31357. #define osLockFile ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
  31358. DWORD))aSyscall[47].pCurrent)
  31359. #endif
  31360. #if !SQLITE_OS_WINCE
  31361. { "LockFileEx", (SYSCALL)LockFileEx, 0 },
  31362. #else
  31363. { "LockFileEx", (SYSCALL)0, 0 },
  31364. #endif
  31365. #ifndef osLockFileEx
  31366. #define osLockFileEx ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD,DWORD, \
  31367. LPOVERLAPPED))aSyscall[48].pCurrent)
  31368. #endif
  31369. #if SQLITE_OS_WINCE || (!SQLITE_OS_WINRT && !defined(SQLITE_OMIT_WAL))
  31370. { "MapViewOfFile", (SYSCALL)MapViewOfFile, 0 },
  31371. #else
  31372. { "MapViewOfFile", (SYSCALL)0, 0 },
  31373. #endif
  31374. #define osMapViewOfFile ((LPVOID(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
  31375. SIZE_T))aSyscall[49].pCurrent)
  31376. { "MultiByteToWideChar", (SYSCALL)MultiByteToWideChar, 0 },
  31377. #define osMultiByteToWideChar ((int(WINAPI*)(UINT,DWORD,LPCSTR,int,LPWSTR, \
  31378. int))aSyscall[50].pCurrent)
  31379. { "QueryPerformanceCounter", (SYSCALL)QueryPerformanceCounter, 0 },
  31380. #define osQueryPerformanceCounter ((BOOL(WINAPI*)( \
  31381. LARGE_INTEGER*))aSyscall[51].pCurrent)
  31382. { "ReadFile", (SYSCALL)ReadFile, 0 },
  31383. #define osReadFile ((BOOL(WINAPI*)(HANDLE,LPVOID,DWORD,LPDWORD, \
  31384. LPOVERLAPPED))aSyscall[52].pCurrent)
  31385. { "SetEndOfFile", (SYSCALL)SetEndOfFile, 0 },
  31386. #define osSetEndOfFile ((BOOL(WINAPI*)(HANDLE))aSyscall[53].pCurrent)
  31387. #if !SQLITE_OS_WINRT
  31388. { "SetFilePointer", (SYSCALL)SetFilePointer, 0 },
  31389. #else
  31390. { "SetFilePointer", (SYSCALL)0, 0 },
  31391. #endif
  31392. #define osSetFilePointer ((DWORD(WINAPI*)(HANDLE,LONG,PLONG, \
  31393. DWORD))aSyscall[54].pCurrent)
  31394. #if !SQLITE_OS_WINRT
  31395. { "Sleep", (SYSCALL)Sleep, 0 },
  31396. #else
  31397. { "Sleep", (SYSCALL)0, 0 },
  31398. #endif
  31399. #define osSleep ((VOID(WINAPI*)(DWORD))aSyscall[55].pCurrent)
  31400. { "SystemTimeToFileTime", (SYSCALL)SystemTimeToFileTime, 0 },
  31401. #define osSystemTimeToFileTime ((BOOL(WINAPI*)(CONST SYSTEMTIME*, \
  31402. LPFILETIME))aSyscall[56].pCurrent)
  31403. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
  31404. { "UnlockFile", (SYSCALL)UnlockFile, 0 },
  31405. #else
  31406. { "UnlockFile", (SYSCALL)0, 0 },
  31407. #endif
  31408. #ifndef osUnlockFile
  31409. #define osUnlockFile ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
  31410. DWORD))aSyscall[57].pCurrent)
  31411. #endif
  31412. #if !SQLITE_OS_WINCE
  31413. { "UnlockFileEx", (SYSCALL)UnlockFileEx, 0 },
  31414. #else
  31415. { "UnlockFileEx", (SYSCALL)0, 0 },
  31416. #endif
  31417. #define osUnlockFileEx ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
  31418. LPOVERLAPPED))aSyscall[58].pCurrent)
  31419. #if SQLITE_OS_WINCE || !defined(SQLITE_OMIT_WAL)
  31420. { "UnmapViewOfFile", (SYSCALL)UnmapViewOfFile, 0 },
  31421. #else
  31422. { "UnmapViewOfFile", (SYSCALL)0, 0 },
  31423. #endif
  31424. #define osUnmapViewOfFile ((BOOL(WINAPI*)(LPCVOID))aSyscall[59].pCurrent)
  31425. { "WideCharToMultiByte", (SYSCALL)WideCharToMultiByte, 0 },
  31426. #define osWideCharToMultiByte ((int(WINAPI*)(UINT,DWORD,LPCWSTR,int,LPSTR,int, \
  31427. LPCSTR,LPBOOL))aSyscall[60].pCurrent)
  31428. { "WriteFile", (SYSCALL)WriteFile, 0 },
  31429. #define osWriteFile ((BOOL(WINAPI*)(HANDLE,LPCVOID,DWORD,LPDWORD, \
  31430. LPOVERLAPPED))aSyscall[61].pCurrent)
  31431. #if SQLITE_OS_WINRT
  31432. { "CreateEventExW", (SYSCALL)CreateEventExW, 0 },
  31433. #else
  31434. { "CreateEventExW", (SYSCALL)0, 0 },
  31435. #endif
  31436. #define osCreateEventExW ((HANDLE(WINAPI*)(LPSECURITY_ATTRIBUTES,LPCWSTR, \
  31437. DWORD,DWORD))aSyscall[62].pCurrent)
  31438. #if !SQLITE_OS_WINRT
  31439. { "WaitForSingleObject", (SYSCALL)WaitForSingleObject, 0 },
  31440. #else
  31441. { "WaitForSingleObject", (SYSCALL)0, 0 },
  31442. #endif
  31443. #define osWaitForSingleObject ((DWORD(WINAPI*)(HANDLE, \
  31444. DWORD))aSyscall[63].pCurrent)
  31445. #if !SQLITE_OS_WINCE
  31446. { "WaitForSingleObjectEx", (SYSCALL)WaitForSingleObjectEx, 0 },
  31447. #else
  31448. { "WaitForSingleObjectEx", (SYSCALL)0, 0 },
  31449. #endif
  31450. #define osWaitForSingleObjectEx ((DWORD(WINAPI*)(HANDLE,DWORD, \
  31451. BOOL))aSyscall[64].pCurrent)
  31452. #if SQLITE_OS_WINRT
  31453. { "SetFilePointerEx", (SYSCALL)SetFilePointerEx, 0 },
  31454. #else
  31455. { "SetFilePointerEx", (SYSCALL)0, 0 },
  31456. #endif
  31457. #define osSetFilePointerEx ((BOOL(WINAPI*)(HANDLE,LARGE_INTEGER, \
  31458. PLARGE_INTEGER,DWORD))aSyscall[65].pCurrent)
  31459. #if SQLITE_OS_WINRT
  31460. { "GetFileInformationByHandleEx", (SYSCALL)GetFileInformationByHandleEx, 0 },
  31461. #else
  31462. { "GetFileInformationByHandleEx", (SYSCALL)0, 0 },
  31463. #endif
  31464. #define osGetFileInformationByHandleEx ((BOOL(WINAPI*)(HANDLE, \
  31465. FILE_INFO_BY_HANDLE_CLASS,LPVOID,DWORD))aSyscall[66].pCurrent)
  31466. #if SQLITE_OS_WINRT && !defined(SQLITE_OMIT_WAL)
  31467. { "MapViewOfFileFromApp", (SYSCALL)MapViewOfFileFromApp, 0 },
  31468. #else
  31469. { "MapViewOfFileFromApp", (SYSCALL)0, 0 },
  31470. #endif
  31471. #define osMapViewOfFileFromApp ((LPVOID(WINAPI*)(HANDLE,ULONG,ULONG64, \
  31472. SIZE_T))aSyscall[67].pCurrent)
  31473. #if SQLITE_OS_WINRT
  31474. { "CreateFile2", (SYSCALL)CreateFile2, 0 },
  31475. #else
  31476. { "CreateFile2", (SYSCALL)0, 0 },
  31477. #endif
  31478. #define osCreateFile2 ((HANDLE(WINAPI*)(LPCWSTR,DWORD,DWORD,DWORD, \
  31479. LPCREATEFILE2_EXTENDED_PARAMETERS))aSyscall[68].pCurrent)
  31480. #if SQLITE_OS_WINRT && !defined(SQLITE_OMIT_LOAD_EXTENSION)
  31481. { "LoadPackagedLibrary", (SYSCALL)LoadPackagedLibrary, 0 },
  31482. #else
  31483. { "LoadPackagedLibrary", (SYSCALL)0, 0 },
  31484. #endif
  31485. #define osLoadPackagedLibrary ((HMODULE(WINAPI*)(LPCWSTR, \
  31486. DWORD))aSyscall[69].pCurrent)
  31487. #if SQLITE_OS_WINRT
  31488. { "GetTickCount64", (SYSCALL)GetTickCount64, 0 },
  31489. #else
  31490. { "GetTickCount64", (SYSCALL)0, 0 },
  31491. #endif
  31492. #define osGetTickCount64 ((ULONGLONG(WINAPI*)(VOID))aSyscall[70].pCurrent)
  31493. #if SQLITE_OS_WINRT
  31494. { "GetNativeSystemInfo", (SYSCALL)GetNativeSystemInfo, 0 },
  31495. #else
  31496. { "GetNativeSystemInfo", (SYSCALL)0, 0 },
  31497. #endif
  31498. #define osGetNativeSystemInfo ((VOID(WINAPI*)( \
  31499. LPSYSTEM_INFO))aSyscall[71].pCurrent)
  31500. #if defined(SQLITE_WIN32_HAS_ANSI)
  31501. { "OutputDebugStringA", (SYSCALL)OutputDebugStringA, 0 },
  31502. #else
  31503. { "OutputDebugStringA", (SYSCALL)0, 0 },
  31504. #endif
  31505. #define osOutputDebugStringA ((VOID(WINAPI*)(LPCSTR))aSyscall[72].pCurrent)
  31506. #if defined(SQLITE_WIN32_HAS_WIDE)
  31507. { "OutputDebugStringW", (SYSCALL)OutputDebugStringW, 0 },
  31508. #else
  31509. { "OutputDebugStringW", (SYSCALL)0, 0 },
  31510. #endif
  31511. #define osOutputDebugStringW ((VOID(WINAPI*)(LPCWSTR))aSyscall[73].pCurrent)
  31512. { "GetProcessHeap", (SYSCALL)GetProcessHeap, 0 },
  31513. #define osGetProcessHeap ((HANDLE(WINAPI*)(VOID))aSyscall[74].pCurrent)
  31514. #if SQLITE_OS_WINRT && !defined(SQLITE_OMIT_WAL)
  31515. { "CreateFileMappingFromApp", (SYSCALL)CreateFileMappingFromApp, 0 },
  31516. #else
  31517. { "CreateFileMappingFromApp", (SYSCALL)0, 0 },
  31518. #endif
  31519. #define osCreateFileMappingFromApp ((HANDLE(WINAPI*)(HANDLE, \
  31520. LPSECURITY_ATTRIBUTES,ULONG,ULONG64,LPCWSTR))aSyscall[75].pCurrent)
  31521. /*
  31522. ** NOTE: On some sub-platforms, the InterlockedCompareExchange "function"
  31523. ** is really just a macro that uses a compiler intrinsic (e.g. x64).
  31524. ** So do not try to make this is into a redefinable interface.
  31525. */
  31526. #if defined(InterlockedCompareExchange)
  31527. { "InterlockedCompareExchange", (SYSCALL)0, 0 },
  31528. #define osInterlockedCompareExchange InterlockedCompareExchange
  31529. #else
  31530. { "InterlockedCompareExchange", (SYSCALL)InterlockedCompareExchange, 0 },
  31531. #define osInterlockedCompareExchange ((LONG(WINAPI*)(LONG \
  31532. SQLITE_WIN32_VOLATILE*, LONG,LONG))aSyscall[76].pCurrent)
  31533. #endif /* defined(InterlockedCompareExchange) */
  31534. }; /* End of the overrideable system calls */
  31535. /*
  31536. ** This is the xSetSystemCall() method of sqlite3_vfs for all of the
  31537. ** "win32" VFSes. Return SQLITE_OK opon successfully updating the
  31538. ** system call pointer, or SQLITE_NOTFOUND if there is no configurable
  31539. ** system call named zName.
  31540. */
  31541. static int winSetSystemCall(
  31542. sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */
  31543. const char *zName, /* Name of system call to override */
  31544. sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */
  31545. ){
  31546. unsigned int i;
  31547. int rc = SQLITE_NOTFOUND;
  31548. UNUSED_PARAMETER(pNotUsed);
  31549. if( zName==0 ){
  31550. /* If no zName is given, restore all system calls to their default
  31551. ** settings and return NULL
  31552. */
  31553. rc = SQLITE_OK;
  31554. for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
  31555. if( aSyscall[i].pDefault ){
  31556. aSyscall[i].pCurrent = aSyscall[i].pDefault;
  31557. }
  31558. }
  31559. }else{
  31560. /* If zName is specified, operate on only the one system call
  31561. ** specified.
  31562. */
  31563. for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
  31564. if( strcmp(zName, aSyscall[i].zName)==0 ){
  31565. if( aSyscall[i].pDefault==0 ){
  31566. aSyscall[i].pDefault = aSyscall[i].pCurrent;
  31567. }
  31568. rc = SQLITE_OK;
  31569. if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
  31570. aSyscall[i].pCurrent = pNewFunc;
  31571. break;
  31572. }
  31573. }
  31574. }
  31575. return rc;
  31576. }
  31577. /*
  31578. ** Return the value of a system call. Return NULL if zName is not a
  31579. ** recognized system call name. NULL is also returned if the system call
  31580. ** is currently undefined.
  31581. */
  31582. static sqlite3_syscall_ptr winGetSystemCall(
  31583. sqlite3_vfs *pNotUsed,
  31584. const char *zName
  31585. ){
  31586. unsigned int i;
  31587. UNUSED_PARAMETER(pNotUsed);
  31588. for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
  31589. if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
  31590. }
  31591. return 0;
  31592. }
  31593. /*
  31594. ** Return the name of the first system call after zName. If zName==NULL
  31595. ** then return the name of the first system call. Return NULL if zName
  31596. ** is the last system call or if zName is not the name of a valid
  31597. ** system call.
  31598. */
  31599. static const char *winNextSystemCall(sqlite3_vfs *p, const char *zName){
  31600. int i = -1;
  31601. UNUSED_PARAMETER(p);
  31602. if( zName ){
  31603. for(i=0; i<ArraySize(aSyscall)-1; i++){
  31604. if( strcmp(zName, aSyscall[i].zName)==0 ) break;
  31605. }
  31606. }
  31607. for(i++; i<ArraySize(aSyscall); i++){
  31608. if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
  31609. }
  31610. return 0;
  31611. }
  31612. #ifdef SQLITE_WIN32_MALLOC
  31613. /*
  31614. ** If a Win32 native heap has been configured, this function will attempt to
  31615. ** compact it. Upon success, SQLITE_OK will be returned. Upon failure, one
  31616. ** of SQLITE_NOMEM, SQLITE_ERROR, or SQLITE_NOTFOUND will be returned. The
  31617. ** "pnLargest" argument, if non-zero, will be used to return the size of the
  31618. ** largest committed free block in the heap, in bytes.
  31619. */
  31620. SQLITE_API int sqlite3_win32_compact_heap(LPUINT pnLargest){
  31621. int rc = SQLITE_OK;
  31622. UINT nLargest = 0;
  31623. HANDLE hHeap;
  31624. winMemAssertMagic();
  31625. hHeap = winMemGetHeap();
  31626. assert( hHeap!=0 );
  31627. assert( hHeap!=INVALID_HANDLE_VALUE );
  31628. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
  31629. assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
  31630. #endif
  31631. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
  31632. if( (nLargest=osHeapCompact(hHeap, SQLITE_WIN32_HEAP_FLAGS))==0 ){
  31633. DWORD lastErrno = osGetLastError();
  31634. if( lastErrno==NO_ERROR ){
  31635. sqlite3_log(SQLITE_NOMEM, "failed to HeapCompact (no space), heap=%p",
  31636. (void*)hHeap);
  31637. rc = SQLITE_NOMEM;
  31638. }else{
  31639. sqlite3_log(SQLITE_ERROR, "failed to HeapCompact (%lu), heap=%p",
  31640. osGetLastError(), (void*)hHeap);
  31641. rc = SQLITE_ERROR;
  31642. }
  31643. }
  31644. #else
  31645. sqlite3_log(SQLITE_NOTFOUND, "failed to HeapCompact, heap=%p",
  31646. (void*)hHeap);
  31647. rc = SQLITE_NOTFOUND;
  31648. #endif
  31649. if( pnLargest ) *pnLargest = nLargest;
  31650. return rc;
  31651. }
  31652. /*
  31653. ** If a Win32 native heap has been configured, this function will attempt to
  31654. ** destroy and recreate it. If the Win32 native heap is not isolated and/or
  31655. ** the sqlite3_memory_used() function does not return zero, SQLITE_BUSY will
  31656. ** be returned and no changes will be made to the Win32 native heap.
  31657. */
  31658. SQLITE_API int sqlite3_win32_reset_heap(){
  31659. int rc;
  31660. MUTEX_LOGIC( sqlite3_mutex *pMaster; ) /* The main static mutex */
  31661. MUTEX_LOGIC( sqlite3_mutex *pMem; ) /* The memsys static mutex */
  31662. MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
  31663. MUTEX_LOGIC( pMem = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM); )
  31664. sqlite3_mutex_enter(pMaster);
  31665. sqlite3_mutex_enter(pMem);
  31666. winMemAssertMagic();
  31667. if( winMemGetHeap()!=NULL && winMemGetOwned() && sqlite3_memory_used()==0 ){
  31668. /*
  31669. ** At this point, there should be no outstanding memory allocations on
  31670. ** the heap. Also, since both the master and memsys locks are currently
  31671. ** being held by us, no other function (i.e. from another thread) should
  31672. ** be able to even access the heap. Attempt to destroy and recreate our
  31673. ** isolated Win32 native heap now.
  31674. */
  31675. assert( winMemGetHeap()!=NULL );
  31676. assert( winMemGetOwned() );
  31677. assert( sqlite3_memory_used()==0 );
  31678. winMemShutdown(winMemGetDataPtr());
  31679. assert( winMemGetHeap()==NULL );
  31680. assert( !winMemGetOwned() );
  31681. assert( sqlite3_memory_used()==0 );
  31682. rc = winMemInit(winMemGetDataPtr());
  31683. assert( rc!=SQLITE_OK || winMemGetHeap()!=NULL );
  31684. assert( rc!=SQLITE_OK || winMemGetOwned() );
  31685. assert( rc!=SQLITE_OK || sqlite3_memory_used()==0 );
  31686. }else{
  31687. /*
  31688. ** The Win32 native heap cannot be modified because it may be in use.
  31689. */
  31690. rc = SQLITE_BUSY;
  31691. }
  31692. sqlite3_mutex_leave(pMem);
  31693. sqlite3_mutex_leave(pMaster);
  31694. return rc;
  31695. }
  31696. #endif /* SQLITE_WIN32_MALLOC */
  31697. /*
  31698. ** This function outputs the specified (ANSI) string to the Win32 debugger
  31699. ** (if available).
  31700. */
  31701. SQLITE_API void sqlite3_win32_write_debug(const char *zBuf, int nBuf){
  31702. char zDbgBuf[SQLITE_WIN32_DBG_BUF_SIZE];
  31703. int nMin = MIN(nBuf, (SQLITE_WIN32_DBG_BUF_SIZE - 1)); /* may be negative. */
  31704. if( nMin<-1 ) nMin = -1; /* all negative values become -1. */
  31705. assert( nMin==-1 || nMin==0 || nMin<SQLITE_WIN32_DBG_BUF_SIZE );
  31706. #if defined(SQLITE_WIN32_HAS_ANSI)
  31707. if( nMin>0 ){
  31708. memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
  31709. memcpy(zDbgBuf, zBuf, nMin);
  31710. osOutputDebugStringA(zDbgBuf);
  31711. }else{
  31712. osOutputDebugStringA(zBuf);
  31713. }
  31714. #elif defined(SQLITE_WIN32_HAS_WIDE)
  31715. memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
  31716. if ( osMultiByteToWideChar(
  31717. osAreFileApisANSI() ? CP_ACP : CP_OEMCP, 0, zBuf,
  31718. nMin, (LPWSTR)zDbgBuf, SQLITE_WIN32_DBG_BUF_SIZE/sizeof(WCHAR))<=0 ){
  31719. return;
  31720. }
  31721. osOutputDebugStringW((LPCWSTR)zDbgBuf);
  31722. #else
  31723. if( nMin>0 ){
  31724. memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
  31725. memcpy(zDbgBuf, zBuf, nMin);
  31726. fprintf(stderr, "%s", zDbgBuf);
  31727. }else{
  31728. fprintf(stderr, "%s", zBuf);
  31729. }
  31730. #endif
  31731. }
  31732. /*
  31733. ** The following routine suspends the current thread for at least ms
  31734. ** milliseconds. This is equivalent to the Win32 Sleep() interface.
  31735. */
  31736. #if SQLITE_OS_WINRT
  31737. static HANDLE sleepObj = NULL;
  31738. #endif
  31739. SQLITE_API void sqlite3_win32_sleep(DWORD milliseconds){
  31740. #if SQLITE_OS_WINRT
  31741. if ( sleepObj==NULL ){
  31742. sleepObj = osCreateEventExW(NULL, NULL, CREATE_EVENT_MANUAL_RESET,
  31743. SYNCHRONIZE);
  31744. }
  31745. assert( sleepObj!=NULL );
  31746. osWaitForSingleObjectEx(sleepObj, milliseconds, FALSE);
  31747. #else
  31748. osSleep(milliseconds);
  31749. #endif
  31750. }
  31751. #if SQLITE_MAX_WORKER_THREADS>0 && !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && \
  31752. SQLITE_THREADSAFE>0
  31753. SQLITE_PRIVATE DWORD sqlite3Win32Wait(HANDLE hObject){
  31754. DWORD rc;
  31755. while( (rc = osWaitForSingleObjectEx(hObject, INFINITE,
  31756. TRUE))==WAIT_IO_COMPLETION ){}
  31757. return rc;
  31758. }
  31759. #endif
  31760. /*
  31761. ** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
  31762. ** or WinCE. Return false (zero) for Win95, Win98, or WinME.
  31763. **
  31764. ** Here is an interesting observation: Win95, Win98, and WinME lack
  31765. ** the LockFileEx() API. But we can still statically link against that
  31766. ** API as long as we don't call it when running Win95/98/ME. A call to
  31767. ** this routine is used to determine if the host is Win95/98/ME or
  31768. ** WinNT/2K/XP so that we will know whether or not we can safely call
  31769. ** the LockFileEx() API.
  31770. */
  31771. #if !defined(SQLITE_WIN32_GETVERSIONEX) || !SQLITE_WIN32_GETVERSIONEX
  31772. # define osIsNT() (1)
  31773. #elif SQLITE_OS_WINCE || SQLITE_OS_WINRT || !defined(SQLITE_WIN32_HAS_ANSI)
  31774. # define osIsNT() (1)
  31775. #elif !defined(SQLITE_WIN32_HAS_WIDE)
  31776. # define osIsNT() (0)
  31777. #else
  31778. # define osIsNT() ((sqlite3_os_type==2) || sqlite3_win32_is_nt())
  31779. #endif
  31780. /*
  31781. ** This function determines if the machine is running a version of Windows
  31782. ** based on the NT kernel.
  31783. */
  31784. SQLITE_API int sqlite3_win32_is_nt(void){
  31785. #if SQLITE_OS_WINRT
  31786. /*
  31787. ** NOTE: The WinRT sub-platform is always assumed to be based on the NT
  31788. ** kernel.
  31789. */
  31790. return 1;
  31791. #elif defined(SQLITE_WIN32_GETVERSIONEX) && SQLITE_WIN32_GETVERSIONEX
  31792. if( osInterlockedCompareExchange(&sqlite3_os_type, 0, 0)==0 ){
  31793. #if defined(SQLITE_WIN32_HAS_ANSI)
  31794. OSVERSIONINFOA sInfo;
  31795. sInfo.dwOSVersionInfoSize = sizeof(sInfo);
  31796. osGetVersionExA(&sInfo);
  31797. osInterlockedCompareExchange(&sqlite3_os_type,
  31798. (sInfo.dwPlatformId == VER_PLATFORM_WIN32_NT) ? 2 : 1, 0);
  31799. #elif defined(SQLITE_WIN32_HAS_WIDE)
  31800. OSVERSIONINFOW sInfo;
  31801. sInfo.dwOSVersionInfoSize = sizeof(sInfo);
  31802. osGetVersionExW(&sInfo);
  31803. osInterlockedCompareExchange(&sqlite3_os_type,
  31804. (sInfo.dwPlatformId == VER_PLATFORM_WIN32_NT) ? 2 : 1, 0);
  31805. #endif
  31806. }
  31807. return osInterlockedCompareExchange(&sqlite3_os_type, 2, 2)==2;
  31808. #elif SQLITE_TEST
  31809. return osInterlockedCompareExchange(&sqlite3_os_type, 2, 2)==2;
  31810. #else
  31811. /*
  31812. ** NOTE: All sub-platforms where the GetVersionEx[AW] functions are
  31813. ** deprecated are always assumed to be based on the NT kernel.
  31814. */
  31815. return 1;
  31816. #endif
  31817. }
  31818. #ifdef SQLITE_WIN32_MALLOC
  31819. /*
  31820. ** Allocate nBytes of memory.
  31821. */
  31822. static void *winMemMalloc(int nBytes){
  31823. HANDLE hHeap;
  31824. void *p;
  31825. winMemAssertMagic();
  31826. hHeap = winMemGetHeap();
  31827. assert( hHeap!=0 );
  31828. assert( hHeap!=INVALID_HANDLE_VALUE );
  31829. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
  31830. assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
  31831. #endif
  31832. assert( nBytes>=0 );
  31833. p = osHeapAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, (SIZE_T)nBytes);
  31834. if( !p ){
  31835. sqlite3_log(SQLITE_NOMEM, "failed to HeapAlloc %u bytes (%lu), heap=%p",
  31836. nBytes, osGetLastError(), (void*)hHeap);
  31837. }
  31838. return p;
  31839. }
  31840. /*
  31841. ** Free memory.
  31842. */
  31843. static void winMemFree(void *pPrior){
  31844. HANDLE hHeap;
  31845. winMemAssertMagic();
  31846. hHeap = winMemGetHeap();
  31847. assert( hHeap!=0 );
  31848. assert( hHeap!=INVALID_HANDLE_VALUE );
  31849. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
  31850. assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) );
  31851. #endif
  31852. if( !pPrior ) return; /* Passing NULL to HeapFree is undefined. */
  31853. if( !osHeapFree(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) ){
  31854. sqlite3_log(SQLITE_NOMEM, "failed to HeapFree block %p (%lu), heap=%p",
  31855. pPrior, osGetLastError(), (void*)hHeap);
  31856. }
  31857. }
  31858. /*
  31859. ** Change the size of an existing memory allocation
  31860. */
  31861. static void *winMemRealloc(void *pPrior, int nBytes){
  31862. HANDLE hHeap;
  31863. void *p;
  31864. winMemAssertMagic();
  31865. hHeap = winMemGetHeap();
  31866. assert( hHeap!=0 );
  31867. assert( hHeap!=INVALID_HANDLE_VALUE );
  31868. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
  31869. assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) );
  31870. #endif
  31871. assert( nBytes>=0 );
  31872. if( !pPrior ){
  31873. p = osHeapAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, (SIZE_T)nBytes);
  31874. }else{
  31875. p = osHeapReAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior, (SIZE_T)nBytes);
  31876. }
  31877. if( !p ){
  31878. sqlite3_log(SQLITE_NOMEM, "failed to %s %u bytes (%lu), heap=%p",
  31879. pPrior ? "HeapReAlloc" : "HeapAlloc", nBytes, osGetLastError(),
  31880. (void*)hHeap);
  31881. }
  31882. return p;
  31883. }
  31884. /*
  31885. ** Return the size of an outstanding allocation, in bytes.
  31886. */
  31887. static int winMemSize(void *p){
  31888. HANDLE hHeap;
  31889. SIZE_T n;
  31890. winMemAssertMagic();
  31891. hHeap = winMemGetHeap();
  31892. assert( hHeap!=0 );
  31893. assert( hHeap!=INVALID_HANDLE_VALUE );
  31894. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
  31895. assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, p) );
  31896. #endif
  31897. if( !p ) return 0;
  31898. n = osHeapSize(hHeap, SQLITE_WIN32_HEAP_FLAGS, p);
  31899. if( n==(SIZE_T)-1 ){
  31900. sqlite3_log(SQLITE_NOMEM, "failed to HeapSize block %p (%lu), heap=%p",
  31901. p, osGetLastError(), (void*)hHeap);
  31902. return 0;
  31903. }
  31904. return (int)n;
  31905. }
  31906. /*
  31907. ** Round up a request size to the next valid allocation size.
  31908. */
  31909. static int winMemRoundup(int n){
  31910. return n;
  31911. }
  31912. /*
  31913. ** Initialize this module.
  31914. */
  31915. static int winMemInit(void *pAppData){
  31916. winMemData *pWinMemData = (winMemData *)pAppData;
  31917. if( !pWinMemData ) return SQLITE_ERROR;
  31918. assert( pWinMemData->magic1==WINMEM_MAGIC1 );
  31919. assert( pWinMemData->magic2==WINMEM_MAGIC2 );
  31920. #if !SQLITE_OS_WINRT && SQLITE_WIN32_HEAP_CREATE
  31921. if( !pWinMemData->hHeap ){
  31922. DWORD dwInitialSize = SQLITE_WIN32_HEAP_INIT_SIZE;
  31923. DWORD dwMaximumSize = (DWORD)sqlite3GlobalConfig.nHeap;
  31924. if( dwMaximumSize==0 ){
  31925. dwMaximumSize = SQLITE_WIN32_HEAP_MAX_SIZE;
  31926. }else if( dwInitialSize>dwMaximumSize ){
  31927. dwInitialSize = dwMaximumSize;
  31928. }
  31929. pWinMemData->hHeap = osHeapCreate(SQLITE_WIN32_HEAP_FLAGS,
  31930. dwInitialSize, dwMaximumSize);
  31931. if( !pWinMemData->hHeap ){
  31932. sqlite3_log(SQLITE_NOMEM,
  31933. "failed to HeapCreate (%lu), flags=%u, initSize=%lu, maxSize=%lu",
  31934. osGetLastError(), SQLITE_WIN32_HEAP_FLAGS, dwInitialSize,
  31935. dwMaximumSize);
  31936. return SQLITE_NOMEM;
  31937. }
  31938. pWinMemData->bOwned = TRUE;
  31939. assert( pWinMemData->bOwned );
  31940. }
  31941. #else
  31942. pWinMemData->hHeap = osGetProcessHeap();
  31943. if( !pWinMemData->hHeap ){
  31944. sqlite3_log(SQLITE_NOMEM,
  31945. "failed to GetProcessHeap (%lu)", osGetLastError());
  31946. return SQLITE_NOMEM;
  31947. }
  31948. pWinMemData->bOwned = FALSE;
  31949. assert( !pWinMemData->bOwned );
  31950. #endif
  31951. assert( pWinMemData->hHeap!=0 );
  31952. assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE );
  31953. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
  31954. assert( osHeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
  31955. #endif
  31956. return SQLITE_OK;
  31957. }
  31958. /*
  31959. ** Deinitialize this module.
  31960. */
  31961. static void winMemShutdown(void *pAppData){
  31962. winMemData *pWinMemData = (winMemData *)pAppData;
  31963. if( !pWinMemData ) return;
  31964. assert( pWinMemData->magic1==WINMEM_MAGIC1 );
  31965. assert( pWinMemData->magic2==WINMEM_MAGIC2 );
  31966. if( pWinMemData->hHeap ){
  31967. assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE );
  31968. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
  31969. assert( osHeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
  31970. #endif
  31971. if( pWinMemData->bOwned ){
  31972. if( !osHeapDestroy(pWinMemData->hHeap) ){
  31973. sqlite3_log(SQLITE_NOMEM, "failed to HeapDestroy (%lu), heap=%p",
  31974. osGetLastError(), (void*)pWinMemData->hHeap);
  31975. }
  31976. pWinMemData->bOwned = FALSE;
  31977. }
  31978. pWinMemData->hHeap = NULL;
  31979. }
  31980. }
  31981. /*
  31982. ** Populate the low-level memory allocation function pointers in
  31983. ** sqlite3GlobalConfig.m with pointers to the routines in this file. The
  31984. ** arguments specify the block of memory to manage.
  31985. **
  31986. ** This routine is only called by sqlite3_config(), and therefore
  31987. ** is not required to be threadsafe (it is not).
  31988. */
  31989. SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetWin32(void){
  31990. static const sqlite3_mem_methods winMemMethods = {
  31991. winMemMalloc,
  31992. winMemFree,
  31993. winMemRealloc,
  31994. winMemSize,
  31995. winMemRoundup,
  31996. winMemInit,
  31997. winMemShutdown,
  31998. &win_mem_data
  31999. };
  32000. return &winMemMethods;
  32001. }
  32002. SQLITE_PRIVATE void sqlite3MemSetDefault(void){
  32003. sqlite3_config(SQLITE_CONFIG_MALLOC, sqlite3MemGetWin32());
  32004. }
  32005. #endif /* SQLITE_WIN32_MALLOC */
  32006. /*
  32007. ** Convert a UTF-8 string to Microsoft Unicode (UTF-16?).
  32008. **
  32009. ** Space to hold the returned string is obtained from malloc.
  32010. */
  32011. static LPWSTR winUtf8ToUnicode(const char *zFilename){
  32012. int nChar;
  32013. LPWSTR zWideFilename;
  32014. nChar = osMultiByteToWideChar(CP_UTF8, 0, zFilename, -1, NULL, 0);
  32015. if( nChar==0 ){
  32016. return 0;
  32017. }
  32018. zWideFilename = sqlite3MallocZero( nChar*sizeof(zWideFilename[0]) );
  32019. if( zWideFilename==0 ){
  32020. return 0;
  32021. }
  32022. nChar = osMultiByteToWideChar(CP_UTF8, 0, zFilename, -1, zWideFilename,
  32023. nChar);
  32024. if( nChar==0 ){
  32025. sqlite3_free(zWideFilename);
  32026. zWideFilename = 0;
  32027. }
  32028. return zWideFilename;
  32029. }
  32030. /*
  32031. ** Convert Microsoft Unicode to UTF-8. Space to hold the returned string is
  32032. ** obtained from sqlite3_malloc().
  32033. */
  32034. static char *winUnicodeToUtf8(LPCWSTR zWideFilename){
  32035. int nByte;
  32036. char *zFilename;
  32037. nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, 0, 0, 0, 0);
  32038. if( nByte == 0 ){
  32039. return 0;
  32040. }
  32041. zFilename = sqlite3MallocZero( nByte );
  32042. if( zFilename==0 ){
  32043. return 0;
  32044. }
  32045. nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, zFilename, nByte,
  32046. 0, 0);
  32047. if( nByte == 0 ){
  32048. sqlite3_free(zFilename);
  32049. zFilename = 0;
  32050. }
  32051. return zFilename;
  32052. }
  32053. /*
  32054. ** Convert an ANSI string to Microsoft Unicode, based on the
  32055. ** current codepage settings for file apis.
  32056. **
  32057. ** Space to hold the returned string is obtained
  32058. ** from sqlite3_malloc.
  32059. */
  32060. static LPWSTR winMbcsToUnicode(const char *zFilename){
  32061. int nByte;
  32062. LPWSTR zMbcsFilename;
  32063. int codepage = osAreFileApisANSI() ? CP_ACP : CP_OEMCP;
  32064. nByte = osMultiByteToWideChar(codepage, 0, zFilename, -1, NULL,
  32065. 0)*sizeof(WCHAR);
  32066. if( nByte==0 ){
  32067. return 0;
  32068. }
  32069. zMbcsFilename = sqlite3MallocZero( nByte*sizeof(zMbcsFilename[0]) );
  32070. if( zMbcsFilename==0 ){
  32071. return 0;
  32072. }
  32073. nByte = osMultiByteToWideChar(codepage, 0, zFilename, -1, zMbcsFilename,
  32074. nByte);
  32075. if( nByte==0 ){
  32076. sqlite3_free(zMbcsFilename);
  32077. zMbcsFilename = 0;
  32078. }
  32079. return zMbcsFilename;
  32080. }
  32081. /*
  32082. ** Convert Microsoft Unicode to multi-byte character string, based on the
  32083. ** user's ANSI codepage.
  32084. **
  32085. ** Space to hold the returned string is obtained from
  32086. ** sqlite3_malloc().
  32087. */
  32088. static char *winUnicodeToMbcs(LPCWSTR zWideFilename){
  32089. int nByte;
  32090. char *zFilename;
  32091. int codepage = osAreFileApisANSI() ? CP_ACP : CP_OEMCP;
  32092. nByte = osWideCharToMultiByte(codepage, 0, zWideFilename, -1, 0, 0, 0, 0);
  32093. if( nByte == 0 ){
  32094. return 0;
  32095. }
  32096. zFilename = sqlite3MallocZero( nByte );
  32097. if( zFilename==0 ){
  32098. return 0;
  32099. }
  32100. nByte = osWideCharToMultiByte(codepage, 0, zWideFilename, -1, zFilename,
  32101. nByte, 0, 0);
  32102. if( nByte == 0 ){
  32103. sqlite3_free(zFilename);
  32104. zFilename = 0;
  32105. }
  32106. return zFilename;
  32107. }
  32108. /*
  32109. ** Convert multibyte character string to UTF-8. Space to hold the
  32110. ** returned string is obtained from sqlite3_malloc().
  32111. */
  32112. SQLITE_API char *sqlite3_win32_mbcs_to_utf8(const char *zFilename){
  32113. char *zFilenameUtf8;
  32114. LPWSTR zTmpWide;
  32115. zTmpWide = winMbcsToUnicode(zFilename);
  32116. if( zTmpWide==0 ){
  32117. return 0;
  32118. }
  32119. zFilenameUtf8 = winUnicodeToUtf8(zTmpWide);
  32120. sqlite3_free(zTmpWide);
  32121. return zFilenameUtf8;
  32122. }
  32123. /*
  32124. ** Convert UTF-8 to multibyte character string. Space to hold the
  32125. ** returned string is obtained from sqlite3_malloc().
  32126. */
  32127. SQLITE_API char *sqlite3_win32_utf8_to_mbcs(const char *zFilename){
  32128. char *zFilenameMbcs;
  32129. LPWSTR zTmpWide;
  32130. zTmpWide = winUtf8ToUnicode(zFilename);
  32131. if( zTmpWide==0 ){
  32132. return 0;
  32133. }
  32134. zFilenameMbcs = winUnicodeToMbcs(zTmpWide);
  32135. sqlite3_free(zTmpWide);
  32136. return zFilenameMbcs;
  32137. }
  32138. /*
  32139. ** This function sets the data directory or the temporary directory based on
  32140. ** the provided arguments. The type argument must be 1 in order to set the
  32141. ** data directory or 2 in order to set the temporary directory. The zValue
  32142. ** argument is the name of the directory to use. The return value will be
  32143. ** SQLITE_OK if successful.
  32144. */
  32145. SQLITE_API int sqlite3_win32_set_directory(DWORD type, LPCWSTR zValue){
  32146. char **ppDirectory = 0;
  32147. #ifndef SQLITE_OMIT_AUTOINIT
  32148. int rc = sqlite3_initialize();
  32149. if( rc ) return rc;
  32150. #endif
  32151. if( type==SQLITE_WIN32_DATA_DIRECTORY_TYPE ){
  32152. ppDirectory = &sqlite3_data_directory;
  32153. }else if( type==SQLITE_WIN32_TEMP_DIRECTORY_TYPE ){
  32154. ppDirectory = &sqlite3_temp_directory;
  32155. }
  32156. assert( !ppDirectory || type==SQLITE_WIN32_DATA_DIRECTORY_TYPE
  32157. || type==SQLITE_WIN32_TEMP_DIRECTORY_TYPE
  32158. );
  32159. assert( !ppDirectory || sqlite3MemdebugHasType(*ppDirectory, MEMTYPE_HEAP) );
  32160. if( ppDirectory ){
  32161. char *zValueUtf8 = 0;
  32162. if( zValue && zValue[0] ){
  32163. zValueUtf8 = winUnicodeToUtf8(zValue);
  32164. if ( zValueUtf8==0 ){
  32165. return SQLITE_NOMEM;
  32166. }
  32167. }
  32168. sqlite3_free(*ppDirectory);
  32169. *ppDirectory = zValueUtf8;
  32170. return SQLITE_OK;
  32171. }
  32172. return SQLITE_ERROR;
  32173. }
  32174. /*
  32175. ** The return value of winGetLastErrorMsg
  32176. ** is zero if the error message fits in the buffer, or non-zero
  32177. ** otherwise (if the message was truncated).
  32178. */
  32179. static int winGetLastErrorMsg(DWORD lastErrno, int nBuf, char *zBuf){
  32180. /* FormatMessage returns 0 on failure. Otherwise it
  32181. ** returns the number of TCHARs written to the output
  32182. ** buffer, excluding the terminating null char.
  32183. */
  32184. DWORD dwLen = 0;
  32185. char *zOut = 0;
  32186. if( osIsNT() ){
  32187. #if SQLITE_OS_WINRT
  32188. WCHAR zTempWide[SQLITE_WIN32_MAX_ERRMSG_CHARS+1];
  32189. dwLen = osFormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM |
  32190. FORMAT_MESSAGE_IGNORE_INSERTS,
  32191. NULL,
  32192. lastErrno,
  32193. 0,
  32194. zTempWide,
  32195. SQLITE_WIN32_MAX_ERRMSG_CHARS,
  32196. 0);
  32197. #else
  32198. LPWSTR zTempWide = NULL;
  32199. dwLen = osFormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER |
  32200. FORMAT_MESSAGE_FROM_SYSTEM |
  32201. FORMAT_MESSAGE_IGNORE_INSERTS,
  32202. NULL,
  32203. lastErrno,
  32204. 0,
  32205. (LPWSTR) &zTempWide,
  32206. 0,
  32207. 0);
  32208. #endif
  32209. if( dwLen > 0 ){
  32210. /* allocate a buffer and convert to UTF8 */
  32211. sqlite3BeginBenignMalloc();
  32212. zOut = winUnicodeToUtf8(zTempWide);
  32213. sqlite3EndBenignMalloc();
  32214. #if !SQLITE_OS_WINRT
  32215. /* free the system buffer allocated by FormatMessage */
  32216. osLocalFree(zTempWide);
  32217. #endif
  32218. }
  32219. }
  32220. #ifdef SQLITE_WIN32_HAS_ANSI
  32221. else{
  32222. char *zTemp = NULL;
  32223. dwLen = osFormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER |
  32224. FORMAT_MESSAGE_FROM_SYSTEM |
  32225. FORMAT_MESSAGE_IGNORE_INSERTS,
  32226. NULL,
  32227. lastErrno,
  32228. 0,
  32229. (LPSTR) &zTemp,
  32230. 0,
  32231. 0);
  32232. if( dwLen > 0 ){
  32233. /* allocate a buffer and convert to UTF8 */
  32234. sqlite3BeginBenignMalloc();
  32235. zOut = sqlite3_win32_mbcs_to_utf8(zTemp);
  32236. sqlite3EndBenignMalloc();
  32237. /* free the system buffer allocated by FormatMessage */
  32238. osLocalFree(zTemp);
  32239. }
  32240. }
  32241. #endif
  32242. if( 0 == dwLen ){
  32243. sqlite3_snprintf(nBuf, zBuf, "OsError 0x%lx (%lu)", lastErrno, lastErrno);
  32244. }else{
  32245. /* copy a maximum of nBuf chars to output buffer */
  32246. sqlite3_snprintf(nBuf, zBuf, "%s", zOut);
  32247. /* free the UTF8 buffer */
  32248. sqlite3_free(zOut);
  32249. }
  32250. return 0;
  32251. }
  32252. /*
  32253. **
  32254. ** This function - winLogErrorAtLine() - is only ever called via the macro
  32255. ** winLogError().
  32256. **
  32257. ** This routine is invoked after an error occurs in an OS function.
  32258. ** It logs a message using sqlite3_log() containing the current value of
  32259. ** error code and, if possible, the human-readable equivalent from
  32260. ** FormatMessage.
  32261. **
  32262. ** The first argument passed to the macro should be the error code that
  32263. ** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
  32264. ** The two subsequent arguments should be the name of the OS function that
  32265. ** failed and the associated file-system path, if any.
  32266. */
  32267. #define winLogError(a,b,c,d) winLogErrorAtLine(a,b,c,d,__LINE__)
  32268. static int winLogErrorAtLine(
  32269. int errcode, /* SQLite error code */
  32270. DWORD lastErrno, /* Win32 last error */
  32271. const char *zFunc, /* Name of OS function that failed */
  32272. const char *zPath, /* File path associated with error */
  32273. int iLine /* Source line number where error occurred */
  32274. ){
  32275. char zMsg[500]; /* Human readable error text */
  32276. int i; /* Loop counter */
  32277. zMsg[0] = 0;
  32278. winGetLastErrorMsg(lastErrno, sizeof(zMsg), zMsg);
  32279. assert( errcode!=SQLITE_OK );
  32280. if( zPath==0 ) zPath = "";
  32281. for(i=0; zMsg[i] && zMsg[i]!='\r' && zMsg[i]!='\n'; i++){}
  32282. zMsg[i] = 0;
  32283. sqlite3_log(errcode,
  32284. "os_win.c:%d: (%lu) %s(%s) - %s",
  32285. iLine, lastErrno, zFunc, zPath, zMsg
  32286. );
  32287. return errcode;
  32288. }
  32289. /*
  32290. ** The number of times that a ReadFile(), WriteFile(), and DeleteFile()
  32291. ** will be retried following a locking error - probably caused by
  32292. ** antivirus software. Also the initial delay before the first retry.
  32293. ** The delay increases linearly with each retry.
  32294. */
  32295. #ifndef SQLITE_WIN32_IOERR_RETRY
  32296. # define SQLITE_WIN32_IOERR_RETRY 10
  32297. #endif
  32298. #ifndef SQLITE_WIN32_IOERR_RETRY_DELAY
  32299. # define SQLITE_WIN32_IOERR_RETRY_DELAY 25
  32300. #endif
  32301. static int winIoerrRetry = SQLITE_WIN32_IOERR_RETRY;
  32302. static int winIoerrRetryDelay = SQLITE_WIN32_IOERR_RETRY_DELAY;
  32303. /*
  32304. ** The "winIoerrCanRetry1" macro is used to determine if a particular I/O
  32305. ** error code obtained via GetLastError() is eligible to be retried. It
  32306. ** must accept the error code DWORD as its only argument and should return
  32307. ** non-zero if the error code is transient in nature and the operation
  32308. ** responsible for generating the original error might succeed upon being
  32309. ** retried. The argument to this macro should be a variable.
  32310. **
  32311. ** Additionally, a macro named "winIoerrCanRetry2" may be defined. If it
  32312. ** is defined, it will be consulted only when the macro "winIoerrCanRetry1"
  32313. ** returns zero. The "winIoerrCanRetry2" macro is completely optional and
  32314. ** may be used to include additional error codes in the set that should
  32315. ** result in the failing I/O operation being retried by the caller. If
  32316. ** defined, the "winIoerrCanRetry2" macro must exhibit external semantics
  32317. ** identical to those of the "winIoerrCanRetry1" macro.
  32318. */
  32319. #if !defined(winIoerrCanRetry1)
  32320. #define winIoerrCanRetry1(a) (((a)==ERROR_ACCESS_DENIED) || \
  32321. ((a)==ERROR_SHARING_VIOLATION) || \
  32322. ((a)==ERROR_LOCK_VIOLATION) || \
  32323. ((a)==ERROR_DEV_NOT_EXIST) || \
  32324. ((a)==ERROR_NETNAME_DELETED) || \
  32325. ((a)==ERROR_SEM_TIMEOUT) || \
  32326. ((a)==ERROR_NETWORK_UNREACHABLE))
  32327. #endif
  32328. /*
  32329. ** If a ReadFile() or WriteFile() error occurs, invoke this routine
  32330. ** to see if it should be retried. Return TRUE to retry. Return FALSE
  32331. ** to give up with an error.
  32332. */
  32333. static int winRetryIoerr(int *pnRetry, DWORD *pError){
  32334. DWORD e = osGetLastError();
  32335. if( *pnRetry>=winIoerrRetry ){
  32336. if( pError ){
  32337. *pError = e;
  32338. }
  32339. return 0;
  32340. }
  32341. if( winIoerrCanRetry1(e) ){
  32342. sqlite3_win32_sleep(winIoerrRetryDelay*(1+*pnRetry));
  32343. ++*pnRetry;
  32344. return 1;
  32345. }
  32346. #if defined(winIoerrCanRetry2)
  32347. else if( winIoerrCanRetry2(e) ){
  32348. sqlite3_win32_sleep(winIoerrRetryDelay*(1+*pnRetry));
  32349. ++*pnRetry;
  32350. return 1;
  32351. }
  32352. #endif
  32353. if( pError ){
  32354. *pError = e;
  32355. }
  32356. return 0;
  32357. }
  32358. /*
  32359. ** Log a I/O error retry episode.
  32360. */
  32361. static void winLogIoerr(int nRetry){
  32362. if( nRetry ){
  32363. sqlite3_log(SQLITE_IOERR,
  32364. "delayed %dms for lock/sharing conflict",
  32365. winIoerrRetryDelay*nRetry*(nRetry+1)/2
  32366. );
  32367. }
  32368. }
  32369. #if SQLITE_OS_WINCE
  32370. /*************************************************************************
  32371. ** This section contains code for WinCE only.
  32372. */
  32373. #if !defined(SQLITE_MSVC_LOCALTIME_API) || !SQLITE_MSVC_LOCALTIME_API
  32374. /*
  32375. ** The MSVC CRT on Windows CE may not have a localtime() function. So
  32376. ** create a substitute.
  32377. */
  32378. /* #include <time.h> */
  32379. struct tm *__cdecl localtime(const time_t *t)
  32380. {
  32381. static struct tm y;
  32382. FILETIME uTm, lTm;
  32383. SYSTEMTIME pTm;
  32384. sqlite3_int64 t64;
  32385. t64 = *t;
  32386. t64 = (t64 + 11644473600)*10000000;
  32387. uTm.dwLowDateTime = (DWORD)(t64 & 0xFFFFFFFF);
  32388. uTm.dwHighDateTime= (DWORD)(t64 >> 32);
  32389. osFileTimeToLocalFileTime(&uTm,&lTm);
  32390. osFileTimeToSystemTime(&lTm,&pTm);
  32391. y.tm_year = pTm.wYear - 1900;
  32392. y.tm_mon = pTm.wMonth - 1;
  32393. y.tm_wday = pTm.wDayOfWeek;
  32394. y.tm_mday = pTm.wDay;
  32395. y.tm_hour = pTm.wHour;
  32396. y.tm_min = pTm.wMinute;
  32397. y.tm_sec = pTm.wSecond;
  32398. return &y;
  32399. }
  32400. #endif
  32401. #define HANDLE_TO_WINFILE(a) (winFile*)&((char*)a)[-(int)offsetof(winFile,h)]
  32402. /*
  32403. ** Acquire a lock on the handle h
  32404. */
  32405. static void winceMutexAcquire(HANDLE h){
  32406. DWORD dwErr;
  32407. do {
  32408. dwErr = osWaitForSingleObject(h, INFINITE);
  32409. } while (dwErr != WAIT_OBJECT_0 && dwErr != WAIT_ABANDONED);
  32410. }
  32411. /*
  32412. ** Release a lock acquired by winceMutexAcquire()
  32413. */
  32414. #define winceMutexRelease(h) ReleaseMutex(h)
  32415. /*
  32416. ** Create the mutex and shared memory used for locking in the file
  32417. ** descriptor pFile
  32418. */
  32419. static int winceCreateLock(const char *zFilename, winFile *pFile){
  32420. LPWSTR zTok;
  32421. LPWSTR zName;
  32422. DWORD lastErrno;
  32423. BOOL bLogged = FALSE;
  32424. BOOL bInit = TRUE;
  32425. zName = winUtf8ToUnicode(zFilename);
  32426. if( zName==0 ){
  32427. /* out of memory */
  32428. return SQLITE_IOERR_NOMEM;
  32429. }
  32430. /* Initialize the local lockdata */
  32431. memset(&pFile->local, 0, sizeof(pFile->local));
  32432. /* Replace the backslashes from the filename and lowercase it
  32433. ** to derive a mutex name. */
  32434. zTok = osCharLowerW(zName);
  32435. for (;*zTok;zTok++){
  32436. if (*zTok == '\\') *zTok = '_';
  32437. }
  32438. /* Create/open the named mutex */
  32439. pFile->hMutex = osCreateMutexW(NULL, FALSE, zName);
  32440. if (!pFile->hMutex){
  32441. pFile->lastErrno = osGetLastError();
  32442. sqlite3_free(zName);
  32443. return winLogError(SQLITE_IOERR, pFile->lastErrno,
  32444. "winceCreateLock1", zFilename);
  32445. }
  32446. /* Acquire the mutex before continuing */
  32447. winceMutexAcquire(pFile->hMutex);
  32448. /* Since the names of named mutexes, semaphores, file mappings etc are
  32449. ** case-sensitive, take advantage of that by uppercasing the mutex name
  32450. ** and using that as the shared filemapping name.
  32451. */
  32452. osCharUpperW(zName);
  32453. pFile->hShared = osCreateFileMappingW(INVALID_HANDLE_VALUE, NULL,
  32454. PAGE_READWRITE, 0, sizeof(winceLock),
  32455. zName);
  32456. /* Set a flag that indicates we're the first to create the memory so it
  32457. ** must be zero-initialized */
  32458. lastErrno = osGetLastError();
  32459. if (lastErrno == ERROR_ALREADY_EXISTS){
  32460. bInit = FALSE;
  32461. }
  32462. sqlite3_free(zName);
  32463. /* If we succeeded in making the shared memory handle, map it. */
  32464. if( pFile->hShared ){
  32465. pFile->shared = (winceLock*)osMapViewOfFile(pFile->hShared,
  32466. FILE_MAP_READ|FILE_MAP_WRITE, 0, 0, sizeof(winceLock));
  32467. /* If mapping failed, close the shared memory handle and erase it */
  32468. if( !pFile->shared ){
  32469. pFile->lastErrno = osGetLastError();
  32470. winLogError(SQLITE_IOERR, pFile->lastErrno,
  32471. "winceCreateLock2", zFilename);
  32472. bLogged = TRUE;
  32473. osCloseHandle(pFile->hShared);
  32474. pFile->hShared = NULL;
  32475. }
  32476. }
  32477. /* If shared memory could not be created, then close the mutex and fail */
  32478. if( pFile->hShared==NULL ){
  32479. if( !bLogged ){
  32480. pFile->lastErrno = lastErrno;
  32481. winLogError(SQLITE_IOERR, pFile->lastErrno,
  32482. "winceCreateLock3", zFilename);
  32483. bLogged = TRUE;
  32484. }
  32485. winceMutexRelease(pFile->hMutex);
  32486. osCloseHandle(pFile->hMutex);
  32487. pFile->hMutex = NULL;
  32488. return SQLITE_IOERR;
  32489. }
  32490. /* Initialize the shared memory if we're supposed to */
  32491. if( bInit ){
  32492. memset(pFile->shared, 0, sizeof(winceLock));
  32493. }
  32494. winceMutexRelease(pFile->hMutex);
  32495. return SQLITE_OK;
  32496. }
  32497. /*
  32498. ** Destroy the part of winFile that deals with wince locks
  32499. */
  32500. static void winceDestroyLock(winFile *pFile){
  32501. if (pFile->hMutex){
  32502. /* Acquire the mutex */
  32503. winceMutexAcquire(pFile->hMutex);
  32504. /* The following blocks should probably assert in debug mode, but they
  32505. are to cleanup in case any locks remained open */
  32506. if (pFile->local.nReaders){
  32507. pFile->shared->nReaders --;
  32508. }
  32509. if (pFile->local.bReserved){
  32510. pFile->shared->bReserved = FALSE;
  32511. }
  32512. if (pFile->local.bPending){
  32513. pFile->shared->bPending = FALSE;
  32514. }
  32515. if (pFile->local.bExclusive){
  32516. pFile->shared->bExclusive = FALSE;
  32517. }
  32518. /* De-reference and close our copy of the shared memory handle */
  32519. osUnmapViewOfFile(pFile->shared);
  32520. osCloseHandle(pFile->hShared);
  32521. /* Done with the mutex */
  32522. winceMutexRelease(pFile->hMutex);
  32523. osCloseHandle(pFile->hMutex);
  32524. pFile->hMutex = NULL;
  32525. }
  32526. }
  32527. /*
  32528. ** An implementation of the LockFile() API of Windows for CE
  32529. */
  32530. static BOOL winceLockFile(
  32531. LPHANDLE phFile,
  32532. DWORD dwFileOffsetLow,
  32533. DWORD dwFileOffsetHigh,
  32534. DWORD nNumberOfBytesToLockLow,
  32535. DWORD nNumberOfBytesToLockHigh
  32536. ){
  32537. winFile *pFile = HANDLE_TO_WINFILE(phFile);
  32538. BOOL bReturn = FALSE;
  32539. UNUSED_PARAMETER(dwFileOffsetHigh);
  32540. UNUSED_PARAMETER(nNumberOfBytesToLockHigh);
  32541. if (!pFile->hMutex) return TRUE;
  32542. winceMutexAcquire(pFile->hMutex);
  32543. /* Wanting an exclusive lock? */
  32544. if (dwFileOffsetLow == (DWORD)SHARED_FIRST
  32545. && nNumberOfBytesToLockLow == (DWORD)SHARED_SIZE){
  32546. if (pFile->shared->nReaders == 0 && pFile->shared->bExclusive == 0){
  32547. pFile->shared->bExclusive = TRUE;
  32548. pFile->local.bExclusive = TRUE;
  32549. bReturn = TRUE;
  32550. }
  32551. }
  32552. /* Want a read-only lock? */
  32553. else if (dwFileOffsetLow == (DWORD)SHARED_FIRST &&
  32554. nNumberOfBytesToLockLow == 1){
  32555. if (pFile->shared->bExclusive == 0){
  32556. pFile->local.nReaders ++;
  32557. if (pFile->local.nReaders == 1){
  32558. pFile->shared->nReaders ++;
  32559. }
  32560. bReturn = TRUE;
  32561. }
  32562. }
  32563. /* Want a pending lock? */
  32564. else if (dwFileOffsetLow == (DWORD)PENDING_BYTE
  32565. && nNumberOfBytesToLockLow == 1){
  32566. /* If no pending lock has been acquired, then acquire it */
  32567. if (pFile->shared->bPending == 0) {
  32568. pFile->shared->bPending = TRUE;
  32569. pFile->local.bPending = TRUE;
  32570. bReturn = TRUE;
  32571. }
  32572. }
  32573. /* Want a reserved lock? */
  32574. else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE
  32575. && nNumberOfBytesToLockLow == 1){
  32576. if (pFile->shared->bReserved == 0) {
  32577. pFile->shared->bReserved = TRUE;
  32578. pFile->local.bReserved = TRUE;
  32579. bReturn = TRUE;
  32580. }
  32581. }
  32582. winceMutexRelease(pFile->hMutex);
  32583. return bReturn;
  32584. }
  32585. /*
  32586. ** An implementation of the UnlockFile API of Windows for CE
  32587. */
  32588. static BOOL winceUnlockFile(
  32589. LPHANDLE phFile,
  32590. DWORD dwFileOffsetLow,
  32591. DWORD dwFileOffsetHigh,
  32592. DWORD nNumberOfBytesToUnlockLow,
  32593. DWORD nNumberOfBytesToUnlockHigh
  32594. ){
  32595. winFile *pFile = HANDLE_TO_WINFILE(phFile);
  32596. BOOL bReturn = FALSE;
  32597. UNUSED_PARAMETER(dwFileOffsetHigh);
  32598. UNUSED_PARAMETER(nNumberOfBytesToUnlockHigh);
  32599. if (!pFile->hMutex) return TRUE;
  32600. winceMutexAcquire(pFile->hMutex);
  32601. /* Releasing a reader lock or an exclusive lock */
  32602. if (dwFileOffsetLow == (DWORD)SHARED_FIRST){
  32603. /* Did we have an exclusive lock? */
  32604. if (pFile->local.bExclusive){
  32605. assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE);
  32606. pFile->local.bExclusive = FALSE;
  32607. pFile->shared->bExclusive = FALSE;
  32608. bReturn = TRUE;
  32609. }
  32610. /* Did we just have a reader lock? */
  32611. else if (pFile->local.nReaders){
  32612. assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE
  32613. || nNumberOfBytesToUnlockLow == 1);
  32614. pFile->local.nReaders --;
  32615. if (pFile->local.nReaders == 0)
  32616. {
  32617. pFile->shared->nReaders --;
  32618. }
  32619. bReturn = TRUE;
  32620. }
  32621. }
  32622. /* Releasing a pending lock */
  32623. else if (dwFileOffsetLow == (DWORD)PENDING_BYTE
  32624. && nNumberOfBytesToUnlockLow == 1){
  32625. if (pFile->local.bPending){
  32626. pFile->local.bPending = FALSE;
  32627. pFile->shared->bPending = FALSE;
  32628. bReturn = TRUE;
  32629. }
  32630. }
  32631. /* Releasing a reserved lock */
  32632. else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE
  32633. && nNumberOfBytesToUnlockLow == 1){
  32634. if (pFile->local.bReserved) {
  32635. pFile->local.bReserved = FALSE;
  32636. pFile->shared->bReserved = FALSE;
  32637. bReturn = TRUE;
  32638. }
  32639. }
  32640. winceMutexRelease(pFile->hMutex);
  32641. return bReturn;
  32642. }
  32643. /*
  32644. ** End of the special code for wince
  32645. *****************************************************************************/
  32646. #endif /* SQLITE_OS_WINCE */
  32647. /*
  32648. ** Lock a file region.
  32649. */
  32650. static BOOL winLockFile(
  32651. LPHANDLE phFile,
  32652. DWORD flags,
  32653. DWORD offsetLow,
  32654. DWORD offsetHigh,
  32655. DWORD numBytesLow,
  32656. DWORD numBytesHigh
  32657. ){
  32658. #if SQLITE_OS_WINCE
  32659. /*
  32660. ** NOTE: Windows CE is handled differently here due its lack of the Win32
  32661. ** API LockFile.
  32662. */
  32663. return winceLockFile(phFile, offsetLow, offsetHigh,
  32664. numBytesLow, numBytesHigh);
  32665. #else
  32666. if( osIsNT() ){
  32667. OVERLAPPED ovlp;
  32668. memset(&ovlp, 0, sizeof(OVERLAPPED));
  32669. ovlp.Offset = offsetLow;
  32670. ovlp.OffsetHigh = offsetHigh;
  32671. return osLockFileEx(*phFile, flags, 0, numBytesLow, numBytesHigh, &ovlp);
  32672. }else{
  32673. return osLockFile(*phFile, offsetLow, offsetHigh, numBytesLow,
  32674. numBytesHigh);
  32675. }
  32676. #endif
  32677. }
  32678. /*
  32679. ** Unlock a file region.
  32680. */
  32681. static BOOL winUnlockFile(
  32682. LPHANDLE phFile,
  32683. DWORD offsetLow,
  32684. DWORD offsetHigh,
  32685. DWORD numBytesLow,
  32686. DWORD numBytesHigh
  32687. ){
  32688. #if SQLITE_OS_WINCE
  32689. /*
  32690. ** NOTE: Windows CE is handled differently here due its lack of the Win32
  32691. ** API UnlockFile.
  32692. */
  32693. return winceUnlockFile(phFile, offsetLow, offsetHigh,
  32694. numBytesLow, numBytesHigh);
  32695. #else
  32696. if( osIsNT() ){
  32697. OVERLAPPED ovlp;
  32698. memset(&ovlp, 0, sizeof(OVERLAPPED));
  32699. ovlp.Offset = offsetLow;
  32700. ovlp.OffsetHigh = offsetHigh;
  32701. return osUnlockFileEx(*phFile, 0, numBytesLow, numBytesHigh, &ovlp);
  32702. }else{
  32703. return osUnlockFile(*phFile, offsetLow, offsetHigh, numBytesLow,
  32704. numBytesHigh);
  32705. }
  32706. #endif
  32707. }
  32708. /*****************************************************************************
  32709. ** The next group of routines implement the I/O methods specified
  32710. ** by the sqlite3_io_methods object.
  32711. ******************************************************************************/
  32712. /*
  32713. ** Some Microsoft compilers lack this definition.
  32714. */
  32715. #ifndef INVALID_SET_FILE_POINTER
  32716. # define INVALID_SET_FILE_POINTER ((DWORD)-1)
  32717. #endif
  32718. /*
  32719. ** Move the current position of the file handle passed as the first
  32720. ** argument to offset iOffset within the file. If successful, return 0.
  32721. ** Otherwise, set pFile->lastErrno and return non-zero.
  32722. */
  32723. static int winSeekFile(winFile *pFile, sqlite3_int64 iOffset){
  32724. #if !SQLITE_OS_WINRT
  32725. LONG upperBits; /* Most sig. 32 bits of new offset */
  32726. LONG lowerBits; /* Least sig. 32 bits of new offset */
  32727. DWORD dwRet; /* Value returned by SetFilePointer() */
  32728. DWORD lastErrno; /* Value returned by GetLastError() */
  32729. OSTRACE(("SEEK file=%p, offset=%lld\n", pFile->h, iOffset));
  32730. upperBits = (LONG)((iOffset>>32) & 0x7fffffff);
  32731. lowerBits = (LONG)(iOffset & 0xffffffff);
  32732. /* API oddity: If successful, SetFilePointer() returns a dword
  32733. ** containing the lower 32-bits of the new file-offset. Or, if it fails,
  32734. ** it returns INVALID_SET_FILE_POINTER. However according to MSDN,
  32735. ** INVALID_SET_FILE_POINTER may also be a valid new offset. So to determine
  32736. ** whether an error has actually occurred, it is also necessary to call
  32737. ** GetLastError().
  32738. */
  32739. dwRet = osSetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
  32740. if( (dwRet==INVALID_SET_FILE_POINTER
  32741. && ((lastErrno = osGetLastError())!=NO_ERROR)) ){
  32742. pFile->lastErrno = lastErrno;
  32743. winLogError(SQLITE_IOERR_SEEK, pFile->lastErrno,
  32744. "winSeekFile", pFile->zPath);
  32745. OSTRACE(("SEEK file=%p, rc=SQLITE_IOERR_SEEK\n", pFile->h));
  32746. return 1;
  32747. }
  32748. OSTRACE(("SEEK file=%p, rc=SQLITE_OK\n", pFile->h));
  32749. return 0;
  32750. #else
  32751. /*
  32752. ** Same as above, except that this implementation works for WinRT.
  32753. */
  32754. LARGE_INTEGER x; /* The new offset */
  32755. BOOL bRet; /* Value returned by SetFilePointerEx() */
  32756. x.QuadPart = iOffset;
  32757. bRet = osSetFilePointerEx(pFile->h, x, 0, FILE_BEGIN);
  32758. if(!bRet){
  32759. pFile->lastErrno = osGetLastError();
  32760. winLogError(SQLITE_IOERR_SEEK, pFile->lastErrno,
  32761. "winSeekFile", pFile->zPath);
  32762. OSTRACE(("SEEK file=%p, rc=SQLITE_IOERR_SEEK\n", pFile->h));
  32763. return 1;
  32764. }
  32765. OSTRACE(("SEEK file=%p, rc=SQLITE_OK\n", pFile->h));
  32766. return 0;
  32767. #endif
  32768. }
  32769. #if SQLITE_MAX_MMAP_SIZE>0
  32770. /* Forward references to VFS helper methods used for memory mapped files */
  32771. static int winMapfile(winFile*, sqlite3_int64);
  32772. static int winUnmapfile(winFile*);
  32773. #endif
  32774. /*
  32775. ** Close a file.
  32776. **
  32777. ** It is reported that an attempt to close a handle might sometimes
  32778. ** fail. This is a very unreasonable result, but Windows is notorious
  32779. ** for being unreasonable so I do not doubt that it might happen. If
  32780. ** the close fails, we pause for 100 milliseconds and try again. As
  32781. ** many as MX_CLOSE_ATTEMPT attempts to close the handle are made before
  32782. ** giving up and returning an error.
  32783. */
  32784. #define MX_CLOSE_ATTEMPT 3
  32785. static int winClose(sqlite3_file *id){
  32786. int rc, cnt = 0;
  32787. winFile *pFile = (winFile*)id;
  32788. assert( id!=0 );
  32789. #ifndef SQLITE_OMIT_WAL
  32790. assert( pFile->pShm==0 );
  32791. #endif
  32792. assert( pFile->h!=NULL && pFile->h!=INVALID_HANDLE_VALUE );
  32793. OSTRACE(("CLOSE file=%p\n", pFile->h));
  32794. #if SQLITE_MAX_MMAP_SIZE>0
  32795. winUnmapfile(pFile);
  32796. #endif
  32797. do{
  32798. rc = osCloseHandle(pFile->h);
  32799. /* SimulateIOError( rc=0; cnt=MX_CLOSE_ATTEMPT; ); */
  32800. }while( rc==0 && ++cnt < MX_CLOSE_ATTEMPT && (sqlite3_win32_sleep(100), 1) );
  32801. #if SQLITE_OS_WINCE
  32802. #define WINCE_DELETION_ATTEMPTS 3
  32803. winceDestroyLock(pFile);
  32804. if( pFile->zDeleteOnClose ){
  32805. int cnt = 0;
  32806. while(
  32807. osDeleteFileW(pFile->zDeleteOnClose)==0
  32808. && osGetFileAttributesW(pFile->zDeleteOnClose)!=0xffffffff
  32809. && cnt++ < WINCE_DELETION_ATTEMPTS
  32810. ){
  32811. sqlite3_win32_sleep(100); /* Wait a little before trying again */
  32812. }
  32813. sqlite3_free(pFile->zDeleteOnClose);
  32814. }
  32815. #endif
  32816. if( rc ){
  32817. pFile->h = NULL;
  32818. }
  32819. OpenCounter(-1);
  32820. OSTRACE(("CLOSE file=%p, rc=%s\n", pFile->h, rc ? "ok" : "failed"));
  32821. return rc ? SQLITE_OK
  32822. : winLogError(SQLITE_IOERR_CLOSE, osGetLastError(),
  32823. "winClose", pFile->zPath);
  32824. }
  32825. /*
  32826. ** Read data from a file into a buffer. Return SQLITE_OK if all
  32827. ** bytes were read successfully and SQLITE_IOERR if anything goes
  32828. ** wrong.
  32829. */
  32830. static int winRead(
  32831. sqlite3_file *id, /* File to read from */
  32832. void *pBuf, /* Write content into this buffer */
  32833. int amt, /* Number of bytes to read */
  32834. sqlite3_int64 offset /* Begin reading at this offset */
  32835. ){
  32836. #if !SQLITE_OS_WINCE
  32837. OVERLAPPED overlapped; /* The offset for ReadFile. */
  32838. #endif
  32839. winFile *pFile = (winFile*)id; /* file handle */
  32840. DWORD nRead; /* Number of bytes actually read from file */
  32841. int nRetry = 0; /* Number of retrys */
  32842. assert( id!=0 );
  32843. assert( amt>0 );
  32844. assert( offset>=0 );
  32845. SimulateIOError(return SQLITE_IOERR_READ);
  32846. OSTRACE(("READ file=%p, buffer=%p, amount=%d, offset=%lld, lock=%d\n",
  32847. pFile->h, pBuf, amt, offset, pFile->locktype));
  32848. #if SQLITE_MAX_MMAP_SIZE>0
  32849. /* Deal with as much of this read request as possible by transfering
  32850. ** data from the memory mapping using memcpy(). */
  32851. if( offset<pFile->mmapSize ){
  32852. if( offset+amt <= pFile->mmapSize ){
  32853. memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
  32854. OSTRACE(("READ-MMAP file=%p, rc=SQLITE_OK\n", pFile->h));
  32855. return SQLITE_OK;
  32856. }else{
  32857. int nCopy = (int)(pFile->mmapSize - offset);
  32858. memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
  32859. pBuf = &((u8 *)pBuf)[nCopy];
  32860. amt -= nCopy;
  32861. offset += nCopy;
  32862. }
  32863. }
  32864. #endif
  32865. #if SQLITE_OS_WINCE
  32866. if( winSeekFile(pFile, offset) ){
  32867. OSTRACE(("READ file=%p, rc=SQLITE_FULL\n", pFile->h));
  32868. return SQLITE_FULL;
  32869. }
  32870. while( !osReadFile(pFile->h, pBuf, amt, &nRead, 0) ){
  32871. #else
  32872. memset(&overlapped, 0, sizeof(OVERLAPPED));
  32873. overlapped.Offset = (LONG)(offset & 0xffffffff);
  32874. overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
  32875. while( !osReadFile(pFile->h, pBuf, amt, &nRead, &overlapped) &&
  32876. osGetLastError()!=ERROR_HANDLE_EOF ){
  32877. #endif
  32878. DWORD lastErrno;
  32879. if( winRetryIoerr(&nRetry, &lastErrno) ) continue;
  32880. pFile->lastErrno = lastErrno;
  32881. OSTRACE(("READ file=%p, rc=SQLITE_IOERR_READ\n", pFile->h));
  32882. return winLogError(SQLITE_IOERR_READ, pFile->lastErrno,
  32883. "winRead", pFile->zPath);
  32884. }
  32885. winLogIoerr(nRetry);
  32886. if( nRead<(DWORD)amt ){
  32887. /* Unread parts of the buffer must be zero-filled */
  32888. memset(&((char*)pBuf)[nRead], 0, amt-nRead);
  32889. OSTRACE(("READ file=%p, rc=SQLITE_IOERR_SHORT_READ\n", pFile->h));
  32890. return SQLITE_IOERR_SHORT_READ;
  32891. }
  32892. OSTRACE(("READ file=%p, rc=SQLITE_OK\n", pFile->h));
  32893. return SQLITE_OK;
  32894. }
  32895. /*
  32896. ** Write data from a buffer into a file. Return SQLITE_OK on success
  32897. ** or some other error code on failure.
  32898. */
  32899. static int winWrite(
  32900. sqlite3_file *id, /* File to write into */
  32901. const void *pBuf, /* The bytes to be written */
  32902. int amt, /* Number of bytes to write */
  32903. sqlite3_int64 offset /* Offset into the file to begin writing at */
  32904. ){
  32905. int rc = 0; /* True if error has occurred, else false */
  32906. winFile *pFile = (winFile*)id; /* File handle */
  32907. int nRetry = 0; /* Number of retries */
  32908. assert( amt>0 );
  32909. assert( pFile );
  32910. SimulateIOError(return SQLITE_IOERR_WRITE);
  32911. SimulateDiskfullError(return SQLITE_FULL);
  32912. OSTRACE(("WRITE file=%p, buffer=%p, amount=%d, offset=%lld, lock=%d\n",
  32913. pFile->h, pBuf, amt, offset, pFile->locktype));
  32914. #if SQLITE_MAX_MMAP_SIZE>0
  32915. /* Deal with as much of this write request as possible by transfering
  32916. ** data from the memory mapping using memcpy(). */
  32917. if( offset<pFile->mmapSize ){
  32918. if( offset+amt <= pFile->mmapSize ){
  32919. memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
  32920. OSTRACE(("WRITE-MMAP file=%p, rc=SQLITE_OK\n", pFile->h));
  32921. return SQLITE_OK;
  32922. }else{
  32923. int nCopy = (int)(pFile->mmapSize - offset);
  32924. memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
  32925. pBuf = &((u8 *)pBuf)[nCopy];
  32926. amt -= nCopy;
  32927. offset += nCopy;
  32928. }
  32929. }
  32930. #endif
  32931. #if SQLITE_OS_WINCE
  32932. rc = winSeekFile(pFile, offset);
  32933. if( rc==0 ){
  32934. #else
  32935. {
  32936. #endif
  32937. #if !SQLITE_OS_WINCE
  32938. OVERLAPPED overlapped; /* The offset for WriteFile. */
  32939. #endif
  32940. u8 *aRem = (u8 *)pBuf; /* Data yet to be written */
  32941. int nRem = amt; /* Number of bytes yet to be written */
  32942. DWORD nWrite; /* Bytes written by each WriteFile() call */
  32943. DWORD lastErrno = NO_ERROR; /* Value returned by GetLastError() */
  32944. #if !SQLITE_OS_WINCE
  32945. memset(&overlapped, 0, sizeof(OVERLAPPED));
  32946. overlapped.Offset = (LONG)(offset & 0xffffffff);
  32947. overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
  32948. #endif
  32949. while( nRem>0 ){
  32950. #if SQLITE_OS_WINCE
  32951. if( !osWriteFile(pFile->h, aRem, nRem, &nWrite, 0) ){
  32952. #else
  32953. if( !osWriteFile(pFile->h, aRem, nRem, &nWrite, &overlapped) ){
  32954. #endif
  32955. if( winRetryIoerr(&nRetry, &lastErrno) ) continue;
  32956. break;
  32957. }
  32958. assert( nWrite==0 || nWrite<=(DWORD)nRem );
  32959. if( nWrite==0 || nWrite>(DWORD)nRem ){
  32960. lastErrno = osGetLastError();
  32961. break;
  32962. }
  32963. #if !SQLITE_OS_WINCE
  32964. offset += nWrite;
  32965. overlapped.Offset = (LONG)(offset & 0xffffffff);
  32966. overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
  32967. #endif
  32968. aRem += nWrite;
  32969. nRem -= nWrite;
  32970. }
  32971. if( nRem>0 ){
  32972. pFile->lastErrno = lastErrno;
  32973. rc = 1;
  32974. }
  32975. }
  32976. if( rc ){
  32977. if( ( pFile->lastErrno==ERROR_HANDLE_DISK_FULL )
  32978. || ( pFile->lastErrno==ERROR_DISK_FULL )){
  32979. OSTRACE(("WRITE file=%p, rc=SQLITE_FULL\n", pFile->h));
  32980. return winLogError(SQLITE_FULL, pFile->lastErrno,
  32981. "winWrite1", pFile->zPath);
  32982. }
  32983. OSTRACE(("WRITE file=%p, rc=SQLITE_IOERR_WRITE\n", pFile->h));
  32984. return winLogError(SQLITE_IOERR_WRITE, pFile->lastErrno,
  32985. "winWrite2", pFile->zPath);
  32986. }else{
  32987. winLogIoerr(nRetry);
  32988. }
  32989. OSTRACE(("WRITE file=%p, rc=SQLITE_OK\n", pFile->h));
  32990. return SQLITE_OK;
  32991. }
  32992. /*
  32993. ** Truncate an open file to a specified size
  32994. */
  32995. static int winTruncate(sqlite3_file *id, sqlite3_int64 nByte){
  32996. winFile *pFile = (winFile*)id; /* File handle object */
  32997. int rc = SQLITE_OK; /* Return code for this function */
  32998. DWORD lastErrno;
  32999. assert( pFile );
  33000. SimulateIOError(return SQLITE_IOERR_TRUNCATE);
  33001. OSTRACE(("TRUNCATE file=%p, size=%lld, lock=%d\n",
  33002. pFile->h, nByte, pFile->locktype));
  33003. /* If the user has configured a chunk-size for this file, truncate the
  33004. ** file so that it consists of an integer number of chunks (i.e. the
  33005. ** actual file size after the operation may be larger than the requested
  33006. ** size).
  33007. */
  33008. if( pFile->szChunk>0 ){
  33009. nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
  33010. }
  33011. /* SetEndOfFile() returns non-zero when successful, or zero when it fails. */
  33012. if( winSeekFile(pFile, nByte) ){
  33013. rc = winLogError(SQLITE_IOERR_TRUNCATE, pFile->lastErrno,
  33014. "winTruncate1", pFile->zPath);
  33015. }else if( 0==osSetEndOfFile(pFile->h) &&
  33016. ((lastErrno = osGetLastError())!=ERROR_USER_MAPPED_FILE) ){
  33017. pFile->lastErrno = lastErrno;
  33018. rc = winLogError(SQLITE_IOERR_TRUNCATE, pFile->lastErrno,
  33019. "winTruncate2", pFile->zPath);
  33020. }
  33021. #if SQLITE_MAX_MMAP_SIZE>0
  33022. /* If the file was truncated to a size smaller than the currently
  33023. ** mapped region, reduce the effective mapping size as well. SQLite will
  33024. ** use read() and write() to access data beyond this point from now on.
  33025. */
  33026. if( pFile->pMapRegion && nByte<pFile->mmapSize ){
  33027. pFile->mmapSize = nByte;
  33028. }
  33029. #endif
  33030. OSTRACE(("TRUNCATE file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
  33031. return rc;
  33032. }
  33033. #ifdef SQLITE_TEST
  33034. /*
  33035. ** Count the number of fullsyncs and normal syncs. This is used to test
  33036. ** that syncs and fullsyncs are occuring at the right times.
  33037. */
  33038. SQLITE_API int sqlite3_sync_count = 0;
  33039. SQLITE_API int sqlite3_fullsync_count = 0;
  33040. #endif
  33041. /*
  33042. ** Make sure all writes to a particular file are committed to disk.
  33043. */
  33044. static int winSync(sqlite3_file *id, int flags){
  33045. #ifndef SQLITE_NO_SYNC
  33046. /*
  33047. ** Used only when SQLITE_NO_SYNC is not defined.
  33048. */
  33049. BOOL rc;
  33050. #endif
  33051. #if !defined(NDEBUG) || !defined(SQLITE_NO_SYNC) || \
  33052. (defined(SQLITE_TEST) && defined(SQLITE_DEBUG))
  33053. /*
  33054. ** Used when SQLITE_NO_SYNC is not defined and by the assert() and/or
  33055. ** OSTRACE() macros.
  33056. */
  33057. winFile *pFile = (winFile*)id;
  33058. #else
  33059. UNUSED_PARAMETER(id);
  33060. #endif
  33061. assert( pFile );
  33062. /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
  33063. assert((flags&0x0F)==SQLITE_SYNC_NORMAL
  33064. || (flags&0x0F)==SQLITE_SYNC_FULL
  33065. );
  33066. /* Unix cannot, but some systems may return SQLITE_FULL from here. This
  33067. ** line is to test that doing so does not cause any problems.
  33068. */
  33069. SimulateDiskfullError( return SQLITE_FULL );
  33070. OSTRACE(("SYNC file=%p, flags=%x, lock=%d\n",
  33071. pFile->h, flags, pFile->locktype));
  33072. #ifndef SQLITE_TEST
  33073. UNUSED_PARAMETER(flags);
  33074. #else
  33075. if( (flags&0x0F)==SQLITE_SYNC_FULL ){
  33076. sqlite3_fullsync_count++;
  33077. }
  33078. sqlite3_sync_count++;
  33079. #endif
  33080. /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
  33081. ** no-op
  33082. */
  33083. #ifdef SQLITE_NO_SYNC
  33084. OSTRACE(("SYNC-NOP file=%p, rc=SQLITE_OK\n", pFile->h));
  33085. return SQLITE_OK;
  33086. #else
  33087. rc = osFlushFileBuffers(pFile->h);
  33088. SimulateIOError( rc=FALSE );
  33089. if( rc ){
  33090. OSTRACE(("SYNC file=%p, rc=SQLITE_OK\n", pFile->h));
  33091. return SQLITE_OK;
  33092. }else{
  33093. pFile->lastErrno = osGetLastError();
  33094. OSTRACE(("SYNC file=%p, rc=SQLITE_IOERR_FSYNC\n", pFile->h));
  33095. return winLogError(SQLITE_IOERR_FSYNC, pFile->lastErrno,
  33096. "winSync", pFile->zPath);
  33097. }
  33098. #endif
  33099. }
  33100. /*
  33101. ** Determine the current size of a file in bytes
  33102. */
  33103. static int winFileSize(sqlite3_file *id, sqlite3_int64 *pSize){
  33104. winFile *pFile = (winFile*)id;
  33105. int rc = SQLITE_OK;
  33106. assert( id!=0 );
  33107. assert( pSize!=0 );
  33108. SimulateIOError(return SQLITE_IOERR_FSTAT);
  33109. OSTRACE(("SIZE file=%p, pSize=%p\n", pFile->h, pSize));
  33110. #if SQLITE_OS_WINRT
  33111. {
  33112. FILE_STANDARD_INFO info;
  33113. if( osGetFileInformationByHandleEx(pFile->h, FileStandardInfo,
  33114. &info, sizeof(info)) ){
  33115. *pSize = info.EndOfFile.QuadPart;
  33116. }else{
  33117. pFile->lastErrno = osGetLastError();
  33118. rc = winLogError(SQLITE_IOERR_FSTAT, pFile->lastErrno,
  33119. "winFileSize", pFile->zPath);
  33120. }
  33121. }
  33122. #else
  33123. {
  33124. DWORD upperBits;
  33125. DWORD lowerBits;
  33126. DWORD lastErrno;
  33127. lowerBits = osGetFileSize(pFile->h, &upperBits);
  33128. *pSize = (((sqlite3_int64)upperBits)<<32) + lowerBits;
  33129. if( (lowerBits == INVALID_FILE_SIZE)
  33130. && ((lastErrno = osGetLastError())!=NO_ERROR) ){
  33131. pFile->lastErrno = lastErrno;
  33132. rc = winLogError(SQLITE_IOERR_FSTAT, pFile->lastErrno,
  33133. "winFileSize", pFile->zPath);
  33134. }
  33135. }
  33136. #endif
  33137. OSTRACE(("SIZE file=%p, pSize=%p, *pSize=%lld, rc=%s\n",
  33138. pFile->h, pSize, *pSize, sqlite3ErrName(rc)));
  33139. return rc;
  33140. }
  33141. /*
  33142. ** LOCKFILE_FAIL_IMMEDIATELY is undefined on some Windows systems.
  33143. */
  33144. #ifndef LOCKFILE_FAIL_IMMEDIATELY
  33145. # define LOCKFILE_FAIL_IMMEDIATELY 1
  33146. #endif
  33147. #ifndef LOCKFILE_EXCLUSIVE_LOCK
  33148. # define LOCKFILE_EXCLUSIVE_LOCK 2
  33149. #endif
  33150. /*
  33151. ** Historically, SQLite has used both the LockFile and LockFileEx functions.
  33152. ** When the LockFile function was used, it was always expected to fail
  33153. ** immediately if the lock could not be obtained. Also, it always expected to
  33154. ** obtain an exclusive lock. These flags are used with the LockFileEx function
  33155. ** and reflect those expectations; therefore, they should not be changed.
  33156. */
  33157. #ifndef SQLITE_LOCKFILE_FLAGS
  33158. # define SQLITE_LOCKFILE_FLAGS (LOCKFILE_FAIL_IMMEDIATELY | \
  33159. LOCKFILE_EXCLUSIVE_LOCK)
  33160. #endif
  33161. /*
  33162. ** Currently, SQLite never calls the LockFileEx function without wanting the
  33163. ** call to fail immediately if the lock cannot be obtained.
  33164. */
  33165. #ifndef SQLITE_LOCKFILEEX_FLAGS
  33166. # define SQLITE_LOCKFILEEX_FLAGS (LOCKFILE_FAIL_IMMEDIATELY)
  33167. #endif
  33168. /*
  33169. ** Acquire a reader lock.
  33170. ** Different API routines are called depending on whether or not this
  33171. ** is Win9x or WinNT.
  33172. */
  33173. static int winGetReadLock(winFile *pFile){
  33174. int res;
  33175. OSTRACE(("READ-LOCK file=%p, lock=%d\n", pFile->h, pFile->locktype));
  33176. if( osIsNT() ){
  33177. #if SQLITE_OS_WINCE
  33178. /*
  33179. ** NOTE: Windows CE is handled differently here due its lack of the Win32
  33180. ** API LockFileEx.
  33181. */
  33182. res = winceLockFile(&pFile->h, SHARED_FIRST, 0, 1, 0);
  33183. #else
  33184. res = winLockFile(&pFile->h, SQLITE_LOCKFILEEX_FLAGS, SHARED_FIRST, 0,
  33185. SHARED_SIZE, 0);
  33186. #endif
  33187. }
  33188. #ifdef SQLITE_WIN32_HAS_ANSI
  33189. else{
  33190. int lk;
  33191. sqlite3_randomness(sizeof(lk), &lk);
  33192. pFile->sharedLockByte = (short)((lk & 0x7fffffff)%(SHARED_SIZE - 1));
  33193. res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS,
  33194. SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
  33195. }
  33196. #endif
  33197. if( res == 0 ){
  33198. pFile->lastErrno = osGetLastError();
  33199. /* No need to log a failure to lock */
  33200. }
  33201. OSTRACE(("READ-LOCK file=%p, result=%d\n", pFile->h, res));
  33202. return res;
  33203. }
  33204. /*
  33205. ** Undo a readlock
  33206. */
  33207. static int winUnlockReadLock(winFile *pFile){
  33208. int res;
  33209. DWORD lastErrno;
  33210. OSTRACE(("READ-UNLOCK file=%p, lock=%d\n", pFile->h, pFile->locktype));
  33211. if( osIsNT() ){
  33212. res = winUnlockFile(&pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
  33213. }
  33214. #ifdef SQLITE_WIN32_HAS_ANSI
  33215. else{
  33216. res = winUnlockFile(&pFile->h, SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
  33217. }
  33218. #endif
  33219. if( res==0 && ((lastErrno = osGetLastError())!=ERROR_NOT_LOCKED) ){
  33220. pFile->lastErrno = lastErrno;
  33221. winLogError(SQLITE_IOERR_UNLOCK, pFile->lastErrno,
  33222. "winUnlockReadLock", pFile->zPath);
  33223. }
  33224. OSTRACE(("READ-UNLOCK file=%p, result=%d\n", pFile->h, res));
  33225. return res;
  33226. }
  33227. /*
  33228. ** Lock the file with the lock specified by parameter locktype - one
  33229. ** of the following:
  33230. **
  33231. ** (1) SHARED_LOCK
  33232. ** (2) RESERVED_LOCK
  33233. ** (3) PENDING_LOCK
  33234. ** (4) EXCLUSIVE_LOCK
  33235. **
  33236. ** Sometimes when requesting one lock state, additional lock states
  33237. ** are inserted in between. The locking might fail on one of the later
  33238. ** transitions leaving the lock state different from what it started but
  33239. ** still short of its goal. The following chart shows the allowed
  33240. ** transitions and the inserted intermediate states:
  33241. **
  33242. ** UNLOCKED -> SHARED
  33243. ** SHARED -> RESERVED
  33244. ** SHARED -> (PENDING) -> EXCLUSIVE
  33245. ** RESERVED -> (PENDING) -> EXCLUSIVE
  33246. ** PENDING -> EXCLUSIVE
  33247. **
  33248. ** This routine will only increase a lock. The winUnlock() routine
  33249. ** erases all locks at once and returns us immediately to locking level 0.
  33250. ** It is not possible to lower the locking level one step at a time. You
  33251. ** must go straight to locking level 0.
  33252. */
  33253. static int winLock(sqlite3_file *id, int locktype){
  33254. int rc = SQLITE_OK; /* Return code from subroutines */
  33255. int res = 1; /* Result of a Windows lock call */
  33256. int newLocktype; /* Set pFile->locktype to this value before exiting */
  33257. int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
  33258. winFile *pFile = (winFile*)id;
  33259. DWORD lastErrno = NO_ERROR;
  33260. assert( id!=0 );
  33261. OSTRACE(("LOCK file=%p, oldLock=%d(%d), newLock=%d\n",
  33262. pFile->h, pFile->locktype, pFile->sharedLockByte, locktype));
  33263. /* If there is already a lock of this type or more restrictive on the
  33264. ** OsFile, do nothing. Don't use the end_lock: exit path, as
  33265. ** sqlite3OsEnterMutex() hasn't been called yet.
  33266. */
  33267. if( pFile->locktype>=locktype ){
  33268. OSTRACE(("LOCK-HELD file=%p, rc=SQLITE_OK\n", pFile->h));
  33269. return SQLITE_OK;
  33270. }
  33271. /* Make sure the locking sequence is correct
  33272. */
  33273. assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
  33274. assert( locktype!=PENDING_LOCK );
  33275. assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
  33276. /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
  33277. ** a SHARED lock. If we are acquiring a SHARED lock, the acquisition of
  33278. ** the PENDING_LOCK byte is temporary.
  33279. */
  33280. newLocktype = pFile->locktype;
  33281. if( (pFile->locktype==NO_LOCK)
  33282. || ( (locktype==EXCLUSIVE_LOCK)
  33283. && (pFile->locktype==RESERVED_LOCK))
  33284. ){
  33285. int cnt = 3;
  33286. while( cnt-->0 && (res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS,
  33287. PENDING_BYTE, 0, 1, 0))==0 ){
  33288. /* Try 3 times to get the pending lock. This is needed to work
  33289. ** around problems caused by indexing and/or anti-virus software on
  33290. ** Windows systems.
  33291. ** If you are using this code as a model for alternative VFSes, do not
  33292. ** copy this retry logic. It is a hack intended for Windows only.
  33293. */
  33294. lastErrno = osGetLastError();
  33295. OSTRACE(("LOCK-PENDING-FAIL file=%p, count=%d, result=%d\n",
  33296. pFile->h, cnt, res));
  33297. if( lastErrno==ERROR_INVALID_HANDLE ){
  33298. pFile->lastErrno = lastErrno;
  33299. rc = SQLITE_IOERR_LOCK;
  33300. OSTRACE(("LOCK-FAIL file=%p, count=%d, rc=%s\n",
  33301. pFile->h, cnt, sqlite3ErrName(rc)));
  33302. return rc;
  33303. }
  33304. if( cnt ) sqlite3_win32_sleep(1);
  33305. }
  33306. gotPendingLock = res;
  33307. if( !res ){
  33308. lastErrno = osGetLastError();
  33309. }
  33310. }
  33311. /* Acquire a shared lock
  33312. */
  33313. if( locktype==SHARED_LOCK && res ){
  33314. assert( pFile->locktype==NO_LOCK );
  33315. res = winGetReadLock(pFile);
  33316. if( res ){
  33317. newLocktype = SHARED_LOCK;
  33318. }else{
  33319. lastErrno = osGetLastError();
  33320. }
  33321. }
  33322. /* Acquire a RESERVED lock
  33323. */
  33324. if( locktype==RESERVED_LOCK && res ){
  33325. assert( pFile->locktype==SHARED_LOCK );
  33326. res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, RESERVED_BYTE, 0, 1, 0);
  33327. if( res ){
  33328. newLocktype = RESERVED_LOCK;
  33329. }else{
  33330. lastErrno = osGetLastError();
  33331. }
  33332. }
  33333. /* Acquire a PENDING lock
  33334. */
  33335. if( locktype==EXCLUSIVE_LOCK && res ){
  33336. newLocktype = PENDING_LOCK;
  33337. gotPendingLock = 0;
  33338. }
  33339. /* Acquire an EXCLUSIVE lock
  33340. */
  33341. if( locktype==EXCLUSIVE_LOCK && res ){
  33342. assert( pFile->locktype>=SHARED_LOCK );
  33343. res = winUnlockReadLock(pFile);
  33344. res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, SHARED_FIRST, 0,
  33345. SHARED_SIZE, 0);
  33346. if( res ){
  33347. newLocktype = EXCLUSIVE_LOCK;
  33348. }else{
  33349. lastErrno = osGetLastError();
  33350. winGetReadLock(pFile);
  33351. }
  33352. }
  33353. /* If we are holding a PENDING lock that ought to be released, then
  33354. ** release it now.
  33355. */
  33356. if( gotPendingLock && locktype==SHARED_LOCK ){
  33357. winUnlockFile(&pFile->h, PENDING_BYTE, 0, 1, 0);
  33358. }
  33359. /* Update the state of the lock has held in the file descriptor then
  33360. ** return the appropriate result code.
  33361. */
  33362. if( res ){
  33363. rc = SQLITE_OK;
  33364. }else{
  33365. pFile->lastErrno = lastErrno;
  33366. rc = SQLITE_BUSY;
  33367. OSTRACE(("LOCK-FAIL file=%p, wanted=%d, got=%d\n",
  33368. pFile->h, locktype, newLocktype));
  33369. }
  33370. pFile->locktype = (u8)newLocktype;
  33371. OSTRACE(("LOCK file=%p, lock=%d, rc=%s\n",
  33372. pFile->h, pFile->locktype, sqlite3ErrName(rc)));
  33373. return rc;
  33374. }
  33375. /*
  33376. ** This routine checks if there is a RESERVED lock held on the specified
  33377. ** file by this or any other process. If such a lock is held, return
  33378. ** non-zero, otherwise zero.
  33379. */
  33380. static int winCheckReservedLock(sqlite3_file *id, int *pResOut){
  33381. int res;
  33382. winFile *pFile = (winFile*)id;
  33383. SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
  33384. OSTRACE(("TEST-WR-LOCK file=%p, pResOut=%p\n", pFile->h, pResOut));
  33385. assert( id!=0 );
  33386. if( pFile->locktype>=RESERVED_LOCK ){
  33387. res = 1;
  33388. OSTRACE(("TEST-WR-LOCK file=%p, result=%d (local)\n", pFile->h, res));
  33389. }else{
  33390. res = winLockFile(&pFile->h, SQLITE_LOCKFILEEX_FLAGS,RESERVED_BYTE, 0, 1, 0);
  33391. if( res ){
  33392. winUnlockFile(&pFile->h, RESERVED_BYTE, 0, 1, 0);
  33393. }
  33394. res = !res;
  33395. OSTRACE(("TEST-WR-LOCK file=%p, result=%d (remote)\n", pFile->h, res));
  33396. }
  33397. *pResOut = res;
  33398. OSTRACE(("TEST-WR-LOCK file=%p, pResOut=%p, *pResOut=%d, rc=SQLITE_OK\n",
  33399. pFile->h, pResOut, *pResOut));
  33400. return SQLITE_OK;
  33401. }
  33402. /*
  33403. ** Lower the locking level on file descriptor id to locktype. locktype
  33404. ** must be either NO_LOCK or SHARED_LOCK.
  33405. **
  33406. ** If the locking level of the file descriptor is already at or below
  33407. ** the requested locking level, this routine is a no-op.
  33408. **
  33409. ** It is not possible for this routine to fail if the second argument
  33410. ** is NO_LOCK. If the second argument is SHARED_LOCK then this routine
  33411. ** might return SQLITE_IOERR;
  33412. */
  33413. static int winUnlock(sqlite3_file *id, int locktype){
  33414. int type;
  33415. winFile *pFile = (winFile*)id;
  33416. int rc = SQLITE_OK;
  33417. assert( pFile!=0 );
  33418. assert( locktype<=SHARED_LOCK );
  33419. OSTRACE(("UNLOCK file=%p, oldLock=%d(%d), newLock=%d\n",
  33420. pFile->h, pFile->locktype, pFile->sharedLockByte, locktype));
  33421. type = pFile->locktype;
  33422. if( type>=EXCLUSIVE_LOCK ){
  33423. winUnlockFile(&pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
  33424. if( locktype==SHARED_LOCK && !winGetReadLock(pFile) ){
  33425. /* This should never happen. We should always be able to
  33426. ** reacquire the read lock */
  33427. rc = winLogError(SQLITE_IOERR_UNLOCK, osGetLastError(),
  33428. "winUnlock", pFile->zPath);
  33429. }
  33430. }
  33431. if( type>=RESERVED_LOCK ){
  33432. winUnlockFile(&pFile->h, RESERVED_BYTE, 0, 1, 0);
  33433. }
  33434. if( locktype==NO_LOCK && type>=SHARED_LOCK ){
  33435. winUnlockReadLock(pFile);
  33436. }
  33437. if( type>=PENDING_LOCK ){
  33438. winUnlockFile(&pFile->h, PENDING_BYTE, 0, 1, 0);
  33439. }
  33440. pFile->locktype = (u8)locktype;
  33441. OSTRACE(("UNLOCK file=%p, lock=%d, rc=%s\n",
  33442. pFile->h, pFile->locktype, sqlite3ErrName(rc)));
  33443. return rc;
  33444. }
  33445. /*
  33446. ** If *pArg is initially negative then this is a query. Set *pArg to
  33447. ** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
  33448. **
  33449. ** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
  33450. */
  33451. static void winModeBit(winFile *pFile, unsigned char mask, int *pArg){
  33452. if( *pArg<0 ){
  33453. *pArg = (pFile->ctrlFlags & mask)!=0;
  33454. }else if( (*pArg)==0 ){
  33455. pFile->ctrlFlags &= ~mask;
  33456. }else{
  33457. pFile->ctrlFlags |= mask;
  33458. }
  33459. }
  33460. /* Forward references to VFS helper methods used for temporary files */
  33461. static int winGetTempname(sqlite3_vfs *, char **);
  33462. static int winIsDir(const void *);
  33463. static BOOL winIsDriveLetterAndColon(const char *);
  33464. /*
  33465. ** Control and query of the open file handle.
  33466. */
  33467. static int winFileControl(sqlite3_file *id, int op, void *pArg){
  33468. winFile *pFile = (winFile*)id;
  33469. OSTRACE(("FCNTL file=%p, op=%d, pArg=%p\n", pFile->h, op, pArg));
  33470. switch( op ){
  33471. case SQLITE_FCNTL_LOCKSTATE: {
  33472. *(int*)pArg = pFile->locktype;
  33473. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  33474. return SQLITE_OK;
  33475. }
  33476. case SQLITE_LAST_ERRNO: {
  33477. *(int*)pArg = (int)pFile->lastErrno;
  33478. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  33479. return SQLITE_OK;
  33480. }
  33481. case SQLITE_FCNTL_CHUNK_SIZE: {
  33482. pFile->szChunk = *(int *)pArg;
  33483. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  33484. return SQLITE_OK;
  33485. }
  33486. case SQLITE_FCNTL_SIZE_HINT: {
  33487. if( pFile->szChunk>0 ){
  33488. sqlite3_int64 oldSz;
  33489. int rc = winFileSize(id, &oldSz);
  33490. if( rc==SQLITE_OK ){
  33491. sqlite3_int64 newSz = *(sqlite3_int64*)pArg;
  33492. if( newSz>oldSz ){
  33493. SimulateIOErrorBenign(1);
  33494. rc = winTruncate(id, newSz);
  33495. SimulateIOErrorBenign(0);
  33496. }
  33497. }
  33498. OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
  33499. return rc;
  33500. }
  33501. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  33502. return SQLITE_OK;
  33503. }
  33504. case SQLITE_FCNTL_PERSIST_WAL: {
  33505. winModeBit(pFile, WINFILE_PERSIST_WAL, (int*)pArg);
  33506. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  33507. return SQLITE_OK;
  33508. }
  33509. case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
  33510. winModeBit(pFile, WINFILE_PSOW, (int*)pArg);
  33511. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  33512. return SQLITE_OK;
  33513. }
  33514. case SQLITE_FCNTL_VFSNAME: {
  33515. *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
  33516. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  33517. return SQLITE_OK;
  33518. }
  33519. case SQLITE_FCNTL_WIN32_AV_RETRY: {
  33520. int *a = (int*)pArg;
  33521. if( a[0]>0 ){
  33522. winIoerrRetry = a[0];
  33523. }else{
  33524. a[0] = winIoerrRetry;
  33525. }
  33526. if( a[1]>0 ){
  33527. winIoerrRetryDelay = a[1];
  33528. }else{
  33529. a[1] = winIoerrRetryDelay;
  33530. }
  33531. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  33532. return SQLITE_OK;
  33533. }
  33534. #ifdef SQLITE_TEST
  33535. case SQLITE_FCNTL_WIN32_SET_HANDLE: {
  33536. LPHANDLE phFile = (LPHANDLE)pArg;
  33537. HANDLE hOldFile = pFile->h;
  33538. pFile->h = *phFile;
  33539. *phFile = hOldFile;
  33540. OSTRACE(("FCNTL oldFile=%p, newFile=%p, rc=SQLITE_OK\n",
  33541. hOldFile, pFile->h));
  33542. return SQLITE_OK;
  33543. }
  33544. #endif
  33545. case SQLITE_FCNTL_TEMPFILENAME: {
  33546. char *zTFile = 0;
  33547. int rc = winGetTempname(pFile->pVfs, &zTFile);
  33548. if( rc==SQLITE_OK ){
  33549. *(char**)pArg = zTFile;
  33550. }
  33551. OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
  33552. return rc;
  33553. }
  33554. #if SQLITE_MAX_MMAP_SIZE>0
  33555. case SQLITE_FCNTL_MMAP_SIZE: {
  33556. i64 newLimit = *(i64*)pArg;
  33557. int rc = SQLITE_OK;
  33558. if( newLimit>sqlite3GlobalConfig.mxMmap ){
  33559. newLimit = sqlite3GlobalConfig.mxMmap;
  33560. }
  33561. *(i64*)pArg = pFile->mmapSizeMax;
  33562. if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
  33563. pFile->mmapSizeMax = newLimit;
  33564. if( pFile->mmapSize>0 ){
  33565. winUnmapfile(pFile);
  33566. rc = winMapfile(pFile, -1);
  33567. }
  33568. }
  33569. OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
  33570. return rc;
  33571. }
  33572. #endif
  33573. }
  33574. OSTRACE(("FCNTL file=%p, rc=SQLITE_NOTFOUND\n", pFile->h));
  33575. return SQLITE_NOTFOUND;
  33576. }
  33577. /*
  33578. ** Return the sector size in bytes of the underlying block device for
  33579. ** the specified file. This is almost always 512 bytes, but may be
  33580. ** larger for some devices.
  33581. **
  33582. ** SQLite code assumes this function cannot fail. It also assumes that
  33583. ** if two files are created in the same file-system directory (i.e.
  33584. ** a database and its journal file) that the sector size will be the
  33585. ** same for both.
  33586. */
  33587. static int winSectorSize(sqlite3_file *id){
  33588. (void)id;
  33589. return SQLITE_DEFAULT_SECTOR_SIZE;
  33590. }
  33591. /*
  33592. ** Return a vector of device characteristics.
  33593. */
  33594. static int winDeviceCharacteristics(sqlite3_file *id){
  33595. winFile *p = (winFile*)id;
  33596. return SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN |
  33597. ((p->ctrlFlags & WINFILE_PSOW)?SQLITE_IOCAP_POWERSAFE_OVERWRITE:0);
  33598. }
  33599. /*
  33600. ** Windows will only let you create file view mappings
  33601. ** on allocation size granularity boundaries.
  33602. ** During sqlite3_os_init() we do a GetSystemInfo()
  33603. ** to get the granularity size.
  33604. */
  33605. static SYSTEM_INFO winSysInfo;
  33606. #ifndef SQLITE_OMIT_WAL
  33607. /*
  33608. ** Helper functions to obtain and relinquish the global mutex. The
  33609. ** global mutex is used to protect the winLockInfo objects used by
  33610. ** this file, all of which may be shared by multiple threads.
  33611. **
  33612. ** Function winShmMutexHeld() is used to assert() that the global mutex
  33613. ** is held when required. This function is only used as part of assert()
  33614. ** statements. e.g.
  33615. **
  33616. ** winShmEnterMutex()
  33617. ** assert( winShmMutexHeld() );
  33618. ** winShmLeaveMutex()
  33619. */
  33620. static void winShmEnterMutex(void){
  33621. sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  33622. }
  33623. static void winShmLeaveMutex(void){
  33624. sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  33625. }
  33626. #ifndef NDEBUG
  33627. static int winShmMutexHeld(void) {
  33628. return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  33629. }
  33630. #endif
  33631. /*
  33632. ** Object used to represent a single file opened and mmapped to provide
  33633. ** shared memory. When multiple threads all reference the same
  33634. ** log-summary, each thread has its own winFile object, but they all
  33635. ** point to a single instance of this object. In other words, each
  33636. ** log-summary is opened only once per process.
  33637. **
  33638. ** winShmMutexHeld() must be true when creating or destroying
  33639. ** this object or while reading or writing the following fields:
  33640. **
  33641. ** nRef
  33642. ** pNext
  33643. **
  33644. ** The following fields are read-only after the object is created:
  33645. **
  33646. ** fid
  33647. ** zFilename
  33648. **
  33649. ** Either winShmNode.mutex must be held or winShmNode.nRef==0 and
  33650. ** winShmMutexHeld() is true when reading or writing any other field
  33651. ** in this structure.
  33652. **
  33653. */
  33654. struct winShmNode {
  33655. sqlite3_mutex *mutex; /* Mutex to access this object */
  33656. char *zFilename; /* Name of the file */
  33657. winFile hFile; /* File handle from winOpen */
  33658. int szRegion; /* Size of shared-memory regions */
  33659. int nRegion; /* Size of array apRegion */
  33660. struct ShmRegion {
  33661. HANDLE hMap; /* File handle from CreateFileMapping */
  33662. void *pMap;
  33663. } *aRegion;
  33664. DWORD lastErrno; /* The Windows errno from the last I/O error */
  33665. int nRef; /* Number of winShm objects pointing to this */
  33666. winShm *pFirst; /* All winShm objects pointing to this */
  33667. winShmNode *pNext; /* Next in list of all winShmNode objects */
  33668. #ifdef SQLITE_DEBUG
  33669. u8 nextShmId; /* Next available winShm.id value */
  33670. #endif
  33671. };
  33672. /*
  33673. ** A global array of all winShmNode objects.
  33674. **
  33675. ** The winShmMutexHeld() must be true while reading or writing this list.
  33676. */
  33677. static winShmNode *winShmNodeList = 0;
  33678. /*
  33679. ** Structure used internally by this VFS to record the state of an
  33680. ** open shared memory connection.
  33681. **
  33682. ** The following fields are initialized when this object is created and
  33683. ** are read-only thereafter:
  33684. **
  33685. ** winShm.pShmNode
  33686. ** winShm.id
  33687. **
  33688. ** All other fields are read/write. The winShm.pShmNode->mutex must be held
  33689. ** while accessing any read/write fields.
  33690. */
  33691. struct winShm {
  33692. winShmNode *pShmNode; /* The underlying winShmNode object */
  33693. winShm *pNext; /* Next winShm with the same winShmNode */
  33694. u8 hasMutex; /* True if holding the winShmNode mutex */
  33695. u16 sharedMask; /* Mask of shared locks held */
  33696. u16 exclMask; /* Mask of exclusive locks held */
  33697. #ifdef SQLITE_DEBUG
  33698. u8 id; /* Id of this connection with its winShmNode */
  33699. #endif
  33700. };
  33701. /*
  33702. ** Constants used for locking
  33703. */
  33704. #define WIN_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
  33705. #define WIN_SHM_DMS (WIN_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
  33706. /*
  33707. ** Apply advisory locks for all n bytes beginning at ofst.
  33708. */
  33709. #define _SHM_UNLCK 1
  33710. #define _SHM_RDLCK 2
  33711. #define _SHM_WRLCK 3
  33712. static int winShmSystemLock(
  33713. winShmNode *pFile, /* Apply locks to this open shared-memory segment */
  33714. int lockType, /* _SHM_UNLCK, _SHM_RDLCK, or _SHM_WRLCK */
  33715. int ofst, /* Offset to first byte to be locked/unlocked */
  33716. int nByte /* Number of bytes to lock or unlock */
  33717. ){
  33718. int rc = 0; /* Result code form Lock/UnlockFileEx() */
  33719. /* Access to the winShmNode object is serialized by the caller */
  33720. assert( sqlite3_mutex_held(pFile->mutex) || pFile->nRef==0 );
  33721. OSTRACE(("SHM-LOCK file=%p, lock=%d, offset=%d, size=%d\n",
  33722. pFile->hFile.h, lockType, ofst, nByte));
  33723. /* Release/Acquire the system-level lock */
  33724. if( lockType==_SHM_UNLCK ){
  33725. rc = winUnlockFile(&pFile->hFile.h, ofst, 0, nByte, 0);
  33726. }else{
  33727. /* Initialize the locking parameters */
  33728. DWORD dwFlags = LOCKFILE_FAIL_IMMEDIATELY;
  33729. if( lockType == _SHM_WRLCK ) dwFlags |= LOCKFILE_EXCLUSIVE_LOCK;
  33730. rc = winLockFile(&pFile->hFile.h, dwFlags, ofst, 0, nByte, 0);
  33731. }
  33732. if( rc!= 0 ){
  33733. rc = SQLITE_OK;
  33734. }else{
  33735. pFile->lastErrno = osGetLastError();
  33736. rc = SQLITE_BUSY;
  33737. }
  33738. OSTRACE(("SHM-LOCK file=%p, func=%s, errno=%lu, rc=%s\n",
  33739. pFile->hFile.h, (lockType == _SHM_UNLCK) ? "winUnlockFile" :
  33740. "winLockFile", pFile->lastErrno, sqlite3ErrName(rc)));
  33741. return rc;
  33742. }
  33743. /* Forward references to VFS methods */
  33744. static int winOpen(sqlite3_vfs*,const char*,sqlite3_file*,int,int*);
  33745. static int winDelete(sqlite3_vfs *,const char*,int);
  33746. /*
  33747. ** Purge the winShmNodeList list of all entries with winShmNode.nRef==0.
  33748. **
  33749. ** This is not a VFS shared-memory method; it is a utility function called
  33750. ** by VFS shared-memory methods.
  33751. */
  33752. static void winShmPurge(sqlite3_vfs *pVfs, int deleteFlag){
  33753. winShmNode **pp;
  33754. winShmNode *p;
  33755. assert( winShmMutexHeld() );
  33756. OSTRACE(("SHM-PURGE pid=%lu, deleteFlag=%d\n",
  33757. osGetCurrentProcessId(), deleteFlag));
  33758. pp = &winShmNodeList;
  33759. while( (p = *pp)!=0 ){
  33760. if( p->nRef==0 ){
  33761. int i;
  33762. if( p->mutex ){ sqlite3_mutex_free(p->mutex); }
  33763. for(i=0; i<p->nRegion; i++){
  33764. BOOL bRc = osUnmapViewOfFile(p->aRegion[i].pMap);
  33765. OSTRACE(("SHM-PURGE-UNMAP pid=%lu, region=%d, rc=%s\n",
  33766. osGetCurrentProcessId(), i, bRc ? "ok" : "failed"));
  33767. UNUSED_VARIABLE_VALUE(bRc);
  33768. bRc = osCloseHandle(p->aRegion[i].hMap);
  33769. OSTRACE(("SHM-PURGE-CLOSE pid=%lu, region=%d, rc=%s\n",
  33770. osGetCurrentProcessId(), i, bRc ? "ok" : "failed"));
  33771. UNUSED_VARIABLE_VALUE(bRc);
  33772. }
  33773. if( p->hFile.h!=NULL && p->hFile.h!=INVALID_HANDLE_VALUE ){
  33774. SimulateIOErrorBenign(1);
  33775. winClose((sqlite3_file *)&p->hFile);
  33776. SimulateIOErrorBenign(0);
  33777. }
  33778. if( deleteFlag ){
  33779. SimulateIOErrorBenign(1);
  33780. sqlite3BeginBenignMalloc();
  33781. winDelete(pVfs, p->zFilename, 0);
  33782. sqlite3EndBenignMalloc();
  33783. SimulateIOErrorBenign(0);
  33784. }
  33785. *pp = p->pNext;
  33786. sqlite3_free(p->aRegion);
  33787. sqlite3_free(p);
  33788. }else{
  33789. pp = &p->pNext;
  33790. }
  33791. }
  33792. }
  33793. /*
  33794. ** Open the shared-memory area associated with database file pDbFd.
  33795. **
  33796. ** When opening a new shared-memory file, if no other instances of that
  33797. ** file are currently open, in this process or in other processes, then
  33798. ** the file must be truncated to zero length or have its header cleared.
  33799. */
  33800. static int winOpenSharedMemory(winFile *pDbFd){
  33801. struct winShm *p; /* The connection to be opened */
  33802. struct winShmNode *pShmNode = 0; /* The underlying mmapped file */
  33803. int rc; /* Result code */
  33804. struct winShmNode *pNew; /* Newly allocated winShmNode */
  33805. int nName; /* Size of zName in bytes */
  33806. assert( pDbFd->pShm==0 ); /* Not previously opened */
  33807. /* Allocate space for the new sqlite3_shm object. Also speculatively
  33808. ** allocate space for a new winShmNode and filename.
  33809. */
  33810. p = sqlite3MallocZero( sizeof(*p) );
  33811. if( p==0 ) return SQLITE_IOERR_NOMEM;
  33812. nName = sqlite3Strlen30(pDbFd->zPath);
  33813. pNew = sqlite3MallocZero( sizeof(*pShmNode) + nName + 17 );
  33814. if( pNew==0 ){
  33815. sqlite3_free(p);
  33816. return SQLITE_IOERR_NOMEM;
  33817. }
  33818. pNew->zFilename = (char*)&pNew[1];
  33819. sqlite3_snprintf(nName+15, pNew->zFilename, "%s-shm", pDbFd->zPath);
  33820. sqlite3FileSuffix3(pDbFd->zPath, pNew->zFilename);
  33821. /* Look to see if there is an existing winShmNode that can be used.
  33822. ** If no matching winShmNode currently exists, create a new one.
  33823. */
  33824. winShmEnterMutex();
  33825. for(pShmNode = winShmNodeList; pShmNode; pShmNode=pShmNode->pNext){
  33826. /* TBD need to come up with better match here. Perhaps
  33827. ** use FILE_ID_BOTH_DIR_INFO Structure.
  33828. */
  33829. if( sqlite3StrICmp(pShmNode->zFilename, pNew->zFilename)==0 ) break;
  33830. }
  33831. if( pShmNode ){
  33832. sqlite3_free(pNew);
  33833. }else{
  33834. pShmNode = pNew;
  33835. pNew = 0;
  33836. ((winFile*)(&pShmNode->hFile))->h = INVALID_HANDLE_VALUE;
  33837. pShmNode->pNext = winShmNodeList;
  33838. winShmNodeList = pShmNode;
  33839. pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
  33840. if( pShmNode->mutex==0 ){
  33841. rc = SQLITE_IOERR_NOMEM;
  33842. goto shm_open_err;
  33843. }
  33844. rc = winOpen(pDbFd->pVfs,
  33845. pShmNode->zFilename, /* Name of the file (UTF-8) */
  33846. (sqlite3_file*)&pShmNode->hFile, /* File handle here */
  33847. SQLITE_OPEN_WAL | SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE,
  33848. 0);
  33849. if( SQLITE_OK!=rc ){
  33850. goto shm_open_err;
  33851. }
  33852. /* Check to see if another process is holding the dead-man switch.
  33853. ** If not, truncate the file to zero length.
  33854. */
  33855. if( winShmSystemLock(pShmNode, _SHM_WRLCK, WIN_SHM_DMS, 1)==SQLITE_OK ){
  33856. rc = winTruncate((sqlite3_file *)&pShmNode->hFile, 0);
  33857. if( rc!=SQLITE_OK ){
  33858. rc = winLogError(SQLITE_IOERR_SHMOPEN, osGetLastError(),
  33859. "winOpenShm", pDbFd->zPath);
  33860. }
  33861. }
  33862. if( rc==SQLITE_OK ){
  33863. winShmSystemLock(pShmNode, _SHM_UNLCK, WIN_SHM_DMS, 1);
  33864. rc = winShmSystemLock(pShmNode, _SHM_RDLCK, WIN_SHM_DMS, 1);
  33865. }
  33866. if( rc ) goto shm_open_err;
  33867. }
  33868. /* Make the new connection a child of the winShmNode */
  33869. p->pShmNode = pShmNode;
  33870. #ifdef SQLITE_DEBUG
  33871. p->id = pShmNode->nextShmId++;
  33872. #endif
  33873. pShmNode->nRef++;
  33874. pDbFd->pShm = p;
  33875. winShmLeaveMutex();
  33876. /* The reference count on pShmNode has already been incremented under
  33877. ** the cover of the winShmEnterMutex() mutex and the pointer from the
  33878. ** new (struct winShm) object to the pShmNode has been set. All that is
  33879. ** left to do is to link the new object into the linked list starting
  33880. ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
  33881. ** mutex.
  33882. */
  33883. sqlite3_mutex_enter(pShmNode->mutex);
  33884. p->pNext = pShmNode->pFirst;
  33885. pShmNode->pFirst = p;
  33886. sqlite3_mutex_leave(pShmNode->mutex);
  33887. return SQLITE_OK;
  33888. /* Jump here on any error */
  33889. shm_open_err:
  33890. winShmSystemLock(pShmNode, _SHM_UNLCK, WIN_SHM_DMS, 1);
  33891. winShmPurge(pDbFd->pVfs, 0); /* This call frees pShmNode if required */
  33892. sqlite3_free(p);
  33893. sqlite3_free(pNew);
  33894. winShmLeaveMutex();
  33895. return rc;
  33896. }
  33897. /*
  33898. ** Close a connection to shared-memory. Delete the underlying
  33899. ** storage if deleteFlag is true.
  33900. */
  33901. static int winShmUnmap(
  33902. sqlite3_file *fd, /* Database holding shared memory */
  33903. int deleteFlag /* Delete after closing if true */
  33904. ){
  33905. winFile *pDbFd; /* Database holding shared-memory */
  33906. winShm *p; /* The connection to be closed */
  33907. winShmNode *pShmNode; /* The underlying shared-memory file */
  33908. winShm **pp; /* For looping over sibling connections */
  33909. pDbFd = (winFile*)fd;
  33910. p = pDbFd->pShm;
  33911. if( p==0 ) return SQLITE_OK;
  33912. pShmNode = p->pShmNode;
  33913. /* Remove connection p from the set of connections associated
  33914. ** with pShmNode */
  33915. sqlite3_mutex_enter(pShmNode->mutex);
  33916. for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
  33917. *pp = p->pNext;
  33918. /* Free the connection p */
  33919. sqlite3_free(p);
  33920. pDbFd->pShm = 0;
  33921. sqlite3_mutex_leave(pShmNode->mutex);
  33922. /* If pShmNode->nRef has reached 0, then close the underlying
  33923. ** shared-memory file, too */
  33924. winShmEnterMutex();
  33925. assert( pShmNode->nRef>0 );
  33926. pShmNode->nRef--;
  33927. if( pShmNode->nRef==0 ){
  33928. winShmPurge(pDbFd->pVfs, deleteFlag);
  33929. }
  33930. winShmLeaveMutex();
  33931. return SQLITE_OK;
  33932. }
  33933. /*
  33934. ** Change the lock state for a shared-memory segment.
  33935. */
  33936. static int winShmLock(
  33937. sqlite3_file *fd, /* Database file holding the shared memory */
  33938. int ofst, /* First lock to acquire or release */
  33939. int n, /* Number of locks to acquire or release */
  33940. int flags /* What to do with the lock */
  33941. ){
  33942. winFile *pDbFd = (winFile*)fd; /* Connection holding shared memory */
  33943. winShm *p = pDbFd->pShm; /* The shared memory being locked */
  33944. winShm *pX; /* For looping over all siblings */
  33945. winShmNode *pShmNode = p->pShmNode;
  33946. int rc = SQLITE_OK; /* Result code */
  33947. u16 mask; /* Mask of locks to take or release */
  33948. assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
  33949. assert( n>=1 );
  33950. assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
  33951. || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
  33952. || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
  33953. || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
  33954. assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
  33955. mask = (u16)((1U<<(ofst+n)) - (1U<<ofst));
  33956. assert( n>1 || mask==(1<<ofst) );
  33957. sqlite3_mutex_enter(pShmNode->mutex);
  33958. if( flags & SQLITE_SHM_UNLOCK ){
  33959. u16 allMask = 0; /* Mask of locks held by siblings */
  33960. /* See if any siblings hold this same lock */
  33961. for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
  33962. if( pX==p ) continue;
  33963. assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
  33964. allMask |= pX->sharedMask;
  33965. }
  33966. /* Unlock the system-level locks */
  33967. if( (mask & allMask)==0 ){
  33968. rc = winShmSystemLock(pShmNode, _SHM_UNLCK, ofst+WIN_SHM_BASE, n);
  33969. }else{
  33970. rc = SQLITE_OK;
  33971. }
  33972. /* Undo the local locks */
  33973. if( rc==SQLITE_OK ){
  33974. p->exclMask &= ~mask;
  33975. p->sharedMask &= ~mask;
  33976. }
  33977. }else if( flags & SQLITE_SHM_SHARED ){
  33978. u16 allShared = 0; /* Union of locks held by connections other than "p" */
  33979. /* Find out which shared locks are already held by sibling connections.
  33980. ** If any sibling already holds an exclusive lock, go ahead and return
  33981. ** SQLITE_BUSY.
  33982. */
  33983. for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
  33984. if( (pX->exclMask & mask)!=0 ){
  33985. rc = SQLITE_BUSY;
  33986. break;
  33987. }
  33988. allShared |= pX->sharedMask;
  33989. }
  33990. /* Get shared locks at the system level, if necessary */
  33991. if( rc==SQLITE_OK ){
  33992. if( (allShared & mask)==0 ){
  33993. rc = winShmSystemLock(pShmNode, _SHM_RDLCK, ofst+WIN_SHM_BASE, n);
  33994. }else{
  33995. rc = SQLITE_OK;
  33996. }
  33997. }
  33998. /* Get the local shared locks */
  33999. if( rc==SQLITE_OK ){
  34000. p->sharedMask |= mask;
  34001. }
  34002. }else{
  34003. /* Make sure no sibling connections hold locks that will block this
  34004. ** lock. If any do, return SQLITE_BUSY right away.
  34005. */
  34006. for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
  34007. if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
  34008. rc = SQLITE_BUSY;
  34009. break;
  34010. }
  34011. }
  34012. /* Get the exclusive locks at the system level. Then if successful
  34013. ** also mark the local connection as being locked.
  34014. */
  34015. if( rc==SQLITE_OK ){
  34016. rc = winShmSystemLock(pShmNode, _SHM_WRLCK, ofst+WIN_SHM_BASE, n);
  34017. if( rc==SQLITE_OK ){
  34018. assert( (p->sharedMask & mask)==0 );
  34019. p->exclMask |= mask;
  34020. }
  34021. }
  34022. }
  34023. sqlite3_mutex_leave(pShmNode->mutex);
  34024. OSTRACE(("SHM-LOCK pid=%lu, id=%d, sharedMask=%03x, exclMask=%03x, rc=%s\n",
  34025. osGetCurrentProcessId(), p->id, p->sharedMask, p->exclMask,
  34026. sqlite3ErrName(rc)));
  34027. return rc;
  34028. }
  34029. /*
  34030. ** Implement a memory barrier or memory fence on shared memory.
  34031. **
  34032. ** All loads and stores begun before the barrier must complete before
  34033. ** any load or store begun after the barrier.
  34034. */
  34035. static void winShmBarrier(
  34036. sqlite3_file *fd /* Database holding the shared memory */
  34037. ){
  34038. UNUSED_PARAMETER(fd);
  34039. /* MemoryBarrier(); // does not work -- do not know why not */
  34040. winShmEnterMutex();
  34041. winShmLeaveMutex();
  34042. }
  34043. /*
  34044. ** This function is called to obtain a pointer to region iRegion of the
  34045. ** shared-memory associated with the database file fd. Shared-memory regions
  34046. ** are numbered starting from zero. Each shared-memory region is szRegion
  34047. ** bytes in size.
  34048. **
  34049. ** If an error occurs, an error code is returned and *pp is set to NULL.
  34050. **
  34051. ** Otherwise, if the isWrite parameter is 0 and the requested shared-memory
  34052. ** region has not been allocated (by any client, including one running in a
  34053. ** separate process), then *pp is set to NULL and SQLITE_OK returned. If
  34054. ** isWrite is non-zero and the requested shared-memory region has not yet
  34055. ** been allocated, it is allocated by this function.
  34056. **
  34057. ** If the shared-memory region has already been allocated or is allocated by
  34058. ** this call as described above, then it is mapped into this processes
  34059. ** address space (if it is not already), *pp is set to point to the mapped
  34060. ** memory and SQLITE_OK returned.
  34061. */
  34062. static int winShmMap(
  34063. sqlite3_file *fd, /* Handle open on database file */
  34064. int iRegion, /* Region to retrieve */
  34065. int szRegion, /* Size of regions */
  34066. int isWrite, /* True to extend file if necessary */
  34067. void volatile **pp /* OUT: Mapped memory */
  34068. ){
  34069. winFile *pDbFd = (winFile*)fd;
  34070. winShm *p = pDbFd->pShm;
  34071. winShmNode *pShmNode;
  34072. int rc = SQLITE_OK;
  34073. if( !p ){
  34074. rc = winOpenSharedMemory(pDbFd);
  34075. if( rc!=SQLITE_OK ) return rc;
  34076. p = pDbFd->pShm;
  34077. }
  34078. pShmNode = p->pShmNode;
  34079. sqlite3_mutex_enter(pShmNode->mutex);
  34080. assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
  34081. if( pShmNode->nRegion<=iRegion ){
  34082. struct ShmRegion *apNew; /* New aRegion[] array */
  34083. int nByte = (iRegion+1)*szRegion; /* Minimum required file size */
  34084. sqlite3_int64 sz; /* Current size of wal-index file */
  34085. pShmNode->szRegion = szRegion;
  34086. /* The requested region is not mapped into this processes address space.
  34087. ** Check to see if it has been allocated (i.e. if the wal-index file is
  34088. ** large enough to contain the requested region).
  34089. */
  34090. rc = winFileSize((sqlite3_file *)&pShmNode->hFile, &sz);
  34091. if( rc!=SQLITE_OK ){
  34092. rc = winLogError(SQLITE_IOERR_SHMSIZE, osGetLastError(),
  34093. "winShmMap1", pDbFd->zPath);
  34094. goto shmpage_out;
  34095. }
  34096. if( sz<nByte ){
  34097. /* The requested memory region does not exist. If isWrite is set to
  34098. ** zero, exit early. *pp will be set to NULL and SQLITE_OK returned.
  34099. **
  34100. ** Alternatively, if isWrite is non-zero, use ftruncate() to allocate
  34101. ** the requested memory region.
  34102. */
  34103. if( !isWrite ) goto shmpage_out;
  34104. rc = winTruncate((sqlite3_file *)&pShmNode->hFile, nByte);
  34105. if( rc!=SQLITE_OK ){
  34106. rc = winLogError(SQLITE_IOERR_SHMSIZE, osGetLastError(),
  34107. "winShmMap2", pDbFd->zPath);
  34108. goto shmpage_out;
  34109. }
  34110. }
  34111. /* Map the requested memory region into this processes address space. */
  34112. apNew = (struct ShmRegion *)sqlite3_realloc(
  34113. pShmNode->aRegion, (iRegion+1)*sizeof(apNew[0])
  34114. );
  34115. if( !apNew ){
  34116. rc = SQLITE_IOERR_NOMEM;
  34117. goto shmpage_out;
  34118. }
  34119. pShmNode->aRegion = apNew;
  34120. while( pShmNode->nRegion<=iRegion ){
  34121. HANDLE hMap = NULL; /* file-mapping handle */
  34122. void *pMap = 0; /* Mapped memory region */
  34123. #if SQLITE_OS_WINRT
  34124. hMap = osCreateFileMappingFromApp(pShmNode->hFile.h,
  34125. NULL, PAGE_READWRITE, nByte, NULL
  34126. );
  34127. #elif defined(SQLITE_WIN32_HAS_WIDE)
  34128. hMap = osCreateFileMappingW(pShmNode->hFile.h,
  34129. NULL, PAGE_READWRITE, 0, nByte, NULL
  34130. );
  34131. #elif defined(SQLITE_WIN32_HAS_ANSI)
  34132. hMap = osCreateFileMappingA(pShmNode->hFile.h,
  34133. NULL, PAGE_READWRITE, 0, nByte, NULL
  34134. );
  34135. #endif
  34136. OSTRACE(("SHM-MAP-CREATE pid=%lu, region=%d, size=%d, rc=%s\n",
  34137. osGetCurrentProcessId(), pShmNode->nRegion, nByte,
  34138. hMap ? "ok" : "failed"));
  34139. if( hMap ){
  34140. int iOffset = pShmNode->nRegion*szRegion;
  34141. int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
  34142. #if SQLITE_OS_WINRT
  34143. pMap = osMapViewOfFileFromApp(hMap, FILE_MAP_WRITE | FILE_MAP_READ,
  34144. iOffset - iOffsetShift, szRegion + iOffsetShift
  34145. );
  34146. #else
  34147. pMap = osMapViewOfFile(hMap, FILE_MAP_WRITE | FILE_MAP_READ,
  34148. 0, iOffset - iOffsetShift, szRegion + iOffsetShift
  34149. );
  34150. #endif
  34151. OSTRACE(("SHM-MAP-MAP pid=%lu, region=%d, offset=%d, size=%d, rc=%s\n",
  34152. osGetCurrentProcessId(), pShmNode->nRegion, iOffset,
  34153. szRegion, pMap ? "ok" : "failed"));
  34154. }
  34155. if( !pMap ){
  34156. pShmNode->lastErrno = osGetLastError();
  34157. rc = winLogError(SQLITE_IOERR_SHMMAP, pShmNode->lastErrno,
  34158. "winShmMap3", pDbFd->zPath);
  34159. if( hMap ) osCloseHandle(hMap);
  34160. goto shmpage_out;
  34161. }
  34162. pShmNode->aRegion[pShmNode->nRegion].pMap = pMap;
  34163. pShmNode->aRegion[pShmNode->nRegion].hMap = hMap;
  34164. pShmNode->nRegion++;
  34165. }
  34166. }
  34167. shmpage_out:
  34168. if( pShmNode->nRegion>iRegion ){
  34169. int iOffset = iRegion*szRegion;
  34170. int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
  34171. char *p = (char *)pShmNode->aRegion[iRegion].pMap;
  34172. *pp = (void *)&p[iOffsetShift];
  34173. }else{
  34174. *pp = 0;
  34175. }
  34176. sqlite3_mutex_leave(pShmNode->mutex);
  34177. return rc;
  34178. }
  34179. #else
  34180. # define winShmMap 0
  34181. # define winShmLock 0
  34182. # define winShmBarrier 0
  34183. # define winShmUnmap 0
  34184. #endif /* #ifndef SQLITE_OMIT_WAL */
  34185. /*
  34186. ** Cleans up the mapped region of the specified file, if any.
  34187. */
  34188. #if SQLITE_MAX_MMAP_SIZE>0
  34189. static int winUnmapfile(winFile *pFile){
  34190. assert( pFile!=0 );
  34191. OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, hMap=%p, pMapRegion=%p, "
  34192. "mmapSize=%lld, mmapSizeActual=%lld, mmapSizeMax=%lld\n",
  34193. osGetCurrentProcessId(), pFile, pFile->hMap, pFile->pMapRegion,
  34194. pFile->mmapSize, pFile->mmapSizeActual, pFile->mmapSizeMax));
  34195. if( pFile->pMapRegion ){
  34196. if( !osUnmapViewOfFile(pFile->pMapRegion) ){
  34197. pFile->lastErrno = osGetLastError();
  34198. OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, pMapRegion=%p, "
  34199. "rc=SQLITE_IOERR_MMAP\n", osGetCurrentProcessId(), pFile,
  34200. pFile->pMapRegion));
  34201. return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno,
  34202. "winUnmapfile1", pFile->zPath);
  34203. }
  34204. pFile->pMapRegion = 0;
  34205. pFile->mmapSize = 0;
  34206. pFile->mmapSizeActual = 0;
  34207. }
  34208. if( pFile->hMap!=NULL ){
  34209. if( !osCloseHandle(pFile->hMap) ){
  34210. pFile->lastErrno = osGetLastError();
  34211. OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, hMap=%p, rc=SQLITE_IOERR_MMAP\n",
  34212. osGetCurrentProcessId(), pFile, pFile->hMap));
  34213. return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno,
  34214. "winUnmapfile2", pFile->zPath);
  34215. }
  34216. pFile->hMap = NULL;
  34217. }
  34218. OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, rc=SQLITE_OK\n",
  34219. osGetCurrentProcessId(), pFile));
  34220. return SQLITE_OK;
  34221. }
  34222. /*
  34223. ** Memory map or remap the file opened by file-descriptor pFd (if the file
  34224. ** is already mapped, the existing mapping is replaced by the new). Or, if
  34225. ** there already exists a mapping for this file, and there are still
  34226. ** outstanding xFetch() references to it, this function is a no-op.
  34227. **
  34228. ** If parameter nByte is non-negative, then it is the requested size of
  34229. ** the mapping to create. Otherwise, if nByte is less than zero, then the
  34230. ** requested size is the size of the file on disk. The actual size of the
  34231. ** created mapping is either the requested size or the value configured
  34232. ** using SQLITE_FCNTL_MMAP_SIZE, whichever is smaller.
  34233. **
  34234. ** SQLITE_OK is returned if no error occurs (even if the mapping is not
  34235. ** recreated as a result of outstanding references) or an SQLite error
  34236. ** code otherwise.
  34237. */
  34238. static int winMapfile(winFile *pFd, sqlite3_int64 nByte){
  34239. sqlite3_int64 nMap = nByte;
  34240. int rc;
  34241. assert( nMap>=0 || pFd->nFetchOut==0 );
  34242. OSTRACE(("MAP-FILE pid=%lu, pFile=%p, size=%lld\n",
  34243. osGetCurrentProcessId(), pFd, nByte));
  34244. if( pFd->nFetchOut>0 ) return SQLITE_OK;
  34245. if( nMap<0 ){
  34246. rc = winFileSize((sqlite3_file*)pFd, &nMap);
  34247. if( rc ){
  34248. OSTRACE(("MAP-FILE pid=%lu, pFile=%p, rc=SQLITE_IOERR_FSTAT\n",
  34249. osGetCurrentProcessId(), pFd));
  34250. return SQLITE_IOERR_FSTAT;
  34251. }
  34252. }
  34253. if( nMap>pFd->mmapSizeMax ){
  34254. nMap = pFd->mmapSizeMax;
  34255. }
  34256. nMap &= ~(sqlite3_int64)(winSysInfo.dwPageSize - 1);
  34257. if( nMap==0 && pFd->mmapSize>0 ){
  34258. winUnmapfile(pFd);
  34259. }
  34260. if( nMap!=pFd->mmapSize ){
  34261. void *pNew = 0;
  34262. DWORD protect = PAGE_READONLY;
  34263. DWORD flags = FILE_MAP_READ;
  34264. winUnmapfile(pFd);
  34265. if( (pFd->ctrlFlags & WINFILE_RDONLY)==0 ){
  34266. protect = PAGE_READWRITE;
  34267. flags |= FILE_MAP_WRITE;
  34268. }
  34269. #if SQLITE_OS_WINRT
  34270. pFd->hMap = osCreateFileMappingFromApp(pFd->h, NULL, protect, nMap, NULL);
  34271. #elif defined(SQLITE_WIN32_HAS_WIDE)
  34272. pFd->hMap = osCreateFileMappingW(pFd->h, NULL, protect,
  34273. (DWORD)((nMap>>32) & 0xffffffff),
  34274. (DWORD)(nMap & 0xffffffff), NULL);
  34275. #elif defined(SQLITE_WIN32_HAS_ANSI)
  34276. pFd->hMap = osCreateFileMappingA(pFd->h, NULL, protect,
  34277. (DWORD)((nMap>>32) & 0xffffffff),
  34278. (DWORD)(nMap & 0xffffffff), NULL);
  34279. #endif
  34280. if( pFd->hMap==NULL ){
  34281. pFd->lastErrno = osGetLastError();
  34282. rc = winLogError(SQLITE_IOERR_MMAP, pFd->lastErrno,
  34283. "winMapfile1", pFd->zPath);
  34284. /* Log the error, but continue normal operation using xRead/xWrite */
  34285. OSTRACE(("MAP-FILE-CREATE pid=%lu, pFile=%p, rc=%s\n",
  34286. osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));
  34287. return SQLITE_OK;
  34288. }
  34289. assert( (nMap % winSysInfo.dwPageSize)==0 );
  34290. assert( sizeof(SIZE_T)==sizeof(sqlite3_int64) || nMap<=0xffffffff );
  34291. #if SQLITE_OS_WINRT
  34292. pNew = osMapViewOfFileFromApp(pFd->hMap, flags, 0, (SIZE_T)nMap);
  34293. #else
  34294. pNew = osMapViewOfFile(pFd->hMap, flags, 0, 0, (SIZE_T)nMap);
  34295. #endif
  34296. if( pNew==NULL ){
  34297. osCloseHandle(pFd->hMap);
  34298. pFd->hMap = NULL;
  34299. pFd->lastErrno = osGetLastError();
  34300. rc = winLogError(SQLITE_IOERR_MMAP, pFd->lastErrno,
  34301. "winMapfile2", pFd->zPath);
  34302. /* Log the error, but continue normal operation using xRead/xWrite */
  34303. OSTRACE(("MAP-FILE-MAP pid=%lu, pFile=%p, rc=%s\n",
  34304. osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));
  34305. return SQLITE_OK;
  34306. }
  34307. pFd->pMapRegion = pNew;
  34308. pFd->mmapSize = nMap;
  34309. pFd->mmapSizeActual = nMap;
  34310. }
  34311. OSTRACE(("MAP-FILE pid=%lu, pFile=%p, rc=SQLITE_OK\n",
  34312. osGetCurrentProcessId(), pFd));
  34313. return SQLITE_OK;
  34314. }
  34315. #endif /* SQLITE_MAX_MMAP_SIZE>0 */
  34316. /*
  34317. ** If possible, return a pointer to a mapping of file fd starting at offset
  34318. ** iOff. The mapping must be valid for at least nAmt bytes.
  34319. **
  34320. ** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
  34321. ** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
  34322. ** Finally, if an error does occur, return an SQLite error code. The final
  34323. ** value of *pp is undefined in this case.
  34324. **
  34325. ** If this function does return a pointer, the caller must eventually
  34326. ** release the reference by calling winUnfetch().
  34327. */
  34328. static int winFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
  34329. #if SQLITE_MAX_MMAP_SIZE>0
  34330. winFile *pFd = (winFile*)fd; /* The underlying database file */
  34331. #endif
  34332. *pp = 0;
  34333. OSTRACE(("FETCH pid=%lu, pFile=%p, offset=%lld, amount=%d, pp=%p\n",
  34334. osGetCurrentProcessId(), fd, iOff, nAmt, pp));
  34335. #if SQLITE_MAX_MMAP_SIZE>0
  34336. if( pFd->mmapSizeMax>0 ){
  34337. if( pFd->pMapRegion==0 ){
  34338. int rc = winMapfile(pFd, -1);
  34339. if( rc!=SQLITE_OK ){
  34340. OSTRACE(("FETCH pid=%lu, pFile=%p, rc=%s\n",
  34341. osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));
  34342. return rc;
  34343. }
  34344. }
  34345. if( pFd->mmapSize >= iOff+nAmt ){
  34346. *pp = &((u8 *)pFd->pMapRegion)[iOff];
  34347. pFd->nFetchOut++;
  34348. }
  34349. }
  34350. #endif
  34351. OSTRACE(("FETCH pid=%lu, pFile=%p, pp=%p, *pp=%p, rc=SQLITE_OK\n",
  34352. osGetCurrentProcessId(), fd, pp, *pp));
  34353. return SQLITE_OK;
  34354. }
  34355. /*
  34356. ** If the third argument is non-NULL, then this function releases a
  34357. ** reference obtained by an earlier call to winFetch(). The second
  34358. ** argument passed to this function must be the same as the corresponding
  34359. ** argument that was passed to the winFetch() invocation.
  34360. **
  34361. ** Or, if the third argument is NULL, then this function is being called
  34362. ** to inform the VFS layer that, according to POSIX, any existing mapping
  34363. ** may now be invalid and should be unmapped.
  34364. */
  34365. static int winUnfetch(sqlite3_file *fd, i64 iOff, void *p){
  34366. #if SQLITE_MAX_MMAP_SIZE>0
  34367. winFile *pFd = (winFile*)fd; /* The underlying database file */
  34368. /* If p==0 (unmap the entire file) then there must be no outstanding
  34369. ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
  34370. ** then there must be at least one outstanding. */
  34371. assert( (p==0)==(pFd->nFetchOut==0) );
  34372. /* If p!=0, it must match the iOff value. */
  34373. assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
  34374. OSTRACE(("UNFETCH pid=%lu, pFile=%p, offset=%lld, p=%p\n",
  34375. osGetCurrentProcessId(), pFd, iOff, p));
  34376. if( p ){
  34377. pFd->nFetchOut--;
  34378. }else{
  34379. /* FIXME: If Windows truly always prevents truncating or deleting a
  34380. ** file while a mapping is held, then the following winUnmapfile() call
  34381. ** is unnecessary can be omitted - potentially improving
  34382. ** performance. */
  34383. winUnmapfile(pFd);
  34384. }
  34385. assert( pFd->nFetchOut>=0 );
  34386. #endif
  34387. OSTRACE(("UNFETCH pid=%lu, pFile=%p, rc=SQLITE_OK\n",
  34388. osGetCurrentProcessId(), fd));
  34389. return SQLITE_OK;
  34390. }
  34391. /*
  34392. ** Here ends the implementation of all sqlite3_file methods.
  34393. **
  34394. ********************** End sqlite3_file Methods *******************************
  34395. ******************************************************************************/
  34396. /*
  34397. ** This vector defines all the methods that can operate on an
  34398. ** sqlite3_file for win32.
  34399. */
  34400. static const sqlite3_io_methods winIoMethod = {
  34401. 3, /* iVersion */
  34402. winClose, /* xClose */
  34403. winRead, /* xRead */
  34404. winWrite, /* xWrite */
  34405. winTruncate, /* xTruncate */
  34406. winSync, /* xSync */
  34407. winFileSize, /* xFileSize */
  34408. winLock, /* xLock */
  34409. winUnlock, /* xUnlock */
  34410. winCheckReservedLock, /* xCheckReservedLock */
  34411. winFileControl, /* xFileControl */
  34412. winSectorSize, /* xSectorSize */
  34413. winDeviceCharacteristics, /* xDeviceCharacteristics */
  34414. winShmMap, /* xShmMap */
  34415. winShmLock, /* xShmLock */
  34416. winShmBarrier, /* xShmBarrier */
  34417. winShmUnmap, /* xShmUnmap */
  34418. winFetch, /* xFetch */
  34419. winUnfetch /* xUnfetch */
  34420. };
  34421. /****************************************************************************
  34422. **************************** sqlite3_vfs methods ****************************
  34423. **
  34424. ** This division contains the implementation of methods on the
  34425. ** sqlite3_vfs object.
  34426. */
  34427. #if defined(__CYGWIN__)
  34428. /*
  34429. ** Convert a filename from whatever the underlying operating system
  34430. ** supports for filenames into UTF-8. Space to hold the result is
  34431. ** obtained from malloc and must be freed by the calling function.
  34432. */
  34433. static char *winConvertToUtf8Filename(const void *zFilename){
  34434. char *zConverted = 0;
  34435. if( osIsNT() ){
  34436. zConverted = winUnicodeToUtf8(zFilename);
  34437. }
  34438. #ifdef SQLITE_WIN32_HAS_ANSI
  34439. else{
  34440. zConverted = sqlite3_win32_mbcs_to_utf8(zFilename);
  34441. }
  34442. #endif
  34443. /* caller will handle out of memory */
  34444. return zConverted;
  34445. }
  34446. #endif
  34447. /*
  34448. ** Convert a UTF-8 filename into whatever form the underlying
  34449. ** operating system wants filenames in. Space to hold the result
  34450. ** is obtained from malloc and must be freed by the calling
  34451. ** function.
  34452. */
  34453. static void *winConvertFromUtf8Filename(const char *zFilename){
  34454. void *zConverted = 0;
  34455. if( osIsNT() ){
  34456. zConverted = winUtf8ToUnicode(zFilename);
  34457. }
  34458. #ifdef SQLITE_WIN32_HAS_ANSI
  34459. else{
  34460. zConverted = sqlite3_win32_utf8_to_mbcs(zFilename);
  34461. }
  34462. #endif
  34463. /* caller will handle out of memory */
  34464. return zConverted;
  34465. }
  34466. /*
  34467. ** This function returns non-zero if the specified UTF-8 string buffer
  34468. ** ends with a directory separator character or one was successfully
  34469. ** added to it.
  34470. */
  34471. static int winMakeEndInDirSep(int nBuf, char *zBuf){
  34472. if( zBuf ){
  34473. int nLen = sqlite3Strlen30(zBuf);
  34474. if( nLen>0 ){
  34475. if( winIsDirSep(zBuf[nLen-1]) ){
  34476. return 1;
  34477. }else if( nLen+1<nBuf ){
  34478. zBuf[nLen] = winGetDirSep();
  34479. zBuf[nLen+1] = '\0';
  34480. return 1;
  34481. }
  34482. }
  34483. }
  34484. return 0;
  34485. }
  34486. /*
  34487. ** Create a temporary file name and store the resulting pointer into pzBuf.
  34488. ** The pointer returned in pzBuf must be freed via sqlite3_free().
  34489. */
  34490. static int winGetTempname(sqlite3_vfs *pVfs, char **pzBuf){
  34491. static char zChars[] =
  34492. "abcdefghijklmnopqrstuvwxyz"
  34493. "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  34494. "0123456789";
  34495. size_t i, j;
  34496. int nPre = sqlite3Strlen30(SQLITE_TEMP_FILE_PREFIX);
  34497. int nMax, nBuf, nDir, nLen;
  34498. char *zBuf;
  34499. /* It's odd to simulate an io-error here, but really this is just
  34500. ** using the io-error infrastructure to test that SQLite handles this
  34501. ** function failing.
  34502. */
  34503. SimulateIOError( return SQLITE_IOERR );
  34504. /* Allocate a temporary buffer to store the fully qualified file
  34505. ** name for the temporary file. If this fails, we cannot continue.
  34506. */
  34507. nMax = pVfs->mxPathname; nBuf = nMax + 2;
  34508. zBuf = sqlite3MallocZero( nBuf );
  34509. if( !zBuf ){
  34510. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  34511. return SQLITE_IOERR_NOMEM;
  34512. }
  34513. /* Figure out the effective temporary directory. First, check if one
  34514. ** has been explicitly set by the application; otherwise, use the one
  34515. ** configured by the operating system.
  34516. */
  34517. nDir = nMax - (nPre + 15);
  34518. assert( nDir>0 );
  34519. if( sqlite3_temp_directory ){
  34520. int nDirLen = sqlite3Strlen30(sqlite3_temp_directory);
  34521. if( nDirLen>0 ){
  34522. if( !winIsDirSep(sqlite3_temp_directory[nDirLen-1]) ){
  34523. nDirLen++;
  34524. }
  34525. if( nDirLen>nDir ){
  34526. sqlite3_free(zBuf);
  34527. OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n"));
  34528. return winLogError(SQLITE_ERROR, 0, "winGetTempname1", 0);
  34529. }
  34530. sqlite3_snprintf(nMax, zBuf, "%s", sqlite3_temp_directory);
  34531. }
  34532. }
  34533. #if defined(__CYGWIN__)
  34534. else{
  34535. static const char *azDirs[] = {
  34536. 0, /* getenv("SQLITE_TMPDIR") */
  34537. 0, /* getenv("TMPDIR") */
  34538. 0, /* getenv("TMP") */
  34539. 0, /* getenv("TEMP") */
  34540. 0, /* getenv("USERPROFILE") */
  34541. "/var/tmp",
  34542. "/usr/tmp",
  34543. "/tmp",
  34544. ".",
  34545. 0 /* List terminator */
  34546. };
  34547. unsigned int i;
  34548. const char *zDir = 0;
  34549. if( !azDirs[0] ) azDirs[0] = getenv("SQLITE_TMPDIR");
  34550. if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
  34551. if( !azDirs[2] ) azDirs[2] = getenv("TMP");
  34552. if( !azDirs[3] ) azDirs[3] = getenv("TEMP");
  34553. if( !azDirs[4] ) azDirs[4] = getenv("USERPROFILE");
  34554. for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
  34555. void *zConverted;
  34556. if( zDir==0 ) continue;
  34557. /* If the path starts with a drive letter followed by the colon
  34558. ** character, assume it is already a native Win32 path; otherwise,
  34559. ** it must be converted to a native Win32 path via the Cygwin API
  34560. ** prior to using it.
  34561. */
  34562. if( winIsDriveLetterAndColon(zDir) ){
  34563. zConverted = winConvertFromUtf8Filename(zDir);
  34564. if( !zConverted ){
  34565. sqlite3_free(zBuf);
  34566. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  34567. return SQLITE_IOERR_NOMEM;
  34568. }
  34569. if( winIsDir(zConverted) ){
  34570. sqlite3_snprintf(nMax, zBuf, "%s", zDir);
  34571. sqlite3_free(zConverted);
  34572. break;
  34573. }
  34574. sqlite3_free(zConverted);
  34575. }else{
  34576. zConverted = sqlite3MallocZero( nMax+1 );
  34577. if( !zConverted ){
  34578. sqlite3_free(zBuf);
  34579. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  34580. return SQLITE_IOERR_NOMEM;
  34581. }
  34582. if( cygwin_conv_path(
  34583. osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A, zDir,
  34584. zConverted, nMax+1)<0 ){
  34585. sqlite3_free(zConverted);
  34586. sqlite3_free(zBuf);
  34587. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_CONVPATH\n"));
  34588. return winLogError(SQLITE_IOERR_CONVPATH, (DWORD)errno,
  34589. "winGetTempname2", zDir);
  34590. }
  34591. if( winIsDir(zConverted) ){
  34592. /* At this point, we know the candidate directory exists and should
  34593. ** be used. However, we may need to convert the string containing
  34594. ** its name into UTF-8 (i.e. if it is UTF-16 right now).
  34595. */
  34596. char *zUtf8 = winConvertToUtf8Filename(zConverted);
  34597. if( !zUtf8 ){
  34598. sqlite3_free(zConverted);
  34599. sqlite3_free(zBuf);
  34600. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  34601. return SQLITE_IOERR_NOMEM;
  34602. }
  34603. sqlite3_snprintf(nMax, zBuf, "%s", zUtf8);
  34604. sqlite3_free(zUtf8);
  34605. sqlite3_free(zConverted);
  34606. break;
  34607. }
  34608. sqlite3_free(zConverted);
  34609. }
  34610. }
  34611. }
  34612. #elif !SQLITE_OS_WINRT && !defined(__CYGWIN__)
  34613. else if( osIsNT() ){
  34614. char *zMulti;
  34615. LPWSTR zWidePath = sqlite3MallocZero( nMax*sizeof(WCHAR) );
  34616. if( !zWidePath ){
  34617. sqlite3_free(zBuf);
  34618. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  34619. return SQLITE_IOERR_NOMEM;
  34620. }
  34621. if( osGetTempPathW(nMax, zWidePath)==0 ){
  34622. sqlite3_free(zWidePath);
  34623. sqlite3_free(zBuf);
  34624. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_GETTEMPPATH\n"));
  34625. return winLogError(SQLITE_IOERR_GETTEMPPATH, osGetLastError(),
  34626. "winGetTempname2", 0);
  34627. }
  34628. zMulti = winUnicodeToUtf8(zWidePath);
  34629. if( zMulti ){
  34630. sqlite3_snprintf(nMax, zBuf, "%s", zMulti);
  34631. sqlite3_free(zMulti);
  34632. sqlite3_free(zWidePath);
  34633. }else{
  34634. sqlite3_free(zWidePath);
  34635. sqlite3_free(zBuf);
  34636. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  34637. return SQLITE_IOERR_NOMEM;
  34638. }
  34639. }
  34640. #ifdef SQLITE_WIN32_HAS_ANSI
  34641. else{
  34642. char *zUtf8;
  34643. char *zMbcsPath = sqlite3MallocZero( nMax );
  34644. if( !zMbcsPath ){
  34645. sqlite3_free(zBuf);
  34646. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  34647. return SQLITE_IOERR_NOMEM;
  34648. }
  34649. if( osGetTempPathA(nMax, zMbcsPath)==0 ){
  34650. sqlite3_free(zBuf);
  34651. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_GETTEMPPATH\n"));
  34652. return winLogError(SQLITE_IOERR_GETTEMPPATH, osGetLastError(),
  34653. "winGetTempname3", 0);
  34654. }
  34655. zUtf8 = sqlite3_win32_mbcs_to_utf8(zMbcsPath);
  34656. if( zUtf8 ){
  34657. sqlite3_snprintf(nMax, zBuf, "%s", zUtf8);
  34658. sqlite3_free(zUtf8);
  34659. }else{
  34660. sqlite3_free(zBuf);
  34661. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  34662. return SQLITE_IOERR_NOMEM;
  34663. }
  34664. }
  34665. #endif /* SQLITE_WIN32_HAS_ANSI */
  34666. #endif /* !SQLITE_OS_WINRT */
  34667. /*
  34668. ** Check to make sure the temporary directory ends with an appropriate
  34669. ** separator. If it does not and there is not enough space left to add
  34670. ** one, fail.
  34671. */
  34672. if( !winMakeEndInDirSep(nDir+1, zBuf) ){
  34673. sqlite3_free(zBuf);
  34674. OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n"));
  34675. return winLogError(SQLITE_ERROR, 0, "winGetTempname4", 0);
  34676. }
  34677. /*
  34678. ** Check that the output buffer is large enough for the temporary file
  34679. ** name in the following format:
  34680. **
  34681. ** "<temporary_directory>/etilqs_XXXXXXXXXXXXXXX\0\0"
  34682. **
  34683. ** If not, return SQLITE_ERROR. The number 17 is used here in order to
  34684. ** account for the space used by the 15 character random suffix and the
  34685. ** two trailing NUL characters. The final directory separator character
  34686. ** has already added if it was not already present.
  34687. */
  34688. nLen = sqlite3Strlen30(zBuf);
  34689. if( (nLen + nPre + 17) > nBuf ){
  34690. sqlite3_free(zBuf);
  34691. OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n"));
  34692. return winLogError(SQLITE_ERROR, 0, "winGetTempname5", 0);
  34693. }
  34694. sqlite3_snprintf(nBuf-16-nLen, zBuf+nLen, SQLITE_TEMP_FILE_PREFIX);
  34695. j = sqlite3Strlen30(zBuf);
  34696. sqlite3_randomness(15, &zBuf[j]);
  34697. for(i=0; i<15; i++, j++){
  34698. zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
  34699. }
  34700. zBuf[j] = 0;
  34701. zBuf[j+1] = 0;
  34702. *pzBuf = zBuf;
  34703. OSTRACE(("TEMP-FILENAME name=%s, rc=SQLITE_OK\n", zBuf));
  34704. return SQLITE_OK;
  34705. }
  34706. /*
  34707. ** Return TRUE if the named file is really a directory. Return false if
  34708. ** it is something other than a directory, or if there is any kind of memory
  34709. ** allocation failure.
  34710. */
  34711. static int winIsDir(const void *zConverted){
  34712. DWORD attr;
  34713. int rc = 0;
  34714. DWORD lastErrno;
  34715. if( osIsNT() ){
  34716. int cnt = 0;
  34717. WIN32_FILE_ATTRIBUTE_DATA sAttrData;
  34718. memset(&sAttrData, 0, sizeof(sAttrData));
  34719. while( !(rc = osGetFileAttributesExW((LPCWSTR)zConverted,
  34720. GetFileExInfoStandard,
  34721. &sAttrData)) && winRetryIoerr(&cnt, &lastErrno) ){}
  34722. if( !rc ){
  34723. return 0; /* Invalid name? */
  34724. }
  34725. attr = sAttrData.dwFileAttributes;
  34726. #if SQLITE_OS_WINCE==0
  34727. }else{
  34728. attr = osGetFileAttributesA((char*)zConverted);
  34729. #endif
  34730. }
  34731. return (attr!=INVALID_FILE_ATTRIBUTES) && (attr&FILE_ATTRIBUTE_DIRECTORY);
  34732. }
  34733. /*
  34734. ** Open a file.
  34735. */
  34736. static int winOpen(
  34737. sqlite3_vfs *pVfs, /* Used to get maximum path name length */
  34738. const char *zName, /* Name of the file (UTF-8) */
  34739. sqlite3_file *id, /* Write the SQLite file handle here */
  34740. int flags, /* Open mode flags */
  34741. int *pOutFlags /* Status return flags */
  34742. ){
  34743. HANDLE h;
  34744. DWORD lastErrno = 0;
  34745. DWORD dwDesiredAccess;
  34746. DWORD dwShareMode;
  34747. DWORD dwCreationDisposition;
  34748. DWORD dwFlagsAndAttributes = 0;
  34749. #if SQLITE_OS_WINCE
  34750. int isTemp = 0;
  34751. #endif
  34752. winFile *pFile = (winFile*)id;
  34753. void *zConverted; /* Filename in OS encoding */
  34754. const char *zUtf8Name = zName; /* Filename in UTF-8 encoding */
  34755. int cnt = 0;
  34756. /* If argument zPath is a NULL pointer, this function is required to open
  34757. ** a temporary file. Use this buffer to store the file name in.
  34758. */
  34759. char *zTmpname = 0; /* For temporary filename, if necessary. */
  34760. int rc = SQLITE_OK; /* Function Return Code */
  34761. #if !defined(NDEBUG) || SQLITE_OS_WINCE
  34762. int eType = flags&0xFFFFFF00; /* Type of file to open */
  34763. #endif
  34764. int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
  34765. int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
  34766. int isCreate = (flags & SQLITE_OPEN_CREATE);
  34767. int isReadonly = (flags & SQLITE_OPEN_READONLY);
  34768. int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
  34769. #ifndef NDEBUG
  34770. int isOpenJournal = (isCreate && (
  34771. eType==SQLITE_OPEN_MASTER_JOURNAL
  34772. || eType==SQLITE_OPEN_MAIN_JOURNAL
  34773. || eType==SQLITE_OPEN_WAL
  34774. ));
  34775. #endif
  34776. OSTRACE(("OPEN name=%s, pFile=%p, flags=%x, pOutFlags=%p\n",
  34777. zUtf8Name, id, flags, pOutFlags));
  34778. /* Check the following statements are true:
  34779. **
  34780. ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
  34781. ** (b) if CREATE is set, then READWRITE must also be set, and
  34782. ** (c) if EXCLUSIVE is set, then CREATE must also be set.
  34783. ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
  34784. */
  34785. assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
  34786. assert(isCreate==0 || isReadWrite);
  34787. assert(isExclusive==0 || isCreate);
  34788. assert(isDelete==0 || isCreate);
  34789. /* The main DB, main journal, WAL file and master journal are never
  34790. ** automatically deleted. Nor are they ever temporary files. */
  34791. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
  34792. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
  34793. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
  34794. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
  34795. /* Assert that the upper layer has set one of the "file-type" flags. */
  34796. assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
  34797. || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
  34798. || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
  34799. || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
  34800. );
  34801. assert( pFile!=0 );
  34802. memset(pFile, 0, sizeof(winFile));
  34803. pFile->h = INVALID_HANDLE_VALUE;
  34804. #if SQLITE_OS_WINRT
  34805. if( !zUtf8Name && !sqlite3_temp_directory ){
  34806. sqlite3_log(SQLITE_ERROR,
  34807. "sqlite3_temp_directory variable should be set for WinRT");
  34808. }
  34809. #endif
  34810. /* If the second argument to this function is NULL, generate a
  34811. ** temporary file name to use
  34812. */
  34813. if( !zUtf8Name ){
  34814. assert( isDelete && !isOpenJournal );
  34815. rc = winGetTempname(pVfs, &zTmpname);
  34816. if( rc!=SQLITE_OK ){
  34817. OSTRACE(("OPEN name=%s, rc=%s", zUtf8Name, sqlite3ErrName(rc)));
  34818. return rc;
  34819. }
  34820. zUtf8Name = zTmpname;
  34821. }
  34822. /* Database filenames are double-zero terminated if they are not
  34823. ** URIs with parameters. Hence, they can always be passed into
  34824. ** sqlite3_uri_parameter().
  34825. */
  34826. assert( (eType!=SQLITE_OPEN_MAIN_DB) || (flags & SQLITE_OPEN_URI) ||
  34827. zUtf8Name[sqlite3Strlen30(zUtf8Name)+1]==0 );
  34828. /* Convert the filename to the system encoding. */
  34829. zConverted = winConvertFromUtf8Filename(zUtf8Name);
  34830. if( zConverted==0 ){
  34831. sqlite3_free(zTmpname);
  34832. OSTRACE(("OPEN name=%s, rc=SQLITE_IOERR_NOMEM", zUtf8Name));
  34833. return SQLITE_IOERR_NOMEM;
  34834. }
  34835. if( winIsDir(zConverted) ){
  34836. sqlite3_free(zConverted);
  34837. sqlite3_free(zTmpname);
  34838. OSTRACE(("OPEN name=%s, rc=SQLITE_CANTOPEN_ISDIR", zUtf8Name));
  34839. return SQLITE_CANTOPEN_ISDIR;
  34840. }
  34841. if( isReadWrite ){
  34842. dwDesiredAccess = GENERIC_READ | GENERIC_WRITE;
  34843. }else{
  34844. dwDesiredAccess = GENERIC_READ;
  34845. }
  34846. /* SQLITE_OPEN_EXCLUSIVE is used to make sure that a new file is
  34847. ** created. SQLite doesn't use it to indicate "exclusive access"
  34848. ** as it is usually understood.
  34849. */
  34850. if( isExclusive ){
  34851. /* Creates a new file, only if it does not already exist. */
  34852. /* If the file exists, it fails. */
  34853. dwCreationDisposition = CREATE_NEW;
  34854. }else if( isCreate ){
  34855. /* Open existing file, or create if it doesn't exist */
  34856. dwCreationDisposition = OPEN_ALWAYS;
  34857. }else{
  34858. /* Opens a file, only if it exists. */
  34859. dwCreationDisposition = OPEN_EXISTING;
  34860. }
  34861. dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
  34862. if( isDelete ){
  34863. #if SQLITE_OS_WINCE
  34864. dwFlagsAndAttributes = FILE_ATTRIBUTE_HIDDEN;
  34865. isTemp = 1;
  34866. #else
  34867. dwFlagsAndAttributes = FILE_ATTRIBUTE_TEMPORARY
  34868. | FILE_ATTRIBUTE_HIDDEN
  34869. | FILE_FLAG_DELETE_ON_CLOSE;
  34870. #endif
  34871. }else{
  34872. dwFlagsAndAttributes = FILE_ATTRIBUTE_NORMAL;
  34873. }
  34874. /* Reports from the internet are that performance is always
  34875. ** better if FILE_FLAG_RANDOM_ACCESS is used. Ticket #2699. */
  34876. #if SQLITE_OS_WINCE
  34877. dwFlagsAndAttributes |= FILE_FLAG_RANDOM_ACCESS;
  34878. #endif
  34879. if( osIsNT() ){
  34880. #if SQLITE_OS_WINRT
  34881. CREATEFILE2_EXTENDED_PARAMETERS extendedParameters;
  34882. extendedParameters.dwSize = sizeof(CREATEFILE2_EXTENDED_PARAMETERS);
  34883. extendedParameters.dwFileAttributes =
  34884. dwFlagsAndAttributes & FILE_ATTRIBUTE_MASK;
  34885. extendedParameters.dwFileFlags = dwFlagsAndAttributes & FILE_FLAG_MASK;
  34886. extendedParameters.dwSecurityQosFlags = SECURITY_ANONYMOUS;
  34887. extendedParameters.lpSecurityAttributes = NULL;
  34888. extendedParameters.hTemplateFile = NULL;
  34889. while( (h = osCreateFile2((LPCWSTR)zConverted,
  34890. dwDesiredAccess,
  34891. dwShareMode,
  34892. dwCreationDisposition,
  34893. &extendedParameters))==INVALID_HANDLE_VALUE &&
  34894. winRetryIoerr(&cnt, &lastErrno) ){
  34895. /* Noop */
  34896. }
  34897. #else
  34898. while( (h = osCreateFileW((LPCWSTR)zConverted,
  34899. dwDesiredAccess,
  34900. dwShareMode, NULL,
  34901. dwCreationDisposition,
  34902. dwFlagsAndAttributes,
  34903. NULL))==INVALID_HANDLE_VALUE &&
  34904. winRetryIoerr(&cnt, &lastErrno) ){
  34905. /* Noop */
  34906. }
  34907. #endif
  34908. }
  34909. #ifdef SQLITE_WIN32_HAS_ANSI
  34910. else{
  34911. while( (h = osCreateFileA((LPCSTR)zConverted,
  34912. dwDesiredAccess,
  34913. dwShareMode, NULL,
  34914. dwCreationDisposition,
  34915. dwFlagsAndAttributes,
  34916. NULL))==INVALID_HANDLE_VALUE &&
  34917. winRetryIoerr(&cnt, &lastErrno) ){
  34918. /* Noop */
  34919. }
  34920. }
  34921. #endif
  34922. winLogIoerr(cnt);
  34923. OSTRACE(("OPEN file=%p, name=%s, access=%lx, rc=%s\n", h, zUtf8Name,
  34924. dwDesiredAccess, (h==INVALID_HANDLE_VALUE) ? "failed" : "ok"));
  34925. if( h==INVALID_HANDLE_VALUE ){
  34926. pFile->lastErrno = lastErrno;
  34927. winLogError(SQLITE_CANTOPEN, pFile->lastErrno, "winOpen", zUtf8Name);
  34928. sqlite3_free(zConverted);
  34929. sqlite3_free(zTmpname);
  34930. if( isReadWrite && !isExclusive ){
  34931. return winOpen(pVfs, zName, id,
  34932. ((flags|SQLITE_OPEN_READONLY) &
  34933. ~(SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE)),
  34934. pOutFlags);
  34935. }else{
  34936. return SQLITE_CANTOPEN_BKPT;
  34937. }
  34938. }
  34939. if( pOutFlags ){
  34940. if( isReadWrite ){
  34941. *pOutFlags = SQLITE_OPEN_READWRITE;
  34942. }else{
  34943. *pOutFlags = SQLITE_OPEN_READONLY;
  34944. }
  34945. }
  34946. OSTRACE(("OPEN file=%p, name=%s, access=%lx, pOutFlags=%p, *pOutFlags=%d, "
  34947. "rc=%s\n", h, zUtf8Name, dwDesiredAccess, pOutFlags, pOutFlags ?
  34948. *pOutFlags : 0, (h==INVALID_HANDLE_VALUE) ? "failed" : "ok"));
  34949. #if SQLITE_OS_WINCE
  34950. if( isReadWrite && eType==SQLITE_OPEN_MAIN_DB
  34951. && (rc = winceCreateLock(zName, pFile))!=SQLITE_OK
  34952. ){
  34953. osCloseHandle(h);
  34954. sqlite3_free(zConverted);
  34955. sqlite3_free(zTmpname);
  34956. OSTRACE(("OPEN-CE-LOCK name=%s, rc=%s\n", zName, sqlite3ErrName(rc)));
  34957. return rc;
  34958. }
  34959. if( isTemp ){
  34960. pFile->zDeleteOnClose = zConverted;
  34961. }else
  34962. #endif
  34963. {
  34964. sqlite3_free(zConverted);
  34965. }
  34966. sqlite3_free(zTmpname);
  34967. pFile->pMethod = &winIoMethod;
  34968. pFile->pVfs = pVfs;
  34969. pFile->h = h;
  34970. if( isReadonly ){
  34971. pFile->ctrlFlags |= WINFILE_RDONLY;
  34972. }
  34973. if( sqlite3_uri_boolean(zName, "psow", SQLITE_POWERSAFE_OVERWRITE) ){
  34974. pFile->ctrlFlags |= WINFILE_PSOW;
  34975. }
  34976. pFile->lastErrno = NO_ERROR;
  34977. pFile->zPath = zName;
  34978. #if SQLITE_MAX_MMAP_SIZE>0
  34979. pFile->hMap = NULL;
  34980. pFile->pMapRegion = 0;
  34981. pFile->mmapSize = 0;
  34982. pFile->mmapSizeActual = 0;
  34983. pFile->mmapSizeMax = sqlite3GlobalConfig.szMmap;
  34984. #endif
  34985. OpenCounter(+1);
  34986. return rc;
  34987. }
  34988. /*
  34989. ** Delete the named file.
  34990. **
  34991. ** Note that Windows does not allow a file to be deleted if some other
  34992. ** process has it open. Sometimes a virus scanner or indexing program
  34993. ** will open a journal file shortly after it is created in order to do
  34994. ** whatever it does. While this other process is holding the
  34995. ** file open, we will be unable to delete it. To work around this
  34996. ** problem, we delay 100 milliseconds and try to delete again. Up
  34997. ** to MX_DELETION_ATTEMPTs deletion attempts are run before giving
  34998. ** up and returning an error.
  34999. */
  35000. static int winDelete(
  35001. sqlite3_vfs *pVfs, /* Not used on win32 */
  35002. const char *zFilename, /* Name of file to delete */
  35003. int syncDir /* Not used on win32 */
  35004. ){
  35005. int cnt = 0;
  35006. int rc;
  35007. DWORD attr;
  35008. DWORD lastErrno = 0;
  35009. void *zConverted;
  35010. UNUSED_PARAMETER(pVfs);
  35011. UNUSED_PARAMETER(syncDir);
  35012. SimulateIOError(return SQLITE_IOERR_DELETE);
  35013. OSTRACE(("DELETE name=%s, syncDir=%d\n", zFilename, syncDir));
  35014. zConverted = winConvertFromUtf8Filename(zFilename);
  35015. if( zConverted==0 ){
  35016. OSTRACE(("DELETE name=%s, rc=SQLITE_IOERR_NOMEM\n", zFilename));
  35017. return SQLITE_IOERR_NOMEM;
  35018. }
  35019. if( osIsNT() ){
  35020. do {
  35021. #if SQLITE_OS_WINRT
  35022. WIN32_FILE_ATTRIBUTE_DATA sAttrData;
  35023. memset(&sAttrData, 0, sizeof(sAttrData));
  35024. if ( osGetFileAttributesExW(zConverted, GetFileExInfoStandard,
  35025. &sAttrData) ){
  35026. attr = sAttrData.dwFileAttributes;
  35027. }else{
  35028. lastErrno = osGetLastError();
  35029. if( lastErrno==ERROR_FILE_NOT_FOUND
  35030. || lastErrno==ERROR_PATH_NOT_FOUND ){
  35031. rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
  35032. }else{
  35033. rc = SQLITE_ERROR;
  35034. }
  35035. break;
  35036. }
  35037. #else
  35038. attr = osGetFileAttributesW(zConverted);
  35039. #endif
  35040. if ( attr==INVALID_FILE_ATTRIBUTES ){
  35041. lastErrno = osGetLastError();
  35042. if( lastErrno==ERROR_FILE_NOT_FOUND
  35043. || lastErrno==ERROR_PATH_NOT_FOUND ){
  35044. rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
  35045. }else{
  35046. rc = SQLITE_ERROR;
  35047. }
  35048. break;
  35049. }
  35050. if ( attr&FILE_ATTRIBUTE_DIRECTORY ){
  35051. rc = SQLITE_ERROR; /* Files only. */
  35052. break;
  35053. }
  35054. if ( osDeleteFileW(zConverted) ){
  35055. rc = SQLITE_OK; /* Deleted OK. */
  35056. break;
  35057. }
  35058. if ( !winRetryIoerr(&cnt, &lastErrno) ){
  35059. rc = SQLITE_ERROR; /* No more retries. */
  35060. break;
  35061. }
  35062. } while(1);
  35063. }
  35064. #ifdef SQLITE_WIN32_HAS_ANSI
  35065. else{
  35066. do {
  35067. attr = osGetFileAttributesA(zConverted);
  35068. if ( attr==INVALID_FILE_ATTRIBUTES ){
  35069. lastErrno = osGetLastError();
  35070. if( lastErrno==ERROR_FILE_NOT_FOUND
  35071. || lastErrno==ERROR_PATH_NOT_FOUND ){
  35072. rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
  35073. }else{
  35074. rc = SQLITE_ERROR;
  35075. }
  35076. break;
  35077. }
  35078. if ( attr&FILE_ATTRIBUTE_DIRECTORY ){
  35079. rc = SQLITE_ERROR; /* Files only. */
  35080. break;
  35081. }
  35082. if ( osDeleteFileA(zConverted) ){
  35083. rc = SQLITE_OK; /* Deleted OK. */
  35084. break;
  35085. }
  35086. if ( !winRetryIoerr(&cnt, &lastErrno) ){
  35087. rc = SQLITE_ERROR; /* No more retries. */
  35088. break;
  35089. }
  35090. } while(1);
  35091. }
  35092. #endif
  35093. if( rc && rc!=SQLITE_IOERR_DELETE_NOENT ){
  35094. rc = winLogError(SQLITE_IOERR_DELETE, lastErrno, "winDelete", zFilename);
  35095. }else{
  35096. winLogIoerr(cnt);
  35097. }
  35098. sqlite3_free(zConverted);
  35099. OSTRACE(("DELETE name=%s, rc=%s\n", zFilename, sqlite3ErrName(rc)));
  35100. return rc;
  35101. }
  35102. /*
  35103. ** Check the existence and status of a file.
  35104. */
  35105. static int winAccess(
  35106. sqlite3_vfs *pVfs, /* Not used on win32 */
  35107. const char *zFilename, /* Name of file to check */
  35108. int flags, /* Type of test to make on this file */
  35109. int *pResOut /* OUT: Result */
  35110. ){
  35111. DWORD attr;
  35112. int rc = 0;
  35113. DWORD lastErrno = 0;
  35114. void *zConverted;
  35115. UNUSED_PARAMETER(pVfs);
  35116. SimulateIOError( return SQLITE_IOERR_ACCESS; );
  35117. OSTRACE(("ACCESS name=%s, flags=%x, pResOut=%p\n",
  35118. zFilename, flags, pResOut));
  35119. zConverted = winConvertFromUtf8Filename(zFilename);
  35120. if( zConverted==0 ){
  35121. OSTRACE(("ACCESS name=%s, rc=SQLITE_IOERR_NOMEM\n", zFilename));
  35122. return SQLITE_IOERR_NOMEM;
  35123. }
  35124. if( osIsNT() ){
  35125. int cnt = 0;
  35126. WIN32_FILE_ATTRIBUTE_DATA sAttrData;
  35127. memset(&sAttrData, 0, sizeof(sAttrData));
  35128. while( !(rc = osGetFileAttributesExW((LPCWSTR)zConverted,
  35129. GetFileExInfoStandard,
  35130. &sAttrData)) && winRetryIoerr(&cnt, &lastErrno) ){}
  35131. if( rc ){
  35132. /* For an SQLITE_ACCESS_EXISTS query, treat a zero-length file
  35133. ** as if it does not exist.
  35134. */
  35135. if( flags==SQLITE_ACCESS_EXISTS
  35136. && sAttrData.nFileSizeHigh==0
  35137. && sAttrData.nFileSizeLow==0 ){
  35138. attr = INVALID_FILE_ATTRIBUTES;
  35139. }else{
  35140. attr = sAttrData.dwFileAttributes;
  35141. }
  35142. }else{
  35143. winLogIoerr(cnt);
  35144. if( lastErrno!=ERROR_FILE_NOT_FOUND && lastErrno!=ERROR_PATH_NOT_FOUND ){
  35145. sqlite3_free(zConverted);
  35146. return winLogError(SQLITE_IOERR_ACCESS, lastErrno, "winAccess",
  35147. zFilename);
  35148. }else{
  35149. attr = INVALID_FILE_ATTRIBUTES;
  35150. }
  35151. }
  35152. }
  35153. #ifdef SQLITE_WIN32_HAS_ANSI
  35154. else{
  35155. attr = osGetFileAttributesA((char*)zConverted);
  35156. }
  35157. #endif
  35158. sqlite3_free(zConverted);
  35159. switch( flags ){
  35160. case SQLITE_ACCESS_READ:
  35161. case SQLITE_ACCESS_EXISTS:
  35162. rc = attr!=INVALID_FILE_ATTRIBUTES;
  35163. break;
  35164. case SQLITE_ACCESS_READWRITE:
  35165. rc = attr!=INVALID_FILE_ATTRIBUTES &&
  35166. (attr & FILE_ATTRIBUTE_READONLY)==0;
  35167. break;
  35168. default:
  35169. assert(!"Invalid flags argument");
  35170. }
  35171. *pResOut = rc;
  35172. OSTRACE(("ACCESS name=%s, pResOut=%p, *pResOut=%d, rc=SQLITE_OK\n",
  35173. zFilename, pResOut, *pResOut));
  35174. return SQLITE_OK;
  35175. }
  35176. /*
  35177. ** Returns non-zero if the specified path name starts with a drive letter
  35178. ** followed by a colon character.
  35179. */
  35180. static BOOL winIsDriveLetterAndColon(
  35181. const char *zPathname
  35182. ){
  35183. return ( sqlite3Isalpha(zPathname[0]) && zPathname[1]==':' );
  35184. }
  35185. /*
  35186. ** Returns non-zero if the specified path name should be used verbatim. If
  35187. ** non-zero is returned from this function, the calling function must simply
  35188. ** use the provided path name verbatim -OR- resolve it into a full path name
  35189. ** using the GetFullPathName Win32 API function (if available).
  35190. */
  35191. static BOOL winIsVerbatimPathname(
  35192. const char *zPathname
  35193. ){
  35194. /*
  35195. ** If the path name starts with a forward slash or a backslash, it is either
  35196. ** a legal UNC name, a volume relative path, or an absolute path name in the
  35197. ** "Unix" format on Windows. There is no easy way to differentiate between
  35198. ** the final two cases; therefore, we return the safer return value of TRUE
  35199. ** so that callers of this function will simply use it verbatim.
  35200. */
  35201. if ( winIsDirSep(zPathname[0]) ){
  35202. return TRUE;
  35203. }
  35204. /*
  35205. ** If the path name starts with a letter and a colon it is either a volume
  35206. ** relative path or an absolute path. Callers of this function must not
  35207. ** attempt to treat it as a relative path name (i.e. they should simply use
  35208. ** it verbatim).
  35209. */
  35210. if ( winIsDriveLetterAndColon(zPathname) ){
  35211. return TRUE;
  35212. }
  35213. /*
  35214. ** If we get to this point, the path name should almost certainly be a purely
  35215. ** relative one (i.e. not a UNC name, not absolute, and not volume relative).
  35216. */
  35217. return FALSE;
  35218. }
  35219. /*
  35220. ** Turn a relative pathname into a full pathname. Write the full
  35221. ** pathname into zOut[]. zOut[] will be at least pVfs->mxPathname
  35222. ** bytes in size.
  35223. */
  35224. static int winFullPathname(
  35225. sqlite3_vfs *pVfs, /* Pointer to vfs object */
  35226. const char *zRelative, /* Possibly relative input path */
  35227. int nFull, /* Size of output buffer in bytes */
  35228. char *zFull /* Output buffer */
  35229. ){
  35230. #if defined(__CYGWIN__)
  35231. SimulateIOError( return SQLITE_ERROR );
  35232. UNUSED_PARAMETER(nFull);
  35233. assert( nFull>=pVfs->mxPathname );
  35234. if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
  35235. /*
  35236. ** NOTE: We are dealing with a relative path name and the data
  35237. ** directory has been set. Therefore, use it as the basis
  35238. ** for converting the relative path name to an absolute
  35239. ** one by prepending the data directory and a slash.
  35240. */
  35241. char *zOut = sqlite3MallocZero( pVfs->mxPathname+1 );
  35242. if( !zOut ){
  35243. return SQLITE_IOERR_NOMEM;
  35244. }
  35245. if( cygwin_conv_path(
  35246. (osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A) |
  35247. CCP_RELATIVE, zRelative, zOut, pVfs->mxPathname+1)<0 ){
  35248. sqlite3_free(zOut);
  35249. return winLogError(SQLITE_CANTOPEN_CONVPATH, (DWORD)errno,
  35250. "winFullPathname1", zRelative);
  35251. }else{
  35252. char *zUtf8 = winConvertToUtf8Filename(zOut);
  35253. if( !zUtf8 ){
  35254. sqlite3_free(zOut);
  35255. return SQLITE_IOERR_NOMEM;
  35256. }
  35257. sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s",
  35258. sqlite3_data_directory, winGetDirSep(), zUtf8);
  35259. sqlite3_free(zUtf8);
  35260. sqlite3_free(zOut);
  35261. }
  35262. }else{
  35263. char *zOut = sqlite3MallocZero( pVfs->mxPathname+1 );
  35264. if( !zOut ){
  35265. return SQLITE_IOERR_NOMEM;
  35266. }
  35267. if( cygwin_conv_path(
  35268. (osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A),
  35269. zRelative, zOut, pVfs->mxPathname+1)<0 ){
  35270. sqlite3_free(zOut);
  35271. return winLogError(SQLITE_CANTOPEN_CONVPATH, (DWORD)errno,
  35272. "winFullPathname2", zRelative);
  35273. }else{
  35274. char *zUtf8 = winConvertToUtf8Filename(zOut);
  35275. if( !zUtf8 ){
  35276. sqlite3_free(zOut);
  35277. return SQLITE_IOERR_NOMEM;
  35278. }
  35279. sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zUtf8);
  35280. sqlite3_free(zUtf8);
  35281. sqlite3_free(zOut);
  35282. }
  35283. }
  35284. return SQLITE_OK;
  35285. #endif
  35286. #if (SQLITE_OS_WINCE || SQLITE_OS_WINRT) && !defined(__CYGWIN__)
  35287. SimulateIOError( return SQLITE_ERROR );
  35288. /* WinCE has no concept of a relative pathname, or so I am told. */
  35289. /* WinRT has no way to convert a relative path to an absolute one. */
  35290. if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
  35291. /*
  35292. ** NOTE: We are dealing with a relative path name and the data
  35293. ** directory has been set. Therefore, use it as the basis
  35294. ** for converting the relative path name to an absolute
  35295. ** one by prepending the data directory and a backslash.
  35296. */
  35297. sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s",
  35298. sqlite3_data_directory, winGetDirSep(), zRelative);
  35299. }else{
  35300. sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zRelative);
  35301. }
  35302. return SQLITE_OK;
  35303. #endif
  35304. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && !defined(__CYGWIN__)
  35305. DWORD nByte;
  35306. void *zConverted;
  35307. char *zOut;
  35308. /* If this path name begins with "/X:", where "X" is any alphabetic
  35309. ** character, discard the initial "/" from the pathname.
  35310. */
  35311. if( zRelative[0]=='/' && winIsDriveLetterAndColon(zRelative+1) ){
  35312. zRelative++;
  35313. }
  35314. /* It's odd to simulate an io-error here, but really this is just
  35315. ** using the io-error infrastructure to test that SQLite handles this
  35316. ** function failing. This function could fail if, for example, the
  35317. ** current working directory has been unlinked.
  35318. */
  35319. SimulateIOError( return SQLITE_ERROR );
  35320. if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
  35321. /*
  35322. ** NOTE: We are dealing with a relative path name and the data
  35323. ** directory has been set. Therefore, use it as the basis
  35324. ** for converting the relative path name to an absolute
  35325. ** one by prepending the data directory and a backslash.
  35326. */
  35327. sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s",
  35328. sqlite3_data_directory, winGetDirSep(), zRelative);
  35329. return SQLITE_OK;
  35330. }
  35331. zConverted = winConvertFromUtf8Filename(zRelative);
  35332. if( zConverted==0 ){
  35333. return SQLITE_IOERR_NOMEM;
  35334. }
  35335. if( osIsNT() ){
  35336. LPWSTR zTemp;
  35337. nByte = osGetFullPathNameW((LPCWSTR)zConverted, 0, 0, 0);
  35338. if( nByte==0 ){
  35339. sqlite3_free(zConverted);
  35340. return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
  35341. "winFullPathname1", zRelative);
  35342. }
  35343. nByte += 3;
  35344. zTemp = sqlite3MallocZero( nByte*sizeof(zTemp[0]) );
  35345. if( zTemp==0 ){
  35346. sqlite3_free(zConverted);
  35347. return SQLITE_IOERR_NOMEM;
  35348. }
  35349. nByte = osGetFullPathNameW((LPCWSTR)zConverted, nByte, zTemp, 0);
  35350. if( nByte==0 ){
  35351. sqlite3_free(zConverted);
  35352. sqlite3_free(zTemp);
  35353. return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
  35354. "winFullPathname2", zRelative);
  35355. }
  35356. sqlite3_free(zConverted);
  35357. zOut = winUnicodeToUtf8(zTemp);
  35358. sqlite3_free(zTemp);
  35359. }
  35360. #ifdef SQLITE_WIN32_HAS_ANSI
  35361. else{
  35362. char *zTemp;
  35363. nByte = osGetFullPathNameA((char*)zConverted, 0, 0, 0);
  35364. if( nByte==0 ){
  35365. sqlite3_free(zConverted);
  35366. return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
  35367. "winFullPathname3", zRelative);
  35368. }
  35369. nByte += 3;
  35370. zTemp = sqlite3MallocZero( nByte*sizeof(zTemp[0]) );
  35371. if( zTemp==0 ){
  35372. sqlite3_free(zConverted);
  35373. return SQLITE_IOERR_NOMEM;
  35374. }
  35375. nByte = osGetFullPathNameA((char*)zConverted, nByte, zTemp, 0);
  35376. if( nByte==0 ){
  35377. sqlite3_free(zConverted);
  35378. sqlite3_free(zTemp);
  35379. return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
  35380. "winFullPathname4", zRelative);
  35381. }
  35382. sqlite3_free(zConverted);
  35383. zOut = sqlite3_win32_mbcs_to_utf8(zTemp);
  35384. sqlite3_free(zTemp);
  35385. }
  35386. #endif
  35387. if( zOut ){
  35388. sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zOut);
  35389. sqlite3_free(zOut);
  35390. return SQLITE_OK;
  35391. }else{
  35392. return SQLITE_IOERR_NOMEM;
  35393. }
  35394. #endif
  35395. }
  35396. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  35397. /*
  35398. ** Interfaces for opening a shared library, finding entry points
  35399. ** within the shared library, and closing the shared library.
  35400. */
  35401. static void *winDlOpen(sqlite3_vfs *pVfs, const char *zFilename){
  35402. HANDLE h;
  35403. #if defined(__CYGWIN__)
  35404. int nFull = pVfs->mxPathname+1;
  35405. char *zFull = sqlite3MallocZero( nFull );
  35406. void *zConverted = 0;
  35407. if( zFull==0 ){
  35408. OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)0));
  35409. return 0;
  35410. }
  35411. if( winFullPathname(pVfs, zFilename, nFull, zFull)!=SQLITE_OK ){
  35412. sqlite3_free(zFull);
  35413. OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)0));
  35414. return 0;
  35415. }
  35416. zConverted = winConvertFromUtf8Filename(zFull);
  35417. sqlite3_free(zFull);
  35418. #else
  35419. void *zConverted = winConvertFromUtf8Filename(zFilename);
  35420. UNUSED_PARAMETER(pVfs);
  35421. #endif
  35422. if( zConverted==0 ){
  35423. OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)0));
  35424. return 0;
  35425. }
  35426. if( osIsNT() ){
  35427. #if SQLITE_OS_WINRT
  35428. h = osLoadPackagedLibrary((LPCWSTR)zConverted, 0);
  35429. #else
  35430. h = osLoadLibraryW((LPCWSTR)zConverted);
  35431. #endif
  35432. }
  35433. #ifdef SQLITE_WIN32_HAS_ANSI
  35434. else{
  35435. h = osLoadLibraryA((char*)zConverted);
  35436. }
  35437. #endif
  35438. OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)h));
  35439. sqlite3_free(zConverted);
  35440. return (void*)h;
  35441. }
  35442. static void winDlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
  35443. UNUSED_PARAMETER(pVfs);
  35444. winGetLastErrorMsg(osGetLastError(), nBuf, zBufOut);
  35445. }
  35446. static void (*winDlSym(sqlite3_vfs *pVfs,void *pH,const char *zSym))(void){
  35447. FARPROC proc;
  35448. UNUSED_PARAMETER(pVfs);
  35449. proc = osGetProcAddressA((HANDLE)pH, zSym);
  35450. OSTRACE(("DLSYM handle=%p, symbol=%s, address=%p\n",
  35451. (void*)pH, zSym, (void*)proc));
  35452. return (void(*)(void))proc;
  35453. }
  35454. static void winDlClose(sqlite3_vfs *pVfs, void *pHandle){
  35455. UNUSED_PARAMETER(pVfs);
  35456. osFreeLibrary((HANDLE)pHandle);
  35457. OSTRACE(("DLCLOSE handle=%p\n", (void*)pHandle));
  35458. }
  35459. #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
  35460. #define winDlOpen 0
  35461. #define winDlError 0
  35462. #define winDlSym 0
  35463. #define winDlClose 0
  35464. #endif
  35465. /*
  35466. ** Write up to nBuf bytes of randomness into zBuf.
  35467. */
  35468. static int winRandomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
  35469. int n = 0;
  35470. UNUSED_PARAMETER(pVfs);
  35471. #if defined(SQLITE_TEST)
  35472. n = nBuf;
  35473. memset(zBuf, 0, nBuf);
  35474. #else
  35475. if( sizeof(SYSTEMTIME)<=nBuf-n ){
  35476. SYSTEMTIME x;
  35477. osGetSystemTime(&x);
  35478. memcpy(&zBuf[n], &x, sizeof(x));
  35479. n += sizeof(x);
  35480. }
  35481. if( sizeof(DWORD)<=nBuf-n ){
  35482. DWORD pid = osGetCurrentProcessId();
  35483. memcpy(&zBuf[n], &pid, sizeof(pid));
  35484. n += sizeof(pid);
  35485. }
  35486. #if SQLITE_OS_WINRT
  35487. if( sizeof(ULONGLONG)<=nBuf-n ){
  35488. ULONGLONG cnt = osGetTickCount64();
  35489. memcpy(&zBuf[n], &cnt, sizeof(cnt));
  35490. n += sizeof(cnt);
  35491. }
  35492. #else
  35493. if( sizeof(DWORD)<=nBuf-n ){
  35494. DWORD cnt = osGetTickCount();
  35495. memcpy(&zBuf[n], &cnt, sizeof(cnt));
  35496. n += sizeof(cnt);
  35497. }
  35498. #endif
  35499. if( sizeof(LARGE_INTEGER)<=nBuf-n ){
  35500. LARGE_INTEGER i;
  35501. osQueryPerformanceCounter(&i);
  35502. memcpy(&zBuf[n], &i, sizeof(i));
  35503. n += sizeof(i);
  35504. }
  35505. #endif
  35506. return n;
  35507. }
  35508. /*
  35509. ** Sleep for a little while. Return the amount of time slept.
  35510. */
  35511. static int winSleep(sqlite3_vfs *pVfs, int microsec){
  35512. sqlite3_win32_sleep((microsec+999)/1000);
  35513. UNUSED_PARAMETER(pVfs);
  35514. return ((microsec+999)/1000)*1000;
  35515. }
  35516. /*
  35517. ** The following variable, if set to a non-zero value, is interpreted as
  35518. ** the number of seconds since 1970 and is used to set the result of
  35519. ** sqlite3OsCurrentTime() during testing.
  35520. */
  35521. #ifdef SQLITE_TEST
  35522. SQLITE_API int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
  35523. #endif
  35524. /*
  35525. ** Find the current time (in Universal Coordinated Time). Write into *piNow
  35526. ** the current time and date as a Julian Day number times 86_400_000. In
  35527. ** other words, write into *piNow the number of milliseconds since the Julian
  35528. ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
  35529. ** proleptic Gregorian calendar.
  35530. **
  35531. ** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date
  35532. ** cannot be found.
  35533. */
  35534. static int winCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *piNow){
  35535. /* FILETIME structure is a 64-bit value representing the number of
  35536. 100-nanosecond intervals since January 1, 1601 (= JD 2305813.5).
  35537. */
  35538. FILETIME ft;
  35539. static const sqlite3_int64 winFiletimeEpoch = 23058135*(sqlite3_int64)8640000;
  35540. #ifdef SQLITE_TEST
  35541. static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
  35542. #endif
  35543. /* 2^32 - to avoid use of LL and warnings in gcc */
  35544. static const sqlite3_int64 max32BitValue =
  35545. (sqlite3_int64)2000000000 + (sqlite3_int64)2000000000 +
  35546. (sqlite3_int64)294967296;
  35547. #if SQLITE_OS_WINCE
  35548. SYSTEMTIME time;
  35549. osGetSystemTime(&time);
  35550. /* if SystemTimeToFileTime() fails, it returns zero. */
  35551. if (!osSystemTimeToFileTime(&time,&ft)){
  35552. return SQLITE_ERROR;
  35553. }
  35554. #else
  35555. osGetSystemTimeAsFileTime( &ft );
  35556. #endif
  35557. *piNow = winFiletimeEpoch +
  35558. ((((sqlite3_int64)ft.dwHighDateTime)*max32BitValue) +
  35559. (sqlite3_int64)ft.dwLowDateTime)/(sqlite3_int64)10000;
  35560. #ifdef SQLITE_TEST
  35561. if( sqlite3_current_time ){
  35562. *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
  35563. }
  35564. #endif
  35565. UNUSED_PARAMETER(pVfs);
  35566. return SQLITE_OK;
  35567. }
  35568. /*
  35569. ** Find the current time (in Universal Coordinated Time). Write the
  35570. ** current time and date as a Julian Day number into *prNow and
  35571. ** return 0. Return 1 if the time and date cannot be found.
  35572. */
  35573. static int winCurrentTime(sqlite3_vfs *pVfs, double *prNow){
  35574. int rc;
  35575. sqlite3_int64 i;
  35576. rc = winCurrentTimeInt64(pVfs, &i);
  35577. if( !rc ){
  35578. *prNow = i/86400000.0;
  35579. }
  35580. return rc;
  35581. }
  35582. /*
  35583. ** The idea is that this function works like a combination of
  35584. ** GetLastError() and FormatMessage() on Windows (or errno and
  35585. ** strerror_r() on Unix). After an error is returned by an OS
  35586. ** function, SQLite calls this function with zBuf pointing to
  35587. ** a buffer of nBuf bytes. The OS layer should populate the
  35588. ** buffer with a nul-terminated UTF-8 encoded error message
  35589. ** describing the last IO error to have occurred within the calling
  35590. ** thread.
  35591. **
  35592. ** If the error message is too large for the supplied buffer,
  35593. ** it should be truncated. The return value of xGetLastError
  35594. ** is zero if the error message fits in the buffer, or non-zero
  35595. ** otherwise (if the message was truncated). If non-zero is returned,
  35596. ** then it is not necessary to include the nul-terminator character
  35597. ** in the output buffer.
  35598. **
  35599. ** Not supplying an error message will have no adverse effect
  35600. ** on SQLite. It is fine to have an implementation that never
  35601. ** returns an error message:
  35602. **
  35603. ** int xGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
  35604. ** assert(zBuf[0]=='\0');
  35605. ** return 0;
  35606. ** }
  35607. **
  35608. ** However if an error message is supplied, it will be incorporated
  35609. ** by sqlite into the error message available to the user using
  35610. ** sqlite3_errmsg(), possibly making IO errors easier to debug.
  35611. */
  35612. static int winGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
  35613. UNUSED_PARAMETER(pVfs);
  35614. return winGetLastErrorMsg(osGetLastError(), nBuf, zBuf);
  35615. }
  35616. /*
  35617. ** Initialize and deinitialize the operating system interface.
  35618. */
  35619. SQLITE_API int sqlite3_os_init(void){
  35620. static sqlite3_vfs winVfs = {
  35621. 3, /* iVersion */
  35622. sizeof(winFile), /* szOsFile */
  35623. SQLITE_WIN32_MAX_PATH_BYTES, /* mxPathname */
  35624. 0, /* pNext */
  35625. "win32", /* zName */
  35626. 0, /* pAppData */
  35627. winOpen, /* xOpen */
  35628. winDelete, /* xDelete */
  35629. winAccess, /* xAccess */
  35630. winFullPathname, /* xFullPathname */
  35631. winDlOpen, /* xDlOpen */
  35632. winDlError, /* xDlError */
  35633. winDlSym, /* xDlSym */
  35634. winDlClose, /* xDlClose */
  35635. winRandomness, /* xRandomness */
  35636. winSleep, /* xSleep */
  35637. winCurrentTime, /* xCurrentTime */
  35638. winGetLastError, /* xGetLastError */
  35639. winCurrentTimeInt64, /* xCurrentTimeInt64 */
  35640. winSetSystemCall, /* xSetSystemCall */
  35641. winGetSystemCall, /* xGetSystemCall */
  35642. winNextSystemCall, /* xNextSystemCall */
  35643. };
  35644. #if defined(SQLITE_WIN32_HAS_WIDE)
  35645. static sqlite3_vfs winLongPathVfs = {
  35646. 3, /* iVersion */
  35647. sizeof(winFile), /* szOsFile */
  35648. SQLITE_WINNT_MAX_PATH_BYTES, /* mxPathname */
  35649. 0, /* pNext */
  35650. "win32-longpath", /* zName */
  35651. 0, /* pAppData */
  35652. winOpen, /* xOpen */
  35653. winDelete, /* xDelete */
  35654. winAccess, /* xAccess */
  35655. winFullPathname, /* xFullPathname */
  35656. winDlOpen, /* xDlOpen */
  35657. winDlError, /* xDlError */
  35658. winDlSym, /* xDlSym */
  35659. winDlClose, /* xDlClose */
  35660. winRandomness, /* xRandomness */
  35661. winSleep, /* xSleep */
  35662. winCurrentTime, /* xCurrentTime */
  35663. winGetLastError, /* xGetLastError */
  35664. winCurrentTimeInt64, /* xCurrentTimeInt64 */
  35665. winSetSystemCall, /* xSetSystemCall */
  35666. winGetSystemCall, /* xGetSystemCall */
  35667. winNextSystemCall, /* xNextSystemCall */
  35668. };
  35669. #endif
  35670. /* Double-check that the aSyscall[] array has been constructed
  35671. ** correctly. See ticket [bb3a86e890c8e96ab] */
  35672. assert( ArraySize(aSyscall)==77 );
  35673. /* get memory map allocation granularity */
  35674. memset(&winSysInfo, 0, sizeof(SYSTEM_INFO));
  35675. #if SQLITE_OS_WINRT
  35676. osGetNativeSystemInfo(&winSysInfo);
  35677. #else
  35678. osGetSystemInfo(&winSysInfo);
  35679. #endif
  35680. assert( winSysInfo.dwAllocationGranularity>0 );
  35681. assert( winSysInfo.dwPageSize>0 );
  35682. sqlite3_vfs_register(&winVfs, 1);
  35683. #if defined(SQLITE_WIN32_HAS_WIDE)
  35684. sqlite3_vfs_register(&winLongPathVfs, 0);
  35685. #endif
  35686. return SQLITE_OK;
  35687. }
  35688. SQLITE_API int sqlite3_os_end(void){
  35689. #if SQLITE_OS_WINRT
  35690. if( sleepObj!=NULL ){
  35691. osCloseHandle(sleepObj);
  35692. sleepObj = NULL;
  35693. }
  35694. #endif
  35695. return SQLITE_OK;
  35696. }
  35697. #endif /* SQLITE_OS_WIN */
  35698. /************** End of os_win.c **********************************************/
  35699. /************** Begin file bitvec.c ******************************************/
  35700. /*
  35701. ** 2008 February 16
  35702. **
  35703. ** The author disclaims copyright to this source code. In place of
  35704. ** a legal notice, here is a blessing:
  35705. **
  35706. ** May you do good and not evil.
  35707. ** May you find forgiveness for yourself and forgive others.
  35708. ** May you share freely, never taking more than you give.
  35709. **
  35710. *************************************************************************
  35711. ** This file implements an object that represents a fixed-length
  35712. ** bitmap. Bits are numbered starting with 1.
  35713. **
  35714. ** A bitmap is used to record which pages of a database file have been
  35715. ** journalled during a transaction, or which pages have the "dont-write"
  35716. ** property. Usually only a few pages are meet either condition.
  35717. ** So the bitmap is usually sparse and has low cardinality.
  35718. ** But sometimes (for example when during a DROP of a large table) most
  35719. ** or all of the pages in a database can get journalled. In those cases,
  35720. ** the bitmap becomes dense with high cardinality. The algorithm needs
  35721. ** to handle both cases well.
  35722. **
  35723. ** The size of the bitmap is fixed when the object is created.
  35724. **
  35725. ** All bits are clear when the bitmap is created. Individual bits
  35726. ** may be set or cleared one at a time.
  35727. **
  35728. ** Test operations are about 100 times more common that set operations.
  35729. ** Clear operations are exceedingly rare. There are usually between
  35730. ** 5 and 500 set operations per Bitvec object, though the number of sets can
  35731. ** sometimes grow into tens of thousands or larger. The size of the
  35732. ** Bitvec object is the number of pages in the database file at the
  35733. ** start of a transaction, and is thus usually less than a few thousand,
  35734. ** but can be as large as 2 billion for a really big database.
  35735. */
  35736. /* Size of the Bitvec structure in bytes. */
  35737. #define BITVEC_SZ 512
  35738. /* Round the union size down to the nearest pointer boundary, since that's how
  35739. ** it will be aligned within the Bitvec struct. */
  35740. #define BITVEC_USIZE (((BITVEC_SZ-(3*sizeof(u32)))/sizeof(Bitvec*))*sizeof(Bitvec*))
  35741. /* Type of the array "element" for the bitmap representation.
  35742. ** Should be a power of 2, and ideally, evenly divide into BITVEC_USIZE.
  35743. ** Setting this to the "natural word" size of your CPU may improve
  35744. ** performance. */
  35745. #define BITVEC_TELEM u8
  35746. /* Size, in bits, of the bitmap element. */
  35747. #define BITVEC_SZELEM 8
  35748. /* Number of elements in a bitmap array. */
  35749. #define BITVEC_NELEM (BITVEC_USIZE/sizeof(BITVEC_TELEM))
  35750. /* Number of bits in the bitmap array. */
  35751. #define BITVEC_NBIT (BITVEC_NELEM*BITVEC_SZELEM)
  35752. /* Number of u32 values in hash table. */
  35753. #define BITVEC_NINT (BITVEC_USIZE/sizeof(u32))
  35754. /* Maximum number of entries in hash table before
  35755. ** sub-dividing and re-hashing. */
  35756. #define BITVEC_MXHASH (BITVEC_NINT/2)
  35757. /* Hashing function for the aHash representation.
  35758. ** Empirical testing showed that the *37 multiplier
  35759. ** (an arbitrary prime)in the hash function provided
  35760. ** no fewer collisions than the no-op *1. */
  35761. #define BITVEC_HASH(X) (((X)*1)%BITVEC_NINT)
  35762. #define BITVEC_NPTR (BITVEC_USIZE/sizeof(Bitvec *))
  35763. /*
  35764. ** A bitmap is an instance of the following structure.
  35765. **
  35766. ** This bitmap records the existence of zero or more bits
  35767. ** with values between 1 and iSize, inclusive.
  35768. **
  35769. ** There are three possible representations of the bitmap.
  35770. ** If iSize<=BITVEC_NBIT, then Bitvec.u.aBitmap[] is a straight
  35771. ** bitmap. The least significant bit is bit 1.
  35772. **
  35773. ** If iSize>BITVEC_NBIT and iDivisor==0 then Bitvec.u.aHash[] is
  35774. ** a hash table that will hold up to BITVEC_MXHASH distinct values.
  35775. **
  35776. ** Otherwise, the value i is redirected into one of BITVEC_NPTR
  35777. ** sub-bitmaps pointed to by Bitvec.u.apSub[]. Each subbitmap
  35778. ** handles up to iDivisor separate values of i. apSub[0] holds
  35779. ** values between 1 and iDivisor. apSub[1] holds values between
  35780. ** iDivisor+1 and 2*iDivisor. apSub[N] holds values between
  35781. ** N*iDivisor+1 and (N+1)*iDivisor. Each subbitmap is normalized
  35782. ** to hold deal with values between 1 and iDivisor.
  35783. */
  35784. struct Bitvec {
  35785. u32 iSize; /* Maximum bit index. Max iSize is 4,294,967,296. */
  35786. u32 nSet; /* Number of bits that are set - only valid for aHash
  35787. ** element. Max is BITVEC_NINT. For BITVEC_SZ of 512,
  35788. ** this would be 125. */
  35789. u32 iDivisor; /* Number of bits handled by each apSub[] entry. */
  35790. /* Should >=0 for apSub element. */
  35791. /* Max iDivisor is max(u32) / BITVEC_NPTR + 1. */
  35792. /* For a BITVEC_SZ of 512, this would be 34,359,739. */
  35793. union {
  35794. BITVEC_TELEM aBitmap[BITVEC_NELEM]; /* Bitmap representation */
  35795. u32 aHash[BITVEC_NINT]; /* Hash table representation */
  35796. Bitvec *apSub[BITVEC_NPTR]; /* Recursive representation */
  35797. } u;
  35798. };
  35799. /*
  35800. ** Create a new bitmap object able to handle bits between 0 and iSize,
  35801. ** inclusive. Return a pointer to the new object. Return NULL if
  35802. ** malloc fails.
  35803. */
  35804. SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32 iSize){
  35805. Bitvec *p;
  35806. assert( sizeof(*p)==BITVEC_SZ );
  35807. p = sqlite3MallocZero( sizeof(*p) );
  35808. if( p ){
  35809. p->iSize = iSize;
  35810. }
  35811. return p;
  35812. }
  35813. /*
  35814. ** Check to see if the i-th bit is set. Return true or false.
  35815. ** If p is NULL (if the bitmap has not been created) or if
  35816. ** i is out of range, then return false.
  35817. */
  35818. SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec *p, u32 i){
  35819. if( p==0 ) return 0;
  35820. if( i>p->iSize || i==0 ) return 0;
  35821. i--;
  35822. while( p->iDivisor ){
  35823. u32 bin = i/p->iDivisor;
  35824. i = i%p->iDivisor;
  35825. p = p->u.apSub[bin];
  35826. if (!p) {
  35827. return 0;
  35828. }
  35829. }
  35830. if( p->iSize<=BITVEC_NBIT ){
  35831. return (p->u.aBitmap[i/BITVEC_SZELEM] & (1<<(i&(BITVEC_SZELEM-1))))!=0;
  35832. } else{
  35833. u32 h = BITVEC_HASH(i++);
  35834. while( p->u.aHash[h] ){
  35835. if( p->u.aHash[h]==i ) return 1;
  35836. h = (h+1) % BITVEC_NINT;
  35837. }
  35838. return 0;
  35839. }
  35840. }
  35841. /*
  35842. ** Set the i-th bit. Return 0 on success and an error code if
  35843. ** anything goes wrong.
  35844. **
  35845. ** This routine might cause sub-bitmaps to be allocated. Failing
  35846. ** to get the memory needed to hold the sub-bitmap is the only
  35847. ** that can go wrong with an insert, assuming p and i are valid.
  35848. **
  35849. ** The calling function must ensure that p is a valid Bitvec object
  35850. ** and that the value for "i" is within range of the Bitvec object.
  35851. ** Otherwise the behavior is undefined.
  35852. */
  35853. SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec *p, u32 i){
  35854. u32 h;
  35855. if( p==0 ) return SQLITE_OK;
  35856. assert( i>0 );
  35857. assert( i<=p->iSize );
  35858. i--;
  35859. while((p->iSize > BITVEC_NBIT) && p->iDivisor) {
  35860. u32 bin = i/p->iDivisor;
  35861. i = i%p->iDivisor;
  35862. if( p->u.apSub[bin]==0 ){
  35863. p->u.apSub[bin] = sqlite3BitvecCreate( p->iDivisor );
  35864. if( p->u.apSub[bin]==0 ) return SQLITE_NOMEM;
  35865. }
  35866. p = p->u.apSub[bin];
  35867. }
  35868. if( p->iSize<=BITVEC_NBIT ){
  35869. p->u.aBitmap[i/BITVEC_SZELEM] |= 1 << (i&(BITVEC_SZELEM-1));
  35870. return SQLITE_OK;
  35871. }
  35872. h = BITVEC_HASH(i++);
  35873. /* if there wasn't a hash collision, and this doesn't */
  35874. /* completely fill the hash, then just add it without */
  35875. /* worring about sub-dividing and re-hashing. */
  35876. if( !p->u.aHash[h] ){
  35877. if (p->nSet<(BITVEC_NINT-1)) {
  35878. goto bitvec_set_end;
  35879. } else {
  35880. goto bitvec_set_rehash;
  35881. }
  35882. }
  35883. /* there was a collision, check to see if it's already */
  35884. /* in hash, if not, try to find a spot for it */
  35885. do {
  35886. if( p->u.aHash[h]==i ) return SQLITE_OK;
  35887. h++;
  35888. if( h>=BITVEC_NINT ) h = 0;
  35889. } while( p->u.aHash[h] );
  35890. /* we didn't find it in the hash. h points to the first */
  35891. /* available free spot. check to see if this is going to */
  35892. /* make our hash too "full". */
  35893. bitvec_set_rehash:
  35894. if( p->nSet>=BITVEC_MXHASH ){
  35895. unsigned int j;
  35896. int rc;
  35897. u32 *aiValues = sqlite3StackAllocRaw(0, sizeof(p->u.aHash));
  35898. if( aiValues==0 ){
  35899. return SQLITE_NOMEM;
  35900. }else{
  35901. memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
  35902. memset(p->u.apSub, 0, sizeof(p->u.apSub));
  35903. p->iDivisor = (p->iSize + BITVEC_NPTR - 1)/BITVEC_NPTR;
  35904. rc = sqlite3BitvecSet(p, i);
  35905. for(j=0; j<BITVEC_NINT; j++){
  35906. if( aiValues[j] ) rc |= sqlite3BitvecSet(p, aiValues[j]);
  35907. }
  35908. sqlite3StackFree(0, aiValues);
  35909. return rc;
  35910. }
  35911. }
  35912. bitvec_set_end:
  35913. p->nSet++;
  35914. p->u.aHash[h] = i;
  35915. return SQLITE_OK;
  35916. }
  35917. /*
  35918. ** Clear the i-th bit.
  35919. **
  35920. ** pBuf must be a pointer to at least BITVEC_SZ bytes of temporary storage
  35921. ** that BitvecClear can use to rebuilt its hash table.
  35922. */
  35923. SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec *p, u32 i, void *pBuf){
  35924. if( p==0 ) return;
  35925. assert( i>0 );
  35926. i--;
  35927. while( p->iDivisor ){
  35928. u32 bin = i/p->iDivisor;
  35929. i = i%p->iDivisor;
  35930. p = p->u.apSub[bin];
  35931. if (!p) {
  35932. return;
  35933. }
  35934. }
  35935. if( p->iSize<=BITVEC_NBIT ){
  35936. p->u.aBitmap[i/BITVEC_SZELEM] &= ~(1 << (i&(BITVEC_SZELEM-1)));
  35937. }else{
  35938. unsigned int j;
  35939. u32 *aiValues = pBuf;
  35940. memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
  35941. memset(p->u.aHash, 0, sizeof(p->u.aHash));
  35942. p->nSet = 0;
  35943. for(j=0; j<BITVEC_NINT; j++){
  35944. if( aiValues[j] && aiValues[j]!=(i+1) ){
  35945. u32 h = BITVEC_HASH(aiValues[j]-1);
  35946. p->nSet++;
  35947. while( p->u.aHash[h] ){
  35948. h++;
  35949. if( h>=BITVEC_NINT ) h = 0;
  35950. }
  35951. p->u.aHash[h] = aiValues[j];
  35952. }
  35953. }
  35954. }
  35955. }
  35956. /*
  35957. ** Destroy a bitmap object. Reclaim all memory used.
  35958. */
  35959. SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec *p){
  35960. if( p==0 ) return;
  35961. if( p->iDivisor ){
  35962. unsigned int i;
  35963. for(i=0; i<BITVEC_NPTR; i++){
  35964. sqlite3BitvecDestroy(p->u.apSub[i]);
  35965. }
  35966. }
  35967. sqlite3_free(p);
  35968. }
  35969. /*
  35970. ** Return the value of the iSize parameter specified when Bitvec *p
  35971. ** was created.
  35972. */
  35973. SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec *p){
  35974. return p->iSize;
  35975. }
  35976. #ifndef SQLITE_OMIT_BUILTIN_TEST
  35977. /*
  35978. ** Let V[] be an array of unsigned characters sufficient to hold
  35979. ** up to N bits. Let I be an integer between 0 and N. 0<=I<N.
  35980. ** Then the following macros can be used to set, clear, or test
  35981. ** individual bits within V.
  35982. */
  35983. #define SETBIT(V,I) V[I>>3] |= (1<<(I&7))
  35984. #define CLEARBIT(V,I) V[I>>3] &= ~(1<<(I&7))
  35985. #define TESTBIT(V,I) (V[I>>3]&(1<<(I&7)))!=0
  35986. /*
  35987. ** This routine runs an extensive test of the Bitvec code.
  35988. **
  35989. ** The input is an array of integers that acts as a program
  35990. ** to test the Bitvec. The integers are opcodes followed
  35991. ** by 0, 1, or 3 operands, depending on the opcode. Another
  35992. ** opcode follows immediately after the last operand.
  35993. **
  35994. ** There are 6 opcodes numbered from 0 through 5. 0 is the
  35995. ** "halt" opcode and causes the test to end.
  35996. **
  35997. ** 0 Halt and return the number of errors
  35998. ** 1 N S X Set N bits beginning with S and incrementing by X
  35999. ** 2 N S X Clear N bits beginning with S and incrementing by X
  36000. ** 3 N Set N randomly chosen bits
  36001. ** 4 N Clear N randomly chosen bits
  36002. ** 5 N S X Set N bits from S increment X in array only, not in bitvec
  36003. **
  36004. ** The opcodes 1 through 4 perform set and clear operations are performed
  36005. ** on both a Bitvec object and on a linear array of bits obtained from malloc.
  36006. ** Opcode 5 works on the linear array only, not on the Bitvec.
  36007. ** Opcode 5 is used to deliberately induce a fault in order to
  36008. ** confirm that error detection works.
  36009. **
  36010. ** At the conclusion of the test the linear array is compared
  36011. ** against the Bitvec object. If there are any differences,
  36012. ** an error is returned. If they are the same, zero is returned.
  36013. **
  36014. ** If a memory allocation error occurs, return -1.
  36015. */
  36016. SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int sz, int *aOp){
  36017. Bitvec *pBitvec = 0;
  36018. unsigned char *pV = 0;
  36019. int rc = -1;
  36020. int i, nx, pc, op;
  36021. void *pTmpSpace;
  36022. /* Allocate the Bitvec to be tested and a linear array of
  36023. ** bits to act as the reference */
  36024. pBitvec = sqlite3BitvecCreate( sz );
  36025. pV = sqlite3MallocZero( (sz+7)/8 + 1 );
  36026. pTmpSpace = sqlite3_malloc(BITVEC_SZ);
  36027. if( pBitvec==0 || pV==0 || pTmpSpace==0 ) goto bitvec_end;
  36028. /* NULL pBitvec tests */
  36029. sqlite3BitvecSet(0, 1);
  36030. sqlite3BitvecClear(0, 1, pTmpSpace);
  36031. /* Run the program */
  36032. pc = 0;
  36033. while( (op = aOp[pc])!=0 ){
  36034. switch( op ){
  36035. case 1:
  36036. case 2:
  36037. case 5: {
  36038. nx = 4;
  36039. i = aOp[pc+2] - 1;
  36040. aOp[pc+2] += aOp[pc+3];
  36041. break;
  36042. }
  36043. case 3:
  36044. case 4:
  36045. default: {
  36046. nx = 2;
  36047. sqlite3_randomness(sizeof(i), &i);
  36048. break;
  36049. }
  36050. }
  36051. if( (--aOp[pc+1]) > 0 ) nx = 0;
  36052. pc += nx;
  36053. i = (i & 0x7fffffff)%sz;
  36054. if( (op & 1)!=0 ){
  36055. SETBIT(pV, (i+1));
  36056. if( op!=5 ){
  36057. if( sqlite3BitvecSet(pBitvec, i+1) ) goto bitvec_end;
  36058. }
  36059. }else{
  36060. CLEARBIT(pV, (i+1));
  36061. sqlite3BitvecClear(pBitvec, i+1, pTmpSpace);
  36062. }
  36063. }
  36064. /* Test to make sure the linear array exactly matches the
  36065. ** Bitvec object. Start with the assumption that they do
  36066. ** match (rc==0). Change rc to non-zero if a discrepancy
  36067. ** is found.
  36068. */
  36069. rc = sqlite3BitvecTest(0,0) + sqlite3BitvecTest(pBitvec, sz+1)
  36070. + sqlite3BitvecTest(pBitvec, 0)
  36071. + (sqlite3BitvecSize(pBitvec) - sz);
  36072. for(i=1; i<=sz; i++){
  36073. if( (TESTBIT(pV,i))!=sqlite3BitvecTest(pBitvec,i) ){
  36074. rc = i;
  36075. break;
  36076. }
  36077. }
  36078. /* Free allocated structure */
  36079. bitvec_end:
  36080. sqlite3_free(pTmpSpace);
  36081. sqlite3_free(pV);
  36082. sqlite3BitvecDestroy(pBitvec);
  36083. return rc;
  36084. }
  36085. #endif /* SQLITE_OMIT_BUILTIN_TEST */
  36086. /************** End of bitvec.c **********************************************/
  36087. /************** Begin file pcache.c ******************************************/
  36088. /*
  36089. ** 2008 August 05
  36090. **
  36091. ** The author disclaims copyright to this source code. In place of
  36092. ** a legal notice, here is a blessing:
  36093. **
  36094. ** May you do good and not evil.
  36095. ** May you find forgiveness for yourself and forgive others.
  36096. ** May you share freely, never taking more than you give.
  36097. **
  36098. *************************************************************************
  36099. ** This file implements that page cache.
  36100. */
  36101. /*
  36102. ** A complete page cache is an instance of this structure.
  36103. */
  36104. struct PCache {
  36105. PgHdr *pDirty, *pDirtyTail; /* List of dirty pages in LRU order */
  36106. PgHdr *pSynced; /* Last synced page in dirty page list */
  36107. int nRef; /* Number of referenced pages */
  36108. int szCache; /* Configured cache size */
  36109. int szPage; /* Size of every page in this cache */
  36110. int szExtra; /* Size of extra space for each page */
  36111. u8 bPurgeable; /* True if pages are on backing store */
  36112. u8 eCreate; /* eCreate value for for xFetch() */
  36113. int (*xStress)(void*,PgHdr*); /* Call to try make a page clean */
  36114. void *pStress; /* Argument to xStress */
  36115. sqlite3_pcache *pCache; /* Pluggable cache module */
  36116. PgHdr *pPage1; /* Reference to page 1 */
  36117. };
  36118. /*
  36119. ** Some of the assert() macros in this code are too expensive to run
  36120. ** even during normal debugging. Use them only rarely on long-running
  36121. ** tests. Enable the expensive asserts using the
  36122. ** -DSQLITE_ENABLE_EXPENSIVE_ASSERT=1 compile-time option.
  36123. */
  36124. #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
  36125. # define expensive_assert(X) assert(X)
  36126. #else
  36127. # define expensive_assert(X)
  36128. #endif
  36129. /********************************** Linked List Management ********************/
  36130. /* Allowed values for second argument to pcacheManageDirtyList() */
  36131. #define PCACHE_DIRTYLIST_REMOVE 1 /* Remove pPage from dirty list */
  36132. #define PCACHE_DIRTYLIST_ADD 2 /* Add pPage to the dirty list */
  36133. #define PCACHE_DIRTYLIST_FRONT 3 /* Move pPage to the front of the list */
  36134. /*
  36135. ** Manage pPage's participation on the dirty list. Bits of the addRemove
  36136. ** argument determines what operation to do. The 0x01 bit means first
  36137. ** remove pPage from the dirty list. The 0x02 means add pPage back to
  36138. ** the dirty list. Doing both moves pPage to the front of the dirty list.
  36139. */
  36140. static void pcacheManageDirtyList(PgHdr *pPage, u8 addRemove){
  36141. PCache *p = pPage->pCache;
  36142. if( addRemove & PCACHE_DIRTYLIST_REMOVE ){
  36143. assert( pPage->pDirtyNext || pPage==p->pDirtyTail );
  36144. assert( pPage->pDirtyPrev || pPage==p->pDirty );
  36145. /* Update the PCache1.pSynced variable if necessary. */
  36146. if( p->pSynced==pPage ){
  36147. PgHdr *pSynced = pPage->pDirtyPrev;
  36148. while( pSynced && (pSynced->flags&PGHDR_NEED_SYNC) ){
  36149. pSynced = pSynced->pDirtyPrev;
  36150. }
  36151. p->pSynced = pSynced;
  36152. }
  36153. if( pPage->pDirtyNext ){
  36154. pPage->pDirtyNext->pDirtyPrev = pPage->pDirtyPrev;
  36155. }else{
  36156. assert( pPage==p->pDirtyTail );
  36157. p->pDirtyTail = pPage->pDirtyPrev;
  36158. }
  36159. if( pPage->pDirtyPrev ){
  36160. pPage->pDirtyPrev->pDirtyNext = pPage->pDirtyNext;
  36161. }else{
  36162. assert( pPage==p->pDirty );
  36163. p->pDirty = pPage->pDirtyNext;
  36164. if( p->pDirty==0 && p->bPurgeable ){
  36165. assert( p->eCreate==1 );
  36166. p->eCreate = 2;
  36167. }
  36168. }
  36169. pPage->pDirtyNext = 0;
  36170. pPage->pDirtyPrev = 0;
  36171. }
  36172. if( addRemove & PCACHE_DIRTYLIST_ADD ){
  36173. assert( pPage->pDirtyNext==0 && pPage->pDirtyPrev==0 && p->pDirty!=pPage );
  36174. pPage->pDirtyNext = p->pDirty;
  36175. if( pPage->pDirtyNext ){
  36176. assert( pPage->pDirtyNext->pDirtyPrev==0 );
  36177. pPage->pDirtyNext->pDirtyPrev = pPage;
  36178. }else{
  36179. p->pDirtyTail = pPage;
  36180. if( p->bPurgeable ){
  36181. assert( p->eCreate==2 );
  36182. p->eCreate = 1;
  36183. }
  36184. }
  36185. p->pDirty = pPage;
  36186. if( !p->pSynced && 0==(pPage->flags&PGHDR_NEED_SYNC) ){
  36187. p->pSynced = pPage;
  36188. }
  36189. }
  36190. }
  36191. /*
  36192. ** Wrapper around the pluggable caches xUnpin method. If the cache is
  36193. ** being used for an in-memory database, this function is a no-op.
  36194. */
  36195. static void pcacheUnpin(PgHdr *p){
  36196. if( p->pCache->bPurgeable ){
  36197. if( p->pgno==1 ){
  36198. p->pCache->pPage1 = 0;
  36199. }
  36200. sqlite3GlobalConfig.pcache2.xUnpin(p->pCache->pCache, p->pPage, 0);
  36201. }
  36202. }
  36203. /*
  36204. ** Compute the number of pages of cache requested.
  36205. */
  36206. static int numberOfCachePages(PCache *p){
  36207. if( p->szCache>=0 ){
  36208. return p->szCache;
  36209. }else{
  36210. return (int)((-1024*(i64)p->szCache)/(p->szPage+p->szExtra));
  36211. }
  36212. }
  36213. /*************************************************** General Interfaces ******
  36214. **
  36215. ** Initialize and shutdown the page cache subsystem. Neither of these
  36216. ** functions are threadsafe.
  36217. */
  36218. SQLITE_PRIVATE int sqlite3PcacheInitialize(void){
  36219. if( sqlite3GlobalConfig.pcache2.xInit==0 ){
  36220. /* IMPLEMENTATION-OF: R-26801-64137 If the xInit() method is NULL, then the
  36221. ** built-in default page cache is used instead of the application defined
  36222. ** page cache. */
  36223. sqlite3PCacheSetDefault();
  36224. }
  36225. return sqlite3GlobalConfig.pcache2.xInit(sqlite3GlobalConfig.pcache2.pArg);
  36226. }
  36227. SQLITE_PRIVATE void sqlite3PcacheShutdown(void){
  36228. if( sqlite3GlobalConfig.pcache2.xShutdown ){
  36229. /* IMPLEMENTATION-OF: R-26000-56589 The xShutdown() method may be NULL. */
  36230. sqlite3GlobalConfig.pcache2.xShutdown(sqlite3GlobalConfig.pcache2.pArg);
  36231. }
  36232. }
  36233. /*
  36234. ** Return the size in bytes of a PCache object.
  36235. */
  36236. SQLITE_PRIVATE int sqlite3PcacheSize(void){ return sizeof(PCache); }
  36237. /*
  36238. ** Create a new PCache object. Storage space to hold the object
  36239. ** has already been allocated and is passed in as the p pointer.
  36240. ** The caller discovers how much space needs to be allocated by
  36241. ** calling sqlite3PcacheSize().
  36242. */
  36243. SQLITE_PRIVATE int sqlite3PcacheOpen(
  36244. int szPage, /* Size of every page */
  36245. int szExtra, /* Extra space associated with each page */
  36246. int bPurgeable, /* True if pages are on backing store */
  36247. int (*xStress)(void*,PgHdr*),/* Call to try to make pages clean */
  36248. void *pStress, /* Argument to xStress */
  36249. PCache *p /* Preallocated space for the PCache */
  36250. ){
  36251. memset(p, 0, sizeof(PCache));
  36252. p->szPage = 1;
  36253. p->szExtra = szExtra;
  36254. p->bPurgeable = bPurgeable;
  36255. p->eCreate = 2;
  36256. p->xStress = xStress;
  36257. p->pStress = pStress;
  36258. p->szCache = 100;
  36259. return sqlite3PcacheSetPageSize(p, szPage);
  36260. }
  36261. /*
  36262. ** Change the page size for PCache object. The caller must ensure that there
  36263. ** are no outstanding page references when this function is called.
  36264. */
  36265. SQLITE_PRIVATE int sqlite3PcacheSetPageSize(PCache *pCache, int szPage){
  36266. assert( pCache->nRef==0 && pCache->pDirty==0 );
  36267. if( pCache->szPage ){
  36268. sqlite3_pcache *pNew;
  36269. pNew = sqlite3GlobalConfig.pcache2.xCreate(
  36270. szPage, pCache->szExtra + sizeof(PgHdr), pCache->bPurgeable
  36271. );
  36272. if( pNew==0 ) return SQLITE_NOMEM;
  36273. sqlite3GlobalConfig.pcache2.xCachesize(pNew, numberOfCachePages(pCache));
  36274. if( pCache->pCache ){
  36275. sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache);
  36276. }
  36277. pCache->pCache = pNew;
  36278. pCache->pPage1 = 0;
  36279. pCache->szPage = szPage;
  36280. }
  36281. return SQLITE_OK;
  36282. }
  36283. /*
  36284. ** Try to obtain a page from the cache.
  36285. **
  36286. ** This routine returns a pointer to an sqlite3_pcache_page object if
  36287. ** such an object is already in cache, or if a new one is created.
  36288. ** This routine returns a NULL pointer if the object was not in cache
  36289. ** and could not be created.
  36290. **
  36291. ** The createFlags should be 0 to check for existing pages and should
  36292. ** be 3 (not 1, but 3) to try to create a new page.
  36293. **
  36294. ** If the createFlag is 0, then NULL is always returned if the page
  36295. ** is not already in the cache. If createFlag is 1, then a new page
  36296. ** is created only if that can be done without spilling dirty pages
  36297. ** and without exceeding the cache size limit.
  36298. **
  36299. ** The caller needs to invoke sqlite3PcacheFetchFinish() to properly
  36300. ** initialize the sqlite3_pcache_page object and convert it into a
  36301. ** PgHdr object. The sqlite3PcacheFetch() and sqlite3PcacheFetchFinish()
  36302. ** routines are split this way for performance reasons. When separated
  36303. ** they can both (usually) operate without having to push values to
  36304. ** the stack on entry and pop them back off on exit, which saves a
  36305. ** lot of pushing and popping.
  36306. */
  36307. SQLITE_PRIVATE sqlite3_pcache_page *sqlite3PcacheFetch(
  36308. PCache *pCache, /* Obtain the page from this cache */
  36309. Pgno pgno, /* Page number to obtain */
  36310. int createFlag /* If true, create page if it does not exist already */
  36311. ){
  36312. int eCreate;
  36313. assert( pCache!=0 );
  36314. assert( pCache->pCache!=0 );
  36315. assert( createFlag==3 || createFlag==0 );
  36316. assert( pgno>0 );
  36317. /* eCreate defines what to do if the page does not exist.
  36318. ** 0 Do not allocate a new page. (createFlag==0)
  36319. ** 1 Allocate a new page if doing so is inexpensive.
  36320. ** (createFlag==1 AND bPurgeable AND pDirty)
  36321. ** 2 Allocate a new page even it doing so is difficult.
  36322. ** (createFlag==1 AND !(bPurgeable AND pDirty)
  36323. */
  36324. eCreate = createFlag & pCache->eCreate;
  36325. assert( eCreate==0 || eCreate==1 || eCreate==2 );
  36326. assert( createFlag==0 || pCache->eCreate==eCreate );
  36327. assert( createFlag==0 || eCreate==1+(!pCache->bPurgeable||!pCache->pDirty) );
  36328. return sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, pgno, eCreate);
  36329. }
  36330. /*
  36331. ** If the sqlite3PcacheFetch() routine is unable to allocate a new
  36332. ** page because new clean pages are available for reuse and the cache
  36333. ** size limit has been reached, then this routine can be invoked to
  36334. ** try harder to allocate a page. This routine might invoke the stress
  36335. ** callback to spill dirty pages to the journal. It will then try to
  36336. ** allocate the new page and will only fail to allocate a new page on
  36337. ** an OOM error.
  36338. **
  36339. ** This routine should be invoked only after sqlite3PcacheFetch() fails.
  36340. */
  36341. SQLITE_PRIVATE int sqlite3PcacheFetchStress(
  36342. PCache *pCache, /* Obtain the page from this cache */
  36343. Pgno pgno, /* Page number to obtain */
  36344. sqlite3_pcache_page **ppPage /* Write result here */
  36345. ){
  36346. PgHdr *pPg;
  36347. if( pCache->eCreate==2 ) return 0;
  36348. /* Find a dirty page to write-out and recycle. First try to find a
  36349. ** page that does not require a journal-sync (one with PGHDR_NEED_SYNC
  36350. ** cleared), but if that is not possible settle for any other
  36351. ** unreferenced dirty page.
  36352. */
  36353. for(pPg=pCache->pSynced;
  36354. pPg && (pPg->nRef || (pPg->flags&PGHDR_NEED_SYNC));
  36355. pPg=pPg->pDirtyPrev
  36356. );
  36357. pCache->pSynced = pPg;
  36358. if( !pPg ){
  36359. for(pPg=pCache->pDirtyTail; pPg && pPg->nRef; pPg=pPg->pDirtyPrev);
  36360. }
  36361. if( pPg ){
  36362. int rc;
  36363. #ifdef SQLITE_LOG_CACHE_SPILL
  36364. sqlite3_log(SQLITE_FULL,
  36365. "spill page %d making room for %d - cache used: %d/%d",
  36366. pPg->pgno, pgno,
  36367. sqlite3GlobalConfig.pcache.xPagecount(pCache->pCache),
  36368. numberOfCachePages(pCache));
  36369. #endif
  36370. rc = pCache->xStress(pCache->pStress, pPg);
  36371. if( rc!=SQLITE_OK && rc!=SQLITE_BUSY ){
  36372. return rc;
  36373. }
  36374. }
  36375. *ppPage = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, pgno, 2);
  36376. return *ppPage==0 ? SQLITE_NOMEM : SQLITE_OK;
  36377. }
  36378. /*
  36379. ** This is a helper routine for sqlite3PcacheFetchFinish()
  36380. **
  36381. ** In the uncommon case where the page being fetched has not been
  36382. ** initialized, this routine is invoked to do the initialization.
  36383. ** This routine is broken out into a separate function since it
  36384. ** requires extra stack manipulation that can be avoided in the common
  36385. ** case.
  36386. */
  36387. static SQLITE_NOINLINE PgHdr *pcacheFetchFinishWithInit(
  36388. PCache *pCache, /* Obtain the page from this cache */
  36389. Pgno pgno, /* Page number obtained */
  36390. sqlite3_pcache_page *pPage /* Page obtained by prior PcacheFetch() call */
  36391. ){
  36392. PgHdr *pPgHdr;
  36393. assert( pPage!=0 );
  36394. pPgHdr = (PgHdr*)pPage->pExtra;
  36395. assert( pPgHdr->pPage==0 );
  36396. memset(pPgHdr, 0, sizeof(PgHdr));
  36397. pPgHdr->pPage = pPage;
  36398. pPgHdr->pData = pPage->pBuf;
  36399. pPgHdr->pExtra = (void *)&pPgHdr[1];
  36400. memset(pPgHdr->pExtra, 0, pCache->szExtra);
  36401. pPgHdr->pCache = pCache;
  36402. pPgHdr->pgno = pgno;
  36403. return sqlite3PcacheFetchFinish(pCache,pgno,pPage);
  36404. }
  36405. /*
  36406. ** This routine converts the sqlite3_pcache_page object returned by
  36407. ** sqlite3PcacheFetch() into an initialized PgHdr object. This routine
  36408. ** must be called after sqlite3PcacheFetch() in order to get a usable
  36409. ** result.
  36410. */
  36411. SQLITE_PRIVATE PgHdr *sqlite3PcacheFetchFinish(
  36412. PCache *pCache, /* Obtain the page from this cache */
  36413. Pgno pgno, /* Page number obtained */
  36414. sqlite3_pcache_page *pPage /* Page obtained by prior PcacheFetch() call */
  36415. ){
  36416. PgHdr *pPgHdr;
  36417. if( pPage==0 ) return 0;
  36418. pPgHdr = (PgHdr *)pPage->pExtra;
  36419. if( !pPgHdr->pPage ){
  36420. return pcacheFetchFinishWithInit(pCache, pgno, pPage);
  36421. }
  36422. if( 0==pPgHdr->nRef ){
  36423. pCache->nRef++;
  36424. }
  36425. pPgHdr->nRef++;
  36426. if( pgno==1 ){
  36427. pCache->pPage1 = pPgHdr;
  36428. }
  36429. return pPgHdr;
  36430. }
  36431. /*
  36432. ** Decrement the reference count on a page. If the page is clean and the
  36433. ** reference count drops to 0, then it is made eligible for recycling.
  36434. */
  36435. SQLITE_PRIVATE void SQLITE_NOINLINE sqlite3PcacheRelease(PgHdr *p){
  36436. assert( p->nRef>0 );
  36437. p->nRef--;
  36438. if( p->nRef==0 ){
  36439. p->pCache->nRef--;
  36440. if( (p->flags&PGHDR_DIRTY)==0 ){
  36441. pcacheUnpin(p);
  36442. }else if( p->pDirtyPrev!=0 ){
  36443. /* Move the page to the head of the dirty list. */
  36444. pcacheManageDirtyList(p, PCACHE_DIRTYLIST_FRONT);
  36445. }
  36446. }
  36447. }
  36448. /*
  36449. ** Increase the reference count of a supplied page by 1.
  36450. */
  36451. SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr *p){
  36452. assert(p->nRef>0);
  36453. p->nRef++;
  36454. }
  36455. /*
  36456. ** Drop a page from the cache. There must be exactly one reference to the
  36457. ** page. This function deletes that reference, so after it returns the
  36458. ** page pointed to by p is invalid.
  36459. */
  36460. SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr *p){
  36461. assert( p->nRef==1 );
  36462. if( p->flags&PGHDR_DIRTY ){
  36463. pcacheManageDirtyList(p, PCACHE_DIRTYLIST_REMOVE);
  36464. }
  36465. p->pCache->nRef--;
  36466. if( p->pgno==1 ){
  36467. p->pCache->pPage1 = 0;
  36468. }
  36469. sqlite3GlobalConfig.pcache2.xUnpin(p->pCache->pCache, p->pPage, 1);
  36470. }
  36471. /*
  36472. ** Make sure the page is marked as dirty. If it isn't dirty already,
  36473. ** make it so.
  36474. */
  36475. SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr *p){
  36476. p->flags &= ~PGHDR_DONT_WRITE;
  36477. assert( p->nRef>0 );
  36478. if( 0==(p->flags & PGHDR_DIRTY) ){
  36479. p->flags |= PGHDR_DIRTY;
  36480. pcacheManageDirtyList(p, PCACHE_DIRTYLIST_ADD);
  36481. }
  36482. }
  36483. /*
  36484. ** Make sure the page is marked as clean. If it isn't clean already,
  36485. ** make it so.
  36486. */
  36487. SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr *p){
  36488. if( (p->flags & PGHDR_DIRTY) ){
  36489. pcacheManageDirtyList(p, PCACHE_DIRTYLIST_REMOVE);
  36490. p->flags &= ~(PGHDR_DIRTY|PGHDR_NEED_SYNC);
  36491. if( p->nRef==0 ){
  36492. pcacheUnpin(p);
  36493. }
  36494. }
  36495. }
  36496. /*
  36497. ** Make every page in the cache clean.
  36498. */
  36499. SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache *pCache){
  36500. PgHdr *p;
  36501. while( (p = pCache->pDirty)!=0 ){
  36502. sqlite3PcacheMakeClean(p);
  36503. }
  36504. }
  36505. /*
  36506. ** Clear the PGHDR_NEED_SYNC flag from all dirty pages.
  36507. */
  36508. SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *pCache){
  36509. PgHdr *p;
  36510. for(p=pCache->pDirty; p; p=p->pDirtyNext){
  36511. p->flags &= ~PGHDR_NEED_SYNC;
  36512. }
  36513. pCache->pSynced = pCache->pDirtyTail;
  36514. }
  36515. /*
  36516. ** Change the page number of page p to newPgno.
  36517. */
  36518. SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr *p, Pgno newPgno){
  36519. PCache *pCache = p->pCache;
  36520. assert( p->nRef>0 );
  36521. assert( newPgno>0 );
  36522. sqlite3GlobalConfig.pcache2.xRekey(pCache->pCache, p->pPage, p->pgno,newPgno);
  36523. p->pgno = newPgno;
  36524. if( (p->flags&PGHDR_DIRTY) && (p->flags&PGHDR_NEED_SYNC) ){
  36525. pcacheManageDirtyList(p, PCACHE_DIRTYLIST_FRONT);
  36526. }
  36527. }
  36528. /*
  36529. ** Drop every cache entry whose page number is greater than "pgno". The
  36530. ** caller must ensure that there are no outstanding references to any pages
  36531. ** other than page 1 with a page number greater than pgno.
  36532. **
  36533. ** If there is a reference to page 1 and the pgno parameter passed to this
  36534. ** function is 0, then the data area associated with page 1 is zeroed, but
  36535. ** the page object is not dropped.
  36536. */
  36537. SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache *pCache, Pgno pgno){
  36538. if( pCache->pCache ){
  36539. PgHdr *p;
  36540. PgHdr *pNext;
  36541. for(p=pCache->pDirty; p; p=pNext){
  36542. pNext = p->pDirtyNext;
  36543. /* This routine never gets call with a positive pgno except right
  36544. ** after sqlite3PcacheCleanAll(). So if there are dirty pages,
  36545. ** it must be that pgno==0.
  36546. */
  36547. assert( p->pgno>0 );
  36548. if( ALWAYS(p->pgno>pgno) ){
  36549. assert( p->flags&PGHDR_DIRTY );
  36550. sqlite3PcacheMakeClean(p);
  36551. }
  36552. }
  36553. if( pgno==0 && pCache->pPage1 ){
  36554. memset(pCache->pPage1->pData, 0, pCache->szPage);
  36555. pgno = 1;
  36556. }
  36557. sqlite3GlobalConfig.pcache2.xTruncate(pCache->pCache, pgno+1);
  36558. }
  36559. }
  36560. /*
  36561. ** Close a cache.
  36562. */
  36563. SQLITE_PRIVATE void sqlite3PcacheClose(PCache *pCache){
  36564. assert( pCache->pCache!=0 );
  36565. sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache);
  36566. }
  36567. /*
  36568. ** Discard the contents of the cache.
  36569. */
  36570. SQLITE_PRIVATE void sqlite3PcacheClear(PCache *pCache){
  36571. sqlite3PcacheTruncate(pCache, 0);
  36572. }
  36573. /*
  36574. ** Merge two lists of pages connected by pDirty and in pgno order.
  36575. ** Do not both fixing the pDirtyPrev pointers.
  36576. */
  36577. static PgHdr *pcacheMergeDirtyList(PgHdr *pA, PgHdr *pB){
  36578. PgHdr result, *pTail;
  36579. pTail = &result;
  36580. while( pA && pB ){
  36581. if( pA->pgno<pB->pgno ){
  36582. pTail->pDirty = pA;
  36583. pTail = pA;
  36584. pA = pA->pDirty;
  36585. }else{
  36586. pTail->pDirty = pB;
  36587. pTail = pB;
  36588. pB = pB->pDirty;
  36589. }
  36590. }
  36591. if( pA ){
  36592. pTail->pDirty = pA;
  36593. }else if( pB ){
  36594. pTail->pDirty = pB;
  36595. }else{
  36596. pTail->pDirty = 0;
  36597. }
  36598. return result.pDirty;
  36599. }
  36600. /*
  36601. ** Sort the list of pages in accending order by pgno. Pages are
  36602. ** connected by pDirty pointers. The pDirtyPrev pointers are
  36603. ** corrupted by this sort.
  36604. **
  36605. ** Since there cannot be more than 2^31 distinct pages in a database,
  36606. ** there cannot be more than 31 buckets required by the merge sorter.
  36607. ** One extra bucket is added to catch overflow in case something
  36608. ** ever changes to make the previous sentence incorrect.
  36609. */
  36610. #define N_SORT_BUCKET 32
  36611. static PgHdr *pcacheSortDirtyList(PgHdr *pIn){
  36612. PgHdr *a[N_SORT_BUCKET], *p;
  36613. int i;
  36614. memset(a, 0, sizeof(a));
  36615. while( pIn ){
  36616. p = pIn;
  36617. pIn = p->pDirty;
  36618. p->pDirty = 0;
  36619. for(i=0; ALWAYS(i<N_SORT_BUCKET-1); i++){
  36620. if( a[i]==0 ){
  36621. a[i] = p;
  36622. break;
  36623. }else{
  36624. p = pcacheMergeDirtyList(a[i], p);
  36625. a[i] = 0;
  36626. }
  36627. }
  36628. if( NEVER(i==N_SORT_BUCKET-1) ){
  36629. /* To get here, there need to be 2^(N_SORT_BUCKET) elements in
  36630. ** the input list. But that is impossible.
  36631. */
  36632. a[i] = pcacheMergeDirtyList(a[i], p);
  36633. }
  36634. }
  36635. p = a[0];
  36636. for(i=1; i<N_SORT_BUCKET; i++){
  36637. p = pcacheMergeDirtyList(p, a[i]);
  36638. }
  36639. return p;
  36640. }
  36641. /*
  36642. ** Return a list of all dirty pages in the cache, sorted by page number.
  36643. */
  36644. SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache *pCache){
  36645. PgHdr *p;
  36646. for(p=pCache->pDirty; p; p=p->pDirtyNext){
  36647. p->pDirty = p->pDirtyNext;
  36648. }
  36649. return pcacheSortDirtyList(pCache->pDirty);
  36650. }
  36651. /*
  36652. ** Return the total number of referenced pages held by the cache.
  36653. */
  36654. SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache *pCache){
  36655. return pCache->nRef;
  36656. }
  36657. /*
  36658. ** Return the number of references to the page supplied as an argument.
  36659. */
  36660. SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr *p){
  36661. return p->nRef;
  36662. }
  36663. /*
  36664. ** Return the total number of pages in the cache.
  36665. */
  36666. SQLITE_PRIVATE int sqlite3PcachePagecount(PCache *pCache){
  36667. assert( pCache->pCache!=0 );
  36668. return sqlite3GlobalConfig.pcache2.xPagecount(pCache->pCache);
  36669. }
  36670. #ifdef SQLITE_TEST
  36671. /*
  36672. ** Get the suggested cache-size value.
  36673. */
  36674. SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *pCache){
  36675. return numberOfCachePages(pCache);
  36676. }
  36677. #endif
  36678. /*
  36679. ** Set the suggested cache-size value.
  36680. */
  36681. SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *pCache, int mxPage){
  36682. assert( pCache->pCache!=0 );
  36683. pCache->szCache = mxPage;
  36684. sqlite3GlobalConfig.pcache2.xCachesize(pCache->pCache,
  36685. numberOfCachePages(pCache));
  36686. }
  36687. /*
  36688. ** Free up as much memory as possible from the page cache.
  36689. */
  36690. SQLITE_PRIVATE void sqlite3PcacheShrink(PCache *pCache){
  36691. assert( pCache->pCache!=0 );
  36692. sqlite3GlobalConfig.pcache2.xShrink(pCache->pCache);
  36693. }
  36694. #if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
  36695. /*
  36696. ** For all dirty pages currently in the cache, invoke the specified
  36697. ** callback. This is only used if the SQLITE_CHECK_PAGES macro is
  36698. ** defined.
  36699. */
  36700. SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *)){
  36701. PgHdr *pDirty;
  36702. for(pDirty=pCache->pDirty; pDirty; pDirty=pDirty->pDirtyNext){
  36703. xIter(pDirty);
  36704. }
  36705. }
  36706. #endif
  36707. /************** End of pcache.c **********************************************/
  36708. /************** Begin file pcache1.c *****************************************/
  36709. /*
  36710. ** 2008 November 05
  36711. **
  36712. ** The author disclaims copyright to this source code. In place of
  36713. ** a legal notice, here is a blessing:
  36714. **
  36715. ** May you do good and not evil.
  36716. ** May you find forgiveness for yourself and forgive others.
  36717. ** May you share freely, never taking more than you give.
  36718. **
  36719. *************************************************************************
  36720. **
  36721. ** This file implements the default page cache implementation (the
  36722. ** sqlite3_pcache interface). It also contains part of the implementation
  36723. ** of the SQLITE_CONFIG_PAGECACHE and sqlite3_release_memory() features.
  36724. ** If the default page cache implementation is overridden, then neither of
  36725. ** these two features are available.
  36726. */
  36727. typedef struct PCache1 PCache1;
  36728. typedef struct PgHdr1 PgHdr1;
  36729. typedef struct PgFreeslot PgFreeslot;
  36730. typedef struct PGroup PGroup;
  36731. /* Each page cache (or PCache) belongs to a PGroup. A PGroup is a set
  36732. ** of one or more PCaches that are able to recycle each other's unpinned
  36733. ** pages when they are under memory pressure. A PGroup is an instance of
  36734. ** the following object.
  36735. **
  36736. ** This page cache implementation works in one of two modes:
  36737. **
  36738. ** (1) Every PCache is the sole member of its own PGroup. There is
  36739. ** one PGroup per PCache.
  36740. **
  36741. ** (2) There is a single global PGroup that all PCaches are a member
  36742. ** of.
  36743. **
  36744. ** Mode 1 uses more memory (since PCache instances are not able to rob
  36745. ** unused pages from other PCaches) but it also operates without a mutex,
  36746. ** and is therefore often faster. Mode 2 requires a mutex in order to be
  36747. ** threadsafe, but recycles pages more efficiently.
  36748. **
  36749. ** For mode (1), PGroup.mutex is NULL. For mode (2) there is only a single
  36750. ** PGroup which is the pcache1.grp global variable and its mutex is
  36751. ** SQLITE_MUTEX_STATIC_LRU.
  36752. */
  36753. struct PGroup {
  36754. sqlite3_mutex *mutex; /* MUTEX_STATIC_LRU or NULL */
  36755. unsigned int nMaxPage; /* Sum of nMax for purgeable caches */
  36756. unsigned int nMinPage; /* Sum of nMin for purgeable caches */
  36757. unsigned int mxPinned; /* nMaxpage + 10 - nMinPage */
  36758. unsigned int nCurrentPage; /* Number of purgeable pages allocated */
  36759. PgHdr1 *pLruHead, *pLruTail; /* LRU list of unpinned pages */
  36760. };
  36761. /* Each page cache is an instance of the following object. Every
  36762. ** open database file (including each in-memory database and each
  36763. ** temporary or transient database) has a single page cache which
  36764. ** is an instance of this object.
  36765. **
  36766. ** Pointers to structures of this type are cast and returned as
  36767. ** opaque sqlite3_pcache* handles.
  36768. */
  36769. struct PCache1 {
  36770. /* Cache configuration parameters. Page size (szPage) and the purgeable
  36771. ** flag (bPurgeable) are set when the cache is created. nMax may be
  36772. ** modified at any time by a call to the pcache1Cachesize() method.
  36773. ** The PGroup mutex must be held when accessing nMax.
  36774. */
  36775. PGroup *pGroup; /* PGroup this cache belongs to */
  36776. int szPage; /* Size of allocated pages in bytes */
  36777. int szExtra; /* Size of extra space in bytes */
  36778. int bPurgeable; /* True if cache is purgeable */
  36779. unsigned int nMin; /* Minimum number of pages reserved */
  36780. unsigned int nMax; /* Configured "cache_size" value */
  36781. unsigned int n90pct; /* nMax*9/10 */
  36782. unsigned int iMaxKey; /* Largest key seen since xTruncate() */
  36783. /* Hash table of all pages. The following variables may only be accessed
  36784. ** when the accessor is holding the PGroup mutex.
  36785. */
  36786. unsigned int nRecyclable; /* Number of pages in the LRU list */
  36787. unsigned int nPage; /* Total number of pages in apHash */
  36788. unsigned int nHash; /* Number of slots in apHash[] */
  36789. PgHdr1 **apHash; /* Hash table for fast lookup by key */
  36790. };
  36791. /*
  36792. ** Each cache entry is represented by an instance of the following
  36793. ** structure. Unless SQLITE_PCACHE_SEPARATE_HEADER is defined, a buffer of
  36794. ** PgHdr1.pCache->szPage bytes is allocated directly before this structure
  36795. ** in memory.
  36796. */
  36797. struct PgHdr1 {
  36798. sqlite3_pcache_page page;
  36799. unsigned int iKey; /* Key value (page number) */
  36800. u8 isPinned; /* Page in use, not on the LRU list */
  36801. PgHdr1 *pNext; /* Next in hash table chain */
  36802. PCache1 *pCache; /* Cache that currently owns this page */
  36803. PgHdr1 *pLruNext; /* Next in LRU list of unpinned pages */
  36804. PgHdr1 *pLruPrev; /* Previous in LRU list of unpinned pages */
  36805. };
  36806. /*
  36807. ** Free slots in the allocator used to divide up the buffer provided using
  36808. ** the SQLITE_CONFIG_PAGECACHE mechanism.
  36809. */
  36810. struct PgFreeslot {
  36811. PgFreeslot *pNext; /* Next free slot */
  36812. };
  36813. /*
  36814. ** Global data used by this cache.
  36815. */
  36816. static SQLITE_WSD struct PCacheGlobal {
  36817. PGroup grp; /* The global PGroup for mode (2) */
  36818. /* Variables related to SQLITE_CONFIG_PAGECACHE settings. The
  36819. ** szSlot, nSlot, pStart, pEnd, nReserve, and isInit values are all
  36820. ** fixed at sqlite3_initialize() time and do not require mutex protection.
  36821. ** The nFreeSlot and pFree values do require mutex protection.
  36822. */
  36823. int isInit; /* True if initialized */
  36824. int szSlot; /* Size of each free slot */
  36825. int nSlot; /* The number of pcache slots */
  36826. int nReserve; /* Try to keep nFreeSlot above this */
  36827. void *pStart, *pEnd; /* Bounds of pagecache malloc range */
  36828. /* Above requires no mutex. Use mutex below for variable that follow. */
  36829. sqlite3_mutex *mutex; /* Mutex for accessing the following: */
  36830. PgFreeslot *pFree; /* Free page blocks */
  36831. int nFreeSlot; /* Number of unused pcache slots */
  36832. /* The following value requires a mutex to change. We skip the mutex on
  36833. ** reading because (1) most platforms read a 32-bit integer atomically and
  36834. ** (2) even if an incorrect value is read, no great harm is done since this
  36835. ** is really just an optimization. */
  36836. int bUnderPressure; /* True if low on PAGECACHE memory */
  36837. } pcache1_g;
  36838. /*
  36839. ** All code in this file should access the global structure above via the
  36840. ** alias "pcache1". This ensures that the WSD emulation is used when
  36841. ** compiling for systems that do not support real WSD.
  36842. */
  36843. #define pcache1 (GLOBAL(struct PCacheGlobal, pcache1_g))
  36844. /*
  36845. ** Macros to enter and leave the PCache LRU mutex.
  36846. */
  36847. #define pcache1EnterMutex(X) sqlite3_mutex_enter((X)->mutex)
  36848. #define pcache1LeaveMutex(X) sqlite3_mutex_leave((X)->mutex)
  36849. /******************************************************************************/
  36850. /******** Page Allocation/SQLITE_CONFIG_PCACHE Related Functions **************/
  36851. /*
  36852. ** This function is called during initialization if a static buffer is
  36853. ** supplied to use for the page-cache by passing the SQLITE_CONFIG_PAGECACHE
  36854. ** verb to sqlite3_config(). Parameter pBuf points to an allocation large
  36855. ** enough to contain 'n' buffers of 'sz' bytes each.
  36856. **
  36857. ** This routine is called from sqlite3_initialize() and so it is guaranteed
  36858. ** to be serialized already. There is no need for further mutexing.
  36859. */
  36860. SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *pBuf, int sz, int n){
  36861. if( pcache1.isInit ){
  36862. PgFreeslot *p;
  36863. sz = ROUNDDOWN8(sz);
  36864. pcache1.szSlot = sz;
  36865. pcache1.nSlot = pcache1.nFreeSlot = n;
  36866. pcache1.nReserve = n>90 ? 10 : (n/10 + 1);
  36867. pcache1.pStart = pBuf;
  36868. pcache1.pFree = 0;
  36869. pcache1.bUnderPressure = 0;
  36870. while( n-- ){
  36871. p = (PgFreeslot*)pBuf;
  36872. p->pNext = pcache1.pFree;
  36873. pcache1.pFree = p;
  36874. pBuf = (void*)&((char*)pBuf)[sz];
  36875. }
  36876. pcache1.pEnd = pBuf;
  36877. }
  36878. }
  36879. /*
  36880. ** Malloc function used within this file to allocate space from the buffer
  36881. ** configured using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no
  36882. ** such buffer exists or there is no space left in it, this function falls
  36883. ** back to sqlite3Malloc().
  36884. **
  36885. ** Multiple threads can run this routine at the same time. Global variables
  36886. ** in pcache1 need to be protected via mutex.
  36887. */
  36888. static void *pcache1Alloc(int nByte){
  36889. void *p = 0;
  36890. assert( sqlite3_mutex_notheld(pcache1.grp.mutex) );
  36891. sqlite3StatusSet(SQLITE_STATUS_PAGECACHE_SIZE, nByte);
  36892. if( nByte<=pcache1.szSlot ){
  36893. sqlite3_mutex_enter(pcache1.mutex);
  36894. p = (PgHdr1 *)pcache1.pFree;
  36895. if( p ){
  36896. pcache1.pFree = pcache1.pFree->pNext;
  36897. pcache1.nFreeSlot--;
  36898. pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;
  36899. assert( pcache1.nFreeSlot>=0 );
  36900. sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_USED, 1);
  36901. }
  36902. sqlite3_mutex_leave(pcache1.mutex);
  36903. }
  36904. if( p==0 ){
  36905. /* Memory is not available in the SQLITE_CONFIG_PAGECACHE pool. Get
  36906. ** it from sqlite3Malloc instead.
  36907. */
  36908. p = sqlite3Malloc(nByte);
  36909. #ifndef SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS
  36910. if( p ){
  36911. int sz = sqlite3MallocSize(p);
  36912. sqlite3_mutex_enter(pcache1.mutex);
  36913. sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_OVERFLOW, sz);
  36914. sqlite3_mutex_leave(pcache1.mutex);
  36915. }
  36916. #endif
  36917. sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
  36918. }
  36919. return p;
  36920. }
  36921. /*
  36922. ** Free an allocated buffer obtained from pcache1Alloc().
  36923. */
  36924. static int pcache1Free(void *p){
  36925. int nFreed = 0;
  36926. if( p==0 ) return 0;
  36927. if( p>=pcache1.pStart && p<pcache1.pEnd ){
  36928. PgFreeslot *pSlot;
  36929. sqlite3_mutex_enter(pcache1.mutex);
  36930. sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_USED, -1);
  36931. pSlot = (PgFreeslot*)p;
  36932. pSlot->pNext = pcache1.pFree;
  36933. pcache1.pFree = pSlot;
  36934. pcache1.nFreeSlot++;
  36935. pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;
  36936. assert( pcache1.nFreeSlot<=pcache1.nSlot );
  36937. sqlite3_mutex_leave(pcache1.mutex);
  36938. }else{
  36939. assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
  36940. sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
  36941. nFreed = sqlite3MallocSize(p);
  36942. #ifndef SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS
  36943. sqlite3_mutex_enter(pcache1.mutex);
  36944. sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_OVERFLOW, -nFreed);
  36945. sqlite3_mutex_leave(pcache1.mutex);
  36946. #endif
  36947. sqlite3_free(p);
  36948. }
  36949. return nFreed;
  36950. }
  36951. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  36952. /*
  36953. ** Return the size of a pcache allocation
  36954. */
  36955. static int pcache1MemSize(void *p){
  36956. if( p>=pcache1.pStart && p<pcache1.pEnd ){
  36957. return pcache1.szSlot;
  36958. }else{
  36959. int iSize;
  36960. assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
  36961. sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
  36962. iSize = sqlite3MallocSize(p);
  36963. sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
  36964. return iSize;
  36965. }
  36966. }
  36967. #endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
  36968. /*
  36969. ** Allocate a new page object initially associated with cache pCache.
  36970. */
  36971. static PgHdr1 *pcache1AllocPage(PCache1 *pCache){
  36972. PgHdr1 *p = 0;
  36973. void *pPg;
  36974. /* The group mutex must be released before pcache1Alloc() is called. This
  36975. ** is because it may call sqlite3_release_memory(), which assumes that
  36976. ** this mutex is not held. */
  36977. assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
  36978. pcache1LeaveMutex(pCache->pGroup);
  36979. #ifdef SQLITE_PCACHE_SEPARATE_HEADER
  36980. pPg = pcache1Alloc(pCache->szPage);
  36981. p = sqlite3Malloc(sizeof(PgHdr1) + pCache->szExtra);
  36982. if( !pPg || !p ){
  36983. pcache1Free(pPg);
  36984. sqlite3_free(p);
  36985. pPg = 0;
  36986. }
  36987. #else
  36988. pPg = pcache1Alloc(sizeof(PgHdr1) + pCache->szPage + pCache->szExtra);
  36989. p = (PgHdr1 *)&((u8 *)pPg)[pCache->szPage];
  36990. #endif
  36991. pcache1EnterMutex(pCache->pGroup);
  36992. if( pPg ){
  36993. p->page.pBuf = pPg;
  36994. p->page.pExtra = &p[1];
  36995. if( pCache->bPurgeable ){
  36996. pCache->pGroup->nCurrentPage++;
  36997. }
  36998. return p;
  36999. }
  37000. return 0;
  37001. }
  37002. /*
  37003. ** Free a page object allocated by pcache1AllocPage().
  37004. **
  37005. ** The pointer is allowed to be NULL, which is prudent. But it turns out
  37006. ** that the current implementation happens to never call this routine
  37007. ** with a NULL pointer, so we mark the NULL test with ALWAYS().
  37008. */
  37009. static void pcache1FreePage(PgHdr1 *p){
  37010. if( ALWAYS(p) ){
  37011. PCache1 *pCache = p->pCache;
  37012. assert( sqlite3_mutex_held(p->pCache->pGroup->mutex) );
  37013. pcache1Free(p->page.pBuf);
  37014. #ifdef SQLITE_PCACHE_SEPARATE_HEADER
  37015. sqlite3_free(p);
  37016. #endif
  37017. if( pCache->bPurgeable ){
  37018. pCache->pGroup->nCurrentPage--;
  37019. }
  37020. }
  37021. }
  37022. /*
  37023. ** Malloc function used by SQLite to obtain space from the buffer configured
  37024. ** using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no such buffer
  37025. ** exists, this function falls back to sqlite3Malloc().
  37026. */
  37027. SQLITE_PRIVATE void *sqlite3PageMalloc(int sz){
  37028. return pcache1Alloc(sz);
  37029. }
  37030. /*
  37031. ** Free an allocated buffer obtained from sqlite3PageMalloc().
  37032. */
  37033. SQLITE_PRIVATE void sqlite3PageFree(void *p){
  37034. pcache1Free(p);
  37035. }
  37036. /*
  37037. ** Return true if it desirable to avoid allocating a new page cache
  37038. ** entry.
  37039. **
  37040. ** If memory was allocated specifically to the page cache using
  37041. ** SQLITE_CONFIG_PAGECACHE but that memory has all been used, then
  37042. ** it is desirable to avoid allocating a new page cache entry because
  37043. ** presumably SQLITE_CONFIG_PAGECACHE was suppose to be sufficient
  37044. ** for all page cache needs and we should not need to spill the
  37045. ** allocation onto the heap.
  37046. **
  37047. ** Or, the heap is used for all page cache memory but the heap is
  37048. ** under memory pressure, then again it is desirable to avoid
  37049. ** allocating a new page cache entry in order to avoid stressing
  37050. ** the heap even further.
  37051. */
  37052. static int pcache1UnderMemoryPressure(PCache1 *pCache){
  37053. if( pcache1.nSlot && (pCache->szPage+pCache->szExtra)<=pcache1.szSlot ){
  37054. return pcache1.bUnderPressure;
  37055. }else{
  37056. return sqlite3HeapNearlyFull();
  37057. }
  37058. }
  37059. /******************************************************************************/
  37060. /******** General Implementation Functions ************************************/
  37061. /*
  37062. ** This function is used to resize the hash table used by the cache passed
  37063. ** as the first argument.
  37064. **
  37065. ** The PCache mutex must be held when this function is called.
  37066. */
  37067. static void pcache1ResizeHash(PCache1 *p){
  37068. PgHdr1 **apNew;
  37069. unsigned int nNew;
  37070. unsigned int i;
  37071. assert( sqlite3_mutex_held(p->pGroup->mutex) );
  37072. nNew = p->nHash*2;
  37073. if( nNew<256 ){
  37074. nNew = 256;
  37075. }
  37076. pcache1LeaveMutex(p->pGroup);
  37077. if( p->nHash ){ sqlite3BeginBenignMalloc(); }
  37078. apNew = (PgHdr1 **)sqlite3MallocZero(sizeof(PgHdr1 *)*nNew);
  37079. if( p->nHash ){ sqlite3EndBenignMalloc(); }
  37080. pcache1EnterMutex(p->pGroup);
  37081. if( apNew ){
  37082. for(i=0; i<p->nHash; i++){
  37083. PgHdr1 *pPage;
  37084. PgHdr1 *pNext = p->apHash[i];
  37085. while( (pPage = pNext)!=0 ){
  37086. unsigned int h = pPage->iKey % nNew;
  37087. pNext = pPage->pNext;
  37088. pPage->pNext = apNew[h];
  37089. apNew[h] = pPage;
  37090. }
  37091. }
  37092. sqlite3_free(p->apHash);
  37093. p->apHash = apNew;
  37094. p->nHash = nNew;
  37095. }
  37096. }
  37097. /*
  37098. ** This function is used internally to remove the page pPage from the
  37099. ** PGroup LRU list, if is part of it. If pPage is not part of the PGroup
  37100. ** LRU list, then this function is a no-op.
  37101. **
  37102. ** The PGroup mutex must be held when this function is called.
  37103. */
  37104. static void pcache1PinPage(PgHdr1 *pPage){
  37105. PCache1 *pCache;
  37106. PGroup *pGroup;
  37107. assert( pPage!=0 );
  37108. assert( pPage->isPinned==0 );
  37109. pCache = pPage->pCache;
  37110. pGroup = pCache->pGroup;
  37111. assert( pPage->pLruNext || pPage==pGroup->pLruTail );
  37112. assert( pPage->pLruPrev || pPage==pGroup->pLruHead );
  37113. assert( sqlite3_mutex_held(pGroup->mutex) );
  37114. if( pPage->pLruPrev ){
  37115. pPage->pLruPrev->pLruNext = pPage->pLruNext;
  37116. }else{
  37117. pGroup->pLruHead = pPage->pLruNext;
  37118. }
  37119. if( pPage->pLruNext ){
  37120. pPage->pLruNext->pLruPrev = pPage->pLruPrev;
  37121. }else{
  37122. pGroup->pLruTail = pPage->pLruPrev;
  37123. }
  37124. pPage->pLruNext = 0;
  37125. pPage->pLruPrev = 0;
  37126. pPage->isPinned = 1;
  37127. pCache->nRecyclable--;
  37128. }
  37129. /*
  37130. ** Remove the page supplied as an argument from the hash table
  37131. ** (PCache1.apHash structure) that it is currently stored in.
  37132. **
  37133. ** The PGroup mutex must be held when this function is called.
  37134. */
  37135. static void pcache1RemoveFromHash(PgHdr1 *pPage){
  37136. unsigned int h;
  37137. PCache1 *pCache = pPage->pCache;
  37138. PgHdr1 **pp;
  37139. assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
  37140. h = pPage->iKey % pCache->nHash;
  37141. for(pp=&pCache->apHash[h]; (*pp)!=pPage; pp=&(*pp)->pNext);
  37142. *pp = (*pp)->pNext;
  37143. pCache->nPage--;
  37144. }
  37145. /*
  37146. ** If there are currently more than nMaxPage pages allocated, try
  37147. ** to recycle pages to reduce the number allocated to nMaxPage.
  37148. */
  37149. static void pcache1EnforceMaxPage(PGroup *pGroup){
  37150. assert( sqlite3_mutex_held(pGroup->mutex) );
  37151. while( pGroup->nCurrentPage>pGroup->nMaxPage && pGroup->pLruTail ){
  37152. PgHdr1 *p = pGroup->pLruTail;
  37153. assert( p->pCache->pGroup==pGroup );
  37154. assert( p->isPinned==0 );
  37155. pcache1PinPage(p);
  37156. pcache1RemoveFromHash(p);
  37157. pcache1FreePage(p);
  37158. }
  37159. }
  37160. /*
  37161. ** Discard all pages from cache pCache with a page number (key value)
  37162. ** greater than or equal to iLimit. Any pinned pages that meet this
  37163. ** criteria are unpinned before they are discarded.
  37164. **
  37165. ** The PCache mutex must be held when this function is called.
  37166. */
  37167. static void pcache1TruncateUnsafe(
  37168. PCache1 *pCache, /* The cache to truncate */
  37169. unsigned int iLimit /* Drop pages with this pgno or larger */
  37170. ){
  37171. TESTONLY( unsigned int nPage = 0; ) /* To assert pCache->nPage is correct */
  37172. unsigned int h;
  37173. assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
  37174. for(h=0; h<pCache->nHash; h++){
  37175. PgHdr1 **pp = &pCache->apHash[h];
  37176. PgHdr1 *pPage;
  37177. while( (pPage = *pp)!=0 ){
  37178. if( pPage->iKey>=iLimit ){
  37179. pCache->nPage--;
  37180. *pp = pPage->pNext;
  37181. if( !pPage->isPinned ) pcache1PinPage(pPage);
  37182. pcache1FreePage(pPage);
  37183. }else{
  37184. pp = &pPage->pNext;
  37185. TESTONLY( nPage++; )
  37186. }
  37187. }
  37188. }
  37189. assert( pCache->nPage==nPage );
  37190. }
  37191. /******************************************************************************/
  37192. /******** sqlite3_pcache Methods **********************************************/
  37193. /*
  37194. ** Implementation of the sqlite3_pcache.xInit method.
  37195. */
  37196. static int pcache1Init(void *NotUsed){
  37197. UNUSED_PARAMETER(NotUsed);
  37198. assert( pcache1.isInit==0 );
  37199. memset(&pcache1, 0, sizeof(pcache1));
  37200. if( sqlite3GlobalConfig.bCoreMutex ){
  37201. pcache1.grp.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_LRU);
  37202. pcache1.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_PMEM);
  37203. }
  37204. pcache1.grp.mxPinned = 10;
  37205. pcache1.isInit = 1;
  37206. return SQLITE_OK;
  37207. }
  37208. /*
  37209. ** Implementation of the sqlite3_pcache.xShutdown method.
  37210. ** Note that the static mutex allocated in xInit does
  37211. ** not need to be freed.
  37212. */
  37213. static void pcache1Shutdown(void *NotUsed){
  37214. UNUSED_PARAMETER(NotUsed);
  37215. assert( pcache1.isInit!=0 );
  37216. memset(&pcache1, 0, sizeof(pcache1));
  37217. }
  37218. /* forward declaration */
  37219. static void pcache1Destroy(sqlite3_pcache *p);
  37220. /*
  37221. ** Implementation of the sqlite3_pcache.xCreate method.
  37222. **
  37223. ** Allocate a new cache.
  37224. */
  37225. static sqlite3_pcache *pcache1Create(int szPage, int szExtra, int bPurgeable){
  37226. PCache1 *pCache; /* The newly created page cache */
  37227. PGroup *pGroup; /* The group the new page cache will belong to */
  37228. int sz; /* Bytes of memory required to allocate the new cache */
  37229. /*
  37230. ** The separateCache variable is true if each PCache has its own private
  37231. ** PGroup. In other words, separateCache is true for mode (1) where no
  37232. ** mutexing is required.
  37233. **
  37234. ** * Always use a unified cache (mode-2) if ENABLE_MEMORY_MANAGEMENT
  37235. **
  37236. ** * Always use a unified cache in single-threaded applications
  37237. **
  37238. ** * Otherwise (if multi-threaded and ENABLE_MEMORY_MANAGEMENT is off)
  37239. ** use separate caches (mode-1)
  37240. */
  37241. #if defined(SQLITE_ENABLE_MEMORY_MANAGEMENT) || SQLITE_THREADSAFE==0
  37242. const int separateCache = 0;
  37243. #else
  37244. int separateCache = sqlite3GlobalConfig.bCoreMutex>0;
  37245. #endif
  37246. assert( (szPage & (szPage-1))==0 && szPage>=512 && szPage<=65536 );
  37247. assert( szExtra < 300 );
  37248. sz = sizeof(PCache1) + sizeof(PGroup)*separateCache;
  37249. pCache = (PCache1 *)sqlite3MallocZero(sz);
  37250. if( pCache ){
  37251. if( separateCache ){
  37252. pGroup = (PGroup*)&pCache[1];
  37253. pGroup->mxPinned = 10;
  37254. }else{
  37255. pGroup = &pcache1.grp;
  37256. }
  37257. pCache->pGroup = pGroup;
  37258. pCache->szPage = szPage;
  37259. pCache->szExtra = szExtra;
  37260. pCache->bPurgeable = (bPurgeable ? 1 : 0);
  37261. pcache1EnterMutex(pGroup);
  37262. pcache1ResizeHash(pCache);
  37263. if( bPurgeable ){
  37264. pCache->nMin = 10;
  37265. pGroup->nMinPage += pCache->nMin;
  37266. pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
  37267. }
  37268. pcache1LeaveMutex(pGroup);
  37269. if( pCache->nHash==0 ){
  37270. pcache1Destroy((sqlite3_pcache*)pCache);
  37271. pCache = 0;
  37272. }
  37273. }
  37274. return (sqlite3_pcache *)pCache;
  37275. }
  37276. /*
  37277. ** Implementation of the sqlite3_pcache.xCachesize method.
  37278. **
  37279. ** Configure the cache_size limit for a cache.
  37280. */
  37281. static void pcache1Cachesize(sqlite3_pcache *p, int nMax){
  37282. PCache1 *pCache = (PCache1 *)p;
  37283. if( pCache->bPurgeable ){
  37284. PGroup *pGroup = pCache->pGroup;
  37285. pcache1EnterMutex(pGroup);
  37286. pGroup->nMaxPage += (nMax - pCache->nMax);
  37287. pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
  37288. pCache->nMax = nMax;
  37289. pCache->n90pct = pCache->nMax*9/10;
  37290. pcache1EnforceMaxPage(pGroup);
  37291. pcache1LeaveMutex(pGroup);
  37292. }
  37293. }
  37294. /*
  37295. ** Implementation of the sqlite3_pcache.xShrink method.
  37296. **
  37297. ** Free up as much memory as possible.
  37298. */
  37299. static void pcache1Shrink(sqlite3_pcache *p){
  37300. PCache1 *pCache = (PCache1*)p;
  37301. if( pCache->bPurgeable ){
  37302. PGroup *pGroup = pCache->pGroup;
  37303. int savedMaxPage;
  37304. pcache1EnterMutex(pGroup);
  37305. savedMaxPage = pGroup->nMaxPage;
  37306. pGroup->nMaxPage = 0;
  37307. pcache1EnforceMaxPage(pGroup);
  37308. pGroup->nMaxPage = savedMaxPage;
  37309. pcache1LeaveMutex(pGroup);
  37310. }
  37311. }
  37312. /*
  37313. ** Implementation of the sqlite3_pcache.xPagecount method.
  37314. */
  37315. static int pcache1Pagecount(sqlite3_pcache *p){
  37316. int n;
  37317. PCache1 *pCache = (PCache1*)p;
  37318. pcache1EnterMutex(pCache->pGroup);
  37319. n = pCache->nPage;
  37320. pcache1LeaveMutex(pCache->pGroup);
  37321. return n;
  37322. }
  37323. /*
  37324. ** Implement steps 3, 4, and 5 of the pcache1Fetch() algorithm described
  37325. ** in the header of the pcache1Fetch() procedure.
  37326. **
  37327. ** This steps are broken out into a separate procedure because they are
  37328. ** usually not needed, and by avoiding the stack initialization required
  37329. ** for these steps, the main pcache1Fetch() procedure can run faster.
  37330. */
  37331. static SQLITE_NOINLINE PgHdr1 *pcache1FetchStage2(
  37332. PCache1 *pCache,
  37333. unsigned int iKey,
  37334. int createFlag
  37335. ){
  37336. unsigned int nPinned;
  37337. PGroup *pGroup = pCache->pGroup;
  37338. PgHdr1 *pPage = 0;
  37339. /* Step 3: Abort if createFlag is 1 but the cache is nearly full */
  37340. assert( pCache->nPage >= pCache->nRecyclable );
  37341. nPinned = pCache->nPage - pCache->nRecyclable;
  37342. assert( pGroup->mxPinned == pGroup->nMaxPage + 10 - pGroup->nMinPage );
  37343. assert( pCache->n90pct == pCache->nMax*9/10 );
  37344. if( createFlag==1 && (
  37345. nPinned>=pGroup->mxPinned
  37346. || nPinned>=pCache->n90pct
  37347. || (pcache1UnderMemoryPressure(pCache) && pCache->nRecyclable<nPinned)
  37348. )){
  37349. return 0;
  37350. }
  37351. if( pCache->nPage>=pCache->nHash ) pcache1ResizeHash(pCache);
  37352. assert( pCache->nHash>0 && pCache->apHash );
  37353. /* Step 4. Try to recycle a page. */
  37354. if( pCache->bPurgeable && pGroup->pLruTail && (
  37355. (pCache->nPage+1>=pCache->nMax)
  37356. || pGroup->nCurrentPage>=pGroup->nMaxPage
  37357. || pcache1UnderMemoryPressure(pCache)
  37358. )){
  37359. PCache1 *pOther;
  37360. pPage = pGroup->pLruTail;
  37361. assert( pPage->isPinned==0 );
  37362. pcache1RemoveFromHash(pPage);
  37363. pcache1PinPage(pPage);
  37364. pOther = pPage->pCache;
  37365. /* We want to verify that szPage and szExtra are the same for pOther
  37366. ** and pCache. Assert that we can verify this by comparing sums. */
  37367. assert( (pCache->szPage & (pCache->szPage-1))==0 && pCache->szPage>=512 );
  37368. assert( pCache->szExtra<512 );
  37369. assert( (pOther->szPage & (pOther->szPage-1))==0 && pOther->szPage>=512 );
  37370. assert( pOther->szExtra<512 );
  37371. if( pOther->szPage+pOther->szExtra != pCache->szPage+pCache->szExtra ){
  37372. pcache1FreePage(pPage);
  37373. pPage = 0;
  37374. }else{
  37375. pGroup->nCurrentPage -= (pOther->bPurgeable - pCache->bPurgeable);
  37376. }
  37377. }
  37378. /* Step 5. If a usable page buffer has still not been found,
  37379. ** attempt to allocate a new one.
  37380. */
  37381. if( !pPage ){
  37382. if( createFlag==1 ) sqlite3BeginBenignMalloc();
  37383. pPage = pcache1AllocPage(pCache);
  37384. if( createFlag==1 ) sqlite3EndBenignMalloc();
  37385. }
  37386. if( pPage ){
  37387. unsigned int h = iKey % pCache->nHash;
  37388. pCache->nPage++;
  37389. pPage->iKey = iKey;
  37390. pPage->pNext = pCache->apHash[h];
  37391. pPage->pCache = pCache;
  37392. pPage->pLruPrev = 0;
  37393. pPage->pLruNext = 0;
  37394. pPage->isPinned = 1;
  37395. *(void **)pPage->page.pExtra = 0;
  37396. pCache->apHash[h] = pPage;
  37397. if( iKey>pCache->iMaxKey ){
  37398. pCache->iMaxKey = iKey;
  37399. }
  37400. }
  37401. return pPage;
  37402. }
  37403. /*
  37404. ** Implementation of the sqlite3_pcache.xFetch method.
  37405. **
  37406. ** Fetch a page by key value.
  37407. **
  37408. ** Whether or not a new page may be allocated by this function depends on
  37409. ** the value of the createFlag argument. 0 means do not allocate a new
  37410. ** page. 1 means allocate a new page if space is easily available. 2
  37411. ** means to try really hard to allocate a new page.
  37412. **
  37413. ** For a non-purgeable cache (a cache used as the storage for an in-memory
  37414. ** database) there is really no difference between createFlag 1 and 2. So
  37415. ** the calling function (pcache.c) will never have a createFlag of 1 on
  37416. ** a non-purgeable cache.
  37417. **
  37418. ** There are three different approaches to obtaining space for a page,
  37419. ** depending on the value of parameter createFlag (which may be 0, 1 or 2).
  37420. **
  37421. ** 1. Regardless of the value of createFlag, the cache is searched for a
  37422. ** copy of the requested page. If one is found, it is returned.
  37423. **
  37424. ** 2. If createFlag==0 and the page is not already in the cache, NULL is
  37425. ** returned.
  37426. **
  37427. ** 3. If createFlag is 1, and the page is not already in the cache, then
  37428. ** return NULL (do not allocate a new page) if any of the following
  37429. ** conditions are true:
  37430. **
  37431. ** (a) the number of pages pinned by the cache is greater than
  37432. ** PCache1.nMax, or
  37433. **
  37434. ** (b) the number of pages pinned by the cache is greater than
  37435. ** the sum of nMax for all purgeable caches, less the sum of
  37436. ** nMin for all other purgeable caches, or
  37437. **
  37438. ** 4. If none of the first three conditions apply and the cache is marked
  37439. ** as purgeable, and if one of the following is true:
  37440. **
  37441. ** (a) The number of pages allocated for the cache is already
  37442. ** PCache1.nMax, or
  37443. **
  37444. ** (b) The number of pages allocated for all purgeable caches is
  37445. ** already equal to or greater than the sum of nMax for all
  37446. ** purgeable caches,
  37447. **
  37448. ** (c) The system is under memory pressure and wants to avoid
  37449. ** unnecessary pages cache entry allocations
  37450. **
  37451. ** then attempt to recycle a page from the LRU list. If it is the right
  37452. ** size, return the recycled buffer. Otherwise, free the buffer and
  37453. ** proceed to step 5.
  37454. **
  37455. ** 5. Otherwise, allocate and return a new page buffer.
  37456. */
  37457. static sqlite3_pcache_page *pcache1Fetch(
  37458. sqlite3_pcache *p,
  37459. unsigned int iKey,
  37460. int createFlag
  37461. ){
  37462. PCache1 *pCache = (PCache1 *)p;
  37463. PgHdr1 *pPage = 0;
  37464. assert( offsetof(PgHdr1,page)==0 );
  37465. assert( pCache->bPurgeable || createFlag!=1 );
  37466. assert( pCache->bPurgeable || pCache->nMin==0 );
  37467. assert( pCache->bPurgeable==0 || pCache->nMin==10 );
  37468. assert( pCache->nMin==0 || pCache->bPurgeable );
  37469. assert( pCache->nHash>0 );
  37470. pcache1EnterMutex(pCache->pGroup);
  37471. /* Step 1: Search the hash table for an existing entry. */
  37472. pPage = pCache->apHash[iKey % pCache->nHash];
  37473. while( pPage && pPage->iKey!=iKey ){ pPage = pPage->pNext; }
  37474. /* Step 2: Abort if no existing page is found and createFlag is 0 */
  37475. if( pPage ){
  37476. if( !pPage->isPinned ) pcache1PinPage(pPage);
  37477. }else if( createFlag ){
  37478. /* Steps 3, 4, and 5 implemented by this subroutine */
  37479. pPage = pcache1FetchStage2(pCache, iKey, createFlag);
  37480. }
  37481. assert( pPage==0 || pCache->iMaxKey>=iKey );
  37482. pcache1LeaveMutex(pCache->pGroup);
  37483. return (sqlite3_pcache_page*)pPage;
  37484. }
  37485. /*
  37486. ** Implementation of the sqlite3_pcache.xUnpin method.
  37487. **
  37488. ** Mark a page as unpinned (eligible for asynchronous recycling).
  37489. */
  37490. static void pcache1Unpin(
  37491. sqlite3_pcache *p,
  37492. sqlite3_pcache_page *pPg,
  37493. int reuseUnlikely
  37494. ){
  37495. PCache1 *pCache = (PCache1 *)p;
  37496. PgHdr1 *pPage = (PgHdr1 *)pPg;
  37497. PGroup *pGroup = pCache->pGroup;
  37498. assert( pPage->pCache==pCache );
  37499. pcache1EnterMutex(pGroup);
  37500. /* It is an error to call this function if the page is already
  37501. ** part of the PGroup LRU list.
  37502. */
  37503. assert( pPage->pLruPrev==0 && pPage->pLruNext==0 );
  37504. assert( pGroup->pLruHead!=pPage && pGroup->pLruTail!=pPage );
  37505. assert( pPage->isPinned==1 );
  37506. if( reuseUnlikely || pGroup->nCurrentPage>pGroup->nMaxPage ){
  37507. pcache1RemoveFromHash(pPage);
  37508. pcache1FreePage(pPage);
  37509. }else{
  37510. /* Add the page to the PGroup LRU list. */
  37511. if( pGroup->pLruHead ){
  37512. pGroup->pLruHead->pLruPrev = pPage;
  37513. pPage->pLruNext = pGroup->pLruHead;
  37514. pGroup->pLruHead = pPage;
  37515. }else{
  37516. pGroup->pLruTail = pPage;
  37517. pGroup->pLruHead = pPage;
  37518. }
  37519. pCache->nRecyclable++;
  37520. pPage->isPinned = 0;
  37521. }
  37522. pcache1LeaveMutex(pCache->pGroup);
  37523. }
  37524. /*
  37525. ** Implementation of the sqlite3_pcache.xRekey method.
  37526. */
  37527. static void pcache1Rekey(
  37528. sqlite3_pcache *p,
  37529. sqlite3_pcache_page *pPg,
  37530. unsigned int iOld,
  37531. unsigned int iNew
  37532. ){
  37533. PCache1 *pCache = (PCache1 *)p;
  37534. PgHdr1 *pPage = (PgHdr1 *)pPg;
  37535. PgHdr1 **pp;
  37536. unsigned int h;
  37537. assert( pPage->iKey==iOld );
  37538. assert( pPage->pCache==pCache );
  37539. pcache1EnterMutex(pCache->pGroup);
  37540. h = iOld%pCache->nHash;
  37541. pp = &pCache->apHash[h];
  37542. while( (*pp)!=pPage ){
  37543. pp = &(*pp)->pNext;
  37544. }
  37545. *pp = pPage->pNext;
  37546. h = iNew%pCache->nHash;
  37547. pPage->iKey = iNew;
  37548. pPage->pNext = pCache->apHash[h];
  37549. pCache->apHash[h] = pPage;
  37550. if( iNew>pCache->iMaxKey ){
  37551. pCache->iMaxKey = iNew;
  37552. }
  37553. pcache1LeaveMutex(pCache->pGroup);
  37554. }
  37555. /*
  37556. ** Implementation of the sqlite3_pcache.xTruncate method.
  37557. **
  37558. ** Discard all unpinned pages in the cache with a page number equal to
  37559. ** or greater than parameter iLimit. Any pinned pages with a page number
  37560. ** equal to or greater than iLimit are implicitly unpinned.
  37561. */
  37562. static void pcache1Truncate(sqlite3_pcache *p, unsigned int iLimit){
  37563. PCache1 *pCache = (PCache1 *)p;
  37564. pcache1EnterMutex(pCache->pGroup);
  37565. if( iLimit<=pCache->iMaxKey ){
  37566. pcache1TruncateUnsafe(pCache, iLimit);
  37567. pCache->iMaxKey = iLimit-1;
  37568. }
  37569. pcache1LeaveMutex(pCache->pGroup);
  37570. }
  37571. /*
  37572. ** Implementation of the sqlite3_pcache.xDestroy method.
  37573. **
  37574. ** Destroy a cache allocated using pcache1Create().
  37575. */
  37576. static void pcache1Destroy(sqlite3_pcache *p){
  37577. PCache1 *pCache = (PCache1 *)p;
  37578. PGroup *pGroup = pCache->pGroup;
  37579. assert( pCache->bPurgeable || (pCache->nMax==0 && pCache->nMin==0) );
  37580. pcache1EnterMutex(pGroup);
  37581. pcache1TruncateUnsafe(pCache, 0);
  37582. assert( pGroup->nMaxPage >= pCache->nMax );
  37583. pGroup->nMaxPage -= pCache->nMax;
  37584. assert( pGroup->nMinPage >= pCache->nMin );
  37585. pGroup->nMinPage -= pCache->nMin;
  37586. pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
  37587. pcache1EnforceMaxPage(pGroup);
  37588. pcache1LeaveMutex(pGroup);
  37589. sqlite3_free(pCache->apHash);
  37590. sqlite3_free(pCache);
  37591. }
  37592. /*
  37593. ** This function is called during initialization (sqlite3_initialize()) to
  37594. ** install the default pluggable cache module, assuming the user has not
  37595. ** already provided an alternative.
  37596. */
  37597. SQLITE_PRIVATE void sqlite3PCacheSetDefault(void){
  37598. static const sqlite3_pcache_methods2 defaultMethods = {
  37599. 1, /* iVersion */
  37600. 0, /* pArg */
  37601. pcache1Init, /* xInit */
  37602. pcache1Shutdown, /* xShutdown */
  37603. pcache1Create, /* xCreate */
  37604. pcache1Cachesize, /* xCachesize */
  37605. pcache1Pagecount, /* xPagecount */
  37606. pcache1Fetch, /* xFetch */
  37607. pcache1Unpin, /* xUnpin */
  37608. pcache1Rekey, /* xRekey */
  37609. pcache1Truncate, /* xTruncate */
  37610. pcache1Destroy, /* xDestroy */
  37611. pcache1Shrink /* xShrink */
  37612. };
  37613. sqlite3_config(SQLITE_CONFIG_PCACHE2, &defaultMethods);
  37614. }
  37615. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  37616. /*
  37617. ** This function is called to free superfluous dynamically allocated memory
  37618. ** held by the pager system. Memory in use by any SQLite pager allocated
  37619. ** by the current thread may be sqlite3_free()ed.
  37620. **
  37621. ** nReq is the number of bytes of memory required. Once this much has
  37622. ** been released, the function returns. The return value is the total number
  37623. ** of bytes of memory released.
  37624. */
  37625. SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int nReq){
  37626. int nFree = 0;
  37627. assert( sqlite3_mutex_notheld(pcache1.grp.mutex) );
  37628. assert( sqlite3_mutex_notheld(pcache1.mutex) );
  37629. if( pcache1.pStart==0 ){
  37630. PgHdr1 *p;
  37631. pcache1EnterMutex(&pcache1.grp);
  37632. while( (nReq<0 || nFree<nReq) && ((p=pcache1.grp.pLruTail)!=0) ){
  37633. nFree += pcache1MemSize(p->page.pBuf);
  37634. #ifdef SQLITE_PCACHE_SEPARATE_HEADER
  37635. nFree += sqlite3MemSize(p);
  37636. #endif
  37637. assert( p->isPinned==0 );
  37638. pcache1PinPage(p);
  37639. pcache1RemoveFromHash(p);
  37640. pcache1FreePage(p);
  37641. }
  37642. pcache1LeaveMutex(&pcache1.grp);
  37643. }
  37644. return nFree;
  37645. }
  37646. #endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
  37647. #ifdef SQLITE_TEST
  37648. /*
  37649. ** This function is used by test procedures to inspect the internal state
  37650. ** of the global cache.
  37651. */
  37652. SQLITE_PRIVATE void sqlite3PcacheStats(
  37653. int *pnCurrent, /* OUT: Total number of pages cached */
  37654. int *pnMax, /* OUT: Global maximum cache size */
  37655. int *pnMin, /* OUT: Sum of PCache1.nMin for purgeable caches */
  37656. int *pnRecyclable /* OUT: Total number of pages available for recycling */
  37657. ){
  37658. PgHdr1 *p;
  37659. int nRecyclable = 0;
  37660. for(p=pcache1.grp.pLruHead; p; p=p->pLruNext){
  37661. assert( p->isPinned==0 );
  37662. nRecyclable++;
  37663. }
  37664. *pnCurrent = pcache1.grp.nCurrentPage;
  37665. *pnMax = (int)pcache1.grp.nMaxPage;
  37666. *pnMin = (int)pcache1.grp.nMinPage;
  37667. *pnRecyclable = nRecyclable;
  37668. }
  37669. #endif
  37670. /************** End of pcache1.c *********************************************/
  37671. /************** Begin file rowset.c ******************************************/
  37672. /*
  37673. ** 2008 December 3
  37674. **
  37675. ** The author disclaims copyright to this source code. In place of
  37676. ** a legal notice, here is a blessing:
  37677. **
  37678. ** May you do good and not evil.
  37679. ** May you find forgiveness for yourself and forgive others.
  37680. ** May you share freely, never taking more than you give.
  37681. **
  37682. *************************************************************************
  37683. **
  37684. ** This module implements an object we call a "RowSet".
  37685. **
  37686. ** The RowSet object is a collection of rowids. Rowids
  37687. ** are inserted into the RowSet in an arbitrary order. Inserts
  37688. ** can be intermixed with tests to see if a given rowid has been
  37689. ** previously inserted into the RowSet.
  37690. **
  37691. ** After all inserts are finished, it is possible to extract the
  37692. ** elements of the RowSet in sorted order. Once this extraction
  37693. ** process has started, no new elements may be inserted.
  37694. **
  37695. ** Hence, the primitive operations for a RowSet are:
  37696. **
  37697. ** CREATE
  37698. ** INSERT
  37699. ** TEST
  37700. ** SMALLEST
  37701. ** DESTROY
  37702. **
  37703. ** The CREATE and DESTROY primitives are the constructor and destructor,
  37704. ** obviously. The INSERT primitive adds a new element to the RowSet.
  37705. ** TEST checks to see if an element is already in the RowSet. SMALLEST
  37706. ** extracts the least value from the RowSet.
  37707. **
  37708. ** The INSERT primitive might allocate additional memory. Memory is
  37709. ** allocated in chunks so most INSERTs do no allocation. There is an
  37710. ** upper bound on the size of allocated memory. No memory is freed
  37711. ** until DESTROY.
  37712. **
  37713. ** The TEST primitive includes a "batch" number. The TEST primitive
  37714. ** will only see elements that were inserted before the last change
  37715. ** in the batch number. In other words, if an INSERT occurs between
  37716. ** two TESTs where the TESTs have the same batch nubmer, then the
  37717. ** value added by the INSERT will not be visible to the second TEST.
  37718. ** The initial batch number is zero, so if the very first TEST contains
  37719. ** a non-zero batch number, it will see all prior INSERTs.
  37720. **
  37721. ** No INSERTs may occurs after a SMALLEST. An assertion will fail if
  37722. ** that is attempted.
  37723. **
  37724. ** The cost of an INSERT is roughly constant. (Sometimes new memory
  37725. ** has to be allocated on an INSERT.) The cost of a TEST with a new
  37726. ** batch number is O(NlogN) where N is the number of elements in the RowSet.
  37727. ** The cost of a TEST using the same batch number is O(logN). The cost
  37728. ** of the first SMALLEST is O(NlogN). Second and subsequent SMALLEST
  37729. ** primitives are constant time. The cost of DESTROY is O(N).
  37730. **
  37731. ** There is an added cost of O(N) when switching between TEST and
  37732. ** SMALLEST primitives.
  37733. */
  37734. /*
  37735. ** Target size for allocation chunks.
  37736. */
  37737. #define ROWSET_ALLOCATION_SIZE 1024
  37738. /*
  37739. ** The number of rowset entries per allocation chunk.
  37740. */
  37741. #define ROWSET_ENTRY_PER_CHUNK \
  37742. ((ROWSET_ALLOCATION_SIZE-8)/sizeof(struct RowSetEntry))
  37743. /*
  37744. ** Each entry in a RowSet is an instance of the following object.
  37745. **
  37746. ** This same object is reused to store a linked list of trees of RowSetEntry
  37747. ** objects. In that alternative use, pRight points to the next entry
  37748. ** in the list, pLeft points to the tree, and v is unused. The
  37749. ** RowSet.pForest value points to the head of this forest list.
  37750. */
  37751. struct RowSetEntry {
  37752. i64 v; /* ROWID value for this entry */
  37753. struct RowSetEntry *pRight; /* Right subtree (larger entries) or list */
  37754. struct RowSetEntry *pLeft; /* Left subtree (smaller entries) */
  37755. };
  37756. /*
  37757. ** RowSetEntry objects are allocated in large chunks (instances of the
  37758. ** following structure) to reduce memory allocation overhead. The
  37759. ** chunks are kept on a linked list so that they can be deallocated
  37760. ** when the RowSet is destroyed.
  37761. */
  37762. struct RowSetChunk {
  37763. struct RowSetChunk *pNextChunk; /* Next chunk on list of them all */
  37764. struct RowSetEntry aEntry[ROWSET_ENTRY_PER_CHUNK]; /* Allocated entries */
  37765. };
  37766. /*
  37767. ** A RowSet in an instance of the following structure.
  37768. **
  37769. ** A typedef of this structure if found in sqliteInt.h.
  37770. */
  37771. struct RowSet {
  37772. struct RowSetChunk *pChunk; /* List of all chunk allocations */
  37773. sqlite3 *db; /* The database connection */
  37774. struct RowSetEntry *pEntry; /* List of entries using pRight */
  37775. struct RowSetEntry *pLast; /* Last entry on the pEntry list */
  37776. struct RowSetEntry *pFresh; /* Source of new entry objects */
  37777. struct RowSetEntry *pForest; /* List of binary trees of entries */
  37778. u16 nFresh; /* Number of objects on pFresh */
  37779. u16 rsFlags; /* Various flags */
  37780. int iBatch; /* Current insert batch */
  37781. };
  37782. /*
  37783. ** Allowed values for RowSet.rsFlags
  37784. */
  37785. #define ROWSET_SORTED 0x01 /* True if RowSet.pEntry is sorted */
  37786. #define ROWSET_NEXT 0x02 /* True if sqlite3RowSetNext() has been called */
  37787. /*
  37788. ** Turn bulk memory into a RowSet object. N bytes of memory
  37789. ** are available at pSpace. The db pointer is used as a memory context
  37790. ** for any subsequent allocations that need to occur.
  37791. ** Return a pointer to the new RowSet object.
  37792. **
  37793. ** It must be the case that N is sufficient to make a Rowset. If not
  37794. ** an assertion fault occurs.
  37795. **
  37796. ** If N is larger than the minimum, use the surplus as an initial
  37797. ** allocation of entries available to be filled.
  37798. */
  37799. SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3 *db, void *pSpace, unsigned int N){
  37800. RowSet *p;
  37801. assert( N >= ROUND8(sizeof(*p)) );
  37802. p = pSpace;
  37803. p->pChunk = 0;
  37804. p->db = db;
  37805. p->pEntry = 0;
  37806. p->pLast = 0;
  37807. p->pForest = 0;
  37808. p->pFresh = (struct RowSetEntry*)(ROUND8(sizeof(*p)) + (char*)p);
  37809. p->nFresh = (u16)((N - ROUND8(sizeof(*p)))/sizeof(struct RowSetEntry));
  37810. p->rsFlags = ROWSET_SORTED;
  37811. p->iBatch = 0;
  37812. return p;
  37813. }
  37814. /*
  37815. ** Deallocate all chunks from a RowSet. This frees all memory that
  37816. ** the RowSet has allocated over its lifetime. This routine is
  37817. ** the destructor for the RowSet.
  37818. */
  37819. SQLITE_PRIVATE void sqlite3RowSetClear(RowSet *p){
  37820. struct RowSetChunk *pChunk, *pNextChunk;
  37821. for(pChunk=p->pChunk; pChunk; pChunk = pNextChunk){
  37822. pNextChunk = pChunk->pNextChunk;
  37823. sqlite3DbFree(p->db, pChunk);
  37824. }
  37825. p->pChunk = 0;
  37826. p->nFresh = 0;
  37827. p->pEntry = 0;
  37828. p->pLast = 0;
  37829. p->pForest = 0;
  37830. p->rsFlags = ROWSET_SORTED;
  37831. }
  37832. /*
  37833. ** Allocate a new RowSetEntry object that is associated with the
  37834. ** given RowSet. Return a pointer to the new and completely uninitialized
  37835. ** objected.
  37836. **
  37837. ** In an OOM situation, the RowSet.db->mallocFailed flag is set and this
  37838. ** routine returns NULL.
  37839. */
  37840. static struct RowSetEntry *rowSetEntryAlloc(RowSet *p){
  37841. assert( p!=0 );
  37842. if( p->nFresh==0 ){
  37843. struct RowSetChunk *pNew;
  37844. pNew = sqlite3DbMallocRaw(p->db, sizeof(*pNew));
  37845. if( pNew==0 ){
  37846. return 0;
  37847. }
  37848. pNew->pNextChunk = p->pChunk;
  37849. p->pChunk = pNew;
  37850. p->pFresh = pNew->aEntry;
  37851. p->nFresh = ROWSET_ENTRY_PER_CHUNK;
  37852. }
  37853. p->nFresh--;
  37854. return p->pFresh++;
  37855. }
  37856. /*
  37857. ** Insert a new value into a RowSet.
  37858. **
  37859. ** The mallocFailed flag of the database connection is set if a
  37860. ** memory allocation fails.
  37861. */
  37862. SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet *p, i64 rowid){
  37863. struct RowSetEntry *pEntry; /* The new entry */
  37864. struct RowSetEntry *pLast; /* The last prior entry */
  37865. /* This routine is never called after sqlite3RowSetNext() */
  37866. assert( p!=0 && (p->rsFlags & ROWSET_NEXT)==0 );
  37867. pEntry = rowSetEntryAlloc(p);
  37868. if( pEntry==0 ) return;
  37869. pEntry->v = rowid;
  37870. pEntry->pRight = 0;
  37871. pLast = p->pLast;
  37872. if( pLast ){
  37873. if( (p->rsFlags & ROWSET_SORTED)!=0 && rowid<=pLast->v ){
  37874. p->rsFlags &= ~ROWSET_SORTED;
  37875. }
  37876. pLast->pRight = pEntry;
  37877. }else{
  37878. p->pEntry = pEntry;
  37879. }
  37880. p->pLast = pEntry;
  37881. }
  37882. /*
  37883. ** Merge two lists of RowSetEntry objects. Remove duplicates.
  37884. **
  37885. ** The input lists are connected via pRight pointers and are
  37886. ** assumed to each already be in sorted order.
  37887. */
  37888. static struct RowSetEntry *rowSetEntryMerge(
  37889. struct RowSetEntry *pA, /* First sorted list to be merged */
  37890. struct RowSetEntry *pB /* Second sorted list to be merged */
  37891. ){
  37892. struct RowSetEntry head;
  37893. struct RowSetEntry *pTail;
  37894. pTail = &head;
  37895. while( pA && pB ){
  37896. assert( pA->pRight==0 || pA->v<=pA->pRight->v );
  37897. assert( pB->pRight==0 || pB->v<=pB->pRight->v );
  37898. if( pA->v<pB->v ){
  37899. pTail->pRight = pA;
  37900. pA = pA->pRight;
  37901. pTail = pTail->pRight;
  37902. }else if( pB->v<pA->v ){
  37903. pTail->pRight = pB;
  37904. pB = pB->pRight;
  37905. pTail = pTail->pRight;
  37906. }else{
  37907. pA = pA->pRight;
  37908. }
  37909. }
  37910. if( pA ){
  37911. assert( pA->pRight==0 || pA->v<=pA->pRight->v );
  37912. pTail->pRight = pA;
  37913. }else{
  37914. assert( pB==0 || pB->pRight==0 || pB->v<=pB->pRight->v );
  37915. pTail->pRight = pB;
  37916. }
  37917. return head.pRight;
  37918. }
  37919. /*
  37920. ** Sort all elements on the list of RowSetEntry objects into order of
  37921. ** increasing v.
  37922. */
  37923. static struct RowSetEntry *rowSetEntrySort(struct RowSetEntry *pIn){
  37924. unsigned int i;
  37925. struct RowSetEntry *pNext, *aBucket[40];
  37926. memset(aBucket, 0, sizeof(aBucket));
  37927. while( pIn ){
  37928. pNext = pIn->pRight;
  37929. pIn->pRight = 0;
  37930. for(i=0; aBucket[i]; i++){
  37931. pIn = rowSetEntryMerge(aBucket[i], pIn);
  37932. aBucket[i] = 0;
  37933. }
  37934. aBucket[i] = pIn;
  37935. pIn = pNext;
  37936. }
  37937. pIn = 0;
  37938. for(i=0; i<sizeof(aBucket)/sizeof(aBucket[0]); i++){
  37939. pIn = rowSetEntryMerge(pIn, aBucket[i]);
  37940. }
  37941. return pIn;
  37942. }
  37943. /*
  37944. ** The input, pIn, is a binary tree (or subtree) of RowSetEntry objects.
  37945. ** Convert this tree into a linked list connected by the pRight pointers
  37946. ** and return pointers to the first and last elements of the new list.
  37947. */
  37948. static void rowSetTreeToList(
  37949. struct RowSetEntry *pIn, /* Root of the input tree */
  37950. struct RowSetEntry **ppFirst, /* Write head of the output list here */
  37951. struct RowSetEntry **ppLast /* Write tail of the output list here */
  37952. ){
  37953. assert( pIn!=0 );
  37954. if( pIn->pLeft ){
  37955. struct RowSetEntry *p;
  37956. rowSetTreeToList(pIn->pLeft, ppFirst, &p);
  37957. p->pRight = pIn;
  37958. }else{
  37959. *ppFirst = pIn;
  37960. }
  37961. if( pIn->pRight ){
  37962. rowSetTreeToList(pIn->pRight, &pIn->pRight, ppLast);
  37963. }else{
  37964. *ppLast = pIn;
  37965. }
  37966. assert( (*ppLast)->pRight==0 );
  37967. }
  37968. /*
  37969. ** Convert a sorted list of elements (connected by pRight) into a binary
  37970. ** tree with depth of iDepth. A depth of 1 means the tree contains a single
  37971. ** node taken from the head of *ppList. A depth of 2 means a tree with
  37972. ** three nodes. And so forth.
  37973. **
  37974. ** Use as many entries from the input list as required and update the
  37975. ** *ppList to point to the unused elements of the list. If the input
  37976. ** list contains too few elements, then construct an incomplete tree
  37977. ** and leave *ppList set to NULL.
  37978. **
  37979. ** Return a pointer to the root of the constructed binary tree.
  37980. */
  37981. static struct RowSetEntry *rowSetNDeepTree(
  37982. struct RowSetEntry **ppList,
  37983. int iDepth
  37984. ){
  37985. struct RowSetEntry *p; /* Root of the new tree */
  37986. struct RowSetEntry *pLeft; /* Left subtree */
  37987. if( *ppList==0 ){
  37988. return 0;
  37989. }
  37990. if( iDepth==1 ){
  37991. p = *ppList;
  37992. *ppList = p->pRight;
  37993. p->pLeft = p->pRight = 0;
  37994. return p;
  37995. }
  37996. pLeft = rowSetNDeepTree(ppList, iDepth-1);
  37997. p = *ppList;
  37998. if( p==0 ){
  37999. return pLeft;
  38000. }
  38001. p->pLeft = pLeft;
  38002. *ppList = p->pRight;
  38003. p->pRight = rowSetNDeepTree(ppList, iDepth-1);
  38004. return p;
  38005. }
  38006. /*
  38007. ** Convert a sorted list of elements into a binary tree. Make the tree
  38008. ** as deep as it needs to be in order to contain the entire list.
  38009. */
  38010. static struct RowSetEntry *rowSetListToTree(struct RowSetEntry *pList){
  38011. int iDepth; /* Depth of the tree so far */
  38012. struct RowSetEntry *p; /* Current tree root */
  38013. struct RowSetEntry *pLeft; /* Left subtree */
  38014. assert( pList!=0 );
  38015. p = pList;
  38016. pList = p->pRight;
  38017. p->pLeft = p->pRight = 0;
  38018. for(iDepth=1; pList; iDepth++){
  38019. pLeft = p;
  38020. p = pList;
  38021. pList = p->pRight;
  38022. p->pLeft = pLeft;
  38023. p->pRight = rowSetNDeepTree(&pList, iDepth);
  38024. }
  38025. return p;
  38026. }
  38027. /*
  38028. ** Take all the entries on p->pEntry and on the trees in p->pForest and
  38029. ** sort them all together into one big ordered list on p->pEntry.
  38030. **
  38031. ** This routine should only be called once in the life of a RowSet.
  38032. */
  38033. static void rowSetToList(RowSet *p){
  38034. /* This routine is called only once */
  38035. assert( p!=0 && (p->rsFlags & ROWSET_NEXT)==0 );
  38036. if( (p->rsFlags & ROWSET_SORTED)==0 ){
  38037. p->pEntry = rowSetEntrySort(p->pEntry);
  38038. }
  38039. /* While this module could theoretically support it, sqlite3RowSetNext()
  38040. ** is never called after sqlite3RowSetText() for the same RowSet. So
  38041. ** there is never a forest to deal with. Should this change, simply
  38042. ** remove the assert() and the #if 0. */
  38043. assert( p->pForest==0 );
  38044. #if 0
  38045. while( p->pForest ){
  38046. struct RowSetEntry *pTree = p->pForest->pLeft;
  38047. if( pTree ){
  38048. struct RowSetEntry *pHead, *pTail;
  38049. rowSetTreeToList(pTree, &pHead, &pTail);
  38050. p->pEntry = rowSetEntryMerge(p->pEntry, pHead);
  38051. }
  38052. p->pForest = p->pForest->pRight;
  38053. }
  38054. #endif
  38055. p->rsFlags |= ROWSET_NEXT; /* Verify this routine is never called again */
  38056. }
  38057. /*
  38058. ** Extract the smallest element from the RowSet.
  38059. ** Write the element into *pRowid. Return 1 on success. Return
  38060. ** 0 if the RowSet is already empty.
  38061. **
  38062. ** After this routine has been called, the sqlite3RowSetInsert()
  38063. ** routine may not be called again.
  38064. */
  38065. SQLITE_PRIVATE int sqlite3RowSetNext(RowSet *p, i64 *pRowid){
  38066. assert( p!=0 );
  38067. /* Merge the forest into a single sorted list on first call */
  38068. if( (p->rsFlags & ROWSET_NEXT)==0 ) rowSetToList(p);
  38069. /* Return the next entry on the list */
  38070. if( p->pEntry ){
  38071. *pRowid = p->pEntry->v;
  38072. p->pEntry = p->pEntry->pRight;
  38073. if( p->pEntry==0 ){
  38074. sqlite3RowSetClear(p);
  38075. }
  38076. return 1;
  38077. }else{
  38078. return 0;
  38079. }
  38080. }
  38081. /*
  38082. ** Check to see if element iRowid was inserted into the rowset as
  38083. ** part of any insert batch prior to iBatch. Return 1 or 0.
  38084. **
  38085. ** If this is the first test of a new batch and if there exist entries
  38086. ** on pRowSet->pEntry, then sort those entries into the forest at
  38087. ** pRowSet->pForest so that they can be tested.
  38088. */
  38089. SQLITE_PRIVATE int sqlite3RowSetTest(RowSet *pRowSet, int iBatch, sqlite3_int64 iRowid){
  38090. struct RowSetEntry *p, *pTree;
  38091. /* This routine is never called after sqlite3RowSetNext() */
  38092. assert( pRowSet!=0 && (pRowSet->rsFlags & ROWSET_NEXT)==0 );
  38093. /* Sort entries into the forest on the first test of a new batch
  38094. */
  38095. if( iBatch!=pRowSet->iBatch ){
  38096. p = pRowSet->pEntry;
  38097. if( p ){
  38098. struct RowSetEntry **ppPrevTree = &pRowSet->pForest;
  38099. if( (pRowSet->rsFlags & ROWSET_SORTED)==0 ){
  38100. p = rowSetEntrySort(p);
  38101. }
  38102. for(pTree = pRowSet->pForest; pTree; pTree=pTree->pRight){
  38103. ppPrevTree = &pTree->pRight;
  38104. if( pTree->pLeft==0 ){
  38105. pTree->pLeft = rowSetListToTree(p);
  38106. break;
  38107. }else{
  38108. struct RowSetEntry *pAux, *pTail;
  38109. rowSetTreeToList(pTree->pLeft, &pAux, &pTail);
  38110. pTree->pLeft = 0;
  38111. p = rowSetEntryMerge(pAux, p);
  38112. }
  38113. }
  38114. if( pTree==0 ){
  38115. *ppPrevTree = pTree = rowSetEntryAlloc(pRowSet);
  38116. if( pTree ){
  38117. pTree->v = 0;
  38118. pTree->pRight = 0;
  38119. pTree->pLeft = rowSetListToTree(p);
  38120. }
  38121. }
  38122. pRowSet->pEntry = 0;
  38123. pRowSet->pLast = 0;
  38124. pRowSet->rsFlags |= ROWSET_SORTED;
  38125. }
  38126. pRowSet->iBatch = iBatch;
  38127. }
  38128. /* Test to see if the iRowid value appears anywhere in the forest.
  38129. ** Return 1 if it does and 0 if not.
  38130. */
  38131. for(pTree = pRowSet->pForest; pTree; pTree=pTree->pRight){
  38132. p = pTree->pLeft;
  38133. while( p ){
  38134. if( p->v<iRowid ){
  38135. p = p->pRight;
  38136. }else if( p->v>iRowid ){
  38137. p = p->pLeft;
  38138. }else{
  38139. return 1;
  38140. }
  38141. }
  38142. }
  38143. return 0;
  38144. }
  38145. /************** End of rowset.c **********************************************/
  38146. /************** Begin file pager.c *******************************************/
  38147. /*
  38148. ** 2001 September 15
  38149. **
  38150. ** The author disclaims copyright to this source code. In place of
  38151. ** a legal notice, here is a blessing:
  38152. **
  38153. ** May you do good and not evil.
  38154. ** May you find forgiveness for yourself and forgive others.
  38155. ** May you share freely, never taking more than you give.
  38156. **
  38157. *************************************************************************
  38158. ** This is the implementation of the page cache subsystem or "pager".
  38159. **
  38160. ** The pager is used to access a database disk file. It implements
  38161. ** atomic commit and rollback through the use of a journal file that
  38162. ** is separate from the database file. The pager also implements file
  38163. ** locking to prevent two processes from writing the same database
  38164. ** file simultaneously, or one process from reading the database while
  38165. ** another is writing.
  38166. */
  38167. #ifndef SQLITE_OMIT_DISKIO
  38168. /************** Include wal.h in the middle of pager.c ***********************/
  38169. /************** Begin file wal.h *********************************************/
  38170. /*
  38171. ** 2010 February 1
  38172. **
  38173. ** The author disclaims copyright to this source code. In place of
  38174. ** a legal notice, here is a blessing:
  38175. **
  38176. ** May you do good and not evil.
  38177. ** May you find forgiveness for yourself and forgive others.
  38178. ** May you share freely, never taking more than you give.
  38179. **
  38180. *************************************************************************
  38181. ** This header file defines the interface to the write-ahead logging
  38182. ** system. Refer to the comments below and the header comment attached to
  38183. ** the implementation of each function in log.c for further details.
  38184. */
  38185. #ifndef _WAL_H_
  38186. #define _WAL_H_
  38187. /* Additional values that can be added to the sync_flags argument of
  38188. ** sqlite3WalFrames():
  38189. */
  38190. #define WAL_SYNC_TRANSACTIONS 0x20 /* Sync at the end of each transaction */
  38191. #define SQLITE_SYNC_MASK 0x13 /* Mask off the SQLITE_SYNC_* values */
  38192. #ifdef SQLITE_OMIT_WAL
  38193. # define sqlite3WalOpen(x,y,z) 0
  38194. # define sqlite3WalLimit(x,y)
  38195. # define sqlite3WalClose(w,x,y,z) 0
  38196. # define sqlite3WalBeginReadTransaction(y,z) 0
  38197. # define sqlite3WalEndReadTransaction(z)
  38198. # define sqlite3WalDbsize(y) 0
  38199. # define sqlite3WalBeginWriteTransaction(y) 0
  38200. # define sqlite3WalEndWriteTransaction(x) 0
  38201. # define sqlite3WalUndo(x,y,z) 0
  38202. # define sqlite3WalSavepoint(y,z)
  38203. # define sqlite3WalSavepointUndo(y,z) 0
  38204. # define sqlite3WalFrames(u,v,w,x,y,z) 0
  38205. # define sqlite3WalCheckpoint(r,s,t,u,v,w,x,y,z) 0
  38206. # define sqlite3WalCallback(z) 0
  38207. # define sqlite3WalExclusiveMode(y,z) 0
  38208. # define sqlite3WalHeapMemory(z) 0
  38209. # define sqlite3WalFramesize(z) 0
  38210. # define sqlite3WalFindFrame(x,y,z) 0
  38211. #else
  38212. #define WAL_SAVEPOINT_NDATA 4
  38213. /* Connection to a write-ahead log (WAL) file.
  38214. ** There is one object of this type for each pager.
  38215. */
  38216. typedef struct Wal Wal;
  38217. /* Open and close a connection to a write-ahead log. */
  38218. SQLITE_PRIVATE int sqlite3WalOpen(sqlite3_vfs*, sqlite3_file*, const char *, int, i64, Wal**);
  38219. SQLITE_PRIVATE int sqlite3WalClose(Wal *pWal, int sync_flags, int, u8 *);
  38220. /* Set the limiting size of a WAL file. */
  38221. SQLITE_PRIVATE void sqlite3WalLimit(Wal*, i64);
  38222. /* Used by readers to open (lock) and close (unlock) a snapshot. A
  38223. ** snapshot is like a read-transaction. It is the state of the database
  38224. ** at an instant in time. sqlite3WalOpenSnapshot gets a read lock and
  38225. ** preserves the current state even if the other threads or processes
  38226. ** write to or checkpoint the WAL. sqlite3WalCloseSnapshot() closes the
  38227. ** transaction and releases the lock.
  38228. */
  38229. SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *);
  38230. SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal);
  38231. /* Read a page from the write-ahead log, if it is present. */
  38232. SQLITE_PRIVATE int sqlite3WalFindFrame(Wal *, Pgno, u32 *);
  38233. SQLITE_PRIVATE int sqlite3WalReadFrame(Wal *, u32, int, u8 *);
  38234. /* If the WAL is not empty, return the size of the database. */
  38235. SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal);
  38236. /* Obtain or release the WRITER lock. */
  38237. SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal);
  38238. SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal);
  38239. /* Undo any frames written (but not committed) to the log */
  38240. SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx);
  38241. /* Return an integer that records the current (uncommitted) write
  38242. ** position in the WAL */
  38243. SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData);
  38244. /* Move the write position of the WAL back to iFrame. Called in
  38245. ** response to a ROLLBACK TO command. */
  38246. SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData);
  38247. /* Write a frame or frames to the log. */
  38248. SQLITE_PRIVATE int sqlite3WalFrames(Wal *pWal, int, PgHdr *, Pgno, int, int);
  38249. /* Copy pages from the log to the database file */
  38250. SQLITE_PRIVATE int sqlite3WalCheckpoint(
  38251. Wal *pWal, /* Write-ahead log connection */
  38252. int eMode, /* One of PASSIVE, FULL and RESTART */
  38253. int (*xBusy)(void*), /* Function to call when busy */
  38254. void *pBusyArg, /* Context argument for xBusyHandler */
  38255. int sync_flags, /* Flags to sync db file with (or 0) */
  38256. int nBuf, /* Size of buffer nBuf */
  38257. u8 *zBuf, /* Temporary buffer to use */
  38258. int *pnLog, /* OUT: Number of frames in WAL */
  38259. int *pnCkpt /* OUT: Number of backfilled frames in WAL */
  38260. );
  38261. /* Return the value to pass to a sqlite3_wal_hook callback, the
  38262. ** number of frames in the WAL at the point of the last commit since
  38263. ** sqlite3WalCallback() was called. If no commits have occurred since
  38264. ** the last call, then return 0.
  38265. */
  38266. SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal);
  38267. /* Tell the wal layer that an EXCLUSIVE lock has been obtained (or released)
  38268. ** by the pager layer on the database file.
  38269. */
  38270. SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op);
  38271. /* Return true if the argument is non-NULL and the WAL module is using
  38272. ** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
  38273. ** WAL module is using shared-memory, return false.
  38274. */
  38275. SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal);
  38276. #ifdef SQLITE_ENABLE_ZIPVFS
  38277. /* If the WAL file is not empty, return the number of bytes of content
  38278. ** stored in each frame (i.e. the db page-size when the WAL was created).
  38279. */
  38280. SQLITE_PRIVATE int sqlite3WalFramesize(Wal *pWal);
  38281. #endif
  38282. #endif /* ifndef SQLITE_OMIT_WAL */
  38283. #endif /* _WAL_H_ */
  38284. /************** End of wal.h *************************************************/
  38285. /************** Continuing where we left off in pager.c **********************/
  38286. /******************* NOTES ON THE DESIGN OF THE PAGER ************************
  38287. **
  38288. ** This comment block describes invariants that hold when using a rollback
  38289. ** journal. These invariants do not apply for journal_mode=WAL,
  38290. ** journal_mode=MEMORY, or journal_mode=OFF.
  38291. **
  38292. ** Within this comment block, a page is deemed to have been synced
  38293. ** automatically as soon as it is written when PRAGMA synchronous=OFF.
  38294. ** Otherwise, the page is not synced until the xSync method of the VFS
  38295. ** is called successfully on the file containing the page.
  38296. **
  38297. ** Definition: A page of the database file is said to be "overwriteable" if
  38298. ** one or more of the following are true about the page:
  38299. **
  38300. ** (a) The original content of the page as it was at the beginning of
  38301. ** the transaction has been written into the rollback journal and
  38302. ** synced.
  38303. **
  38304. ** (b) The page was a freelist leaf page at the start of the transaction.
  38305. **
  38306. ** (c) The page number is greater than the largest page that existed in
  38307. ** the database file at the start of the transaction.
  38308. **
  38309. ** (1) A page of the database file is never overwritten unless one of the
  38310. ** following are true:
  38311. **
  38312. ** (a) The page and all other pages on the same sector are overwriteable.
  38313. **
  38314. ** (b) The atomic page write optimization is enabled, and the entire
  38315. ** transaction other than the update of the transaction sequence
  38316. ** number consists of a single page change.
  38317. **
  38318. ** (2) The content of a page written into the rollback journal exactly matches
  38319. ** both the content in the database when the rollback journal was written
  38320. ** and the content in the database at the beginning of the current
  38321. ** transaction.
  38322. **
  38323. ** (3) Writes to the database file are an integer multiple of the page size
  38324. ** in length and are aligned on a page boundary.
  38325. **
  38326. ** (4) Reads from the database file are either aligned on a page boundary and
  38327. ** an integer multiple of the page size in length or are taken from the
  38328. ** first 100 bytes of the database file.
  38329. **
  38330. ** (5) All writes to the database file are synced prior to the rollback journal
  38331. ** being deleted, truncated, or zeroed.
  38332. **
  38333. ** (6) If a master journal file is used, then all writes to the database file
  38334. ** are synced prior to the master journal being deleted.
  38335. **
  38336. ** Definition: Two databases (or the same database at two points it time)
  38337. ** are said to be "logically equivalent" if they give the same answer to
  38338. ** all queries. Note in particular the content of freelist leaf
  38339. ** pages can be changed arbitrarily without affecting the logical equivalence
  38340. ** of the database.
  38341. **
  38342. ** (7) At any time, if any subset, including the empty set and the total set,
  38343. ** of the unsynced changes to a rollback journal are removed and the
  38344. ** journal is rolled back, the resulting database file will be logically
  38345. ** equivalent to the database file at the beginning of the transaction.
  38346. **
  38347. ** (8) When a transaction is rolled back, the xTruncate method of the VFS
  38348. ** is called to restore the database file to the same size it was at
  38349. ** the beginning of the transaction. (In some VFSes, the xTruncate
  38350. ** method is a no-op, but that does not change the fact the SQLite will
  38351. ** invoke it.)
  38352. **
  38353. ** (9) Whenever the database file is modified, at least one bit in the range
  38354. ** of bytes from 24 through 39 inclusive will be changed prior to releasing
  38355. ** the EXCLUSIVE lock, thus signaling other connections on the same
  38356. ** database to flush their caches.
  38357. **
  38358. ** (10) The pattern of bits in bytes 24 through 39 shall not repeat in less
  38359. ** than one billion transactions.
  38360. **
  38361. ** (11) A database file is well-formed at the beginning and at the conclusion
  38362. ** of every transaction.
  38363. **
  38364. ** (12) An EXCLUSIVE lock is held on the database file when writing to
  38365. ** the database file.
  38366. **
  38367. ** (13) A SHARED lock is held on the database file while reading any
  38368. ** content out of the database file.
  38369. **
  38370. ******************************************************************************/
  38371. /*
  38372. ** Macros for troubleshooting. Normally turned off
  38373. */
  38374. #if 0
  38375. int sqlite3PagerTrace=1; /* True to enable tracing */
  38376. #define sqlite3DebugPrintf printf
  38377. #define PAGERTRACE(X) if( sqlite3PagerTrace ){ sqlite3DebugPrintf X; }
  38378. #else
  38379. #define PAGERTRACE(X)
  38380. #endif
  38381. /*
  38382. ** The following two macros are used within the PAGERTRACE() macros above
  38383. ** to print out file-descriptors.
  38384. **
  38385. ** PAGERID() takes a pointer to a Pager struct as its argument. The
  38386. ** associated file-descriptor is returned. FILEHANDLEID() takes an sqlite3_file
  38387. ** struct as its argument.
  38388. */
  38389. #define PAGERID(p) ((int)(p->fd))
  38390. #define FILEHANDLEID(fd) ((int)fd)
  38391. /*
  38392. ** The Pager.eState variable stores the current 'state' of a pager. A
  38393. ** pager may be in any one of the seven states shown in the following
  38394. ** state diagram.
  38395. **
  38396. ** OPEN <------+------+
  38397. ** | | |
  38398. ** V | |
  38399. ** +---------> READER-------+ |
  38400. ** | | |
  38401. ** | V |
  38402. ** |<-------WRITER_LOCKED------> ERROR
  38403. ** | | ^
  38404. ** | V |
  38405. ** |<------WRITER_CACHEMOD-------->|
  38406. ** | | |
  38407. ** | V |
  38408. ** |<-------WRITER_DBMOD---------->|
  38409. ** | | |
  38410. ** | V |
  38411. ** +<------WRITER_FINISHED-------->+
  38412. **
  38413. **
  38414. ** List of state transitions and the C [function] that performs each:
  38415. **
  38416. ** OPEN -> READER [sqlite3PagerSharedLock]
  38417. ** READER -> OPEN [pager_unlock]
  38418. **
  38419. ** READER -> WRITER_LOCKED [sqlite3PagerBegin]
  38420. ** WRITER_LOCKED -> WRITER_CACHEMOD [pager_open_journal]
  38421. ** WRITER_CACHEMOD -> WRITER_DBMOD [syncJournal]
  38422. ** WRITER_DBMOD -> WRITER_FINISHED [sqlite3PagerCommitPhaseOne]
  38423. ** WRITER_*** -> READER [pager_end_transaction]
  38424. **
  38425. ** WRITER_*** -> ERROR [pager_error]
  38426. ** ERROR -> OPEN [pager_unlock]
  38427. **
  38428. **
  38429. ** OPEN:
  38430. **
  38431. ** The pager starts up in this state. Nothing is guaranteed in this
  38432. ** state - the file may or may not be locked and the database size is
  38433. ** unknown. The database may not be read or written.
  38434. **
  38435. ** * No read or write transaction is active.
  38436. ** * Any lock, or no lock at all, may be held on the database file.
  38437. ** * The dbSize, dbOrigSize and dbFileSize variables may not be trusted.
  38438. **
  38439. ** READER:
  38440. **
  38441. ** In this state all the requirements for reading the database in
  38442. ** rollback (non-WAL) mode are met. Unless the pager is (or recently
  38443. ** was) in exclusive-locking mode, a user-level read transaction is
  38444. ** open. The database size is known in this state.
  38445. **
  38446. ** A connection running with locking_mode=normal enters this state when
  38447. ** it opens a read-transaction on the database and returns to state
  38448. ** OPEN after the read-transaction is completed. However a connection
  38449. ** running in locking_mode=exclusive (including temp databases) remains in
  38450. ** this state even after the read-transaction is closed. The only way
  38451. ** a locking_mode=exclusive connection can transition from READER to OPEN
  38452. ** is via the ERROR state (see below).
  38453. **
  38454. ** * A read transaction may be active (but a write-transaction cannot).
  38455. ** * A SHARED or greater lock is held on the database file.
  38456. ** * The dbSize variable may be trusted (even if a user-level read
  38457. ** transaction is not active). The dbOrigSize and dbFileSize variables
  38458. ** may not be trusted at this point.
  38459. ** * If the database is a WAL database, then the WAL connection is open.
  38460. ** * Even if a read-transaction is not open, it is guaranteed that
  38461. ** there is no hot-journal in the file-system.
  38462. **
  38463. ** WRITER_LOCKED:
  38464. **
  38465. ** The pager moves to this state from READER when a write-transaction
  38466. ** is first opened on the database. In WRITER_LOCKED state, all locks
  38467. ** required to start a write-transaction are held, but no actual
  38468. ** modifications to the cache or database have taken place.
  38469. **
  38470. ** In rollback mode, a RESERVED or (if the transaction was opened with
  38471. ** BEGIN EXCLUSIVE) EXCLUSIVE lock is obtained on the database file when
  38472. ** moving to this state, but the journal file is not written to or opened
  38473. ** to in this state. If the transaction is committed or rolled back while
  38474. ** in WRITER_LOCKED state, all that is required is to unlock the database
  38475. ** file.
  38476. **
  38477. ** IN WAL mode, WalBeginWriteTransaction() is called to lock the log file.
  38478. ** If the connection is running with locking_mode=exclusive, an attempt
  38479. ** is made to obtain an EXCLUSIVE lock on the database file.
  38480. **
  38481. ** * A write transaction is active.
  38482. ** * If the connection is open in rollback-mode, a RESERVED or greater
  38483. ** lock is held on the database file.
  38484. ** * If the connection is open in WAL-mode, a WAL write transaction
  38485. ** is open (i.e. sqlite3WalBeginWriteTransaction() has been successfully
  38486. ** called).
  38487. ** * The dbSize, dbOrigSize and dbFileSize variables are all valid.
  38488. ** * The contents of the pager cache have not been modified.
  38489. ** * The journal file may or may not be open.
  38490. ** * Nothing (not even the first header) has been written to the journal.
  38491. **
  38492. ** WRITER_CACHEMOD:
  38493. **
  38494. ** A pager moves from WRITER_LOCKED state to this state when a page is
  38495. ** first modified by the upper layer. In rollback mode the journal file
  38496. ** is opened (if it is not already open) and a header written to the
  38497. ** start of it. The database file on disk has not been modified.
  38498. **
  38499. ** * A write transaction is active.
  38500. ** * A RESERVED or greater lock is held on the database file.
  38501. ** * The journal file is open and the first header has been written
  38502. ** to it, but the header has not been synced to disk.
  38503. ** * The contents of the page cache have been modified.
  38504. **
  38505. ** WRITER_DBMOD:
  38506. **
  38507. ** The pager transitions from WRITER_CACHEMOD into WRITER_DBMOD state
  38508. ** when it modifies the contents of the database file. WAL connections
  38509. ** never enter this state (since they do not modify the database file,
  38510. ** just the log file).
  38511. **
  38512. ** * A write transaction is active.
  38513. ** * An EXCLUSIVE or greater lock is held on the database file.
  38514. ** * The journal file is open and the first header has been written
  38515. ** and synced to disk.
  38516. ** * The contents of the page cache have been modified (and possibly
  38517. ** written to disk).
  38518. **
  38519. ** WRITER_FINISHED:
  38520. **
  38521. ** It is not possible for a WAL connection to enter this state.
  38522. **
  38523. ** A rollback-mode pager changes to WRITER_FINISHED state from WRITER_DBMOD
  38524. ** state after the entire transaction has been successfully written into the
  38525. ** database file. In this state the transaction may be committed simply
  38526. ** by finalizing the journal file. Once in WRITER_FINISHED state, it is
  38527. ** not possible to modify the database further. At this point, the upper
  38528. ** layer must either commit or rollback the transaction.
  38529. **
  38530. ** * A write transaction is active.
  38531. ** * An EXCLUSIVE or greater lock is held on the database file.
  38532. ** * All writing and syncing of journal and database data has finished.
  38533. ** If no error occurred, all that remains is to finalize the journal to
  38534. ** commit the transaction. If an error did occur, the caller will need
  38535. ** to rollback the transaction.
  38536. **
  38537. ** ERROR:
  38538. **
  38539. ** The ERROR state is entered when an IO or disk-full error (including
  38540. ** SQLITE_IOERR_NOMEM) occurs at a point in the code that makes it
  38541. ** difficult to be sure that the in-memory pager state (cache contents,
  38542. ** db size etc.) are consistent with the contents of the file-system.
  38543. **
  38544. ** Temporary pager files may enter the ERROR state, but in-memory pagers
  38545. ** cannot.
  38546. **
  38547. ** For example, if an IO error occurs while performing a rollback,
  38548. ** the contents of the page-cache may be left in an inconsistent state.
  38549. ** At this point it would be dangerous to change back to READER state
  38550. ** (as usually happens after a rollback). Any subsequent readers might
  38551. ** report database corruption (due to the inconsistent cache), and if
  38552. ** they upgrade to writers, they may inadvertently corrupt the database
  38553. ** file. To avoid this hazard, the pager switches into the ERROR state
  38554. ** instead of READER following such an error.
  38555. **
  38556. ** Once it has entered the ERROR state, any attempt to use the pager
  38557. ** to read or write data returns an error. Eventually, once all
  38558. ** outstanding transactions have been abandoned, the pager is able to
  38559. ** transition back to OPEN state, discarding the contents of the
  38560. ** page-cache and any other in-memory state at the same time. Everything
  38561. ** is reloaded from disk (and, if necessary, hot-journal rollback peformed)
  38562. ** when a read-transaction is next opened on the pager (transitioning
  38563. ** the pager into READER state). At that point the system has recovered
  38564. ** from the error.
  38565. **
  38566. ** Specifically, the pager jumps into the ERROR state if:
  38567. **
  38568. ** 1. An error occurs while attempting a rollback. This happens in
  38569. ** function sqlite3PagerRollback().
  38570. **
  38571. ** 2. An error occurs while attempting to finalize a journal file
  38572. ** following a commit in function sqlite3PagerCommitPhaseTwo().
  38573. **
  38574. ** 3. An error occurs while attempting to write to the journal or
  38575. ** database file in function pagerStress() in order to free up
  38576. ** memory.
  38577. **
  38578. ** In other cases, the error is returned to the b-tree layer. The b-tree
  38579. ** layer then attempts a rollback operation. If the error condition
  38580. ** persists, the pager enters the ERROR state via condition (1) above.
  38581. **
  38582. ** Condition (3) is necessary because it can be triggered by a read-only
  38583. ** statement executed within a transaction. In this case, if the error
  38584. ** code were simply returned to the user, the b-tree layer would not
  38585. ** automatically attempt a rollback, as it assumes that an error in a
  38586. ** read-only statement cannot leave the pager in an internally inconsistent
  38587. ** state.
  38588. **
  38589. ** * The Pager.errCode variable is set to something other than SQLITE_OK.
  38590. ** * There are one or more outstanding references to pages (after the
  38591. ** last reference is dropped the pager should move back to OPEN state).
  38592. ** * The pager is not an in-memory pager.
  38593. **
  38594. **
  38595. ** Notes:
  38596. **
  38597. ** * A pager is never in WRITER_DBMOD or WRITER_FINISHED state if the
  38598. ** connection is open in WAL mode. A WAL connection is always in one
  38599. ** of the first four states.
  38600. **
  38601. ** * Normally, a connection open in exclusive mode is never in PAGER_OPEN
  38602. ** state. There are two exceptions: immediately after exclusive-mode has
  38603. ** been turned on (and before any read or write transactions are
  38604. ** executed), and when the pager is leaving the "error state".
  38605. **
  38606. ** * See also: assert_pager_state().
  38607. */
  38608. #define PAGER_OPEN 0
  38609. #define PAGER_READER 1
  38610. #define PAGER_WRITER_LOCKED 2
  38611. #define PAGER_WRITER_CACHEMOD 3
  38612. #define PAGER_WRITER_DBMOD 4
  38613. #define PAGER_WRITER_FINISHED 5
  38614. #define PAGER_ERROR 6
  38615. /*
  38616. ** The Pager.eLock variable is almost always set to one of the
  38617. ** following locking-states, according to the lock currently held on
  38618. ** the database file: NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
  38619. ** This variable is kept up to date as locks are taken and released by
  38620. ** the pagerLockDb() and pagerUnlockDb() wrappers.
  38621. **
  38622. ** If the VFS xLock() or xUnlock() returns an error other than SQLITE_BUSY
  38623. ** (i.e. one of the SQLITE_IOERR subtypes), it is not clear whether or not
  38624. ** the operation was successful. In these circumstances pagerLockDb() and
  38625. ** pagerUnlockDb() take a conservative approach - eLock is always updated
  38626. ** when unlocking the file, and only updated when locking the file if the
  38627. ** VFS call is successful. This way, the Pager.eLock variable may be set
  38628. ** to a less exclusive (lower) value than the lock that is actually held
  38629. ** at the system level, but it is never set to a more exclusive value.
  38630. **
  38631. ** This is usually safe. If an xUnlock fails or appears to fail, there may
  38632. ** be a few redundant xLock() calls or a lock may be held for longer than
  38633. ** required, but nothing really goes wrong.
  38634. **
  38635. ** The exception is when the database file is unlocked as the pager moves
  38636. ** from ERROR to OPEN state. At this point there may be a hot-journal file
  38637. ** in the file-system that needs to be rolled back (as part of an OPEN->SHARED
  38638. ** transition, by the same pager or any other). If the call to xUnlock()
  38639. ** fails at this point and the pager is left holding an EXCLUSIVE lock, this
  38640. ** can confuse the call to xCheckReservedLock() call made later as part
  38641. ** of hot-journal detection.
  38642. **
  38643. ** xCheckReservedLock() is defined as returning true "if there is a RESERVED
  38644. ** lock held by this process or any others". So xCheckReservedLock may
  38645. ** return true because the caller itself is holding an EXCLUSIVE lock (but
  38646. ** doesn't know it because of a previous error in xUnlock). If this happens
  38647. ** a hot-journal may be mistaken for a journal being created by an active
  38648. ** transaction in another process, causing SQLite to read from the database
  38649. ** without rolling it back.
  38650. **
  38651. ** To work around this, if a call to xUnlock() fails when unlocking the
  38652. ** database in the ERROR state, Pager.eLock is set to UNKNOWN_LOCK. It
  38653. ** is only changed back to a real locking state after a successful call
  38654. ** to xLock(EXCLUSIVE). Also, the code to do the OPEN->SHARED state transition
  38655. ** omits the check for a hot-journal if Pager.eLock is set to UNKNOWN_LOCK
  38656. ** lock. Instead, it assumes a hot-journal exists and obtains an EXCLUSIVE
  38657. ** lock on the database file before attempting to roll it back. See function
  38658. ** PagerSharedLock() for more detail.
  38659. **
  38660. ** Pager.eLock may only be set to UNKNOWN_LOCK when the pager is in
  38661. ** PAGER_OPEN state.
  38662. */
  38663. #define UNKNOWN_LOCK (EXCLUSIVE_LOCK+1)
  38664. /*
  38665. ** A macro used for invoking the codec if there is one
  38666. */
  38667. #ifdef SQLITE_HAS_CODEC
  38668. # define CODEC1(P,D,N,X,E) \
  38669. if( P->xCodec && P->xCodec(P->pCodec,D,N,X)==0 ){ E; }
  38670. # define CODEC2(P,D,N,X,E,O) \
  38671. if( P->xCodec==0 ){ O=(char*)D; }else \
  38672. if( (O=(char*)(P->xCodec(P->pCodec,D,N,X)))==0 ){ E; }
  38673. #else
  38674. # define CODEC1(P,D,N,X,E) /* NO-OP */
  38675. # define CODEC2(P,D,N,X,E,O) O=(char*)D
  38676. #endif
  38677. /*
  38678. ** The maximum allowed sector size. 64KiB. If the xSectorsize() method
  38679. ** returns a value larger than this, then MAX_SECTOR_SIZE is used instead.
  38680. ** This could conceivably cause corruption following a power failure on
  38681. ** such a system. This is currently an undocumented limit.
  38682. */
  38683. #define MAX_SECTOR_SIZE 0x10000
  38684. /*
  38685. ** An instance of the following structure is allocated for each active
  38686. ** savepoint and statement transaction in the system. All such structures
  38687. ** are stored in the Pager.aSavepoint[] array, which is allocated and
  38688. ** resized using sqlite3Realloc().
  38689. **
  38690. ** When a savepoint is created, the PagerSavepoint.iHdrOffset field is
  38691. ** set to 0. If a journal-header is written into the main journal while
  38692. ** the savepoint is active, then iHdrOffset is set to the byte offset
  38693. ** immediately following the last journal record written into the main
  38694. ** journal before the journal-header. This is required during savepoint
  38695. ** rollback (see pagerPlaybackSavepoint()).
  38696. */
  38697. typedef struct PagerSavepoint PagerSavepoint;
  38698. struct PagerSavepoint {
  38699. i64 iOffset; /* Starting offset in main journal */
  38700. i64 iHdrOffset; /* See above */
  38701. Bitvec *pInSavepoint; /* Set of pages in this savepoint */
  38702. Pgno nOrig; /* Original number of pages in file */
  38703. Pgno iSubRec; /* Index of first record in sub-journal */
  38704. #ifndef SQLITE_OMIT_WAL
  38705. u32 aWalData[WAL_SAVEPOINT_NDATA]; /* WAL savepoint context */
  38706. #endif
  38707. };
  38708. /*
  38709. ** Bits of the Pager.doNotSpill flag. See further description below.
  38710. */
  38711. #define SPILLFLAG_OFF 0x01 /* Never spill cache. Set via pragma */
  38712. #define SPILLFLAG_ROLLBACK 0x02 /* Current rolling back, so do not spill */
  38713. #define SPILLFLAG_NOSYNC 0x04 /* Spill is ok, but do not sync */
  38714. /*
  38715. ** An open page cache is an instance of struct Pager. A description of
  38716. ** some of the more important member variables follows:
  38717. **
  38718. ** eState
  38719. **
  38720. ** The current 'state' of the pager object. See the comment and state
  38721. ** diagram above for a description of the pager state.
  38722. **
  38723. ** eLock
  38724. **
  38725. ** For a real on-disk database, the current lock held on the database file -
  38726. ** NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
  38727. **
  38728. ** For a temporary or in-memory database (neither of which require any
  38729. ** locks), this variable is always set to EXCLUSIVE_LOCK. Since such
  38730. ** databases always have Pager.exclusiveMode==1, this tricks the pager
  38731. ** logic into thinking that it already has all the locks it will ever
  38732. ** need (and no reason to release them).
  38733. **
  38734. ** In some (obscure) circumstances, this variable may also be set to
  38735. ** UNKNOWN_LOCK. See the comment above the #define of UNKNOWN_LOCK for
  38736. ** details.
  38737. **
  38738. ** changeCountDone
  38739. **
  38740. ** This boolean variable is used to make sure that the change-counter
  38741. ** (the 4-byte header field at byte offset 24 of the database file) is
  38742. ** not updated more often than necessary.
  38743. **
  38744. ** It is set to true when the change-counter field is updated, which
  38745. ** can only happen if an exclusive lock is held on the database file.
  38746. ** It is cleared (set to false) whenever an exclusive lock is
  38747. ** relinquished on the database file. Each time a transaction is committed,
  38748. ** The changeCountDone flag is inspected. If it is true, the work of
  38749. ** updating the change-counter is omitted for the current transaction.
  38750. **
  38751. ** This mechanism means that when running in exclusive mode, a connection
  38752. ** need only update the change-counter once, for the first transaction
  38753. ** committed.
  38754. **
  38755. ** setMaster
  38756. **
  38757. ** When PagerCommitPhaseOne() is called to commit a transaction, it may
  38758. ** (or may not) specify a master-journal name to be written into the
  38759. ** journal file before it is synced to disk.
  38760. **
  38761. ** Whether or not a journal file contains a master-journal pointer affects
  38762. ** the way in which the journal file is finalized after the transaction is
  38763. ** committed or rolled back when running in "journal_mode=PERSIST" mode.
  38764. ** If a journal file does not contain a master-journal pointer, it is
  38765. ** finalized by overwriting the first journal header with zeroes. If
  38766. ** it does contain a master-journal pointer the journal file is finalized
  38767. ** by truncating it to zero bytes, just as if the connection were
  38768. ** running in "journal_mode=truncate" mode.
  38769. **
  38770. ** Journal files that contain master journal pointers cannot be finalized
  38771. ** simply by overwriting the first journal-header with zeroes, as the
  38772. ** master journal pointer could interfere with hot-journal rollback of any
  38773. ** subsequently interrupted transaction that reuses the journal file.
  38774. **
  38775. ** The flag is cleared as soon as the journal file is finalized (either
  38776. ** by PagerCommitPhaseTwo or PagerRollback). If an IO error prevents the
  38777. ** journal file from being successfully finalized, the setMaster flag
  38778. ** is cleared anyway (and the pager will move to ERROR state).
  38779. **
  38780. ** doNotSpill
  38781. **
  38782. ** This variables control the behavior of cache-spills (calls made by
  38783. ** the pcache module to the pagerStress() routine to write cached data
  38784. ** to the file-system in order to free up memory).
  38785. **
  38786. ** When bits SPILLFLAG_OFF or SPILLFLAG_ROLLBACK of doNotSpill are set,
  38787. ** writing to the database from pagerStress() is disabled altogether.
  38788. ** The SPILLFLAG_ROLLBACK case is done in a very obscure case that
  38789. ** comes up during savepoint rollback that requires the pcache module
  38790. ** to allocate a new page to prevent the journal file from being written
  38791. ** while it is being traversed by code in pager_playback(). The SPILLFLAG_OFF
  38792. ** case is a user preference.
  38793. **
  38794. ** If the SPILLFLAG_NOSYNC bit is set, writing to the database from pagerStress()
  38795. ** is permitted, but syncing the journal file is not. This flag is set
  38796. ** by sqlite3PagerWrite() when the file-system sector-size is larger than
  38797. ** the database page-size in order to prevent a journal sync from happening
  38798. ** in between the journalling of two pages on the same sector.
  38799. **
  38800. ** subjInMemory
  38801. **
  38802. ** This is a boolean variable. If true, then any required sub-journal
  38803. ** is opened as an in-memory journal file. If false, then in-memory
  38804. ** sub-journals are only used for in-memory pager files.
  38805. **
  38806. ** This variable is updated by the upper layer each time a new
  38807. ** write-transaction is opened.
  38808. **
  38809. ** dbSize, dbOrigSize, dbFileSize
  38810. **
  38811. ** Variable dbSize is set to the number of pages in the database file.
  38812. ** It is valid in PAGER_READER and higher states (all states except for
  38813. ** OPEN and ERROR).
  38814. **
  38815. ** dbSize is set based on the size of the database file, which may be
  38816. ** larger than the size of the database (the value stored at offset
  38817. ** 28 of the database header by the btree). If the size of the file
  38818. ** is not an integer multiple of the page-size, the value stored in
  38819. ** dbSize is rounded down (i.e. a 5KB file with 2K page-size has dbSize==2).
  38820. ** Except, any file that is greater than 0 bytes in size is considered
  38821. ** to have at least one page. (i.e. a 1KB file with 2K page-size leads
  38822. ** to dbSize==1).
  38823. **
  38824. ** During a write-transaction, if pages with page-numbers greater than
  38825. ** dbSize are modified in the cache, dbSize is updated accordingly.
  38826. ** Similarly, if the database is truncated using PagerTruncateImage(),
  38827. ** dbSize is updated.
  38828. **
  38829. ** Variables dbOrigSize and dbFileSize are valid in states
  38830. ** PAGER_WRITER_LOCKED and higher. dbOrigSize is a copy of the dbSize
  38831. ** variable at the start of the transaction. It is used during rollback,
  38832. ** and to determine whether or not pages need to be journalled before
  38833. ** being modified.
  38834. **
  38835. ** Throughout a write-transaction, dbFileSize contains the size of
  38836. ** the file on disk in pages. It is set to a copy of dbSize when the
  38837. ** write-transaction is first opened, and updated when VFS calls are made
  38838. ** to write or truncate the database file on disk.
  38839. **
  38840. ** The only reason the dbFileSize variable is required is to suppress
  38841. ** unnecessary calls to xTruncate() after committing a transaction. If,
  38842. ** when a transaction is committed, the dbFileSize variable indicates
  38843. ** that the database file is larger than the database image (Pager.dbSize),
  38844. ** pager_truncate() is called. The pager_truncate() call uses xFilesize()
  38845. ** to measure the database file on disk, and then truncates it if required.
  38846. ** dbFileSize is not used when rolling back a transaction. In this case
  38847. ** pager_truncate() is called unconditionally (which means there may be
  38848. ** a call to xFilesize() that is not strictly required). In either case,
  38849. ** pager_truncate() may cause the file to become smaller or larger.
  38850. **
  38851. ** dbHintSize
  38852. **
  38853. ** The dbHintSize variable is used to limit the number of calls made to
  38854. ** the VFS xFileControl(FCNTL_SIZE_HINT) method.
  38855. **
  38856. ** dbHintSize is set to a copy of the dbSize variable when a
  38857. ** write-transaction is opened (at the same time as dbFileSize and
  38858. ** dbOrigSize). If the xFileControl(FCNTL_SIZE_HINT) method is called,
  38859. ** dbHintSize is increased to the number of pages that correspond to the
  38860. ** size-hint passed to the method call. See pager_write_pagelist() for
  38861. ** details.
  38862. **
  38863. ** errCode
  38864. **
  38865. ** The Pager.errCode variable is only ever used in PAGER_ERROR state. It
  38866. ** is set to zero in all other states. In PAGER_ERROR state, Pager.errCode
  38867. ** is always set to SQLITE_FULL, SQLITE_IOERR or one of the SQLITE_IOERR_XXX
  38868. ** sub-codes.
  38869. */
  38870. struct Pager {
  38871. sqlite3_vfs *pVfs; /* OS functions to use for IO */
  38872. u8 exclusiveMode; /* Boolean. True if locking_mode==EXCLUSIVE */
  38873. u8 journalMode; /* One of the PAGER_JOURNALMODE_* values */
  38874. u8 useJournal; /* Use a rollback journal on this file */
  38875. u8 noSync; /* Do not sync the journal if true */
  38876. u8 fullSync; /* Do extra syncs of the journal for robustness */
  38877. u8 ckptSyncFlags; /* SYNC_NORMAL or SYNC_FULL for checkpoint */
  38878. u8 walSyncFlags; /* SYNC_NORMAL or SYNC_FULL for wal writes */
  38879. u8 syncFlags; /* SYNC_NORMAL or SYNC_FULL otherwise */
  38880. u8 tempFile; /* zFilename is a temporary or immutable file */
  38881. u8 noLock; /* Do not lock (except in WAL mode) */
  38882. u8 readOnly; /* True for a read-only database */
  38883. u8 memDb; /* True to inhibit all file I/O */
  38884. /**************************************************************************
  38885. ** The following block contains those class members that change during
  38886. ** routine operation. Class members not in this block are either fixed
  38887. ** when the pager is first created or else only change when there is a
  38888. ** significant mode change (such as changing the page_size, locking_mode,
  38889. ** or the journal_mode). From another view, these class members describe
  38890. ** the "state" of the pager, while other class members describe the
  38891. ** "configuration" of the pager.
  38892. */
  38893. u8 eState; /* Pager state (OPEN, READER, WRITER_LOCKED..) */
  38894. u8 eLock; /* Current lock held on database file */
  38895. u8 changeCountDone; /* Set after incrementing the change-counter */
  38896. u8 setMaster; /* True if a m-j name has been written to jrnl */
  38897. u8 doNotSpill; /* Do not spill the cache when non-zero */
  38898. u8 subjInMemory; /* True to use in-memory sub-journals */
  38899. Pgno dbSize; /* Number of pages in the database */
  38900. Pgno dbOrigSize; /* dbSize before the current transaction */
  38901. Pgno dbFileSize; /* Number of pages in the database file */
  38902. Pgno dbHintSize; /* Value passed to FCNTL_SIZE_HINT call */
  38903. int errCode; /* One of several kinds of errors */
  38904. int nRec; /* Pages journalled since last j-header written */
  38905. u32 cksumInit; /* Quasi-random value added to every checksum */
  38906. u32 nSubRec; /* Number of records written to sub-journal */
  38907. Bitvec *pInJournal; /* One bit for each page in the database file */
  38908. sqlite3_file *fd; /* File descriptor for database */
  38909. sqlite3_file *jfd; /* File descriptor for main journal */
  38910. sqlite3_file *sjfd; /* File descriptor for sub-journal */
  38911. i64 journalOff; /* Current write offset in the journal file */
  38912. i64 journalHdr; /* Byte offset to previous journal header */
  38913. sqlite3_backup *pBackup; /* Pointer to list of ongoing backup processes */
  38914. PagerSavepoint *aSavepoint; /* Array of active savepoints */
  38915. int nSavepoint; /* Number of elements in aSavepoint[] */
  38916. char dbFileVers[16]; /* Changes whenever database file changes */
  38917. u8 bUseFetch; /* True to use xFetch() */
  38918. int nMmapOut; /* Number of mmap pages currently outstanding */
  38919. sqlite3_int64 szMmap; /* Desired maximum mmap size */
  38920. PgHdr *pMmapFreelist; /* List of free mmap page headers (pDirty) */
  38921. /*
  38922. ** End of the routinely-changing class members
  38923. ***************************************************************************/
  38924. u16 nExtra; /* Add this many bytes to each in-memory page */
  38925. i16 nReserve; /* Number of unused bytes at end of each page */
  38926. u32 vfsFlags; /* Flags for sqlite3_vfs.xOpen() */
  38927. u32 sectorSize; /* Assumed sector size during rollback */
  38928. int pageSize; /* Number of bytes in a page */
  38929. Pgno mxPgno; /* Maximum allowed size of the database */
  38930. i64 journalSizeLimit; /* Size limit for persistent journal files */
  38931. char *zFilename; /* Name of the database file */
  38932. char *zJournal; /* Name of the journal file */
  38933. int (*xBusyHandler)(void*); /* Function to call when busy */
  38934. void *pBusyHandlerArg; /* Context argument for xBusyHandler */
  38935. int aStat[3]; /* Total cache hits, misses and writes */
  38936. #ifdef SQLITE_TEST
  38937. int nRead; /* Database pages read */
  38938. #endif
  38939. void (*xReiniter)(DbPage*); /* Call this routine when reloading pages */
  38940. #ifdef SQLITE_HAS_CODEC
  38941. void *(*xCodec)(void*,void*,Pgno,int); /* Routine for en/decoding data */
  38942. void (*xCodecSizeChng)(void*,int,int); /* Notify of page size changes */
  38943. void (*xCodecFree)(void*); /* Destructor for the codec */
  38944. void *pCodec; /* First argument to xCodec... methods */
  38945. #endif
  38946. char *pTmpSpace; /* Pager.pageSize bytes of space for tmp use */
  38947. PCache *pPCache; /* Pointer to page cache object */
  38948. #ifndef SQLITE_OMIT_WAL
  38949. Wal *pWal; /* Write-ahead log used by "journal_mode=wal" */
  38950. char *zWal; /* File name for write-ahead log */
  38951. #endif
  38952. };
  38953. /*
  38954. ** Indexes for use with Pager.aStat[]. The Pager.aStat[] array contains
  38955. ** the values accessed by passing SQLITE_DBSTATUS_CACHE_HIT, CACHE_MISS
  38956. ** or CACHE_WRITE to sqlite3_db_status().
  38957. */
  38958. #define PAGER_STAT_HIT 0
  38959. #define PAGER_STAT_MISS 1
  38960. #define PAGER_STAT_WRITE 2
  38961. /*
  38962. ** The following global variables hold counters used for
  38963. ** testing purposes only. These variables do not exist in
  38964. ** a non-testing build. These variables are not thread-safe.
  38965. */
  38966. #ifdef SQLITE_TEST
  38967. SQLITE_API int sqlite3_pager_readdb_count = 0; /* Number of full pages read from DB */
  38968. SQLITE_API int sqlite3_pager_writedb_count = 0; /* Number of full pages written to DB */
  38969. SQLITE_API int sqlite3_pager_writej_count = 0; /* Number of pages written to journal */
  38970. # define PAGER_INCR(v) v++
  38971. #else
  38972. # define PAGER_INCR(v)
  38973. #endif
  38974. /*
  38975. ** Journal files begin with the following magic string. The data
  38976. ** was obtained from /dev/random. It is used only as a sanity check.
  38977. **
  38978. ** Since version 2.8.0, the journal format contains additional sanity
  38979. ** checking information. If the power fails while the journal is being
  38980. ** written, semi-random garbage data might appear in the journal
  38981. ** file after power is restored. If an attempt is then made
  38982. ** to roll the journal back, the database could be corrupted. The additional
  38983. ** sanity checking data is an attempt to discover the garbage in the
  38984. ** journal and ignore it.
  38985. **
  38986. ** The sanity checking information for the new journal format consists
  38987. ** of a 32-bit checksum on each page of data. The checksum covers both
  38988. ** the page number and the pPager->pageSize bytes of data for the page.
  38989. ** This cksum is initialized to a 32-bit random value that appears in the
  38990. ** journal file right after the header. The random initializer is important,
  38991. ** because garbage data that appears at the end of a journal is likely
  38992. ** data that was once in other files that have now been deleted. If the
  38993. ** garbage data came from an obsolete journal file, the checksums might
  38994. ** be correct. But by initializing the checksum to random value which
  38995. ** is different for every journal, we minimize that risk.
  38996. */
  38997. static const unsigned char aJournalMagic[] = {
  38998. 0xd9, 0xd5, 0x05, 0xf9, 0x20, 0xa1, 0x63, 0xd7,
  38999. };
  39000. /*
  39001. ** The size of the of each page record in the journal is given by
  39002. ** the following macro.
  39003. */
  39004. #define JOURNAL_PG_SZ(pPager) ((pPager->pageSize) + 8)
  39005. /*
  39006. ** The journal header size for this pager. This is usually the same
  39007. ** size as a single disk sector. See also setSectorSize().
  39008. */
  39009. #define JOURNAL_HDR_SZ(pPager) (pPager->sectorSize)
  39010. /*
  39011. ** The macro MEMDB is true if we are dealing with an in-memory database.
  39012. ** We do this as a macro so that if the SQLITE_OMIT_MEMORYDB macro is set,
  39013. ** the value of MEMDB will be a constant and the compiler will optimize
  39014. ** out code that would never execute.
  39015. */
  39016. #ifdef SQLITE_OMIT_MEMORYDB
  39017. # define MEMDB 0
  39018. #else
  39019. # define MEMDB pPager->memDb
  39020. #endif
  39021. /*
  39022. ** The macro USEFETCH is true if we are allowed to use the xFetch and xUnfetch
  39023. ** interfaces to access the database using memory-mapped I/O.
  39024. */
  39025. #if SQLITE_MAX_MMAP_SIZE>0
  39026. # define USEFETCH(x) ((x)->bUseFetch)
  39027. #else
  39028. # define USEFETCH(x) 0
  39029. #endif
  39030. /*
  39031. ** The maximum legal page number is (2^31 - 1).
  39032. */
  39033. #define PAGER_MAX_PGNO 2147483647
  39034. /*
  39035. ** The argument to this macro is a file descriptor (type sqlite3_file*).
  39036. ** Return 0 if it is not open, or non-zero (but not 1) if it is.
  39037. **
  39038. ** This is so that expressions can be written as:
  39039. **
  39040. ** if( isOpen(pPager->jfd) ){ ...
  39041. **
  39042. ** instead of
  39043. **
  39044. ** if( pPager->jfd->pMethods ){ ...
  39045. */
  39046. #define isOpen(pFd) ((pFd)->pMethods)
  39047. /*
  39048. ** Return true if this pager uses a write-ahead log instead of the usual
  39049. ** rollback journal. Otherwise false.
  39050. */
  39051. #ifndef SQLITE_OMIT_WAL
  39052. static int pagerUseWal(Pager *pPager){
  39053. return (pPager->pWal!=0);
  39054. }
  39055. #else
  39056. # define pagerUseWal(x) 0
  39057. # define pagerRollbackWal(x) 0
  39058. # define pagerWalFrames(v,w,x,y) 0
  39059. # define pagerOpenWalIfPresent(z) SQLITE_OK
  39060. # define pagerBeginReadTransaction(z) SQLITE_OK
  39061. #endif
  39062. #ifndef NDEBUG
  39063. /*
  39064. ** Usage:
  39065. **
  39066. ** assert( assert_pager_state(pPager) );
  39067. **
  39068. ** This function runs many asserts to try to find inconsistencies in
  39069. ** the internal state of the Pager object.
  39070. */
  39071. static int assert_pager_state(Pager *p){
  39072. Pager *pPager = p;
  39073. /* State must be valid. */
  39074. assert( p->eState==PAGER_OPEN
  39075. || p->eState==PAGER_READER
  39076. || p->eState==PAGER_WRITER_LOCKED
  39077. || p->eState==PAGER_WRITER_CACHEMOD
  39078. || p->eState==PAGER_WRITER_DBMOD
  39079. || p->eState==PAGER_WRITER_FINISHED
  39080. || p->eState==PAGER_ERROR
  39081. );
  39082. /* Regardless of the current state, a temp-file connection always behaves
  39083. ** as if it has an exclusive lock on the database file. It never updates
  39084. ** the change-counter field, so the changeCountDone flag is always set.
  39085. */
  39086. assert( p->tempFile==0 || p->eLock==EXCLUSIVE_LOCK );
  39087. assert( p->tempFile==0 || pPager->changeCountDone );
  39088. /* If the useJournal flag is clear, the journal-mode must be "OFF".
  39089. ** And if the journal-mode is "OFF", the journal file must not be open.
  39090. */
  39091. assert( p->journalMode==PAGER_JOURNALMODE_OFF || p->useJournal );
  39092. assert( p->journalMode!=PAGER_JOURNALMODE_OFF || !isOpen(p->jfd) );
  39093. /* Check that MEMDB implies noSync. And an in-memory journal. Since
  39094. ** this means an in-memory pager performs no IO at all, it cannot encounter
  39095. ** either SQLITE_IOERR or SQLITE_FULL during rollback or while finalizing
  39096. ** a journal file. (although the in-memory journal implementation may
  39097. ** return SQLITE_IOERR_NOMEM while the journal file is being written). It
  39098. ** is therefore not possible for an in-memory pager to enter the ERROR
  39099. ** state.
  39100. */
  39101. if( MEMDB ){
  39102. assert( p->noSync );
  39103. assert( p->journalMode==PAGER_JOURNALMODE_OFF
  39104. || p->journalMode==PAGER_JOURNALMODE_MEMORY
  39105. );
  39106. assert( p->eState!=PAGER_ERROR && p->eState!=PAGER_OPEN );
  39107. assert( pagerUseWal(p)==0 );
  39108. }
  39109. /* If changeCountDone is set, a RESERVED lock or greater must be held
  39110. ** on the file.
  39111. */
  39112. assert( pPager->changeCountDone==0 || pPager->eLock>=RESERVED_LOCK );
  39113. assert( p->eLock!=PENDING_LOCK );
  39114. switch( p->eState ){
  39115. case PAGER_OPEN:
  39116. assert( !MEMDB );
  39117. assert( pPager->errCode==SQLITE_OK );
  39118. assert( sqlite3PcacheRefCount(pPager->pPCache)==0 || pPager->tempFile );
  39119. break;
  39120. case PAGER_READER:
  39121. assert( pPager->errCode==SQLITE_OK );
  39122. assert( p->eLock!=UNKNOWN_LOCK );
  39123. assert( p->eLock>=SHARED_LOCK );
  39124. break;
  39125. case PAGER_WRITER_LOCKED:
  39126. assert( p->eLock!=UNKNOWN_LOCK );
  39127. assert( pPager->errCode==SQLITE_OK );
  39128. if( !pagerUseWal(pPager) ){
  39129. assert( p->eLock>=RESERVED_LOCK );
  39130. }
  39131. assert( pPager->dbSize==pPager->dbOrigSize );
  39132. assert( pPager->dbOrigSize==pPager->dbFileSize );
  39133. assert( pPager->dbOrigSize==pPager->dbHintSize );
  39134. assert( pPager->setMaster==0 );
  39135. break;
  39136. case PAGER_WRITER_CACHEMOD:
  39137. assert( p->eLock!=UNKNOWN_LOCK );
  39138. assert( pPager->errCode==SQLITE_OK );
  39139. if( !pagerUseWal(pPager) ){
  39140. /* It is possible that if journal_mode=wal here that neither the
  39141. ** journal file nor the WAL file are open. This happens during
  39142. ** a rollback transaction that switches from journal_mode=off
  39143. ** to journal_mode=wal.
  39144. */
  39145. assert( p->eLock>=RESERVED_LOCK );
  39146. assert( isOpen(p->jfd)
  39147. || p->journalMode==PAGER_JOURNALMODE_OFF
  39148. || p->journalMode==PAGER_JOURNALMODE_WAL
  39149. );
  39150. }
  39151. assert( pPager->dbOrigSize==pPager->dbFileSize );
  39152. assert( pPager->dbOrigSize==pPager->dbHintSize );
  39153. break;
  39154. case PAGER_WRITER_DBMOD:
  39155. assert( p->eLock==EXCLUSIVE_LOCK );
  39156. assert( pPager->errCode==SQLITE_OK );
  39157. assert( !pagerUseWal(pPager) );
  39158. assert( p->eLock>=EXCLUSIVE_LOCK );
  39159. assert( isOpen(p->jfd)
  39160. || p->journalMode==PAGER_JOURNALMODE_OFF
  39161. || p->journalMode==PAGER_JOURNALMODE_WAL
  39162. );
  39163. assert( pPager->dbOrigSize<=pPager->dbHintSize );
  39164. break;
  39165. case PAGER_WRITER_FINISHED:
  39166. assert( p->eLock==EXCLUSIVE_LOCK );
  39167. assert( pPager->errCode==SQLITE_OK );
  39168. assert( !pagerUseWal(pPager) );
  39169. assert( isOpen(p->jfd)
  39170. || p->journalMode==PAGER_JOURNALMODE_OFF
  39171. || p->journalMode==PAGER_JOURNALMODE_WAL
  39172. );
  39173. break;
  39174. case PAGER_ERROR:
  39175. /* There must be at least one outstanding reference to the pager if
  39176. ** in ERROR state. Otherwise the pager should have already dropped
  39177. ** back to OPEN state.
  39178. */
  39179. assert( pPager->errCode!=SQLITE_OK );
  39180. assert( sqlite3PcacheRefCount(pPager->pPCache)>0 );
  39181. break;
  39182. }
  39183. return 1;
  39184. }
  39185. #endif /* ifndef NDEBUG */
  39186. #ifdef SQLITE_DEBUG
  39187. /*
  39188. ** Return a pointer to a human readable string in a static buffer
  39189. ** containing the state of the Pager object passed as an argument. This
  39190. ** is intended to be used within debuggers. For example, as an alternative
  39191. ** to "print *pPager" in gdb:
  39192. **
  39193. ** (gdb) printf "%s", print_pager_state(pPager)
  39194. */
  39195. static char *print_pager_state(Pager *p){
  39196. static char zRet[1024];
  39197. sqlite3_snprintf(1024, zRet,
  39198. "Filename: %s\n"
  39199. "State: %s errCode=%d\n"
  39200. "Lock: %s\n"
  39201. "Locking mode: locking_mode=%s\n"
  39202. "Journal mode: journal_mode=%s\n"
  39203. "Backing store: tempFile=%d memDb=%d useJournal=%d\n"
  39204. "Journal: journalOff=%lld journalHdr=%lld\n"
  39205. "Size: dbsize=%d dbOrigSize=%d dbFileSize=%d\n"
  39206. , p->zFilename
  39207. , p->eState==PAGER_OPEN ? "OPEN" :
  39208. p->eState==PAGER_READER ? "READER" :
  39209. p->eState==PAGER_WRITER_LOCKED ? "WRITER_LOCKED" :
  39210. p->eState==PAGER_WRITER_CACHEMOD ? "WRITER_CACHEMOD" :
  39211. p->eState==PAGER_WRITER_DBMOD ? "WRITER_DBMOD" :
  39212. p->eState==PAGER_WRITER_FINISHED ? "WRITER_FINISHED" :
  39213. p->eState==PAGER_ERROR ? "ERROR" : "?error?"
  39214. , (int)p->errCode
  39215. , p->eLock==NO_LOCK ? "NO_LOCK" :
  39216. p->eLock==RESERVED_LOCK ? "RESERVED" :
  39217. p->eLock==EXCLUSIVE_LOCK ? "EXCLUSIVE" :
  39218. p->eLock==SHARED_LOCK ? "SHARED" :
  39219. p->eLock==UNKNOWN_LOCK ? "UNKNOWN" : "?error?"
  39220. , p->exclusiveMode ? "exclusive" : "normal"
  39221. , p->journalMode==PAGER_JOURNALMODE_MEMORY ? "memory" :
  39222. p->journalMode==PAGER_JOURNALMODE_OFF ? "off" :
  39223. p->journalMode==PAGER_JOURNALMODE_DELETE ? "delete" :
  39224. p->journalMode==PAGER_JOURNALMODE_PERSIST ? "persist" :
  39225. p->journalMode==PAGER_JOURNALMODE_TRUNCATE ? "truncate" :
  39226. p->journalMode==PAGER_JOURNALMODE_WAL ? "wal" : "?error?"
  39227. , (int)p->tempFile, (int)p->memDb, (int)p->useJournal
  39228. , p->journalOff, p->journalHdr
  39229. , (int)p->dbSize, (int)p->dbOrigSize, (int)p->dbFileSize
  39230. );
  39231. return zRet;
  39232. }
  39233. #endif
  39234. /*
  39235. ** Return true if it is necessary to write page *pPg into the sub-journal.
  39236. ** A page needs to be written into the sub-journal if there exists one
  39237. ** or more open savepoints for which:
  39238. **
  39239. ** * The page-number is less than or equal to PagerSavepoint.nOrig, and
  39240. ** * The bit corresponding to the page-number is not set in
  39241. ** PagerSavepoint.pInSavepoint.
  39242. */
  39243. static int subjRequiresPage(PgHdr *pPg){
  39244. Pager *pPager = pPg->pPager;
  39245. PagerSavepoint *p;
  39246. Pgno pgno = pPg->pgno;
  39247. int i;
  39248. for(i=0; i<pPager->nSavepoint; i++){
  39249. p = &pPager->aSavepoint[i];
  39250. if( p->nOrig>=pgno && 0==sqlite3BitvecTest(p->pInSavepoint, pgno) ){
  39251. return 1;
  39252. }
  39253. }
  39254. return 0;
  39255. }
  39256. /*
  39257. ** Return true if the page is already in the journal file.
  39258. */
  39259. static int pageInJournal(Pager *pPager, PgHdr *pPg){
  39260. return sqlite3BitvecTest(pPager->pInJournal, pPg->pgno);
  39261. }
  39262. /*
  39263. ** Read a 32-bit integer from the given file descriptor. Store the integer
  39264. ** that is read in *pRes. Return SQLITE_OK if everything worked, or an
  39265. ** error code is something goes wrong.
  39266. **
  39267. ** All values are stored on disk as big-endian.
  39268. */
  39269. static int read32bits(sqlite3_file *fd, i64 offset, u32 *pRes){
  39270. unsigned char ac[4];
  39271. int rc = sqlite3OsRead(fd, ac, sizeof(ac), offset);
  39272. if( rc==SQLITE_OK ){
  39273. *pRes = sqlite3Get4byte(ac);
  39274. }
  39275. return rc;
  39276. }
  39277. /*
  39278. ** Write a 32-bit integer into a string buffer in big-endian byte order.
  39279. */
  39280. #define put32bits(A,B) sqlite3Put4byte((u8*)A,B)
  39281. /*
  39282. ** Write a 32-bit integer into the given file descriptor. Return SQLITE_OK
  39283. ** on success or an error code is something goes wrong.
  39284. */
  39285. static int write32bits(sqlite3_file *fd, i64 offset, u32 val){
  39286. char ac[4];
  39287. put32bits(ac, val);
  39288. return sqlite3OsWrite(fd, ac, 4, offset);
  39289. }
  39290. /*
  39291. ** Unlock the database file to level eLock, which must be either NO_LOCK
  39292. ** or SHARED_LOCK. Regardless of whether or not the call to xUnlock()
  39293. ** succeeds, set the Pager.eLock variable to match the (attempted) new lock.
  39294. **
  39295. ** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is
  39296. ** called, do not modify it. See the comment above the #define of
  39297. ** UNKNOWN_LOCK for an explanation of this.
  39298. */
  39299. static int pagerUnlockDb(Pager *pPager, int eLock){
  39300. int rc = SQLITE_OK;
  39301. assert( !pPager->exclusiveMode || pPager->eLock==eLock );
  39302. assert( eLock==NO_LOCK || eLock==SHARED_LOCK );
  39303. assert( eLock!=NO_LOCK || pagerUseWal(pPager)==0 );
  39304. if( isOpen(pPager->fd) ){
  39305. assert( pPager->eLock>=eLock );
  39306. rc = pPager->noLock ? SQLITE_OK : sqlite3OsUnlock(pPager->fd, eLock);
  39307. if( pPager->eLock!=UNKNOWN_LOCK ){
  39308. pPager->eLock = (u8)eLock;
  39309. }
  39310. IOTRACE(("UNLOCK %p %d\n", pPager, eLock))
  39311. }
  39312. return rc;
  39313. }
  39314. /*
  39315. ** Lock the database file to level eLock, which must be either SHARED_LOCK,
  39316. ** RESERVED_LOCK or EXCLUSIVE_LOCK. If the caller is successful, set the
  39317. ** Pager.eLock variable to the new locking state.
  39318. **
  39319. ** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is
  39320. ** called, do not modify it unless the new locking state is EXCLUSIVE_LOCK.
  39321. ** See the comment above the #define of UNKNOWN_LOCK for an explanation
  39322. ** of this.
  39323. */
  39324. static int pagerLockDb(Pager *pPager, int eLock){
  39325. int rc = SQLITE_OK;
  39326. assert( eLock==SHARED_LOCK || eLock==RESERVED_LOCK || eLock==EXCLUSIVE_LOCK );
  39327. if( pPager->eLock<eLock || pPager->eLock==UNKNOWN_LOCK ){
  39328. rc = pPager->noLock ? SQLITE_OK : sqlite3OsLock(pPager->fd, eLock);
  39329. if( rc==SQLITE_OK && (pPager->eLock!=UNKNOWN_LOCK||eLock==EXCLUSIVE_LOCK) ){
  39330. pPager->eLock = (u8)eLock;
  39331. IOTRACE(("LOCK %p %d\n", pPager, eLock))
  39332. }
  39333. }
  39334. return rc;
  39335. }
  39336. /*
  39337. ** This function determines whether or not the atomic-write optimization
  39338. ** can be used with this pager. The optimization can be used if:
  39339. **
  39340. ** (a) the value returned by OsDeviceCharacteristics() indicates that
  39341. ** a database page may be written atomically, and
  39342. ** (b) the value returned by OsSectorSize() is less than or equal
  39343. ** to the page size.
  39344. **
  39345. ** The optimization is also always enabled for temporary files. It is
  39346. ** an error to call this function if pPager is opened on an in-memory
  39347. ** database.
  39348. **
  39349. ** If the optimization cannot be used, 0 is returned. If it can be used,
  39350. ** then the value returned is the size of the journal file when it
  39351. ** contains rollback data for exactly one page.
  39352. */
  39353. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  39354. static int jrnlBufferSize(Pager *pPager){
  39355. assert( !MEMDB );
  39356. if( !pPager->tempFile ){
  39357. int dc; /* Device characteristics */
  39358. int nSector; /* Sector size */
  39359. int szPage; /* Page size */
  39360. assert( isOpen(pPager->fd) );
  39361. dc = sqlite3OsDeviceCharacteristics(pPager->fd);
  39362. nSector = pPager->sectorSize;
  39363. szPage = pPager->pageSize;
  39364. assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
  39365. assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
  39366. if( 0==(dc&(SQLITE_IOCAP_ATOMIC|(szPage>>8)) || nSector>szPage) ){
  39367. return 0;
  39368. }
  39369. }
  39370. return JOURNAL_HDR_SZ(pPager) + JOURNAL_PG_SZ(pPager);
  39371. }
  39372. #endif
  39373. /*
  39374. ** If SQLITE_CHECK_PAGES is defined then we do some sanity checking
  39375. ** on the cache using a hash function. This is used for testing
  39376. ** and debugging only.
  39377. */
  39378. #ifdef SQLITE_CHECK_PAGES
  39379. /*
  39380. ** Return a 32-bit hash of the page data for pPage.
  39381. */
  39382. static u32 pager_datahash(int nByte, unsigned char *pData){
  39383. u32 hash = 0;
  39384. int i;
  39385. for(i=0; i<nByte; i++){
  39386. hash = (hash*1039) + pData[i];
  39387. }
  39388. return hash;
  39389. }
  39390. static u32 pager_pagehash(PgHdr *pPage){
  39391. return pager_datahash(pPage->pPager->pageSize, (unsigned char *)pPage->pData);
  39392. }
  39393. static void pager_set_pagehash(PgHdr *pPage){
  39394. pPage->pageHash = pager_pagehash(pPage);
  39395. }
  39396. /*
  39397. ** The CHECK_PAGE macro takes a PgHdr* as an argument. If SQLITE_CHECK_PAGES
  39398. ** is defined, and NDEBUG is not defined, an assert() statement checks
  39399. ** that the page is either dirty or still matches the calculated page-hash.
  39400. */
  39401. #define CHECK_PAGE(x) checkPage(x)
  39402. static void checkPage(PgHdr *pPg){
  39403. Pager *pPager = pPg->pPager;
  39404. assert( pPager->eState!=PAGER_ERROR );
  39405. assert( (pPg->flags&PGHDR_DIRTY) || pPg->pageHash==pager_pagehash(pPg) );
  39406. }
  39407. #else
  39408. #define pager_datahash(X,Y) 0
  39409. #define pager_pagehash(X) 0
  39410. #define pager_set_pagehash(X)
  39411. #define CHECK_PAGE(x)
  39412. #endif /* SQLITE_CHECK_PAGES */
  39413. /*
  39414. ** When this is called the journal file for pager pPager must be open.
  39415. ** This function attempts to read a master journal file name from the
  39416. ** end of the file and, if successful, copies it into memory supplied
  39417. ** by the caller. See comments above writeMasterJournal() for the format
  39418. ** used to store a master journal file name at the end of a journal file.
  39419. **
  39420. ** zMaster must point to a buffer of at least nMaster bytes allocated by
  39421. ** the caller. This should be sqlite3_vfs.mxPathname+1 (to ensure there is
  39422. ** enough space to write the master journal name). If the master journal
  39423. ** name in the journal is longer than nMaster bytes (including a
  39424. ** nul-terminator), then this is handled as if no master journal name
  39425. ** were present in the journal.
  39426. **
  39427. ** If a master journal file name is present at the end of the journal
  39428. ** file, then it is copied into the buffer pointed to by zMaster. A
  39429. ** nul-terminator byte is appended to the buffer following the master
  39430. ** journal file name.
  39431. **
  39432. ** If it is determined that no master journal file name is present
  39433. ** zMaster[0] is set to 0 and SQLITE_OK returned.
  39434. **
  39435. ** If an error occurs while reading from the journal file, an SQLite
  39436. ** error code is returned.
  39437. */
  39438. static int readMasterJournal(sqlite3_file *pJrnl, char *zMaster, u32 nMaster){
  39439. int rc; /* Return code */
  39440. u32 len; /* Length in bytes of master journal name */
  39441. i64 szJ; /* Total size in bytes of journal file pJrnl */
  39442. u32 cksum; /* MJ checksum value read from journal */
  39443. u32 u; /* Unsigned loop counter */
  39444. unsigned char aMagic[8]; /* A buffer to hold the magic header */
  39445. zMaster[0] = '\0';
  39446. if( SQLITE_OK!=(rc = sqlite3OsFileSize(pJrnl, &szJ))
  39447. || szJ<16
  39448. || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-16, &len))
  39449. || len>=nMaster
  39450. || len==0
  39451. || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-12, &cksum))
  39452. || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, aMagic, 8, szJ-8))
  39453. || memcmp(aMagic, aJournalMagic, 8)
  39454. || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, zMaster, len, szJ-16-len))
  39455. ){
  39456. return rc;
  39457. }
  39458. /* See if the checksum matches the master journal name */
  39459. for(u=0; u<len; u++){
  39460. cksum -= zMaster[u];
  39461. }
  39462. if( cksum ){
  39463. /* If the checksum doesn't add up, then one or more of the disk sectors
  39464. ** containing the master journal filename is corrupted. This means
  39465. ** definitely roll back, so just return SQLITE_OK and report a (nul)
  39466. ** master-journal filename.
  39467. */
  39468. len = 0;
  39469. }
  39470. zMaster[len] = '\0';
  39471. return SQLITE_OK;
  39472. }
  39473. /*
  39474. ** Return the offset of the sector boundary at or immediately
  39475. ** following the value in pPager->journalOff, assuming a sector
  39476. ** size of pPager->sectorSize bytes.
  39477. **
  39478. ** i.e for a sector size of 512:
  39479. **
  39480. ** Pager.journalOff Return value
  39481. ** ---------------------------------------
  39482. ** 0 0
  39483. ** 512 512
  39484. ** 100 512
  39485. ** 2000 2048
  39486. **
  39487. */
  39488. static i64 journalHdrOffset(Pager *pPager){
  39489. i64 offset = 0;
  39490. i64 c = pPager->journalOff;
  39491. if( c ){
  39492. offset = ((c-1)/JOURNAL_HDR_SZ(pPager) + 1) * JOURNAL_HDR_SZ(pPager);
  39493. }
  39494. assert( offset%JOURNAL_HDR_SZ(pPager)==0 );
  39495. assert( offset>=c );
  39496. assert( (offset-c)<JOURNAL_HDR_SZ(pPager) );
  39497. return offset;
  39498. }
  39499. /*
  39500. ** The journal file must be open when this function is called.
  39501. **
  39502. ** This function is a no-op if the journal file has not been written to
  39503. ** within the current transaction (i.e. if Pager.journalOff==0).
  39504. **
  39505. ** If doTruncate is non-zero or the Pager.journalSizeLimit variable is
  39506. ** set to 0, then truncate the journal file to zero bytes in size. Otherwise,
  39507. ** zero the 28-byte header at the start of the journal file. In either case,
  39508. ** if the pager is not in no-sync mode, sync the journal file immediately
  39509. ** after writing or truncating it.
  39510. **
  39511. ** If Pager.journalSizeLimit is set to a positive, non-zero value, and
  39512. ** following the truncation or zeroing described above the size of the
  39513. ** journal file in bytes is larger than this value, then truncate the
  39514. ** journal file to Pager.journalSizeLimit bytes. The journal file does
  39515. ** not need to be synced following this operation.
  39516. **
  39517. ** If an IO error occurs, abandon processing and return the IO error code.
  39518. ** Otherwise, return SQLITE_OK.
  39519. */
  39520. static int zeroJournalHdr(Pager *pPager, int doTruncate){
  39521. int rc = SQLITE_OK; /* Return code */
  39522. assert( isOpen(pPager->jfd) );
  39523. if( pPager->journalOff ){
  39524. const i64 iLimit = pPager->journalSizeLimit; /* Local cache of jsl */
  39525. IOTRACE(("JZEROHDR %p\n", pPager))
  39526. if( doTruncate || iLimit==0 ){
  39527. rc = sqlite3OsTruncate(pPager->jfd, 0);
  39528. }else{
  39529. static const char zeroHdr[28] = {0};
  39530. rc = sqlite3OsWrite(pPager->jfd, zeroHdr, sizeof(zeroHdr), 0);
  39531. }
  39532. if( rc==SQLITE_OK && !pPager->noSync ){
  39533. rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_DATAONLY|pPager->syncFlags);
  39534. }
  39535. /* At this point the transaction is committed but the write lock
  39536. ** is still held on the file. If there is a size limit configured for
  39537. ** the persistent journal and the journal file currently consumes more
  39538. ** space than that limit allows for, truncate it now. There is no need
  39539. ** to sync the file following this operation.
  39540. */
  39541. if( rc==SQLITE_OK && iLimit>0 ){
  39542. i64 sz;
  39543. rc = sqlite3OsFileSize(pPager->jfd, &sz);
  39544. if( rc==SQLITE_OK && sz>iLimit ){
  39545. rc = sqlite3OsTruncate(pPager->jfd, iLimit);
  39546. }
  39547. }
  39548. }
  39549. return rc;
  39550. }
  39551. /*
  39552. ** The journal file must be open when this routine is called. A journal
  39553. ** header (JOURNAL_HDR_SZ bytes) is written into the journal file at the
  39554. ** current location.
  39555. **
  39556. ** The format for the journal header is as follows:
  39557. ** - 8 bytes: Magic identifying journal format.
  39558. ** - 4 bytes: Number of records in journal, or -1 no-sync mode is on.
  39559. ** - 4 bytes: Random number used for page hash.
  39560. ** - 4 bytes: Initial database page count.
  39561. ** - 4 bytes: Sector size used by the process that wrote this journal.
  39562. ** - 4 bytes: Database page size.
  39563. **
  39564. ** Followed by (JOURNAL_HDR_SZ - 28) bytes of unused space.
  39565. */
  39566. static int writeJournalHdr(Pager *pPager){
  39567. int rc = SQLITE_OK; /* Return code */
  39568. char *zHeader = pPager->pTmpSpace; /* Temporary space used to build header */
  39569. u32 nHeader = (u32)pPager->pageSize;/* Size of buffer pointed to by zHeader */
  39570. u32 nWrite; /* Bytes of header sector written */
  39571. int ii; /* Loop counter */
  39572. assert( isOpen(pPager->jfd) ); /* Journal file must be open. */
  39573. if( nHeader>JOURNAL_HDR_SZ(pPager) ){
  39574. nHeader = JOURNAL_HDR_SZ(pPager);
  39575. }
  39576. /* If there are active savepoints and any of them were created
  39577. ** since the most recent journal header was written, update the
  39578. ** PagerSavepoint.iHdrOffset fields now.
  39579. */
  39580. for(ii=0; ii<pPager->nSavepoint; ii++){
  39581. if( pPager->aSavepoint[ii].iHdrOffset==0 ){
  39582. pPager->aSavepoint[ii].iHdrOffset = pPager->journalOff;
  39583. }
  39584. }
  39585. pPager->journalHdr = pPager->journalOff = journalHdrOffset(pPager);
  39586. /*
  39587. ** Write the nRec Field - the number of page records that follow this
  39588. ** journal header. Normally, zero is written to this value at this time.
  39589. ** After the records are added to the journal (and the journal synced,
  39590. ** if in full-sync mode), the zero is overwritten with the true number
  39591. ** of records (see syncJournal()).
  39592. **
  39593. ** A faster alternative is to write 0xFFFFFFFF to the nRec field. When
  39594. ** reading the journal this value tells SQLite to assume that the
  39595. ** rest of the journal file contains valid page records. This assumption
  39596. ** is dangerous, as if a failure occurred whilst writing to the journal
  39597. ** file it may contain some garbage data. There are two scenarios
  39598. ** where this risk can be ignored:
  39599. **
  39600. ** * When the pager is in no-sync mode. Corruption can follow a
  39601. ** power failure in this case anyway.
  39602. **
  39603. ** * When the SQLITE_IOCAP_SAFE_APPEND flag is set. This guarantees
  39604. ** that garbage data is never appended to the journal file.
  39605. */
  39606. assert( isOpen(pPager->fd) || pPager->noSync );
  39607. if( pPager->noSync || (pPager->journalMode==PAGER_JOURNALMODE_MEMORY)
  39608. || (sqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_SAFE_APPEND)
  39609. ){
  39610. memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
  39611. put32bits(&zHeader[sizeof(aJournalMagic)], 0xffffffff);
  39612. }else{
  39613. memset(zHeader, 0, sizeof(aJournalMagic)+4);
  39614. }
  39615. /* The random check-hash initializer */
  39616. sqlite3_randomness(sizeof(pPager->cksumInit), &pPager->cksumInit);
  39617. put32bits(&zHeader[sizeof(aJournalMagic)+4], pPager->cksumInit);
  39618. /* The initial database size */
  39619. put32bits(&zHeader[sizeof(aJournalMagic)+8], pPager->dbOrigSize);
  39620. /* The assumed sector size for this process */
  39621. put32bits(&zHeader[sizeof(aJournalMagic)+12], pPager->sectorSize);
  39622. /* The page size */
  39623. put32bits(&zHeader[sizeof(aJournalMagic)+16], pPager->pageSize);
  39624. /* Initializing the tail of the buffer is not necessary. Everything
  39625. ** works find if the following memset() is omitted. But initializing
  39626. ** the memory prevents valgrind from complaining, so we are willing to
  39627. ** take the performance hit.
  39628. */
  39629. memset(&zHeader[sizeof(aJournalMagic)+20], 0,
  39630. nHeader-(sizeof(aJournalMagic)+20));
  39631. /* In theory, it is only necessary to write the 28 bytes that the
  39632. ** journal header consumes to the journal file here. Then increment the
  39633. ** Pager.journalOff variable by JOURNAL_HDR_SZ so that the next
  39634. ** record is written to the following sector (leaving a gap in the file
  39635. ** that will be implicitly filled in by the OS).
  39636. **
  39637. ** However it has been discovered that on some systems this pattern can
  39638. ** be significantly slower than contiguously writing data to the file,
  39639. ** even if that means explicitly writing data to the block of
  39640. ** (JOURNAL_HDR_SZ - 28) bytes that will not be used. So that is what
  39641. ** is done.
  39642. **
  39643. ** The loop is required here in case the sector-size is larger than the
  39644. ** database page size. Since the zHeader buffer is only Pager.pageSize
  39645. ** bytes in size, more than one call to sqlite3OsWrite() may be required
  39646. ** to populate the entire journal header sector.
  39647. */
  39648. for(nWrite=0; rc==SQLITE_OK&&nWrite<JOURNAL_HDR_SZ(pPager); nWrite+=nHeader){
  39649. IOTRACE(("JHDR %p %lld %d\n", pPager, pPager->journalHdr, nHeader))
  39650. rc = sqlite3OsWrite(pPager->jfd, zHeader, nHeader, pPager->journalOff);
  39651. assert( pPager->journalHdr <= pPager->journalOff );
  39652. pPager->journalOff += nHeader;
  39653. }
  39654. return rc;
  39655. }
  39656. /*
  39657. ** The journal file must be open when this is called. A journal header file
  39658. ** (JOURNAL_HDR_SZ bytes) is read from the current location in the journal
  39659. ** file. The current location in the journal file is given by
  39660. ** pPager->journalOff. See comments above function writeJournalHdr() for
  39661. ** a description of the journal header format.
  39662. **
  39663. ** If the header is read successfully, *pNRec is set to the number of
  39664. ** page records following this header and *pDbSize is set to the size of the
  39665. ** database before the transaction began, in pages. Also, pPager->cksumInit
  39666. ** is set to the value read from the journal header. SQLITE_OK is returned
  39667. ** in this case.
  39668. **
  39669. ** If the journal header file appears to be corrupted, SQLITE_DONE is
  39670. ** returned and *pNRec and *PDbSize are undefined. If JOURNAL_HDR_SZ bytes
  39671. ** cannot be read from the journal file an error code is returned.
  39672. */
  39673. static int readJournalHdr(
  39674. Pager *pPager, /* Pager object */
  39675. int isHot,
  39676. i64 journalSize, /* Size of the open journal file in bytes */
  39677. u32 *pNRec, /* OUT: Value read from the nRec field */
  39678. u32 *pDbSize /* OUT: Value of original database size field */
  39679. ){
  39680. int rc; /* Return code */
  39681. unsigned char aMagic[8]; /* A buffer to hold the magic header */
  39682. i64 iHdrOff; /* Offset of journal header being read */
  39683. assert( isOpen(pPager->jfd) ); /* Journal file must be open. */
  39684. /* Advance Pager.journalOff to the start of the next sector. If the
  39685. ** journal file is too small for there to be a header stored at this
  39686. ** point, return SQLITE_DONE.
  39687. */
  39688. pPager->journalOff = journalHdrOffset(pPager);
  39689. if( pPager->journalOff+JOURNAL_HDR_SZ(pPager) > journalSize ){
  39690. return SQLITE_DONE;
  39691. }
  39692. iHdrOff = pPager->journalOff;
  39693. /* Read in the first 8 bytes of the journal header. If they do not match
  39694. ** the magic string found at the start of each journal header, return
  39695. ** SQLITE_DONE. If an IO error occurs, return an error code. Otherwise,
  39696. ** proceed.
  39697. */
  39698. if( isHot || iHdrOff!=pPager->journalHdr ){
  39699. rc = sqlite3OsRead(pPager->jfd, aMagic, sizeof(aMagic), iHdrOff);
  39700. if( rc ){
  39701. return rc;
  39702. }
  39703. if( memcmp(aMagic, aJournalMagic, sizeof(aMagic))!=0 ){
  39704. return SQLITE_DONE;
  39705. }
  39706. }
  39707. /* Read the first three 32-bit fields of the journal header: The nRec
  39708. ** field, the checksum-initializer and the database size at the start
  39709. ** of the transaction. Return an error code if anything goes wrong.
  39710. */
  39711. if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+8, pNRec))
  39712. || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+12, &pPager->cksumInit))
  39713. || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+16, pDbSize))
  39714. ){
  39715. return rc;
  39716. }
  39717. if( pPager->journalOff==0 ){
  39718. u32 iPageSize; /* Page-size field of journal header */
  39719. u32 iSectorSize; /* Sector-size field of journal header */
  39720. /* Read the page-size and sector-size journal header fields. */
  39721. if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+20, &iSectorSize))
  39722. || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+24, &iPageSize))
  39723. ){
  39724. return rc;
  39725. }
  39726. /* Versions of SQLite prior to 3.5.8 set the page-size field of the
  39727. ** journal header to zero. In this case, assume that the Pager.pageSize
  39728. ** variable is already set to the correct page size.
  39729. */
  39730. if( iPageSize==0 ){
  39731. iPageSize = pPager->pageSize;
  39732. }
  39733. /* Check that the values read from the page-size and sector-size fields
  39734. ** are within range. To be 'in range', both values need to be a power
  39735. ** of two greater than or equal to 512 or 32, and not greater than their
  39736. ** respective compile time maximum limits.
  39737. */
  39738. if( iPageSize<512 || iSectorSize<32
  39739. || iPageSize>SQLITE_MAX_PAGE_SIZE || iSectorSize>MAX_SECTOR_SIZE
  39740. || ((iPageSize-1)&iPageSize)!=0 || ((iSectorSize-1)&iSectorSize)!=0
  39741. ){
  39742. /* If the either the page-size or sector-size in the journal-header is
  39743. ** invalid, then the process that wrote the journal-header must have
  39744. ** crashed before the header was synced. In this case stop reading
  39745. ** the journal file here.
  39746. */
  39747. return SQLITE_DONE;
  39748. }
  39749. /* Update the page-size to match the value read from the journal.
  39750. ** Use a testcase() macro to make sure that malloc failure within
  39751. ** PagerSetPagesize() is tested.
  39752. */
  39753. rc = sqlite3PagerSetPagesize(pPager, &iPageSize, -1);
  39754. testcase( rc!=SQLITE_OK );
  39755. /* Update the assumed sector-size to match the value used by
  39756. ** the process that created this journal. If this journal was
  39757. ** created by a process other than this one, then this routine
  39758. ** is being called from within pager_playback(). The local value
  39759. ** of Pager.sectorSize is restored at the end of that routine.
  39760. */
  39761. pPager->sectorSize = iSectorSize;
  39762. }
  39763. pPager->journalOff += JOURNAL_HDR_SZ(pPager);
  39764. return rc;
  39765. }
  39766. /*
  39767. ** Write the supplied master journal name into the journal file for pager
  39768. ** pPager at the current location. The master journal name must be the last
  39769. ** thing written to a journal file. If the pager is in full-sync mode, the
  39770. ** journal file descriptor is advanced to the next sector boundary before
  39771. ** anything is written. The format is:
  39772. **
  39773. ** + 4 bytes: PAGER_MJ_PGNO.
  39774. ** + N bytes: Master journal filename in utf-8.
  39775. ** + 4 bytes: N (length of master journal name in bytes, no nul-terminator).
  39776. ** + 4 bytes: Master journal name checksum.
  39777. ** + 8 bytes: aJournalMagic[].
  39778. **
  39779. ** The master journal page checksum is the sum of the bytes in the master
  39780. ** journal name, where each byte is interpreted as a signed 8-bit integer.
  39781. **
  39782. ** If zMaster is a NULL pointer (occurs for a single database transaction),
  39783. ** this call is a no-op.
  39784. */
  39785. static int writeMasterJournal(Pager *pPager, const char *zMaster){
  39786. int rc; /* Return code */
  39787. int nMaster; /* Length of string zMaster */
  39788. i64 iHdrOff; /* Offset of header in journal file */
  39789. i64 jrnlSize; /* Size of journal file on disk */
  39790. u32 cksum = 0; /* Checksum of string zMaster */
  39791. assert( pPager->setMaster==0 );
  39792. assert( !pagerUseWal(pPager) );
  39793. if( !zMaster
  39794. || pPager->journalMode==PAGER_JOURNALMODE_MEMORY
  39795. || !isOpen(pPager->jfd)
  39796. ){
  39797. return SQLITE_OK;
  39798. }
  39799. pPager->setMaster = 1;
  39800. assert( pPager->journalHdr <= pPager->journalOff );
  39801. /* Calculate the length in bytes and the checksum of zMaster */
  39802. for(nMaster=0; zMaster[nMaster]; nMaster++){
  39803. cksum += zMaster[nMaster];
  39804. }
  39805. /* If in full-sync mode, advance to the next disk sector before writing
  39806. ** the master journal name. This is in case the previous page written to
  39807. ** the journal has already been synced.
  39808. */
  39809. if( pPager->fullSync ){
  39810. pPager->journalOff = journalHdrOffset(pPager);
  39811. }
  39812. iHdrOff = pPager->journalOff;
  39813. /* Write the master journal data to the end of the journal file. If
  39814. ** an error occurs, return the error code to the caller.
  39815. */
  39816. if( (0 != (rc = write32bits(pPager->jfd, iHdrOff, PAGER_MJ_PGNO(pPager))))
  39817. || (0 != (rc = sqlite3OsWrite(pPager->jfd, zMaster, nMaster, iHdrOff+4)))
  39818. || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster, nMaster)))
  39819. || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster+4, cksum)))
  39820. || (0 != (rc = sqlite3OsWrite(pPager->jfd, aJournalMagic, 8, iHdrOff+4+nMaster+8)))
  39821. ){
  39822. return rc;
  39823. }
  39824. pPager->journalOff += (nMaster+20);
  39825. /* If the pager is in peristent-journal mode, then the physical
  39826. ** journal-file may extend past the end of the master-journal name
  39827. ** and 8 bytes of magic data just written to the file. This is
  39828. ** dangerous because the code to rollback a hot-journal file
  39829. ** will not be able to find the master-journal name to determine
  39830. ** whether or not the journal is hot.
  39831. **
  39832. ** Easiest thing to do in this scenario is to truncate the journal
  39833. ** file to the required size.
  39834. */
  39835. if( SQLITE_OK==(rc = sqlite3OsFileSize(pPager->jfd, &jrnlSize))
  39836. && jrnlSize>pPager->journalOff
  39837. ){
  39838. rc = sqlite3OsTruncate(pPager->jfd, pPager->journalOff);
  39839. }
  39840. return rc;
  39841. }
  39842. /*
  39843. ** Discard the entire contents of the in-memory page-cache.
  39844. */
  39845. static void pager_reset(Pager *pPager){
  39846. sqlite3BackupRestart(pPager->pBackup);
  39847. sqlite3PcacheClear(pPager->pPCache);
  39848. }
  39849. /*
  39850. ** Free all structures in the Pager.aSavepoint[] array and set both
  39851. ** Pager.aSavepoint and Pager.nSavepoint to zero. Close the sub-journal
  39852. ** if it is open and the pager is not in exclusive mode.
  39853. */
  39854. static void releaseAllSavepoints(Pager *pPager){
  39855. int ii; /* Iterator for looping through Pager.aSavepoint */
  39856. for(ii=0; ii<pPager->nSavepoint; ii++){
  39857. sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
  39858. }
  39859. if( !pPager->exclusiveMode || sqlite3IsMemJournal(pPager->sjfd) ){
  39860. sqlite3OsClose(pPager->sjfd);
  39861. }
  39862. sqlite3_free(pPager->aSavepoint);
  39863. pPager->aSavepoint = 0;
  39864. pPager->nSavepoint = 0;
  39865. pPager->nSubRec = 0;
  39866. }
  39867. /*
  39868. ** Set the bit number pgno in the PagerSavepoint.pInSavepoint
  39869. ** bitvecs of all open savepoints. Return SQLITE_OK if successful
  39870. ** or SQLITE_NOMEM if a malloc failure occurs.
  39871. */
  39872. static int addToSavepointBitvecs(Pager *pPager, Pgno pgno){
  39873. int ii; /* Loop counter */
  39874. int rc = SQLITE_OK; /* Result code */
  39875. for(ii=0; ii<pPager->nSavepoint; ii++){
  39876. PagerSavepoint *p = &pPager->aSavepoint[ii];
  39877. if( pgno<=p->nOrig ){
  39878. rc |= sqlite3BitvecSet(p->pInSavepoint, pgno);
  39879. testcase( rc==SQLITE_NOMEM );
  39880. assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
  39881. }
  39882. }
  39883. return rc;
  39884. }
  39885. /*
  39886. ** This function is a no-op if the pager is in exclusive mode and not
  39887. ** in the ERROR state. Otherwise, it switches the pager to PAGER_OPEN
  39888. ** state.
  39889. **
  39890. ** If the pager is not in exclusive-access mode, the database file is
  39891. ** completely unlocked. If the file is unlocked and the file-system does
  39892. ** not exhibit the UNDELETABLE_WHEN_OPEN property, the journal file is
  39893. ** closed (if it is open).
  39894. **
  39895. ** If the pager is in ERROR state when this function is called, the
  39896. ** contents of the pager cache are discarded before switching back to
  39897. ** the OPEN state. Regardless of whether the pager is in exclusive-mode
  39898. ** or not, any journal file left in the file-system will be treated
  39899. ** as a hot-journal and rolled back the next time a read-transaction
  39900. ** is opened (by this or by any other connection).
  39901. */
  39902. static void pager_unlock(Pager *pPager){
  39903. assert( pPager->eState==PAGER_READER
  39904. || pPager->eState==PAGER_OPEN
  39905. || pPager->eState==PAGER_ERROR
  39906. );
  39907. sqlite3BitvecDestroy(pPager->pInJournal);
  39908. pPager->pInJournal = 0;
  39909. releaseAllSavepoints(pPager);
  39910. if( pagerUseWal(pPager) ){
  39911. assert( !isOpen(pPager->jfd) );
  39912. sqlite3WalEndReadTransaction(pPager->pWal);
  39913. pPager->eState = PAGER_OPEN;
  39914. }else if( !pPager->exclusiveMode ){
  39915. int rc; /* Error code returned by pagerUnlockDb() */
  39916. int iDc = isOpen(pPager->fd)?sqlite3OsDeviceCharacteristics(pPager->fd):0;
  39917. /* If the operating system support deletion of open files, then
  39918. ** close the journal file when dropping the database lock. Otherwise
  39919. ** another connection with journal_mode=delete might delete the file
  39920. ** out from under us.
  39921. */
  39922. assert( (PAGER_JOURNALMODE_MEMORY & 5)!=1 );
  39923. assert( (PAGER_JOURNALMODE_OFF & 5)!=1 );
  39924. assert( (PAGER_JOURNALMODE_WAL & 5)!=1 );
  39925. assert( (PAGER_JOURNALMODE_DELETE & 5)!=1 );
  39926. assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
  39927. assert( (PAGER_JOURNALMODE_PERSIST & 5)==1 );
  39928. if( 0==(iDc & SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN)
  39929. || 1!=(pPager->journalMode & 5)
  39930. ){
  39931. sqlite3OsClose(pPager->jfd);
  39932. }
  39933. /* If the pager is in the ERROR state and the call to unlock the database
  39934. ** file fails, set the current lock to UNKNOWN_LOCK. See the comment
  39935. ** above the #define for UNKNOWN_LOCK for an explanation of why this
  39936. ** is necessary.
  39937. */
  39938. rc = pagerUnlockDb(pPager, NO_LOCK);
  39939. if( rc!=SQLITE_OK && pPager->eState==PAGER_ERROR ){
  39940. pPager->eLock = UNKNOWN_LOCK;
  39941. }
  39942. /* The pager state may be changed from PAGER_ERROR to PAGER_OPEN here
  39943. ** without clearing the error code. This is intentional - the error
  39944. ** code is cleared and the cache reset in the block below.
  39945. */
  39946. assert( pPager->errCode || pPager->eState!=PAGER_ERROR );
  39947. pPager->changeCountDone = 0;
  39948. pPager->eState = PAGER_OPEN;
  39949. }
  39950. /* If Pager.errCode is set, the contents of the pager cache cannot be
  39951. ** trusted. Now that there are no outstanding references to the pager,
  39952. ** it can safely move back to PAGER_OPEN state. This happens in both
  39953. ** normal and exclusive-locking mode.
  39954. */
  39955. if( pPager->errCode ){
  39956. assert( !MEMDB );
  39957. pager_reset(pPager);
  39958. pPager->changeCountDone = pPager->tempFile;
  39959. pPager->eState = PAGER_OPEN;
  39960. pPager->errCode = SQLITE_OK;
  39961. if( USEFETCH(pPager) ) sqlite3OsUnfetch(pPager->fd, 0, 0);
  39962. }
  39963. pPager->journalOff = 0;
  39964. pPager->journalHdr = 0;
  39965. pPager->setMaster = 0;
  39966. }
  39967. /*
  39968. ** This function is called whenever an IOERR or FULL error that requires
  39969. ** the pager to transition into the ERROR state may ahve occurred.
  39970. ** The first argument is a pointer to the pager structure, the second
  39971. ** the error-code about to be returned by a pager API function. The
  39972. ** value returned is a copy of the second argument to this function.
  39973. **
  39974. ** If the second argument is SQLITE_FULL, SQLITE_IOERR or one of the
  39975. ** IOERR sub-codes, the pager enters the ERROR state and the error code
  39976. ** is stored in Pager.errCode. While the pager remains in the ERROR state,
  39977. ** all major API calls on the Pager will immediately return Pager.errCode.
  39978. **
  39979. ** The ERROR state indicates that the contents of the pager-cache
  39980. ** cannot be trusted. This state can be cleared by completely discarding
  39981. ** the contents of the pager-cache. If a transaction was active when
  39982. ** the persistent error occurred, then the rollback journal may need
  39983. ** to be replayed to restore the contents of the database file (as if
  39984. ** it were a hot-journal).
  39985. */
  39986. static int pager_error(Pager *pPager, int rc){
  39987. int rc2 = rc & 0xff;
  39988. assert( rc==SQLITE_OK || !MEMDB );
  39989. assert(
  39990. pPager->errCode==SQLITE_FULL ||
  39991. pPager->errCode==SQLITE_OK ||
  39992. (pPager->errCode & 0xff)==SQLITE_IOERR
  39993. );
  39994. if( rc2==SQLITE_FULL || rc2==SQLITE_IOERR ){
  39995. pPager->errCode = rc;
  39996. pPager->eState = PAGER_ERROR;
  39997. }
  39998. return rc;
  39999. }
  40000. static int pager_truncate(Pager *pPager, Pgno nPage);
  40001. /*
  40002. ** This routine ends a transaction. A transaction is usually ended by
  40003. ** either a COMMIT or a ROLLBACK operation. This routine may be called
  40004. ** after rollback of a hot-journal, or if an error occurs while opening
  40005. ** the journal file or writing the very first journal-header of a
  40006. ** database transaction.
  40007. **
  40008. ** This routine is never called in PAGER_ERROR state. If it is called
  40009. ** in PAGER_NONE or PAGER_SHARED state and the lock held is less
  40010. ** exclusive than a RESERVED lock, it is a no-op.
  40011. **
  40012. ** Otherwise, any active savepoints are released.
  40013. **
  40014. ** If the journal file is open, then it is "finalized". Once a journal
  40015. ** file has been finalized it is not possible to use it to roll back a
  40016. ** transaction. Nor will it be considered to be a hot-journal by this
  40017. ** or any other database connection. Exactly how a journal is finalized
  40018. ** depends on whether or not the pager is running in exclusive mode and
  40019. ** the current journal-mode (Pager.journalMode value), as follows:
  40020. **
  40021. ** journalMode==MEMORY
  40022. ** Journal file descriptor is simply closed. This destroys an
  40023. ** in-memory journal.
  40024. **
  40025. ** journalMode==TRUNCATE
  40026. ** Journal file is truncated to zero bytes in size.
  40027. **
  40028. ** journalMode==PERSIST
  40029. ** The first 28 bytes of the journal file are zeroed. This invalidates
  40030. ** the first journal header in the file, and hence the entire journal
  40031. ** file. An invalid journal file cannot be rolled back.
  40032. **
  40033. ** journalMode==DELETE
  40034. ** The journal file is closed and deleted using sqlite3OsDelete().
  40035. **
  40036. ** If the pager is running in exclusive mode, this method of finalizing
  40037. ** the journal file is never used. Instead, if the journalMode is
  40038. ** DELETE and the pager is in exclusive mode, the method described under
  40039. ** journalMode==PERSIST is used instead.
  40040. **
  40041. ** After the journal is finalized, the pager moves to PAGER_READER state.
  40042. ** If running in non-exclusive rollback mode, the lock on the file is
  40043. ** downgraded to a SHARED_LOCK.
  40044. **
  40045. ** SQLITE_OK is returned if no error occurs. If an error occurs during
  40046. ** any of the IO operations to finalize the journal file or unlock the
  40047. ** database then the IO error code is returned to the user. If the
  40048. ** operation to finalize the journal file fails, then the code still
  40049. ** tries to unlock the database file if not in exclusive mode. If the
  40050. ** unlock operation fails as well, then the first error code related
  40051. ** to the first error encountered (the journal finalization one) is
  40052. ** returned.
  40053. */
  40054. static int pager_end_transaction(Pager *pPager, int hasMaster, int bCommit){
  40055. int rc = SQLITE_OK; /* Error code from journal finalization operation */
  40056. int rc2 = SQLITE_OK; /* Error code from db file unlock operation */
  40057. /* Do nothing if the pager does not have an open write transaction
  40058. ** or at least a RESERVED lock. This function may be called when there
  40059. ** is no write-transaction active but a RESERVED or greater lock is
  40060. ** held under two circumstances:
  40061. **
  40062. ** 1. After a successful hot-journal rollback, it is called with
  40063. ** eState==PAGER_NONE and eLock==EXCLUSIVE_LOCK.
  40064. **
  40065. ** 2. If a connection with locking_mode=exclusive holding an EXCLUSIVE
  40066. ** lock switches back to locking_mode=normal and then executes a
  40067. ** read-transaction, this function is called with eState==PAGER_READER
  40068. ** and eLock==EXCLUSIVE_LOCK when the read-transaction is closed.
  40069. */
  40070. assert( assert_pager_state(pPager) );
  40071. assert( pPager->eState!=PAGER_ERROR );
  40072. if( pPager->eState<PAGER_WRITER_LOCKED && pPager->eLock<RESERVED_LOCK ){
  40073. return SQLITE_OK;
  40074. }
  40075. releaseAllSavepoints(pPager);
  40076. assert( isOpen(pPager->jfd) || pPager->pInJournal==0 );
  40077. if( isOpen(pPager->jfd) ){
  40078. assert( !pagerUseWal(pPager) );
  40079. /* Finalize the journal file. */
  40080. if( sqlite3IsMemJournal(pPager->jfd) ){
  40081. assert( pPager->journalMode==PAGER_JOURNALMODE_MEMORY );
  40082. sqlite3OsClose(pPager->jfd);
  40083. }else if( pPager->journalMode==PAGER_JOURNALMODE_TRUNCATE ){
  40084. if( pPager->journalOff==0 ){
  40085. rc = SQLITE_OK;
  40086. }else{
  40087. rc = sqlite3OsTruncate(pPager->jfd, 0);
  40088. if( rc==SQLITE_OK && pPager->fullSync ){
  40089. /* Make sure the new file size is written into the inode right away.
  40090. ** Otherwise the journal might resurrect following a power loss and
  40091. ** cause the last transaction to roll back. See
  40092. ** https://bugzilla.mozilla.org/show_bug.cgi?id=1072773
  40093. */
  40094. rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags);
  40095. }
  40096. }
  40097. pPager->journalOff = 0;
  40098. }else if( pPager->journalMode==PAGER_JOURNALMODE_PERSIST
  40099. || (pPager->exclusiveMode && pPager->journalMode!=PAGER_JOURNALMODE_WAL)
  40100. ){
  40101. rc = zeroJournalHdr(pPager, hasMaster);
  40102. pPager->journalOff = 0;
  40103. }else{
  40104. /* This branch may be executed with Pager.journalMode==MEMORY if
  40105. ** a hot-journal was just rolled back. In this case the journal
  40106. ** file should be closed and deleted. If this connection writes to
  40107. ** the database file, it will do so using an in-memory journal.
  40108. */
  40109. int bDelete = (!pPager->tempFile && sqlite3JournalExists(pPager->jfd));
  40110. assert( pPager->journalMode==PAGER_JOURNALMODE_DELETE
  40111. || pPager->journalMode==PAGER_JOURNALMODE_MEMORY
  40112. || pPager->journalMode==PAGER_JOURNALMODE_WAL
  40113. );
  40114. sqlite3OsClose(pPager->jfd);
  40115. if( bDelete ){
  40116. rc = sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
  40117. }
  40118. }
  40119. }
  40120. #ifdef SQLITE_CHECK_PAGES
  40121. sqlite3PcacheIterateDirty(pPager->pPCache, pager_set_pagehash);
  40122. if( pPager->dbSize==0 && sqlite3PcacheRefCount(pPager->pPCache)>0 ){
  40123. PgHdr *p = sqlite3PagerLookup(pPager, 1);
  40124. if( p ){
  40125. p->pageHash = 0;
  40126. sqlite3PagerUnrefNotNull(p);
  40127. }
  40128. }
  40129. #endif
  40130. sqlite3BitvecDestroy(pPager->pInJournal);
  40131. pPager->pInJournal = 0;
  40132. pPager->nRec = 0;
  40133. sqlite3PcacheCleanAll(pPager->pPCache);
  40134. sqlite3PcacheTruncate(pPager->pPCache, pPager->dbSize);
  40135. if( pagerUseWal(pPager) ){
  40136. /* Drop the WAL write-lock, if any. Also, if the connection was in
  40137. ** locking_mode=exclusive mode but is no longer, drop the EXCLUSIVE
  40138. ** lock held on the database file.
  40139. */
  40140. rc2 = sqlite3WalEndWriteTransaction(pPager->pWal);
  40141. assert( rc2==SQLITE_OK );
  40142. }else if( rc==SQLITE_OK && bCommit && pPager->dbFileSize>pPager->dbSize ){
  40143. /* This branch is taken when committing a transaction in rollback-journal
  40144. ** mode if the database file on disk is larger than the database image.
  40145. ** At this point the journal has been finalized and the transaction
  40146. ** successfully committed, but the EXCLUSIVE lock is still held on the
  40147. ** file. So it is safe to truncate the database file to its minimum
  40148. ** required size. */
  40149. assert( pPager->eLock==EXCLUSIVE_LOCK );
  40150. rc = pager_truncate(pPager, pPager->dbSize);
  40151. }
  40152. if( rc==SQLITE_OK && bCommit && isOpen(pPager->fd) ){
  40153. rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_COMMIT_PHASETWO, 0);
  40154. if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
  40155. }
  40156. if( !pPager->exclusiveMode
  40157. && (!pagerUseWal(pPager) || sqlite3WalExclusiveMode(pPager->pWal, 0))
  40158. ){
  40159. rc2 = pagerUnlockDb(pPager, SHARED_LOCK);
  40160. pPager->changeCountDone = 0;
  40161. }
  40162. pPager->eState = PAGER_READER;
  40163. pPager->setMaster = 0;
  40164. return (rc==SQLITE_OK?rc2:rc);
  40165. }
  40166. /*
  40167. ** Execute a rollback if a transaction is active and unlock the
  40168. ** database file.
  40169. **
  40170. ** If the pager has already entered the ERROR state, do not attempt
  40171. ** the rollback at this time. Instead, pager_unlock() is called. The
  40172. ** call to pager_unlock() will discard all in-memory pages, unlock
  40173. ** the database file and move the pager back to OPEN state. If this
  40174. ** means that there is a hot-journal left in the file-system, the next
  40175. ** connection to obtain a shared lock on the pager (which may be this one)
  40176. ** will roll it back.
  40177. **
  40178. ** If the pager has not already entered the ERROR state, but an IO or
  40179. ** malloc error occurs during a rollback, then this will itself cause
  40180. ** the pager to enter the ERROR state. Which will be cleared by the
  40181. ** call to pager_unlock(), as described above.
  40182. */
  40183. static void pagerUnlockAndRollback(Pager *pPager){
  40184. if( pPager->eState!=PAGER_ERROR && pPager->eState!=PAGER_OPEN ){
  40185. assert( assert_pager_state(pPager) );
  40186. if( pPager->eState>=PAGER_WRITER_LOCKED ){
  40187. sqlite3BeginBenignMalloc();
  40188. sqlite3PagerRollback(pPager);
  40189. sqlite3EndBenignMalloc();
  40190. }else if( !pPager->exclusiveMode ){
  40191. assert( pPager->eState==PAGER_READER );
  40192. pager_end_transaction(pPager, 0, 0);
  40193. }
  40194. }
  40195. pager_unlock(pPager);
  40196. }
  40197. /*
  40198. ** Parameter aData must point to a buffer of pPager->pageSize bytes
  40199. ** of data. Compute and return a checksum based ont the contents of the
  40200. ** page of data and the current value of pPager->cksumInit.
  40201. **
  40202. ** This is not a real checksum. It is really just the sum of the
  40203. ** random initial value (pPager->cksumInit) and every 200th byte
  40204. ** of the page data, starting with byte offset (pPager->pageSize%200).
  40205. ** Each byte is interpreted as an 8-bit unsigned integer.
  40206. **
  40207. ** Changing the formula used to compute this checksum results in an
  40208. ** incompatible journal file format.
  40209. **
  40210. ** If journal corruption occurs due to a power failure, the most likely
  40211. ** scenario is that one end or the other of the record will be changed.
  40212. ** It is much less likely that the two ends of the journal record will be
  40213. ** correct and the middle be corrupt. Thus, this "checksum" scheme,
  40214. ** though fast and simple, catches the mostly likely kind of corruption.
  40215. */
  40216. static u32 pager_cksum(Pager *pPager, const u8 *aData){
  40217. u32 cksum = pPager->cksumInit; /* Checksum value to return */
  40218. int i = pPager->pageSize-200; /* Loop counter */
  40219. while( i>0 ){
  40220. cksum += aData[i];
  40221. i -= 200;
  40222. }
  40223. return cksum;
  40224. }
  40225. /*
  40226. ** Report the current page size and number of reserved bytes back
  40227. ** to the codec.
  40228. */
  40229. #ifdef SQLITE_HAS_CODEC
  40230. static void pagerReportSize(Pager *pPager){
  40231. if( pPager->xCodecSizeChng ){
  40232. pPager->xCodecSizeChng(pPager->pCodec, pPager->pageSize,
  40233. (int)pPager->nReserve);
  40234. }
  40235. }
  40236. #else
  40237. # define pagerReportSize(X) /* No-op if we do not support a codec */
  40238. #endif
  40239. /*
  40240. ** Read a single page from either the journal file (if isMainJrnl==1) or
  40241. ** from the sub-journal (if isMainJrnl==0) and playback that page.
  40242. ** The page begins at offset *pOffset into the file. The *pOffset
  40243. ** value is increased to the start of the next page in the journal.
  40244. **
  40245. ** The main rollback journal uses checksums - the statement journal does
  40246. ** not.
  40247. **
  40248. ** If the page number of the page record read from the (sub-)journal file
  40249. ** is greater than the current value of Pager.dbSize, then playback is
  40250. ** skipped and SQLITE_OK is returned.
  40251. **
  40252. ** If pDone is not NULL, then it is a record of pages that have already
  40253. ** been played back. If the page at *pOffset has already been played back
  40254. ** (if the corresponding pDone bit is set) then skip the playback.
  40255. ** Make sure the pDone bit corresponding to the *pOffset page is set
  40256. ** prior to returning.
  40257. **
  40258. ** If the page record is successfully read from the (sub-)journal file
  40259. ** and played back, then SQLITE_OK is returned. If an IO error occurs
  40260. ** while reading the record from the (sub-)journal file or while writing
  40261. ** to the database file, then the IO error code is returned. If data
  40262. ** is successfully read from the (sub-)journal file but appears to be
  40263. ** corrupted, SQLITE_DONE is returned. Data is considered corrupted in
  40264. ** two circumstances:
  40265. **
  40266. ** * If the record page-number is illegal (0 or PAGER_MJ_PGNO), or
  40267. ** * If the record is being rolled back from the main journal file
  40268. ** and the checksum field does not match the record content.
  40269. **
  40270. ** Neither of these two scenarios are possible during a savepoint rollback.
  40271. **
  40272. ** If this is a savepoint rollback, then memory may have to be dynamically
  40273. ** allocated by this function. If this is the case and an allocation fails,
  40274. ** SQLITE_NOMEM is returned.
  40275. */
  40276. static int pager_playback_one_page(
  40277. Pager *pPager, /* The pager being played back */
  40278. i64 *pOffset, /* Offset of record to playback */
  40279. Bitvec *pDone, /* Bitvec of pages already played back */
  40280. int isMainJrnl, /* 1 -> main journal. 0 -> sub-journal. */
  40281. int isSavepnt /* True for a savepoint rollback */
  40282. ){
  40283. int rc;
  40284. PgHdr *pPg; /* An existing page in the cache */
  40285. Pgno pgno; /* The page number of a page in journal */
  40286. u32 cksum; /* Checksum used for sanity checking */
  40287. char *aData; /* Temporary storage for the page */
  40288. sqlite3_file *jfd; /* The file descriptor for the journal file */
  40289. int isSynced; /* True if journal page is synced */
  40290. assert( (isMainJrnl&~1)==0 ); /* isMainJrnl is 0 or 1 */
  40291. assert( (isSavepnt&~1)==0 ); /* isSavepnt is 0 or 1 */
  40292. assert( isMainJrnl || pDone ); /* pDone always used on sub-journals */
  40293. assert( isSavepnt || pDone==0 ); /* pDone never used on non-savepoint */
  40294. aData = pPager->pTmpSpace;
  40295. assert( aData ); /* Temp storage must have already been allocated */
  40296. assert( pagerUseWal(pPager)==0 || (!isMainJrnl && isSavepnt) );
  40297. /* Either the state is greater than PAGER_WRITER_CACHEMOD (a transaction
  40298. ** or savepoint rollback done at the request of the caller) or this is
  40299. ** a hot-journal rollback. If it is a hot-journal rollback, the pager
  40300. ** is in state OPEN and holds an EXCLUSIVE lock. Hot-journal rollback
  40301. ** only reads from the main journal, not the sub-journal.
  40302. */
  40303. assert( pPager->eState>=PAGER_WRITER_CACHEMOD
  40304. || (pPager->eState==PAGER_OPEN && pPager->eLock==EXCLUSIVE_LOCK)
  40305. );
  40306. assert( pPager->eState>=PAGER_WRITER_CACHEMOD || isMainJrnl );
  40307. /* Read the page number and page data from the journal or sub-journal
  40308. ** file. Return an error code to the caller if an IO error occurs.
  40309. */
  40310. jfd = isMainJrnl ? pPager->jfd : pPager->sjfd;
  40311. rc = read32bits(jfd, *pOffset, &pgno);
  40312. if( rc!=SQLITE_OK ) return rc;
  40313. rc = sqlite3OsRead(jfd, (u8*)aData, pPager->pageSize, (*pOffset)+4);
  40314. if( rc!=SQLITE_OK ) return rc;
  40315. *pOffset += pPager->pageSize + 4 + isMainJrnl*4;
  40316. /* Sanity checking on the page. This is more important that I originally
  40317. ** thought. If a power failure occurs while the journal is being written,
  40318. ** it could cause invalid data to be written into the journal. We need to
  40319. ** detect this invalid data (with high probability) and ignore it.
  40320. */
  40321. if( pgno==0 || pgno==PAGER_MJ_PGNO(pPager) ){
  40322. assert( !isSavepnt );
  40323. return SQLITE_DONE;
  40324. }
  40325. if( pgno>(Pgno)pPager->dbSize || sqlite3BitvecTest(pDone, pgno) ){
  40326. return SQLITE_OK;
  40327. }
  40328. if( isMainJrnl ){
  40329. rc = read32bits(jfd, (*pOffset)-4, &cksum);
  40330. if( rc ) return rc;
  40331. if( !isSavepnt && pager_cksum(pPager, (u8*)aData)!=cksum ){
  40332. return SQLITE_DONE;
  40333. }
  40334. }
  40335. /* If this page has already been played by before during the current
  40336. ** rollback, then don't bother to play it back again.
  40337. */
  40338. if( pDone && (rc = sqlite3BitvecSet(pDone, pgno))!=SQLITE_OK ){
  40339. return rc;
  40340. }
  40341. /* When playing back page 1, restore the nReserve setting
  40342. */
  40343. if( pgno==1 && pPager->nReserve!=((u8*)aData)[20] ){
  40344. pPager->nReserve = ((u8*)aData)[20];
  40345. pagerReportSize(pPager);
  40346. }
  40347. /* If the pager is in CACHEMOD state, then there must be a copy of this
  40348. ** page in the pager cache. In this case just update the pager cache,
  40349. ** not the database file. The page is left marked dirty in this case.
  40350. **
  40351. ** An exception to the above rule: If the database is in no-sync mode
  40352. ** and a page is moved during an incremental vacuum then the page may
  40353. ** not be in the pager cache. Later: if a malloc() or IO error occurs
  40354. ** during a Movepage() call, then the page may not be in the cache
  40355. ** either. So the condition described in the above paragraph is not
  40356. ** assert()able.
  40357. **
  40358. ** If in WRITER_DBMOD, WRITER_FINISHED or OPEN state, then we update the
  40359. ** pager cache if it exists and the main file. The page is then marked
  40360. ** not dirty. Since this code is only executed in PAGER_OPEN state for
  40361. ** a hot-journal rollback, it is guaranteed that the page-cache is empty
  40362. ** if the pager is in OPEN state.
  40363. **
  40364. ** Ticket #1171: The statement journal might contain page content that is
  40365. ** different from the page content at the start of the transaction.
  40366. ** This occurs when a page is changed prior to the start of a statement
  40367. ** then changed again within the statement. When rolling back such a
  40368. ** statement we must not write to the original database unless we know
  40369. ** for certain that original page contents are synced into the main rollback
  40370. ** journal. Otherwise, a power loss might leave modified data in the
  40371. ** database file without an entry in the rollback journal that can
  40372. ** restore the database to its original form. Two conditions must be
  40373. ** met before writing to the database files. (1) the database must be
  40374. ** locked. (2) we know that the original page content is fully synced
  40375. ** in the main journal either because the page is not in cache or else
  40376. ** the page is marked as needSync==0.
  40377. **
  40378. ** 2008-04-14: When attempting to vacuum a corrupt database file, it
  40379. ** is possible to fail a statement on a database that does not yet exist.
  40380. ** Do not attempt to write if database file has never been opened.
  40381. */
  40382. if( pagerUseWal(pPager) ){
  40383. pPg = 0;
  40384. }else{
  40385. pPg = sqlite3PagerLookup(pPager, pgno);
  40386. }
  40387. assert( pPg || !MEMDB );
  40388. assert( pPager->eState!=PAGER_OPEN || pPg==0 );
  40389. PAGERTRACE(("PLAYBACK %d page %d hash(%08x) %s\n",
  40390. PAGERID(pPager), pgno, pager_datahash(pPager->pageSize, (u8*)aData),
  40391. (isMainJrnl?"main-journal":"sub-journal")
  40392. ));
  40393. if( isMainJrnl ){
  40394. isSynced = pPager->noSync || (*pOffset <= pPager->journalHdr);
  40395. }else{
  40396. isSynced = (pPg==0 || 0==(pPg->flags & PGHDR_NEED_SYNC));
  40397. }
  40398. if( isOpen(pPager->fd)
  40399. && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
  40400. && isSynced
  40401. ){
  40402. i64 ofst = (pgno-1)*(i64)pPager->pageSize;
  40403. testcase( !isSavepnt && pPg!=0 && (pPg->flags&PGHDR_NEED_SYNC)!=0 );
  40404. assert( !pagerUseWal(pPager) );
  40405. rc = sqlite3OsWrite(pPager->fd, (u8 *)aData, pPager->pageSize, ofst);
  40406. if( pgno>pPager->dbFileSize ){
  40407. pPager->dbFileSize = pgno;
  40408. }
  40409. if( pPager->pBackup ){
  40410. CODEC1(pPager, aData, pgno, 3, rc=SQLITE_NOMEM);
  40411. sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)aData);
  40412. CODEC2(pPager, aData, pgno, 7, rc=SQLITE_NOMEM, aData);
  40413. }
  40414. }else if( !isMainJrnl && pPg==0 ){
  40415. /* If this is a rollback of a savepoint and data was not written to
  40416. ** the database and the page is not in-memory, there is a potential
  40417. ** problem. When the page is next fetched by the b-tree layer, it
  40418. ** will be read from the database file, which may or may not be
  40419. ** current.
  40420. **
  40421. ** There are a couple of different ways this can happen. All are quite
  40422. ** obscure. When running in synchronous mode, this can only happen
  40423. ** if the page is on the free-list at the start of the transaction, then
  40424. ** populated, then moved using sqlite3PagerMovepage().
  40425. **
  40426. ** The solution is to add an in-memory page to the cache containing
  40427. ** the data just read from the sub-journal. Mark the page as dirty
  40428. ** and if the pager requires a journal-sync, then mark the page as
  40429. ** requiring a journal-sync before it is written.
  40430. */
  40431. assert( isSavepnt );
  40432. assert( (pPager->doNotSpill & SPILLFLAG_ROLLBACK)==0 );
  40433. pPager->doNotSpill |= SPILLFLAG_ROLLBACK;
  40434. rc = sqlite3PagerAcquire(pPager, pgno, &pPg, 1);
  40435. assert( (pPager->doNotSpill & SPILLFLAG_ROLLBACK)!=0 );
  40436. pPager->doNotSpill &= ~SPILLFLAG_ROLLBACK;
  40437. if( rc!=SQLITE_OK ) return rc;
  40438. pPg->flags &= ~PGHDR_NEED_READ;
  40439. sqlite3PcacheMakeDirty(pPg);
  40440. }
  40441. if( pPg ){
  40442. /* No page should ever be explicitly rolled back that is in use, except
  40443. ** for page 1 which is held in use in order to keep the lock on the
  40444. ** database active. However such a page may be rolled back as a result
  40445. ** of an internal error resulting in an automatic call to
  40446. ** sqlite3PagerRollback().
  40447. */
  40448. void *pData;
  40449. pData = pPg->pData;
  40450. memcpy(pData, (u8*)aData, pPager->pageSize);
  40451. pPager->xReiniter(pPg);
  40452. if( isMainJrnl && (!isSavepnt || *pOffset<=pPager->journalHdr) ){
  40453. /* If the contents of this page were just restored from the main
  40454. ** journal file, then its content must be as they were when the
  40455. ** transaction was first opened. In this case we can mark the page
  40456. ** as clean, since there will be no need to write it out to the
  40457. ** database.
  40458. **
  40459. ** There is one exception to this rule. If the page is being rolled
  40460. ** back as part of a savepoint (or statement) rollback from an
  40461. ** unsynced portion of the main journal file, then it is not safe
  40462. ** to mark the page as clean. This is because marking the page as
  40463. ** clean will clear the PGHDR_NEED_SYNC flag. Since the page is
  40464. ** already in the journal file (recorded in Pager.pInJournal) and
  40465. ** the PGHDR_NEED_SYNC flag is cleared, if the page is written to
  40466. ** again within this transaction, it will be marked as dirty but
  40467. ** the PGHDR_NEED_SYNC flag will not be set. It could then potentially
  40468. ** be written out into the database file before its journal file
  40469. ** segment is synced. If a crash occurs during or following this,
  40470. ** database corruption may ensue.
  40471. */
  40472. assert( !pagerUseWal(pPager) );
  40473. sqlite3PcacheMakeClean(pPg);
  40474. }
  40475. pager_set_pagehash(pPg);
  40476. /* If this was page 1, then restore the value of Pager.dbFileVers.
  40477. ** Do this before any decoding. */
  40478. if( pgno==1 ){
  40479. memcpy(&pPager->dbFileVers, &((u8*)pData)[24],sizeof(pPager->dbFileVers));
  40480. }
  40481. /* Decode the page just read from disk */
  40482. CODEC1(pPager, pData, pPg->pgno, 3, rc=SQLITE_NOMEM);
  40483. sqlite3PcacheRelease(pPg);
  40484. }
  40485. return rc;
  40486. }
  40487. /*
  40488. ** Parameter zMaster is the name of a master journal file. A single journal
  40489. ** file that referred to the master journal file has just been rolled back.
  40490. ** This routine checks if it is possible to delete the master journal file,
  40491. ** and does so if it is.
  40492. **
  40493. ** Argument zMaster may point to Pager.pTmpSpace. So that buffer is not
  40494. ** available for use within this function.
  40495. **
  40496. ** When a master journal file is created, it is populated with the names
  40497. ** of all of its child journals, one after another, formatted as utf-8
  40498. ** encoded text. The end of each child journal file is marked with a
  40499. ** nul-terminator byte (0x00). i.e. the entire contents of a master journal
  40500. ** file for a transaction involving two databases might be:
  40501. **
  40502. ** "/home/bill/a.db-journal\x00/home/bill/b.db-journal\x00"
  40503. **
  40504. ** A master journal file may only be deleted once all of its child
  40505. ** journals have been rolled back.
  40506. **
  40507. ** This function reads the contents of the master-journal file into
  40508. ** memory and loops through each of the child journal names. For
  40509. ** each child journal, it checks if:
  40510. **
  40511. ** * if the child journal exists, and if so
  40512. ** * if the child journal contains a reference to master journal
  40513. ** file zMaster
  40514. **
  40515. ** If a child journal can be found that matches both of the criteria
  40516. ** above, this function returns without doing anything. Otherwise, if
  40517. ** no such child journal can be found, file zMaster is deleted from
  40518. ** the file-system using sqlite3OsDelete().
  40519. **
  40520. ** If an IO error within this function, an error code is returned. This
  40521. ** function allocates memory by calling sqlite3Malloc(). If an allocation
  40522. ** fails, SQLITE_NOMEM is returned. Otherwise, if no IO or malloc errors
  40523. ** occur, SQLITE_OK is returned.
  40524. **
  40525. ** TODO: This function allocates a single block of memory to load
  40526. ** the entire contents of the master journal file. This could be
  40527. ** a couple of kilobytes or so - potentially larger than the page
  40528. ** size.
  40529. */
  40530. static int pager_delmaster(Pager *pPager, const char *zMaster){
  40531. sqlite3_vfs *pVfs = pPager->pVfs;
  40532. int rc; /* Return code */
  40533. sqlite3_file *pMaster; /* Malloc'd master-journal file descriptor */
  40534. sqlite3_file *pJournal; /* Malloc'd child-journal file descriptor */
  40535. char *zMasterJournal = 0; /* Contents of master journal file */
  40536. i64 nMasterJournal; /* Size of master journal file */
  40537. char *zJournal; /* Pointer to one journal within MJ file */
  40538. char *zMasterPtr; /* Space to hold MJ filename from a journal file */
  40539. int nMasterPtr; /* Amount of space allocated to zMasterPtr[] */
  40540. /* Allocate space for both the pJournal and pMaster file descriptors.
  40541. ** If successful, open the master journal file for reading.
  40542. */
  40543. pMaster = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile * 2);
  40544. pJournal = (sqlite3_file *)(((u8 *)pMaster) + pVfs->szOsFile);
  40545. if( !pMaster ){
  40546. rc = SQLITE_NOMEM;
  40547. }else{
  40548. const int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MASTER_JOURNAL);
  40549. rc = sqlite3OsOpen(pVfs, zMaster, pMaster, flags, 0);
  40550. }
  40551. if( rc!=SQLITE_OK ) goto delmaster_out;
  40552. /* Load the entire master journal file into space obtained from
  40553. ** sqlite3_malloc() and pointed to by zMasterJournal. Also obtain
  40554. ** sufficient space (in zMasterPtr) to hold the names of master
  40555. ** journal files extracted from regular rollback-journals.
  40556. */
  40557. rc = sqlite3OsFileSize(pMaster, &nMasterJournal);
  40558. if( rc!=SQLITE_OK ) goto delmaster_out;
  40559. nMasterPtr = pVfs->mxPathname+1;
  40560. zMasterJournal = sqlite3Malloc(nMasterJournal + nMasterPtr + 1);
  40561. if( !zMasterJournal ){
  40562. rc = SQLITE_NOMEM;
  40563. goto delmaster_out;
  40564. }
  40565. zMasterPtr = &zMasterJournal[nMasterJournal+1];
  40566. rc = sqlite3OsRead(pMaster, zMasterJournal, (int)nMasterJournal, 0);
  40567. if( rc!=SQLITE_OK ) goto delmaster_out;
  40568. zMasterJournal[nMasterJournal] = 0;
  40569. zJournal = zMasterJournal;
  40570. while( (zJournal-zMasterJournal)<nMasterJournal ){
  40571. int exists;
  40572. rc = sqlite3OsAccess(pVfs, zJournal, SQLITE_ACCESS_EXISTS, &exists);
  40573. if( rc!=SQLITE_OK ){
  40574. goto delmaster_out;
  40575. }
  40576. if( exists ){
  40577. /* One of the journals pointed to by the master journal exists.
  40578. ** Open it and check if it points at the master journal. If
  40579. ** so, return without deleting the master journal file.
  40580. */
  40581. int c;
  40582. int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL);
  40583. rc = sqlite3OsOpen(pVfs, zJournal, pJournal, flags, 0);
  40584. if( rc!=SQLITE_OK ){
  40585. goto delmaster_out;
  40586. }
  40587. rc = readMasterJournal(pJournal, zMasterPtr, nMasterPtr);
  40588. sqlite3OsClose(pJournal);
  40589. if( rc!=SQLITE_OK ){
  40590. goto delmaster_out;
  40591. }
  40592. c = zMasterPtr[0]!=0 && strcmp(zMasterPtr, zMaster)==0;
  40593. if( c ){
  40594. /* We have a match. Do not delete the master journal file. */
  40595. goto delmaster_out;
  40596. }
  40597. }
  40598. zJournal += (sqlite3Strlen30(zJournal)+1);
  40599. }
  40600. sqlite3OsClose(pMaster);
  40601. rc = sqlite3OsDelete(pVfs, zMaster, 0);
  40602. delmaster_out:
  40603. sqlite3_free(zMasterJournal);
  40604. if( pMaster ){
  40605. sqlite3OsClose(pMaster);
  40606. assert( !isOpen(pJournal) );
  40607. sqlite3_free(pMaster);
  40608. }
  40609. return rc;
  40610. }
  40611. /*
  40612. ** This function is used to change the actual size of the database
  40613. ** file in the file-system. This only happens when committing a transaction,
  40614. ** or rolling back a transaction (including rolling back a hot-journal).
  40615. **
  40616. ** If the main database file is not open, or the pager is not in either
  40617. ** DBMOD or OPEN state, this function is a no-op. Otherwise, the size
  40618. ** of the file is changed to nPage pages (nPage*pPager->pageSize bytes).
  40619. ** If the file on disk is currently larger than nPage pages, then use the VFS
  40620. ** xTruncate() method to truncate it.
  40621. **
  40622. ** Or, it might be the case that the file on disk is smaller than
  40623. ** nPage pages. Some operating system implementations can get confused if
  40624. ** you try to truncate a file to some size that is larger than it
  40625. ** currently is, so detect this case and write a single zero byte to
  40626. ** the end of the new file instead.
  40627. **
  40628. ** If successful, return SQLITE_OK. If an IO error occurs while modifying
  40629. ** the database file, return the error code to the caller.
  40630. */
  40631. static int pager_truncate(Pager *pPager, Pgno nPage){
  40632. int rc = SQLITE_OK;
  40633. assert( pPager->eState!=PAGER_ERROR );
  40634. assert( pPager->eState!=PAGER_READER );
  40635. if( isOpen(pPager->fd)
  40636. && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
  40637. ){
  40638. i64 currentSize, newSize;
  40639. int szPage = pPager->pageSize;
  40640. assert( pPager->eLock==EXCLUSIVE_LOCK );
  40641. /* TODO: Is it safe to use Pager.dbFileSize here? */
  40642. rc = sqlite3OsFileSize(pPager->fd, &currentSize);
  40643. newSize = szPage*(i64)nPage;
  40644. if( rc==SQLITE_OK && currentSize!=newSize ){
  40645. if( currentSize>newSize ){
  40646. rc = sqlite3OsTruncate(pPager->fd, newSize);
  40647. }else if( (currentSize+szPage)<=newSize ){
  40648. char *pTmp = pPager->pTmpSpace;
  40649. memset(pTmp, 0, szPage);
  40650. testcase( (newSize-szPage) == currentSize );
  40651. testcase( (newSize-szPage) > currentSize );
  40652. rc = sqlite3OsWrite(pPager->fd, pTmp, szPage, newSize-szPage);
  40653. }
  40654. if( rc==SQLITE_OK ){
  40655. pPager->dbFileSize = nPage;
  40656. }
  40657. }
  40658. }
  40659. return rc;
  40660. }
  40661. /*
  40662. ** Return a sanitized version of the sector-size of OS file pFile. The
  40663. ** return value is guaranteed to lie between 32 and MAX_SECTOR_SIZE.
  40664. */
  40665. SQLITE_PRIVATE int sqlite3SectorSize(sqlite3_file *pFile){
  40666. int iRet = sqlite3OsSectorSize(pFile);
  40667. if( iRet<32 ){
  40668. iRet = 512;
  40669. }else if( iRet>MAX_SECTOR_SIZE ){
  40670. assert( MAX_SECTOR_SIZE>=512 );
  40671. iRet = MAX_SECTOR_SIZE;
  40672. }
  40673. return iRet;
  40674. }
  40675. /*
  40676. ** Set the value of the Pager.sectorSize variable for the given
  40677. ** pager based on the value returned by the xSectorSize method
  40678. ** of the open database file. The sector size will be used
  40679. ** to determine the size and alignment of journal header and
  40680. ** master journal pointers within created journal files.
  40681. **
  40682. ** For temporary files the effective sector size is always 512 bytes.
  40683. **
  40684. ** Otherwise, for non-temporary files, the effective sector size is
  40685. ** the value returned by the xSectorSize() method rounded up to 32 if
  40686. ** it is less than 32, or rounded down to MAX_SECTOR_SIZE if it
  40687. ** is greater than MAX_SECTOR_SIZE.
  40688. **
  40689. ** If the file has the SQLITE_IOCAP_POWERSAFE_OVERWRITE property, then set
  40690. ** the effective sector size to its minimum value (512). The purpose of
  40691. ** pPager->sectorSize is to define the "blast radius" of bytes that
  40692. ** might change if a crash occurs while writing to a single byte in
  40693. ** that range. But with POWERSAFE_OVERWRITE, the blast radius is zero
  40694. ** (that is what POWERSAFE_OVERWRITE means), so we minimize the sector
  40695. ** size. For backwards compatibility of the rollback journal file format,
  40696. ** we cannot reduce the effective sector size below 512.
  40697. */
  40698. static void setSectorSize(Pager *pPager){
  40699. assert( isOpen(pPager->fd) || pPager->tempFile );
  40700. if( pPager->tempFile
  40701. || (sqlite3OsDeviceCharacteristics(pPager->fd) &
  40702. SQLITE_IOCAP_POWERSAFE_OVERWRITE)!=0
  40703. ){
  40704. /* Sector size doesn't matter for temporary files. Also, the file
  40705. ** may not have been opened yet, in which case the OsSectorSize()
  40706. ** call will segfault. */
  40707. pPager->sectorSize = 512;
  40708. }else{
  40709. pPager->sectorSize = sqlite3SectorSize(pPager->fd);
  40710. }
  40711. }
  40712. /*
  40713. ** Playback the journal and thus restore the database file to
  40714. ** the state it was in before we started making changes.
  40715. **
  40716. ** The journal file format is as follows:
  40717. **
  40718. ** (1) 8 byte prefix. A copy of aJournalMagic[].
  40719. ** (2) 4 byte big-endian integer which is the number of valid page records
  40720. ** in the journal. If this value is 0xffffffff, then compute the
  40721. ** number of page records from the journal size.
  40722. ** (3) 4 byte big-endian integer which is the initial value for the
  40723. ** sanity checksum.
  40724. ** (4) 4 byte integer which is the number of pages to truncate the
  40725. ** database to during a rollback.
  40726. ** (5) 4 byte big-endian integer which is the sector size. The header
  40727. ** is this many bytes in size.
  40728. ** (6) 4 byte big-endian integer which is the page size.
  40729. ** (7) zero padding out to the next sector size.
  40730. ** (8) Zero or more pages instances, each as follows:
  40731. ** + 4 byte page number.
  40732. ** + pPager->pageSize bytes of data.
  40733. ** + 4 byte checksum
  40734. **
  40735. ** When we speak of the journal header, we mean the first 7 items above.
  40736. ** Each entry in the journal is an instance of the 8th item.
  40737. **
  40738. ** Call the value from the second bullet "nRec". nRec is the number of
  40739. ** valid page entries in the journal. In most cases, you can compute the
  40740. ** value of nRec from the size of the journal file. But if a power
  40741. ** failure occurred while the journal was being written, it could be the
  40742. ** case that the size of the journal file had already been increased but
  40743. ** the extra entries had not yet made it safely to disk. In such a case,
  40744. ** the value of nRec computed from the file size would be too large. For
  40745. ** that reason, we always use the nRec value in the header.
  40746. **
  40747. ** If the nRec value is 0xffffffff it means that nRec should be computed
  40748. ** from the file size. This value is used when the user selects the
  40749. ** no-sync option for the journal. A power failure could lead to corruption
  40750. ** in this case. But for things like temporary table (which will be
  40751. ** deleted when the power is restored) we don't care.
  40752. **
  40753. ** If the file opened as the journal file is not a well-formed
  40754. ** journal file then all pages up to the first corrupted page are rolled
  40755. ** back (or no pages if the journal header is corrupted). The journal file
  40756. ** is then deleted and SQLITE_OK returned, just as if no corruption had
  40757. ** been encountered.
  40758. **
  40759. ** If an I/O or malloc() error occurs, the journal-file is not deleted
  40760. ** and an error code is returned.
  40761. **
  40762. ** The isHot parameter indicates that we are trying to rollback a journal
  40763. ** that might be a hot journal. Or, it could be that the journal is
  40764. ** preserved because of JOURNALMODE_PERSIST or JOURNALMODE_TRUNCATE.
  40765. ** If the journal really is hot, reset the pager cache prior rolling
  40766. ** back any content. If the journal is merely persistent, no reset is
  40767. ** needed.
  40768. */
  40769. static int pager_playback(Pager *pPager, int isHot){
  40770. sqlite3_vfs *pVfs = pPager->pVfs;
  40771. i64 szJ; /* Size of the journal file in bytes */
  40772. u32 nRec; /* Number of Records in the journal */
  40773. u32 u; /* Unsigned loop counter */
  40774. Pgno mxPg = 0; /* Size of the original file in pages */
  40775. int rc; /* Result code of a subroutine */
  40776. int res = 1; /* Value returned by sqlite3OsAccess() */
  40777. char *zMaster = 0; /* Name of master journal file if any */
  40778. int needPagerReset; /* True to reset page prior to first page rollback */
  40779. int nPlayback = 0; /* Total number of pages restored from journal */
  40780. /* Figure out how many records are in the journal. Abort early if
  40781. ** the journal is empty.
  40782. */
  40783. assert( isOpen(pPager->jfd) );
  40784. rc = sqlite3OsFileSize(pPager->jfd, &szJ);
  40785. if( rc!=SQLITE_OK ){
  40786. goto end_playback;
  40787. }
  40788. /* Read the master journal name from the journal, if it is present.
  40789. ** If a master journal file name is specified, but the file is not
  40790. ** present on disk, then the journal is not hot and does not need to be
  40791. ** played back.
  40792. **
  40793. ** TODO: Technically the following is an error because it assumes that
  40794. ** buffer Pager.pTmpSpace is (mxPathname+1) bytes or larger. i.e. that
  40795. ** (pPager->pageSize >= pPager->pVfs->mxPathname+1). Using os_unix.c,
  40796. ** mxPathname is 512, which is the same as the minimum allowable value
  40797. ** for pageSize.
  40798. */
  40799. zMaster = pPager->pTmpSpace;
  40800. rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
  40801. if( rc==SQLITE_OK && zMaster[0] ){
  40802. rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
  40803. }
  40804. zMaster = 0;
  40805. if( rc!=SQLITE_OK || !res ){
  40806. goto end_playback;
  40807. }
  40808. pPager->journalOff = 0;
  40809. needPagerReset = isHot;
  40810. /* This loop terminates either when a readJournalHdr() or
  40811. ** pager_playback_one_page() call returns SQLITE_DONE or an IO error
  40812. ** occurs.
  40813. */
  40814. while( 1 ){
  40815. /* Read the next journal header from the journal file. If there are
  40816. ** not enough bytes left in the journal file for a complete header, or
  40817. ** it is corrupted, then a process must have failed while writing it.
  40818. ** This indicates nothing more needs to be rolled back.
  40819. */
  40820. rc = readJournalHdr(pPager, isHot, szJ, &nRec, &mxPg);
  40821. if( rc!=SQLITE_OK ){
  40822. if( rc==SQLITE_DONE ){
  40823. rc = SQLITE_OK;
  40824. }
  40825. goto end_playback;
  40826. }
  40827. /* If nRec is 0xffffffff, then this journal was created by a process
  40828. ** working in no-sync mode. This means that the rest of the journal
  40829. ** file consists of pages, there are no more journal headers. Compute
  40830. ** the value of nRec based on this assumption.
  40831. */
  40832. if( nRec==0xffffffff ){
  40833. assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) );
  40834. nRec = (int)((szJ - JOURNAL_HDR_SZ(pPager))/JOURNAL_PG_SZ(pPager));
  40835. }
  40836. /* If nRec is 0 and this rollback is of a transaction created by this
  40837. ** process and if this is the final header in the journal, then it means
  40838. ** that this part of the journal was being filled but has not yet been
  40839. ** synced to disk. Compute the number of pages based on the remaining
  40840. ** size of the file.
  40841. **
  40842. ** The third term of the test was added to fix ticket #2565.
  40843. ** When rolling back a hot journal, nRec==0 always means that the next
  40844. ** chunk of the journal contains zero pages to be rolled back. But
  40845. ** when doing a ROLLBACK and the nRec==0 chunk is the last chunk in
  40846. ** the journal, it means that the journal might contain additional
  40847. ** pages that need to be rolled back and that the number of pages
  40848. ** should be computed based on the journal file size.
  40849. */
  40850. if( nRec==0 && !isHot &&
  40851. pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff ){
  40852. nRec = (int)((szJ - pPager->journalOff) / JOURNAL_PG_SZ(pPager));
  40853. }
  40854. /* If this is the first header read from the journal, truncate the
  40855. ** database file back to its original size.
  40856. */
  40857. if( pPager->journalOff==JOURNAL_HDR_SZ(pPager) ){
  40858. rc = pager_truncate(pPager, mxPg);
  40859. if( rc!=SQLITE_OK ){
  40860. goto end_playback;
  40861. }
  40862. pPager->dbSize = mxPg;
  40863. }
  40864. /* Copy original pages out of the journal and back into the
  40865. ** database file and/or page cache.
  40866. */
  40867. for(u=0; u<nRec; u++){
  40868. if( needPagerReset ){
  40869. pager_reset(pPager);
  40870. needPagerReset = 0;
  40871. }
  40872. rc = pager_playback_one_page(pPager,&pPager->journalOff,0,1,0);
  40873. if( rc==SQLITE_OK ){
  40874. nPlayback++;
  40875. }else{
  40876. if( rc==SQLITE_DONE ){
  40877. pPager->journalOff = szJ;
  40878. break;
  40879. }else if( rc==SQLITE_IOERR_SHORT_READ ){
  40880. /* If the journal has been truncated, simply stop reading and
  40881. ** processing the journal. This might happen if the journal was
  40882. ** not completely written and synced prior to a crash. In that
  40883. ** case, the database should have never been written in the
  40884. ** first place so it is OK to simply abandon the rollback. */
  40885. rc = SQLITE_OK;
  40886. goto end_playback;
  40887. }else{
  40888. /* If we are unable to rollback, quit and return the error
  40889. ** code. This will cause the pager to enter the error state
  40890. ** so that no further harm will be done. Perhaps the next
  40891. ** process to come along will be able to rollback the database.
  40892. */
  40893. goto end_playback;
  40894. }
  40895. }
  40896. }
  40897. }
  40898. /*NOTREACHED*/
  40899. assert( 0 );
  40900. end_playback:
  40901. /* Following a rollback, the database file should be back in its original
  40902. ** state prior to the start of the transaction, so invoke the
  40903. ** SQLITE_FCNTL_DB_UNCHANGED file-control method to disable the
  40904. ** assertion that the transaction counter was modified.
  40905. */
  40906. #ifdef SQLITE_DEBUG
  40907. if( pPager->fd->pMethods ){
  40908. sqlite3OsFileControlHint(pPager->fd,SQLITE_FCNTL_DB_UNCHANGED,0);
  40909. }
  40910. #endif
  40911. /* If this playback is happening automatically as a result of an IO or
  40912. ** malloc error that occurred after the change-counter was updated but
  40913. ** before the transaction was committed, then the change-counter
  40914. ** modification may just have been reverted. If this happens in exclusive
  40915. ** mode, then subsequent transactions performed by the connection will not
  40916. ** update the change-counter at all. This may lead to cache inconsistency
  40917. ** problems for other processes at some point in the future. So, just
  40918. ** in case this has happened, clear the changeCountDone flag now.
  40919. */
  40920. pPager->changeCountDone = pPager->tempFile;
  40921. if( rc==SQLITE_OK ){
  40922. zMaster = pPager->pTmpSpace;
  40923. rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
  40924. testcase( rc!=SQLITE_OK );
  40925. }
  40926. if( rc==SQLITE_OK
  40927. && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
  40928. ){
  40929. rc = sqlite3PagerSync(pPager, 0);
  40930. }
  40931. if( rc==SQLITE_OK ){
  40932. rc = pager_end_transaction(pPager, zMaster[0]!='\0', 0);
  40933. testcase( rc!=SQLITE_OK );
  40934. }
  40935. if( rc==SQLITE_OK && zMaster[0] && res ){
  40936. /* If there was a master journal and this routine will return success,
  40937. ** see if it is possible to delete the master journal.
  40938. */
  40939. rc = pager_delmaster(pPager, zMaster);
  40940. testcase( rc!=SQLITE_OK );
  40941. }
  40942. if( isHot && nPlayback ){
  40943. sqlite3_log(SQLITE_NOTICE_RECOVER_ROLLBACK, "recovered %d pages from %s",
  40944. nPlayback, pPager->zJournal);
  40945. }
  40946. /* The Pager.sectorSize variable may have been updated while rolling
  40947. ** back a journal created by a process with a different sector size
  40948. ** value. Reset it to the correct value for this process.
  40949. */
  40950. setSectorSize(pPager);
  40951. return rc;
  40952. }
  40953. /*
  40954. ** Read the content for page pPg out of the database file and into
  40955. ** pPg->pData. A shared lock or greater must be held on the database
  40956. ** file before this function is called.
  40957. **
  40958. ** If page 1 is read, then the value of Pager.dbFileVers[] is set to
  40959. ** the value read from the database file.
  40960. **
  40961. ** If an IO error occurs, then the IO error is returned to the caller.
  40962. ** Otherwise, SQLITE_OK is returned.
  40963. */
  40964. static int readDbPage(PgHdr *pPg, u32 iFrame){
  40965. Pager *pPager = pPg->pPager; /* Pager object associated with page pPg */
  40966. Pgno pgno = pPg->pgno; /* Page number to read */
  40967. int rc = SQLITE_OK; /* Return code */
  40968. int pgsz = pPager->pageSize; /* Number of bytes to read */
  40969. assert( pPager->eState>=PAGER_READER && !MEMDB );
  40970. assert( isOpen(pPager->fd) );
  40971. #ifndef SQLITE_OMIT_WAL
  40972. if( iFrame ){
  40973. /* Try to pull the page from the write-ahead log. */
  40974. rc = sqlite3WalReadFrame(pPager->pWal, iFrame, pgsz, pPg->pData);
  40975. }else
  40976. #endif
  40977. {
  40978. i64 iOffset = (pgno-1)*(i64)pPager->pageSize;
  40979. rc = sqlite3OsRead(pPager->fd, pPg->pData, pgsz, iOffset);
  40980. if( rc==SQLITE_IOERR_SHORT_READ ){
  40981. rc = SQLITE_OK;
  40982. }
  40983. }
  40984. if( pgno==1 ){
  40985. if( rc ){
  40986. /* If the read is unsuccessful, set the dbFileVers[] to something
  40987. ** that will never be a valid file version. dbFileVers[] is a copy
  40988. ** of bytes 24..39 of the database. Bytes 28..31 should always be
  40989. ** zero or the size of the database in page. Bytes 32..35 and 35..39
  40990. ** should be page numbers which are never 0xffffffff. So filling
  40991. ** pPager->dbFileVers[] with all 0xff bytes should suffice.
  40992. **
  40993. ** For an encrypted database, the situation is more complex: bytes
  40994. ** 24..39 of the database are white noise. But the probability of
  40995. ** white noising equaling 16 bytes of 0xff is vanishingly small so
  40996. ** we should still be ok.
  40997. */
  40998. memset(pPager->dbFileVers, 0xff, sizeof(pPager->dbFileVers));
  40999. }else{
  41000. u8 *dbFileVers = &((u8*)pPg->pData)[24];
  41001. memcpy(&pPager->dbFileVers, dbFileVers, sizeof(pPager->dbFileVers));
  41002. }
  41003. }
  41004. CODEC1(pPager, pPg->pData, pgno, 3, rc = SQLITE_NOMEM);
  41005. PAGER_INCR(sqlite3_pager_readdb_count);
  41006. PAGER_INCR(pPager->nRead);
  41007. IOTRACE(("PGIN %p %d\n", pPager, pgno));
  41008. PAGERTRACE(("FETCH %d page %d hash(%08x)\n",
  41009. PAGERID(pPager), pgno, pager_pagehash(pPg)));
  41010. return rc;
  41011. }
  41012. /*
  41013. ** Update the value of the change-counter at offsets 24 and 92 in
  41014. ** the header and the sqlite version number at offset 96.
  41015. **
  41016. ** This is an unconditional update. See also the pager_incr_changecounter()
  41017. ** routine which only updates the change-counter if the update is actually
  41018. ** needed, as determined by the pPager->changeCountDone state variable.
  41019. */
  41020. static void pager_write_changecounter(PgHdr *pPg){
  41021. u32 change_counter;
  41022. /* Increment the value just read and write it back to byte 24. */
  41023. change_counter = sqlite3Get4byte((u8*)pPg->pPager->dbFileVers)+1;
  41024. put32bits(((char*)pPg->pData)+24, change_counter);
  41025. /* Also store the SQLite version number in bytes 96..99 and in
  41026. ** bytes 92..95 store the change counter for which the version number
  41027. ** is valid. */
  41028. put32bits(((char*)pPg->pData)+92, change_counter);
  41029. put32bits(((char*)pPg->pData)+96, SQLITE_VERSION_NUMBER);
  41030. }
  41031. #ifndef SQLITE_OMIT_WAL
  41032. /*
  41033. ** This function is invoked once for each page that has already been
  41034. ** written into the log file when a WAL transaction is rolled back.
  41035. ** Parameter iPg is the page number of said page. The pCtx argument
  41036. ** is actually a pointer to the Pager structure.
  41037. **
  41038. ** If page iPg is present in the cache, and has no outstanding references,
  41039. ** it is discarded. Otherwise, if there are one or more outstanding
  41040. ** references, the page content is reloaded from the database. If the
  41041. ** attempt to reload content from the database is required and fails,
  41042. ** return an SQLite error code. Otherwise, SQLITE_OK.
  41043. */
  41044. static int pagerUndoCallback(void *pCtx, Pgno iPg){
  41045. int rc = SQLITE_OK;
  41046. Pager *pPager = (Pager *)pCtx;
  41047. PgHdr *pPg;
  41048. assert( pagerUseWal(pPager) );
  41049. pPg = sqlite3PagerLookup(pPager, iPg);
  41050. if( pPg ){
  41051. if( sqlite3PcachePageRefcount(pPg)==1 ){
  41052. sqlite3PcacheDrop(pPg);
  41053. }else{
  41054. u32 iFrame = 0;
  41055. rc = sqlite3WalFindFrame(pPager->pWal, pPg->pgno, &iFrame);
  41056. if( rc==SQLITE_OK ){
  41057. rc = readDbPage(pPg, iFrame);
  41058. }
  41059. if( rc==SQLITE_OK ){
  41060. pPager->xReiniter(pPg);
  41061. }
  41062. sqlite3PagerUnrefNotNull(pPg);
  41063. }
  41064. }
  41065. /* Normally, if a transaction is rolled back, any backup processes are
  41066. ** updated as data is copied out of the rollback journal and into the
  41067. ** database. This is not generally possible with a WAL database, as
  41068. ** rollback involves simply truncating the log file. Therefore, if one
  41069. ** or more frames have already been written to the log (and therefore
  41070. ** also copied into the backup databases) as part of this transaction,
  41071. ** the backups must be restarted.
  41072. */
  41073. sqlite3BackupRestart(pPager->pBackup);
  41074. return rc;
  41075. }
  41076. /*
  41077. ** This function is called to rollback a transaction on a WAL database.
  41078. */
  41079. static int pagerRollbackWal(Pager *pPager){
  41080. int rc; /* Return Code */
  41081. PgHdr *pList; /* List of dirty pages to revert */
  41082. /* For all pages in the cache that are currently dirty or have already
  41083. ** been written (but not committed) to the log file, do one of the
  41084. ** following:
  41085. **
  41086. ** + Discard the cached page (if refcount==0), or
  41087. ** + Reload page content from the database (if refcount>0).
  41088. */
  41089. pPager->dbSize = pPager->dbOrigSize;
  41090. rc = sqlite3WalUndo(pPager->pWal, pagerUndoCallback, (void *)pPager);
  41091. pList = sqlite3PcacheDirtyList(pPager->pPCache);
  41092. while( pList && rc==SQLITE_OK ){
  41093. PgHdr *pNext = pList->pDirty;
  41094. rc = pagerUndoCallback((void *)pPager, pList->pgno);
  41095. pList = pNext;
  41096. }
  41097. return rc;
  41098. }
  41099. /*
  41100. ** This function is a wrapper around sqlite3WalFrames(). As well as logging
  41101. ** the contents of the list of pages headed by pList (connected by pDirty),
  41102. ** this function notifies any active backup processes that the pages have
  41103. ** changed.
  41104. **
  41105. ** The list of pages passed into this routine is always sorted by page number.
  41106. ** Hence, if page 1 appears anywhere on the list, it will be the first page.
  41107. */
  41108. static int pagerWalFrames(
  41109. Pager *pPager, /* Pager object */
  41110. PgHdr *pList, /* List of frames to log */
  41111. Pgno nTruncate, /* Database size after this commit */
  41112. int isCommit /* True if this is a commit */
  41113. ){
  41114. int rc; /* Return code */
  41115. int nList; /* Number of pages in pList */
  41116. #if defined(SQLITE_DEBUG) || defined(SQLITE_CHECK_PAGES)
  41117. PgHdr *p; /* For looping over pages */
  41118. #endif
  41119. assert( pPager->pWal );
  41120. assert( pList );
  41121. #ifdef SQLITE_DEBUG
  41122. /* Verify that the page list is in accending order */
  41123. for(p=pList; p && p->pDirty; p=p->pDirty){
  41124. assert( p->pgno < p->pDirty->pgno );
  41125. }
  41126. #endif
  41127. assert( pList->pDirty==0 || isCommit );
  41128. if( isCommit ){
  41129. /* If a WAL transaction is being committed, there is no point in writing
  41130. ** any pages with page numbers greater than nTruncate into the WAL file.
  41131. ** They will never be read by any client. So remove them from the pDirty
  41132. ** list here. */
  41133. PgHdr *p;
  41134. PgHdr **ppNext = &pList;
  41135. nList = 0;
  41136. for(p=pList; (*ppNext = p)!=0; p=p->pDirty){
  41137. if( p->pgno<=nTruncate ){
  41138. ppNext = &p->pDirty;
  41139. nList++;
  41140. }
  41141. }
  41142. assert( pList );
  41143. }else{
  41144. nList = 1;
  41145. }
  41146. pPager->aStat[PAGER_STAT_WRITE] += nList;
  41147. if( pList->pgno==1 ) pager_write_changecounter(pList);
  41148. rc = sqlite3WalFrames(pPager->pWal,
  41149. pPager->pageSize, pList, nTruncate, isCommit, pPager->walSyncFlags
  41150. );
  41151. if( rc==SQLITE_OK && pPager->pBackup ){
  41152. PgHdr *p;
  41153. for(p=pList; p; p=p->pDirty){
  41154. sqlite3BackupUpdate(pPager->pBackup, p->pgno, (u8 *)p->pData);
  41155. }
  41156. }
  41157. #ifdef SQLITE_CHECK_PAGES
  41158. pList = sqlite3PcacheDirtyList(pPager->pPCache);
  41159. for(p=pList; p; p=p->pDirty){
  41160. pager_set_pagehash(p);
  41161. }
  41162. #endif
  41163. return rc;
  41164. }
  41165. /*
  41166. ** Begin a read transaction on the WAL.
  41167. **
  41168. ** This routine used to be called "pagerOpenSnapshot()" because it essentially
  41169. ** makes a snapshot of the database at the current point in time and preserves
  41170. ** that snapshot for use by the reader in spite of concurrently changes by
  41171. ** other writers or checkpointers.
  41172. */
  41173. static int pagerBeginReadTransaction(Pager *pPager){
  41174. int rc; /* Return code */
  41175. int changed = 0; /* True if cache must be reset */
  41176. assert( pagerUseWal(pPager) );
  41177. assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
  41178. /* sqlite3WalEndReadTransaction() was not called for the previous
  41179. ** transaction in locking_mode=EXCLUSIVE. So call it now. If we
  41180. ** are in locking_mode=NORMAL and EndRead() was previously called,
  41181. ** the duplicate call is harmless.
  41182. */
  41183. sqlite3WalEndReadTransaction(pPager->pWal);
  41184. rc = sqlite3WalBeginReadTransaction(pPager->pWal, &changed);
  41185. if( rc!=SQLITE_OK || changed ){
  41186. pager_reset(pPager);
  41187. if( USEFETCH(pPager) ) sqlite3OsUnfetch(pPager->fd, 0, 0);
  41188. }
  41189. return rc;
  41190. }
  41191. #endif
  41192. /*
  41193. ** This function is called as part of the transition from PAGER_OPEN
  41194. ** to PAGER_READER state to determine the size of the database file
  41195. ** in pages (assuming the page size currently stored in Pager.pageSize).
  41196. **
  41197. ** If no error occurs, SQLITE_OK is returned and the size of the database
  41198. ** in pages is stored in *pnPage. Otherwise, an error code (perhaps
  41199. ** SQLITE_IOERR_FSTAT) is returned and *pnPage is left unmodified.
  41200. */
  41201. static int pagerPagecount(Pager *pPager, Pgno *pnPage){
  41202. Pgno nPage; /* Value to return via *pnPage */
  41203. /* Query the WAL sub-system for the database size. The WalDbsize()
  41204. ** function returns zero if the WAL is not open (i.e. Pager.pWal==0), or
  41205. ** if the database size is not available. The database size is not
  41206. ** available from the WAL sub-system if the log file is empty or
  41207. ** contains no valid committed transactions.
  41208. */
  41209. assert( pPager->eState==PAGER_OPEN );
  41210. assert( pPager->eLock>=SHARED_LOCK );
  41211. nPage = sqlite3WalDbsize(pPager->pWal);
  41212. /* If the database size was not available from the WAL sub-system,
  41213. ** determine it based on the size of the database file. If the size
  41214. ** of the database file is not an integer multiple of the page-size,
  41215. ** round down to the nearest page. Except, any file larger than 0
  41216. ** bytes in size is considered to contain at least one page.
  41217. */
  41218. if( nPage==0 ){
  41219. i64 n = 0; /* Size of db file in bytes */
  41220. assert( isOpen(pPager->fd) || pPager->tempFile );
  41221. if( isOpen(pPager->fd) ){
  41222. int rc = sqlite3OsFileSize(pPager->fd, &n);
  41223. if( rc!=SQLITE_OK ){
  41224. return rc;
  41225. }
  41226. }
  41227. nPage = (Pgno)((n+pPager->pageSize-1) / pPager->pageSize);
  41228. }
  41229. /* If the current number of pages in the file is greater than the
  41230. ** configured maximum pager number, increase the allowed limit so
  41231. ** that the file can be read.
  41232. */
  41233. if( nPage>pPager->mxPgno ){
  41234. pPager->mxPgno = (Pgno)nPage;
  41235. }
  41236. *pnPage = nPage;
  41237. return SQLITE_OK;
  41238. }
  41239. #ifndef SQLITE_OMIT_WAL
  41240. /*
  41241. ** Check if the *-wal file that corresponds to the database opened by pPager
  41242. ** exists if the database is not empy, or verify that the *-wal file does
  41243. ** not exist (by deleting it) if the database file is empty.
  41244. **
  41245. ** If the database is not empty and the *-wal file exists, open the pager
  41246. ** in WAL mode. If the database is empty or if no *-wal file exists and
  41247. ** if no error occurs, make sure Pager.journalMode is not set to
  41248. ** PAGER_JOURNALMODE_WAL.
  41249. **
  41250. ** Return SQLITE_OK or an error code.
  41251. **
  41252. ** The caller must hold a SHARED lock on the database file to call this
  41253. ** function. Because an EXCLUSIVE lock on the db file is required to delete
  41254. ** a WAL on a none-empty database, this ensures there is no race condition
  41255. ** between the xAccess() below and an xDelete() being executed by some
  41256. ** other connection.
  41257. */
  41258. static int pagerOpenWalIfPresent(Pager *pPager){
  41259. int rc = SQLITE_OK;
  41260. assert( pPager->eState==PAGER_OPEN );
  41261. assert( pPager->eLock>=SHARED_LOCK );
  41262. if( !pPager->tempFile ){
  41263. int isWal; /* True if WAL file exists */
  41264. Pgno nPage; /* Size of the database file */
  41265. rc = pagerPagecount(pPager, &nPage);
  41266. if( rc ) return rc;
  41267. if( nPage==0 ){
  41268. rc = sqlite3OsDelete(pPager->pVfs, pPager->zWal, 0);
  41269. if( rc==SQLITE_IOERR_DELETE_NOENT ) rc = SQLITE_OK;
  41270. isWal = 0;
  41271. }else{
  41272. rc = sqlite3OsAccess(
  41273. pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &isWal
  41274. );
  41275. }
  41276. if( rc==SQLITE_OK ){
  41277. if( isWal ){
  41278. testcase( sqlite3PcachePagecount(pPager->pPCache)==0 );
  41279. rc = sqlite3PagerOpenWal(pPager, 0);
  41280. }else if( pPager->journalMode==PAGER_JOURNALMODE_WAL ){
  41281. pPager->journalMode = PAGER_JOURNALMODE_DELETE;
  41282. }
  41283. }
  41284. }
  41285. return rc;
  41286. }
  41287. #endif
  41288. /*
  41289. ** Playback savepoint pSavepoint. Or, if pSavepoint==NULL, then playback
  41290. ** the entire master journal file. The case pSavepoint==NULL occurs when
  41291. ** a ROLLBACK TO command is invoked on a SAVEPOINT that is a transaction
  41292. ** savepoint.
  41293. **
  41294. ** When pSavepoint is not NULL (meaning a non-transaction savepoint is
  41295. ** being rolled back), then the rollback consists of up to three stages,
  41296. ** performed in the order specified:
  41297. **
  41298. ** * Pages are played back from the main journal starting at byte
  41299. ** offset PagerSavepoint.iOffset and continuing to
  41300. ** PagerSavepoint.iHdrOffset, or to the end of the main journal
  41301. ** file if PagerSavepoint.iHdrOffset is zero.
  41302. **
  41303. ** * If PagerSavepoint.iHdrOffset is not zero, then pages are played
  41304. ** back starting from the journal header immediately following
  41305. ** PagerSavepoint.iHdrOffset to the end of the main journal file.
  41306. **
  41307. ** * Pages are then played back from the sub-journal file, starting
  41308. ** with the PagerSavepoint.iSubRec and continuing to the end of
  41309. ** the journal file.
  41310. **
  41311. ** Throughout the rollback process, each time a page is rolled back, the
  41312. ** corresponding bit is set in a bitvec structure (variable pDone in the
  41313. ** implementation below). This is used to ensure that a page is only
  41314. ** rolled back the first time it is encountered in either journal.
  41315. **
  41316. ** If pSavepoint is NULL, then pages are only played back from the main
  41317. ** journal file. There is no need for a bitvec in this case.
  41318. **
  41319. ** In either case, before playback commences the Pager.dbSize variable
  41320. ** is reset to the value that it held at the start of the savepoint
  41321. ** (or transaction). No page with a page-number greater than this value
  41322. ** is played back. If one is encountered it is simply skipped.
  41323. */
  41324. static int pagerPlaybackSavepoint(Pager *pPager, PagerSavepoint *pSavepoint){
  41325. i64 szJ; /* Effective size of the main journal */
  41326. i64 iHdrOff; /* End of first segment of main-journal records */
  41327. int rc = SQLITE_OK; /* Return code */
  41328. Bitvec *pDone = 0; /* Bitvec to ensure pages played back only once */
  41329. assert( pPager->eState!=PAGER_ERROR );
  41330. assert( pPager->eState>=PAGER_WRITER_LOCKED );
  41331. /* Allocate a bitvec to use to store the set of pages rolled back */
  41332. if( pSavepoint ){
  41333. pDone = sqlite3BitvecCreate(pSavepoint->nOrig);
  41334. if( !pDone ){
  41335. return SQLITE_NOMEM;
  41336. }
  41337. }
  41338. /* Set the database size back to the value it was before the savepoint
  41339. ** being reverted was opened.
  41340. */
  41341. pPager->dbSize = pSavepoint ? pSavepoint->nOrig : pPager->dbOrigSize;
  41342. pPager->changeCountDone = pPager->tempFile;
  41343. if( !pSavepoint && pagerUseWal(pPager) ){
  41344. return pagerRollbackWal(pPager);
  41345. }
  41346. /* Use pPager->journalOff as the effective size of the main rollback
  41347. ** journal. The actual file might be larger than this in
  41348. ** PAGER_JOURNALMODE_TRUNCATE or PAGER_JOURNALMODE_PERSIST. But anything
  41349. ** past pPager->journalOff is off-limits to us.
  41350. */
  41351. szJ = pPager->journalOff;
  41352. assert( pagerUseWal(pPager)==0 || szJ==0 );
  41353. /* Begin by rolling back records from the main journal starting at
  41354. ** PagerSavepoint.iOffset and continuing to the next journal header.
  41355. ** There might be records in the main journal that have a page number
  41356. ** greater than the current database size (pPager->dbSize) but those
  41357. ** will be skipped automatically. Pages are added to pDone as they
  41358. ** are played back.
  41359. */
  41360. if( pSavepoint && !pagerUseWal(pPager) ){
  41361. iHdrOff = pSavepoint->iHdrOffset ? pSavepoint->iHdrOffset : szJ;
  41362. pPager->journalOff = pSavepoint->iOffset;
  41363. while( rc==SQLITE_OK && pPager->journalOff<iHdrOff ){
  41364. rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
  41365. }
  41366. assert( rc!=SQLITE_DONE );
  41367. }else{
  41368. pPager->journalOff = 0;
  41369. }
  41370. /* Continue rolling back records out of the main journal starting at
  41371. ** the first journal header seen and continuing until the effective end
  41372. ** of the main journal file. Continue to skip out-of-range pages and
  41373. ** continue adding pages rolled back to pDone.
  41374. */
  41375. while( rc==SQLITE_OK && pPager->journalOff<szJ ){
  41376. u32 ii; /* Loop counter */
  41377. u32 nJRec = 0; /* Number of Journal Records */
  41378. u32 dummy;
  41379. rc = readJournalHdr(pPager, 0, szJ, &nJRec, &dummy);
  41380. assert( rc!=SQLITE_DONE );
  41381. /*
  41382. ** The "pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff"
  41383. ** test is related to ticket #2565. See the discussion in the
  41384. ** pager_playback() function for additional information.
  41385. */
  41386. if( nJRec==0
  41387. && pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff
  41388. ){
  41389. nJRec = (u32)((szJ - pPager->journalOff)/JOURNAL_PG_SZ(pPager));
  41390. }
  41391. for(ii=0; rc==SQLITE_OK && ii<nJRec && pPager->journalOff<szJ; ii++){
  41392. rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
  41393. }
  41394. assert( rc!=SQLITE_DONE );
  41395. }
  41396. assert( rc!=SQLITE_OK || pPager->journalOff>=szJ );
  41397. /* Finally, rollback pages from the sub-journal. Page that were
  41398. ** previously rolled back out of the main journal (and are hence in pDone)
  41399. ** will be skipped. Out-of-range pages are also skipped.
  41400. */
  41401. if( pSavepoint ){
  41402. u32 ii; /* Loop counter */
  41403. i64 offset = (i64)pSavepoint->iSubRec*(4+pPager->pageSize);
  41404. if( pagerUseWal(pPager) ){
  41405. rc = sqlite3WalSavepointUndo(pPager->pWal, pSavepoint->aWalData);
  41406. }
  41407. for(ii=pSavepoint->iSubRec; rc==SQLITE_OK && ii<pPager->nSubRec; ii++){
  41408. assert( offset==(i64)ii*(4+pPager->pageSize) );
  41409. rc = pager_playback_one_page(pPager, &offset, pDone, 0, 1);
  41410. }
  41411. assert( rc!=SQLITE_DONE );
  41412. }
  41413. sqlite3BitvecDestroy(pDone);
  41414. if( rc==SQLITE_OK ){
  41415. pPager->journalOff = szJ;
  41416. }
  41417. return rc;
  41418. }
  41419. /*
  41420. ** Change the maximum number of in-memory pages that are allowed.
  41421. */
  41422. SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager *pPager, int mxPage){
  41423. sqlite3PcacheSetCachesize(pPager->pPCache, mxPage);
  41424. }
  41425. /*
  41426. ** Invoke SQLITE_FCNTL_MMAP_SIZE based on the current value of szMmap.
  41427. */
  41428. static void pagerFixMaplimit(Pager *pPager){
  41429. #if SQLITE_MAX_MMAP_SIZE>0
  41430. sqlite3_file *fd = pPager->fd;
  41431. if( isOpen(fd) && fd->pMethods->iVersion>=3 ){
  41432. sqlite3_int64 sz;
  41433. sz = pPager->szMmap;
  41434. pPager->bUseFetch = (sz>0);
  41435. sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_MMAP_SIZE, &sz);
  41436. }
  41437. #endif
  41438. }
  41439. /*
  41440. ** Change the maximum size of any memory mapping made of the database file.
  41441. */
  41442. SQLITE_PRIVATE void sqlite3PagerSetMmapLimit(Pager *pPager, sqlite3_int64 szMmap){
  41443. pPager->szMmap = szMmap;
  41444. pagerFixMaplimit(pPager);
  41445. }
  41446. /*
  41447. ** Free as much memory as possible from the pager.
  41448. */
  41449. SQLITE_PRIVATE void sqlite3PagerShrink(Pager *pPager){
  41450. sqlite3PcacheShrink(pPager->pPCache);
  41451. }
  41452. /*
  41453. ** Adjust settings of the pager to those specified in the pgFlags parameter.
  41454. **
  41455. ** The "level" in pgFlags & PAGER_SYNCHRONOUS_MASK sets the robustness
  41456. ** of the database to damage due to OS crashes or power failures by
  41457. ** changing the number of syncs()s when writing the journals.
  41458. ** There are three levels:
  41459. **
  41460. ** OFF sqlite3OsSync() is never called. This is the default
  41461. ** for temporary and transient files.
  41462. **
  41463. ** NORMAL The journal is synced once before writes begin on the
  41464. ** database. This is normally adequate protection, but
  41465. ** it is theoretically possible, though very unlikely,
  41466. ** that an inopertune power failure could leave the journal
  41467. ** in a state which would cause damage to the database
  41468. ** when it is rolled back.
  41469. **
  41470. ** FULL The journal is synced twice before writes begin on the
  41471. ** database (with some additional information - the nRec field
  41472. ** of the journal header - being written in between the two
  41473. ** syncs). If we assume that writing a
  41474. ** single disk sector is atomic, then this mode provides
  41475. ** assurance that the journal will not be corrupted to the
  41476. ** point of causing damage to the database during rollback.
  41477. **
  41478. ** The above is for a rollback-journal mode. For WAL mode, OFF continues
  41479. ** to mean that no syncs ever occur. NORMAL means that the WAL is synced
  41480. ** prior to the start of checkpoint and that the database file is synced
  41481. ** at the conclusion of the checkpoint if the entire content of the WAL
  41482. ** was written back into the database. But no sync operations occur for
  41483. ** an ordinary commit in NORMAL mode with WAL. FULL means that the WAL
  41484. ** file is synced following each commit operation, in addition to the
  41485. ** syncs associated with NORMAL.
  41486. **
  41487. ** Do not confuse synchronous=FULL with SQLITE_SYNC_FULL. The
  41488. ** SQLITE_SYNC_FULL macro means to use the MacOSX-style full-fsync
  41489. ** using fcntl(F_FULLFSYNC). SQLITE_SYNC_NORMAL means to do an
  41490. ** ordinary fsync() call. There is no difference between SQLITE_SYNC_FULL
  41491. ** and SQLITE_SYNC_NORMAL on platforms other than MacOSX. But the
  41492. ** synchronous=FULL versus synchronous=NORMAL setting determines when
  41493. ** the xSync primitive is called and is relevant to all platforms.
  41494. **
  41495. ** Numeric values associated with these states are OFF==1, NORMAL=2,
  41496. ** and FULL=3.
  41497. */
  41498. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  41499. SQLITE_PRIVATE void sqlite3PagerSetFlags(
  41500. Pager *pPager, /* The pager to set safety level for */
  41501. unsigned pgFlags /* Various flags */
  41502. ){
  41503. unsigned level = pgFlags & PAGER_SYNCHRONOUS_MASK;
  41504. assert( level>=1 && level<=3 );
  41505. pPager->noSync = (level==1 || pPager->tempFile) ?1:0;
  41506. pPager->fullSync = (level==3 && !pPager->tempFile) ?1:0;
  41507. if( pPager->noSync ){
  41508. pPager->syncFlags = 0;
  41509. pPager->ckptSyncFlags = 0;
  41510. }else if( pgFlags & PAGER_FULLFSYNC ){
  41511. pPager->syncFlags = SQLITE_SYNC_FULL;
  41512. pPager->ckptSyncFlags = SQLITE_SYNC_FULL;
  41513. }else if( pgFlags & PAGER_CKPT_FULLFSYNC ){
  41514. pPager->syncFlags = SQLITE_SYNC_NORMAL;
  41515. pPager->ckptSyncFlags = SQLITE_SYNC_FULL;
  41516. }else{
  41517. pPager->syncFlags = SQLITE_SYNC_NORMAL;
  41518. pPager->ckptSyncFlags = SQLITE_SYNC_NORMAL;
  41519. }
  41520. pPager->walSyncFlags = pPager->syncFlags;
  41521. if( pPager->fullSync ){
  41522. pPager->walSyncFlags |= WAL_SYNC_TRANSACTIONS;
  41523. }
  41524. if( pgFlags & PAGER_CACHESPILL ){
  41525. pPager->doNotSpill &= ~SPILLFLAG_OFF;
  41526. }else{
  41527. pPager->doNotSpill |= SPILLFLAG_OFF;
  41528. }
  41529. }
  41530. #endif
  41531. /*
  41532. ** The following global variable is incremented whenever the library
  41533. ** attempts to open a temporary file. This information is used for
  41534. ** testing and analysis only.
  41535. */
  41536. #ifdef SQLITE_TEST
  41537. SQLITE_API int sqlite3_opentemp_count = 0;
  41538. #endif
  41539. /*
  41540. ** Open a temporary file.
  41541. **
  41542. ** Write the file descriptor into *pFile. Return SQLITE_OK on success
  41543. ** or some other error code if we fail. The OS will automatically
  41544. ** delete the temporary file when it is closed.
  41545. **
  41546. ** The flags passed to the VFS layer xOpen() call are those specified
  41547. ** by parameter vfsFlags ORed with the following:
  41548. **
  41549. ** SQLITE_OPEN_READWRITE
  41550. ** SQLITE_OPEN_CREATE
  41551. ** SQLITE_OPEN_EXCLUSIVE
  41552. ** SQLITE_OPEN_DELETEONCLOSE
  41553. */
  41554. static int pagerOpentemp(
  41555. Pager *pPager, /* The pager object */
  41556. sqlite3_file *pFile, /* Write the file descriptor here */
  41557. int vfsFlags /* Flags passed through to the VFS */
  41558. ){
  41559. int rc; /* Return code */
  41560. #ifdef SQLITE_TEST
  41561. sqlite3_opentemp_count++; /* Used for testing and analysis only */
  41562. #endif
  41563. vfsFlags |= SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
  41564. SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE;
  41565. rc = sqlite3OsOpen(pPager->pVfs, 0, pFile, vfsFlags, 0);
  41566. assert( rc!=SQLITE_OK || isOpen(pFile) );
  41567. return rc;
  41568. }
  41569. /*
  41570. ** Set the busy handler function.
  41571. **
  41572. ** The pager invokes the busy-handler if sqlite3OsLock() returns
  41573. ** SQLITE_BUSY when trying to upgrade from no-lock to a SHARED lock,
  41574. ** or when trying to upgrade from a RESERVED lock to an EXCLUSIVE
  41575. ** lock. It does *not* invoke the busy handler when upgrading from
  41576. ** SHARED to RESERVED, or when upgrading from SHARED to EXCLUSIVE
  41577. ** (which occurs during hot-journal rollback). Summary:
  41578. **
  41579. ** Transition | Invokes xBusyHandler
  41580. ** --------------------------------------------------------
  41581. ** NO_LOCK -> SHARED_LOCK | Yes
  41582. ** SHARED_LOCK -> RESERVED_LOCK | No
  41583. ** SHARED_LOCK -> EXCLUSIVE_LOCK | No
  41584. ** RESERVED_LOCK -> EXCLUSIVE_LOCK | Yes
  41585. **
  41586. ** If the busy-handler callback returns non-zero, the lock is
  41587. ** retried. If it returns zero, then the SQLITE_BUSY error is
  41588. ** returned to the caller of the pager API function.
  41589. */
  41590. SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(
  41591. Pager *pPager, /* Pager object */
  41592. int (*xBusyHandler)(void *), /* Pointer to busy-handler function */
  41593. void *pBusyHandlerArg /* Argument to pass to xBusyHandler */
  41594. ){
  41595. pPager->xBusyHandler = xBusyHandler;
  41596. pPager->pBusyHandlerArg = pBusyHandlerArg;
  41597. if( isOpen(pPager->fd) ){
  41598. void **ap = (void **)&pPager->xBusyHandler;
  41599. assert( ((int(*)(void *))(ap[0]))==xBusyHandler );
  41600. assert( ap[1]==pBusyHandlerArg );
  41601. sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_BUSYHANDLER, (void *)ap);
  41602. }
  41603. }
  41604. /*
  41605. ** Change the page size used by the Pager object. The new page size
  41606. ** is passed in *pPageSize.
  41607. **
  41608. ** If the pager is in the error state when this function is called, it
  41609. ** is a no-op. The value returned is the error state error code (i.e.
  41610. ** one of SQLITE_IOERR, an SQLITE_IOERR_xxx sub-code or SQLITE_FULL).
  41611. **
  41612. ** Otherwise, if all of the following are true:
  41613. **
  41614. ** * the new page size (value of *pPageSize) is valid (a power
  41615. ** of two between 512 and SQLITE_MAX_PAGE_SIZE, inclusive), and
  41616. **
  41617. ** * there are no outstanding page references, and
  41618. **
  41619. ** * the database is either not an in-memory database or it is
  41620. ** an in-memory database that currently consists of zero pages.
  41621. **
  41622. ** then the pager object page size is set to *pPageSize.
  41623. **
  41624. ** If the page size is changed, then this function uses sqlite3PagerMalloc()
  41625. ** to obtain a new Pager.pTmpSpace buffer. If this allocation attempt
  41626. ** fails, SQLITE_NOMEM is returned and the page size remains unchanged.
  41627. ** In all other cases, SQLITE_OK is returned.
  41628. **
  41629. ** If the page size is not changed, either because one of the enumerated
  41630. ** conditions above is not true, the pager was in error state when this
  41631. ** function was called, or because the memory allocation attempt failed,
  41632. ** then *pPageSize is set to the old, retained page size before returning.
  41633. */
  41634. SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager *pPager, u32 *pPageSize, int nReserve){
  41635. int rc = SQLITE_OK;
  41636. /* It is not possible to do a full assert_pager_state() here, as this
  41637. ** function may be called from within PagerOpen(), before the state
  41638. ** of the Pager object is internally consistent.
  41639. **
  41640. ** At one point this function returned an error if the pager was in
  41641. ** PAGER_ERROR state. But since PAGER_ERROR state guarantees that
  41642. ** there is at least one outstanding page reference, this function
  41643. ** is a no-op for that case anyhow.
  41644. */
  41645. u32 pageSize = *pPageSize;
  41646. assert( pageSize==0 || (pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE) );
  41647. if( (pPager->memDb==0 || pPager->dbSize==0)
  41648. && sqlite3PcacheRefCount(pPager->pPCache)==0
  41649. && pageSize && pageSize!=(u32)pPager->pageSize
  41650. ){
  41651. char *pNew = NULL; /* New temp space */
  41652. i64 nByte = 0;
  41653. if( pPager->eState>PAGER_OPEN && isOpen(pPager->fd) ){
  41654. rc = sqlite3OsFileSize(pPager->fd, &nByte);
  41655. }
  41656. if( rc==SQLITE_OK ){
  41657. pNew = (char *)sqlite3PageMalloc(pageSize);
  41658. if( !pNew ) rc = SQLITE_NOMEM;
  41659. }
  41660. if( rc==SQLITE_OK ){
  41661. pager_reset(pPager);
  41662. rc = sqlite3PcacheSetPageSize(pPager->pPCache, pageSize);
  41663. }
  41664. if( rc==SQLITE_OK ){
  41665. sqlite3PageFree(pPager->pTmpSpace);
  41666. pPager->pTmpSpace = pNew;
  41667. pPager->dbSize = (Pgno)((nByte+pageSize-1)/pageSize);
  41668. pPager->pageSize = pageSize;
  41669. }else{
  41670. sqlite3PageFree(pNew);
  41671. }
  41672. }
  41673. *pPageSize = pPager->pageSize;
  41674. if( rc==SQLITE_OK ){
  41675. if( nReserve<0 ) nReserve = pPager->nReserve;
  41676. assert( nReserve>=0 && nReserve<1000 );
  41677. pPager->nReserve = (i16)nReserve;
  41678. pagerReportSize(pPager);
  41679. pagerFixMaplimit(pPager);
  41680. }
  41681. return rc;
  41682. }
  41683. /*
  41684. ** Return a pointer to the "temporary page" buffer held internally
  41685. ** by the pager. This is a buffer that is big enough to hold the
  41686. ** entire content of a database page. This buffer is used internally
  41687. ** during rollback and will be overwritten whenever a rollback
  41688. ** occurs. But other modules are free to use it too, as long as
  41689. ** no rollbacks are happening.
  41690. */
  41691. SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager *pPager){
  41692. return pPager->pTmpSpace;
  41693. }
  41694. /*
  41695. ** Attempt to set the maximum database page count if mxPage is positive.
  41696. ** Make no changes if mxPage is zero or negative. And never reduce the
  41697. ** maximum page count below the current size of the database.
  41698. **
  41699. ** Regardless of mxPage, return the current maximum page count.
  41700. */
  41701. SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager *pPager, int mxPage){
  41702. if( mxPage>0 ){
  41703. pPager->mxPgno = mxPage;
  41704. }
  41705. assert( pPager->eState!=PAGER_OPEN ); /* Called only by OP_MaxPgcnt */
  41706. assert( pPager->mxPgno>=pPager->dbSize ); /* OP_MaxPgcnt enforces this */
  41707. return pPager->mxPgno;
  41708. }
  41709. /*
  41710. ** The following set of routines are used to disable the simulated
  41711. ** I/O error mechanism. These routines are used to avoid simulated
  41712. ** errors in places where we do not care about errors.
  41713. **
  41714. ** Unless -DSQLITE_TEST=1 is used, these routines are all no-ops
  41715. ** and generate no code.
  41716. */
  41717. #ifdef SQLITE_TEST
  41718. SQLITE_API extern int sqlite3_io_error_pending;
  41719. SQLITE_API extern int sqlite3_io_error_hit;
  41720. static int saved_cnt;
  41721. void disable_simulated_io_errors(void){
  41722. saved_cnt = sqlite3_io_error_pending;
  41723. sqlite3_io_error_pending = -1;
  41724. }
  41725. void enable_simulated_io_errors(void){
  41726. sqlite3_io_error_pending = saved_cnt;
  41727. }
  41728. #else
  41729. # define disable_simulated_io_errors()
  41730. # define enable_simulated_io_errors()
  41731. #endif
  41732. /*
  41733. ** Read the first N bytes from the beginning of the file into memory
  41734. ** that pDest points to.
  41735. **
  41736. ** If the pager was opened on a transient file (zFilename==""), or
  41737. ** opened on a file less than N bytes in size, the output buffer is
  41738. ** zeroed and SQLITE_OK returned. The rationale for this is that this
  41739. ** function is used to read database headers, and a new transient or
  41740. ** zero sized database has a header than consists entirely of zeroes.
  41741. **
  41742. ** If any IO error apart from SQLITE_IOERR_SHORT_READ is encountered,
  41743. ** the error code is returned to the caller and the contents of the
  41744. ** output buffer undefined.
  41745. */
  41746. SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager *pPager, int N, unsigned char *pDest){
  41747. int rc = SQLITE_OK;
  41748. memset(pDest, 0, N);
  41749. assert( isOpen(pPager->fd) || pPager->tempFile );
  41750. /* This routine is only called by btree immediately after creating
  41751. ** the Pager object. There has not been an opportunity to transition
  41752. ** to WAL mode yet.
  41753. */
  41754. assert( !pagerUseWal(pPager) );
  41755. if( isOpen(pPager->fd) ){
  41756. IOTRACE(("DBHDR %p 0 %d\n", pPager, N))
  41757. rc = sqlite3OsRead(pPager->fd, pDest, N, 0);
  41758. if( rc==SQLITE_IOERR_SHORT_READ ){
  41759. rc = SQLITE_OK;
  41760. }
  41761. }
  41762. return rc;
  41763. }
  41764. /*
  41765. ** This function may only be called when a read-transaction is open on
  41766. ** the pager. It returns the total number of pages in the database.
  41767. **
  41768. ** However, if the file is between 1 and <page-size> bytes in size, then
  41769. ** this is considered a 1 page file.
  41770. */
  41771. SQLITE_PRIVATE void sqlite3PagerPagecount(Pager *pPager, int *pnPage){
  41772. assert( pPager->eState>=PAGER_READER );
  41773. assert( pPager->eState!=PAGER_WRITER_FINISHED );
  41774. *pnPage = (int)pPager->dbSize;
  41775. }
  41776. /*
  41777. ** Try to obtain a lock of type locktype on the database file. If
  41778. ** a similar or greater lock is already held, this function is a no-op
  41779. ** (returning SQLITE_OK immediately).
  41780. **
  41781. ** Otherwise, attempt to obtain the lock using sqlite3OsLock(). Invoke
  41782. ** the busy callback if the lock is currently not available. Repeat
  41783. ** until the busy callback returns false or until the attempt to
  41784. ** obtain the lock succeeds.
  41785. **
  41786. ** Return SQLITE_OK on success and an error code if we cannot obtain
  41787. ** the lock. If the lock is obtained successfully, set the Pager.state
  41788. ** variable to locktype before returning.
  41789. */
  41790. static int pager_wait_on_lock(Pager *pPager, int locktype){
  41791. int rc; /* Return code */
  41792. /* Check that this is either a no-op (because the requested lock is
  41793. ** already held), or one of the transitions that the busy-handler
  41794. ** may be invoked during, according to the comment above
  41795. ** sqlite3PagerSetBusyhandler().
  41796. */
  41797. assert( (pPager->eLock>=locktype)
  41798. || (pPager->eLock==NO_LOCK && locktype==SHARED_LOCK)
  41799. || (pPager->eLock==RESERVED_LOCK && locktype==EXCLUSIVE_LOCK)
  41800. );
  41801. do {
  41802. rc = pagerLockDb(pPager, locktype);
  41803. }while( rc==SQLITE_BUSY && pPager->xBusyHandler(pPager->pBusyHandlerArg) );
  41804. return rc;
  41805. }
  41806. /*
  41807. ** Function assertTruncateConstraint(pPager) checks that one of the
  41808. ** following is true for all dirty pages currently in the page-cache:
  41809. **
  41810. ** a) The page number is less than or equal to the size of the
  41811. ** current database image, in pages, OR
  41812. **
  41813. ** b) if the page content were written at this time, it would not
  41814. ** be necessary to write the current content out to the sub-journal
  41815. ** (as determined by function subjRequiresPage()).
  41816. **
  41817. ** If the condition asserted by this function were not true, and the
  41818. ** dirty page were to be discarded from the cache via the pagerStress()
  41819. ** routine, pagerStress() would not write the current page content to
  41820. ** the database file. If a savepoint transaction were rolled back after
  41821. ** this happened, the correct behavior would be to restore the current
  41822. ** content of the page. However, since this content is not present in either
  41823. ** the database file or the portion of the rollback journal and
  41824. ** sub-journal rolled back the content could not be restored and the
  41825. ** database image would become corrupt. It is therefore fortunate that
  41826. ** this circumstance cannot arise.
  41827. */
  41828. #if defined(SQLITE_DEBUG)
  41829. static void assertTruncateConstraintCb(PgHdr *pPg){
  41830. assert( pPg->flags&PGHDR_DIRTY );
  41831. assert( !subjRequiresPage(pPg) || pPg->pgno<=pPg->pPager->dbSize );
  41832. }
  41833. static void assertTruncateConstraint(Pager *pPager){
  41834. sqlite3PcacheIterateDirty(pPager->pPCache, assertTruncateConstraintCb);
  41835. }
  41836. #else
  41837. # define assertTruncateConstraint(pPager)
  41838. #endif
  41839. /*
  41840. ** Truncate the in-memory database file image to nPage pages. This
  41841. ** function does not actually modify the database file on disk. It
  41842. ** just sets the internal state of the pager object so that the
  41843. ** truncation will be done when the current transaction is committed.
  41844. **
  41845. ** This function is only called right before committing a transaction.
  41846. ** Once this function has been called, the transaction must either be
  41847. ** rolled back or committed. It is not safe to call this function and
  41848. ** then continue writing to the database.
  41849. */
  41850. SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager *pPager, Pgno nPage){
  41851. assert( pPager->dbSize>=nPage );
  41852. assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
  41853. pPager->dbSize = nPage;
  41854. /* At one point the code here called assertTruncateConstraint() to
  41855. ** ensure that all pages being truncated away by this operation are,
  41856. ** if one or more savepoints are open, present in the savepoint
  41857. ** journal so that they can be restored if the savepoint is rolled
  41858. ** back. This is no longer necessary as this function is now only
  41859. ** called right before committing a transaction. So although the
  41860. ** Pager object may still have open savepoints (Pager.nSavepoint!=0),
  41861. ** they cannot be rolled back. So the assertTruncateConstraint() call
  41862. ** is no longer correct. */
  41863. }
  41864. /*
  41865. ** This function is called before attempting a hot-journal rollback. It
  41866. ** syncs the journal file to disk, then sets pPager->journalHdr to the
  41867. ** size of the journal file so that the pager_playback() routine knows
  41868. ** that the entire journal file has been synced.
  41869. **
  41870. ** Syncing a hot-journal to disk before attempting to roll it back ensures
  41871. ** that if a power-failure occurs during the rollback, the process that
  41872. ** attempts rollback following system recovery sees the same journal
  41873. ** content as this process.
  41874. **
  41875. ** If everything goes as planned, SQLITE_OK is returned. Otherwise,
  41876. ** an SQLite error code.
  41877. */
  41878. static int pagerSyncHotJournal(Pager *pPager){
  41879. int rc = SQLITE_OK;
  41880. if( !pPager->noSync ){
  41881. rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_NORMAL);
  41882. }
  41883. if( rc==SQLITE_OK ){
  41884. rc = sqlite3OsFileSize(pPager->jfd, &pPager->journalHdr);
  41885. }
  41886. return rc;
  41887. }
  41888. /*
  41889. ** Obtain a reference to a memory mapped page object for page number pgno.
  41890. ** The new object will use the pointer pData, obtained from xFetch().
  41891. ** If successful, set *ppPage to point to the new page reference
  41892. ** and return SQLITE_OK. Otherwise, return an SQLite error code and set
  41893. ** *ppPage to zero.
  41894. **
  41895. ** Page references obtained by calling this function should be released
  41896. ** by calling pagerReleaseMapPage().
  41897. */
  41898. static int pagerAcquireMapPage(
  41899. Pager *pPager, /* Pager object */
  41900. Pgno pgno, /* Page number */
  41901. void *pData, /* xFetch()'d data for this page */
  41902. PgHdr **ppPage /* OUT: Acquired page object */
  41903. ){
  41904. PgHdr *p; /* Memory mapped page to return */
  41905. if( pPager->pMmapFreelist ){
  41906. *ppPage = p = pPager->pMmapFreelist;
  41907. pPager->pMmapFreelist = p->pDirty;
  41908. p->pDirty = 0;
  41909. memset(p->pExtra, 0, pPager->nExtra);
  41910. }else{
  41911. *ppPage = p = (PgHdr *)sqlite3MallocZero(sizeof(PgHdr) + pPager->nExtra);
  41912. if( p==0 ){
  41913. sqlite3OsUnfetch(pPager->fd, (i64)(pgno-1) * pPager->pageSize, pData);
  41914. return SQLITE_NOMEM;
  41915. }
  41916. p->pExtra = (void *)&p[1];
  41917. p->flags = PGHDR_MMAP;
  41918. p->nRef = 1;
  41919. p->pPager = pPager;
  41920. }
  41921. assert( p->pExtra==(void *)&p[1] );
  41922. assert( p->pPage==0 );
  41923. assert( p->flags==PGHDR_MMAP );
  41924. assert( p->pPager==pPager );
  41925. assert( p->nRef==1 );
  41926. p->pgno = pgno;
  41927. p->pData = pData;
  41928. pPager->nMmapOut++;
  41929. return SQLITE_OK;
  41930. }
  41931. /*
  41932. ** Release a reference to page pPg. pPg must have been returned by an
  41933. ** earlier call to pagerAcquireMapPage().
  41934. */
  41935. static void pagerReleaseMapPage(PgHdr *pPg){
  41936. Pager *pPager = pPg->pPager;
  41937. pPager->nMmapOut--;
  41938. pPg->pDirty = pPager->pMmapFreelist;
  41939. pPager->pMmapFreelist = pPg;
  41940. assert( pPager->fd->pMethods->iVersion>=3 );
  41941. sqlite3OsUnfetch(pPager->fd, (i64)(pPg->pgno-1)*pPager->pageSize, pPg->pData);
  41942. }
  41943. /*
  41944. ** Free all PgHdr objects stored in the Pager.pMmapFreelist list.
  41945. */
  41946. static void pagerFreeMapHdrs(Pager *pPager){
  41947. PgHdr *p;
  41948. PgHdr *pNext;
  41949. for(p=pPager->pMmapFreelist; p; p=pNext){
  41950. pNext = p->pDirty;
  41951. sqlite3_free(p);
  41952. }
  41953. }
  41954. /*
  41955. ** Shutdown the page cache. Free all memory and close all files.
  41956. **
  41957. ** If a transaction was in progress when this routine is called, that
  41958. ** transaction is rolled back. All outstanding pages are invalidated
  41959. ** and their memory is freed. Any attempt to use a page associated
  41960. ** with this page cache after this function returns will likely
  41961. ** result in a coredump.
  41962. **
  41963. ** This function always succeeds. If a transaction is active an attempt
  41964. ** is made to roll it back. If an error occurs during the rollback
  41965. ** a hot journal may be left in the filesystem but no error is returned
  41966. ** to the caller.
  41967. */
  41968. SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager){
  41969. u8 *pTmp = (u8 *)pPager->pTmpSpace;
  41970. assert( assert_pager_state(pPager) );
  41971. disable_simulated_io_errors();
  41972. sqlite3BeginBenignMalloc();
  41973. pagerFreeMapHdrs(pPager);
  41974. /* pPager->errCode = 0; */
  41975. pPager->exclusiveMode = 0;
  41976. #ifndef SQLITE_OMIT_WAL
  41977. sqlite3WalClose(pPager->pWal, pPager->ckptSyncFlags, pPager->pageSize, pTmp);
  41978. pPager->pWal = 0;
  41979. #endif
  41980. pager_reset(pPager);
  41981. if( MEMDB ){
  41982. pager_unlock(pPager);
  41983. }else{
  41984. /* If it is open, sync the journal file before calling UnlockAndRollback.
  41985. ** If this is not done, then an unsynced portion of the open journal
  41986. ** file may be played back into the database. If a power failure occurs
  41987. ** while this is happening, the database could become corrupt.
  41988. **
  41989. ** If an error occurs while trying to sync the journal, shift the pager
  41990. ** into the ERROR state. This causes UnlockAndRollback to unlock the
  41991. ** database and close the journal file without attempting to roll it
  41992. ** back or finalize it. The next database user will have to do hot-journal
  41993. ** rollback before accessing the database file.
  41994. */
  41995. if( isOpen(pPager->jfd) ){
  41996. pager_error(pPager, pagerSyncHotJournal(pPager));
  41997. }
  41998. pagerUnlockAndRollback(pPager);
  41999. }
  42000. sqlite3EndBenignMalloc();
  42001. enable_simulated_io_errors();
  42002. PAGERTRACE(("CLOSE %d\n", PAGERID(pPager)));
  42003. IOTRACE(("CLOSE %p\n", pPager))
  42004. sqlite3OsClose(pPager->jfd);
  42005. sqlite3OsClose(pPager->fd);
  42006. sqlite3PageFree(pTmp);
  42007. sqlite3PcacheClose(pPager->pPCache);
  42008. #ifdef SQLITE_HAS_CODEC
  42009. if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
  42010. #endif
  42011. assert( !pPager->aSavepoint && !pPager->pInJournal );
  42012. assert( !isOpen(pPager->jfd) && !isOpen(pPager->sjfd) );
  42013. sqlite3_free(pPager);
  42014. return SQLITE_OK;
  42015. }
  42016. #if !defined(NDEBUG) || defined(SQLITE_TEST)
  42017. /*
  42018. ** Return the page number for page pPg.
  42019. */
  42020. SQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage *pPg){
  42021. return pPg->pgno;
  42022. }
  42023. #endif
  42024. /*
  42025. ** Increment the reference count for page pPg.
  42026. */
  42027. SQLITE_PRIVATE void sqlite3PagerRef(DbPage *pPg){
  42028. sqlite3PcacheRef(pPg);
  42029. }
  42030. /*
  42031. ** Sync the journal. In other words, make sure all the pages that have
  42032. ** been written to the journal have actually reached the surface of the
  42033. ** disk and can be restored in the event of a hot-journal rollback.
  42034. **
  42035. ** If the Pager.noSync flag is set, then this function is a no-op.
  42036. ** Otherwise, the actions required depend on the journal-mode and the
  42037. ** device characteristics of the file-system, as follows:
  42038. **
  42039. ** * If the journal file is an in-memory journal file, no action need
  42040. ** be taken.
  42041. **
  42042. ** * Otherwise, if the device does not support the SAFE_APPEND property,
  42043. ** then the nRec field of the most recently written journal header
  42044. ** is updated to contain the number of journal records that have
  42045. ** been written following it. If the pager is operating in full-sync
  42046. ** mode, then the journal file is synced before this field is updated.
  42047. **
  42048. ** * If the device does not support the SEQUENTIAL property, then
  42049. ** journal file is synced.
  42050. **
  42051. ** Or, in pseudo-code:
  42052. **
  42053. ** if( NOT <in-memory journal> ){
  42054. ** if( NOT SAFE_APPEND ){
  42055. ** if( <full-sync mode> ) xSync(<journal file>);
  42056. ** <update nRec field>
  42057. ** }
  42058. ** if( NOT SEQUENTIAL ) xSync(<journal file>);
  42059. ** }
  42060. **
  42061. ** If successful, this routine clears the PGHDR_NEED_SYNC flag of every
  42062. ** page currently held in memory before returning SQLITE_OK. If an IO
  42063. ** error is encountered, then the IO error code is returned to the caller.
  42064. */
  42065. static int syncJournal(Pager *pPager, int newHdr){
  42066. int rc; /* Return code */
  42067. assert( pPager->eState==PAGER_WRITER_CACHEMOD
  42068. || pPager->eState==PAGER_WRITER_DBMOD
  42069. );
  42070. assert( assert_pager_state(pPager) );
  42071. assert( !pagerUseWal(pPager) );
  42072. rc = sqlite3PagerExclusiveLock(pPager);
  42073. if( rc!=SQLITE_OK ) return rc;
  42074. if( !pPager->noSync ){
  42075. assert( !pPager->tempFile );
  42076. if( isOpen(pPager->jfd) && pPager->journalMode!=PAGER_JOURNALMODE_MEMORY ){
  42077. const int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
  42078. assert( isOpen(pPager->jfd) );
  42079. if( 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
  42080. /* This block deals with an obscure problem. If the last connection
  42081. ** that wrote to this database was operating in persistent-journal
  42082. ** mode, then the journal file may at this point actually be larger
  42083. ** than Pager.journalOff bytes. If the next thing in the journal
  42084. ** file happens to be a journal-header (written as part of the
  42085. ** previous connection's transaction), and a crash or power-failure
  42086. ** occurs after nRec is updated but before this connection writes
  42087. ** anything else to the journal file (or commits/rolls back its
  42088. ** transaction), then SQLite may become confused when doing the
  42089. ** hot-journal rollback following recovery. It may roll back all
  42090. ** of this connections data, then proceed to rolling back the old,
  42091. ** out-of-date data that follows it. Database corruption.
  42092. **
  42093. ** To work around this, if the journal file does appear to contain
  42094. ** a valid header following Pager.journalOff, then write a 0x00
  42095. ** byte to the start of it to prevent it from being recognized.
  42096. **
  42097. ** Variable iNextHdrOffset is set to the offset at which this
  42098. ** problematic header will occur, if it exists. aMagic is used
  42099. ** as a temporary buffer to inspect the first couple of bytes of
  42100. ** the potential journal header.
  42101. */
  42102. i64 iNextHdrOffset;
  42103. u8 aMagic[8];
  42104. u8 zHeader[sizeof(aJournalMagic)+4];
  42105. memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
  42106. put32bits(&zHeader[sizeof(aJournalMagic)], pPager->nRec);
  42107. iNextHdrOffset = journalHdrOffset(pPager);
  42108. rc = sqlite3OsRead(pPager->jfd, aMagic, 8, iNextHdrOffset);
  42109. if( rc==SQLITE_OK && 0==memcmp(aMagic, aJournalMagic, 8) ){
  42110. static const u8 zerobyte = 0;
  42111. rc = sqlite3OsWrite(pPager->jfd, &zerobyte, 1, iNextHdrOffset);
  42112. }
  42113. if( rc!=SQLITE_OK && rc!=SQLITE_IOERR_SHORT_READ ){
  42114. return rc;
  42115. }
  42116. /* Write the nRec value into the journal file header. If in
  42117. ** full-synchronous mode, sync the journal first. This ensures that
  42118. ** all data has really hit the disk before nRec is updated to mark
  42119. ** it as a candidate for rollback.
  42120. **
  42121. ** This is not required if the persistent media supports the
  42122. ** SAFE_APPEND property. Because in this case it is not possible
  42123. ** for garbage data to be appended to the file, the nRec field
  42124. ** is populated with 0xFFFFFFFF when the journal header is written
  42125. ** and never needs to be updated.
  42126. */
  42127. if( pPager->fullSync && 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
  42128. PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
  42129. IOTRACE(("JSYNC %p\n", pPager))
  42130. rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags);
  42131. if( rc!=SQLITE_OK ) return rc;
  42132. }
  42133. IOTRACE(("JHDR %p %lld\n", pPager, pPager->journalHdr));
  42134. rc = sqlite3OsWrite(
  42135. pPager->jfd, zHeader, sizeof(zHeader), pPager->journalHdr
  42136. );
  42137. if( rc!=SQLITE_OK ) return rc;
  42138. }
  42139. if( 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
  42140. PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
  42141. IOTRACE(("JSYNC %p\n", pPager))
  42142. rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags|
  42143. (pPager->syncFlags==SQLITE_SYNC_FULL?SQLITE_SYNC_DATAONLY:0)
  42144. );
  42145. if( rc!=SQLITE_OK ) return rc;
  42146. }
  42147. pPager->journalHdr = pPager->journalOff;
  42148. if( newHdr && 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
  42149. pPager->nRec = 0;
  42150. rc = writeJournalHdr(pPager);
  42151. if( rc!=SQLITE_OK ) return rc;
  42152. }
  42153. }else{
  42154. pPager->journalHdr = pPager->journalOff;
  42155. }
  42156. }
  42157. /* Unless the pager is in noSync mode, the journal file was just
  42158. ** successfully synced. Either way, clear the PGHDR_NEED_SYNC flag on
  42159. ** all pages.
  42160. */
  42161. sqlite3PcacheClearSyncFlags(pPager->pPCache);
  42162. pPager->eState = PAGER_WRITER_DBMOD;
  42163. assert( assert_pager_state(pPager) );
  42164. return SQLITE_OK;
  42165. }
  42166. /*
  42167. ** The argument is the first in a linked list of dirty pages connected
  42168. ** by the PgHdr.pDirty pointer. This function writes each one of the
  42169. ** in-memory pages in the list to the database file. The argument may
  42170. ** be NULL, representing an empty list. In this case this function is
  42171. ** a no-op.
  42172. **
  42173. ** The pager must hold at least a RESERVED lock when this function
  42174. ** is called. Before writing anything to the database file, this lock
  42175. ** is upgraded to an EXCLUSIVE lock. If the lock cannot be obtained,
  42176. ** SQLITE_BUSY is returned and no data is written to the database file.
  42177. **
  42178. ** If the pager is a temp-file pager and the actual file-system file
  42179. ** is not yet open, it is created and opened before any data is
  42180. ** written out.
  42181. **
  42182. ** Once the lock has been upgraded and, if necessary, the file opened,
  42183. ** the pages are written out to the database file in list order. Writing
  42184. ** a page is skipped if it meets either of the following criteria:
  42185. **
  42186. ** * The page number is greater than Pager.dbSize, or
  42187. ** * The PGHDR_DONT_WRITE flag is set on the page.
  42188. **
  42189. ** If writing out a page causes the database file to grow, Pager.dbFileSize
  42190. ** is updated accordingly. If page 1 is written out, then the value cached
  42191. ** in Pager.dbFileVers[] is updated to match the new value stored in
  42192. ** the database file.
  42193. **
  42194. ** If everything is successful, SQLITE_OK is returned. If an IO error
  42195. ** occurs, an IO error code is returned. Or, if the EXCLUSIVE lock cannot
  42196. ** be obtained, SQLITE_BUSY is returned.
  42197. */
  42198. static int pager_write_pagelist(Pager *pPager, PgHdr *pList){
  42199. int rc = SQLITE_OK; /* Return code */
  42200. /* This function is only called for rollback pagers in WRITER_DBMOD state. */
  42201. assert( !pagerUseWal(pPager) );
  42202. assert( pPager->eState==PAGER_WRITER_DBMOD );
  42203. assert( pPager->eLock==EXCLUSIVE_LOCK );
  42204. /* If the file is a temp-file has not yet been opened, open it now. It
  42205. ** is not possible for rc to be other than SQLITE_OK if this branch
  42206. ** is taken, as pager_wait_on_lock() is a no-op for temp-files.
  42207. */
  42208. if( !isOpen(pPager->fd) ){
  42209. assert( pPager->tempFile && rc==SQLITE_OK );
  42210. rc = pagerOpentemp(pPager, pPager->fd, pPager->vfsFlags);
  42211. }
  42212. /* Before the first write, give the VFS a hint of what the final
  42213. ** file size will be.
  42214. */
  42215. assert( rc!=SQLITE_OK || isOpen(pPager->fd) );
  42216. if( rc==SQLITE_OK
  42217. && pPager->dbHintSize<pPager->dbSize
  42218. && (pList->pDirty || pList->pgno>pPager->dbHintSize)
  42219. ){
  42220. sqlite3_int64 szFile = pPager->pageSize * (sqlite3_int64)pPager->dbSize;
  42221. sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_SIZE_HINT, &szFile);
  42222. pPager->dbHintSize = pPager->dbSize;
  42223. }
  42224. while( rc==SQLITE_OK && pList ){
  42225. Pgno pgno = pList->pgno;
  42226. /* If there are dirty pages in the page cache with page numbers greater
  42227. ** than Pager.dbSize, this means sqlite3PagerTruncateImage() was called to
  42228. ** make the file smaller (presumably by auto-vacuum code). Do not write
  42229. ** any such pages to the file.
  42230. **
  42231. ** Also, do not write out any page that has the PGHDR_DONT_WRITE flag
  42232. ** set (set by sqlite3PagerDontWrite()).
  42233. */
  42234. if( pgno<=pPager->dbSize && 0==(pList->flags&PGHDR_DONT_WRITE) ){
  42235. i64 offset = (pgno-1)*(i64)pPager->pageSize; /* Offset to write */
  42236. char *pData; /* Data to write */
  42237. assert( (pList->flags&PGHDR_NEED_SYNC)==0 );
  42238. if( pList->pgno==1 ) pager_write_changecounter(pList);
  42239. /* Encode the database */
  42240. CODEC2(pPager, pList->pData, pgno, 6, return SQLITE_NOMEM, pData);
  42241. /* Write out the page data. */
  42242. rc = sqlite3OsWrite(pPager->fd, pData, pPager->pageSize, offset);
  42243. /* If page 1 was just written, update Pager.dbFileVers to match
  42244. ** the value now stored in the database file. If writing this
  42245. ** page caused the database file to grow, update dbFileSize.
  42246. */
  42247. if( pgno==1 ){
  42248. memcpy(&pPager->dbFileVers, &pData[24], sizeof(pPager->dbFileVers));
  42249. }
  42250. if( pgno>pPager->dbFileSize ){
  42251. pPager->dbFileSize = pgno;
  42252. }
  42253. pPager->aStat[PAGER_STAT_WRITE]++;
  42254. /* Update any backup objects copying the contents of this pager. */
  42255. sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)pList->pData);
  42256. PAGERTRACE(("STORE %d page %d hash(%08x)\n",
  42257. PAGERID(pPager), pgno, pager_pagehash(pList)));
  42258. IOTRACE(("PGOUT %p %d\n", pPager, pgno));
  42259. PAGER_INCR(sqlite3_pager_writedb_count);
  42260. }else{
  42261. PAGERTRACE(("NOSTORE %d page %d\n", PAGERID(pPager), pgno));
  42262. }
  42263. pager_set_pagehash(pList);
  42264. pList = pList->pDirty;
  42265. }
  42266. return rc;
  42267. }
  42268. /*
  42269. ** Ensure that the sub-journal file is open. If it is already open, this
  42270. ** function is a no-op.
  42271. **
  42272. ** SQLITE_OK is returned if everything goes according to plan. An
  42273. ** SQLITE_IOERR_XXX error code is returned if a call to sqlite3OsOpen()
  42274. ** fails.
  42275. */
  42276. static int openSubJournal(Pager *pPager){
  42277. int rc = SQLITE_OK;
  42278. if( !isOpen(pPager->sjfd) ){
  42279. if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY || pPager->subjInMemory ){
  42280. sqlite3MemJournalOpen(pPager->sjfd);
  42281. }else{
  42282. rc = pagerOpentemp(pPager, pPager->sjfd, SQLITE_OPEN_SUBJOURNAL);
  42283. }
  42284. }
  42285. return rc;
  42286. }
  42287. /*
  42288. ** Append a record of the current state of page pPg to the sub-journal.
  42289. ** It is the callers responsibility to use subjRequiresPage() to check
  42290. ** that it is really required before calling this function.
  42291. **
  42292. ** If successful, set the bit corresponding to pPg->pgno in the bitvecs
  42293. ** for all open savepoints before returning.
  42294. **
  42295. ** This function returns SQLITE_OK if everything is successful, an IO
  42296. ** error code if the attempt to write to the sub-journal fails, or
  42297. ** SQLITE_NOMEM if a malloc fails while setting a bit in a savepoint
  42298. ** bitvec.
  42299. */
  42300. static int subjournalPage(PgHdr *pPg){
  42301. int rc = SQLITE_OK;
  42302. Pager *pPager = pPg->pPager;
  42303. if( pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
  42304. /* Open the sub-journal, if it has not already been opened */
  42305. assert( pPager->useJournal );
  42306. assert( isOpen(pPager->jfd) || pagerUseWal(pPager) );
  42307. assert( isOpen(pPager->sjfd) || pPager->nSubRec==0 );
  42308. assert( pagerUseWal(pPager)
  42309. || pageInJournal(pPager, pPg)
  42310. || pPg->pgno>pPager->dbOrigSize
  42311. );
  42312. rc = openSubJournal(pPager);
  42313. /* If the sub-journal was opened successfully (or was already open),
  42314. ** write the journal record into the file. */
  42315. if( rc==SQLITE_OK ){
  42316. void *pData = pPg->pData;
  42317. i64 offset = (i64)pPager->nSubRec*(4+pPager->pageSize);
  42318. char *pData2;
  42319. CODEC2(pPager, pData, pPg->pgno, 7, return SQLITE_NOMEM, pData2);
  42320. PAGERTRACE(("STMT-JOURNAL %d page %d\n", PAGERID(pPager), pPg->pgno));
  42321. rc = write32bits(pPager->sjfd, offset, pPg->pgno);
  42322. if( rc==SQLITE_OK ){
  42323. rc = sqlite3OsWrite(pPager->sjfd, pData2, pPager->pageSize, offset+4);
  42324. }
  42325. }
  42326. }
  42327. if( rc==SQLITE_OK ){
  42328. pPager->nSubRec++;
  42329. assert( pPager->nSavepoint>0 );
  42330. rc = addToSavepointBitvecs(pPager, pPg->pgno);
  42331. }
  42332. return rc;
  42333. }
  42334. /*
  42335. ** This function is called by the pcache layer when it has reached some
  42336. ** soft memory limit. The first argument is a pointer to a Pager object
  42337. ** (cast as a void*). The pager is always 'purgeable' (not an in-memory
  42338. ** database). The second argument is a reference to a page that is
  42339. ** currently dirty but has no outstanding references. The page
  42340. ** is always associated with the Pager object passed as the first
  42341. ** argument.
  42342. **
  42343. ** The job of this function is to make pPg clean by writing its contents
  42344. ** out to the database file, if possible. This may involve syncing the
  42345. ** journal file.
  42346. **
  42347. ** If successful, sqlite3PcacheMakeClean() is called on the page and
  42348. ** SQLITE_OK returned. If an IO error occurs while trying to make the
  42349. ** page clean, the IO error code is returned. If the page cannot be
  42350. ** made clean for some other reason, but no error occurs, then SQLITE_OK
  42351. ** is returned by sqlite3PcacheMakeClean() is not called.
  42352. */
  42353. static int pagerStress(void *p, PgHdr *pPg){
  42354. Pager *pPager = (Pager *)p;
  42355. int rc = SQLITE_OK;
  42356. assert( pPg->pPager==pPager );
  42357. assert( pPg->flags&PGHDR_DIRTY );
  42358. /* The doNotSpill NOSYNC bit is set during times when doing a sync of
  42359. ** journal (and adding a new header) is not allowed. This occurs
  42360. ** during calls to sqlite3PagerWrite() while trying to journal multiple
  42361. ** pages belonging to the same sector.
  42362. **
  42363. ** The doNotSpill ROLLBACK and OFF bits inhibits all cache spilling
  42364. ** regardless of whether or not a sync is required. This is set during
  42365. ** a rollback or by user request, respectively.
  42366. **
  42367. ** Spilling is also prohibited when in an error state since that could
  42368. ** lead to database corruption. In the current implementation it
  42369. ** is impossible for sqlite3PcacheFetch() to be called with createFlag==3
  42370. ** while in the error state, hence it is impossible for this routine to
  42371. ** be called in the error state. Nevertheless, we include a NEVER()
  42372. ** test for the error state as a safeguard against future changes.
  42373. */
  42374. if( NEVER(pPager->errCode) ) return SQLITE_OK;
  42375. testcase( pPager->doNotSpill & SPILLFLAG_ROLLBACK );
  42376. testcase( pPager->doNotSpill & SPILLFLAG_OFF );
  42377. testcase( pPager->doNotSpill & SPILLFLAG_NOSYNC );
  42378. if( pPager->doNotSpill
  42379. && ((pPager->doNotSpill & (SPILLFLAG_ROLLBACK|SPILLFLAG_OFF))!=0
  42380. || (pPg->flags & PGHDR_NEED_SYNC)!=0)
  42381. ){
  42382. return SQLITE_OK;
  42383. }
  42384. pPg->pDirty = 0;
  42385. if( pagerUseWal(pPager) ){
  42386. /* Write a single frame for this page to the log. */
  42387. if( subjRequiresPage(pPg) ){
  42388. rc = subjournalPage(pPg);
  42389. }
  42390. if( rc==SQLITE_OK ){
  42391. rc = pagerWalFrames(pPager, pPg, 0, 0);
  42392. }
  42393. }else{
  42394. /* Sync the journal file if required. */
  42395. if( pPg->flags&PGHDR_NEED_SYNC
  42396. || pPager->eState==PAGER_WRITER_CACHEMOD
  42397. ){
  42398. rc = syncJournal(pPager, 1);
  42399. }
  42400. /* If the page number of this page is larger than the current size of
  42401. ** the database image, it may need to be written to the sub-journal.
  42402. ** This is because the call to pager_write_pagelist() below will not
  42403. ** actually write data to the file in this case.
  42404. **
  42405. ** Consider the following sequence of events:
  42406. **
  42407. ** BEGIN;
  42408. ** <journal page X>
  42409. ** <modify page X>
  42410. ** SAVEPOINT sp;
  42411. ** <shrink database file to Y pages>
  42412. ** pagerStress(page X)
  42413. ** ROLLBACK TO sp;
  42414. **
  42415. ** If (X>Y), then when pagerStress is called page X will not be written
  42416. ** out to the database file, but will be dropped from the cache. Then,
  42417. ** following the "ROLLBACK TO sp" statement, reading page X will read
  42418. ** data from the database file. This will be the copy of page X as it
  42419. ** was when the transaction started, not as it was when "SAVEPOINT sp"
  42420. ** was executed.
  42421. **
  42422. ** The solution is to write the current data for page X into the
  42423. ** sub-journal file now (if it is not already there), so that it will
  42424. ** be restored to its current value when the "ROLLBACK TO sp" is
  42425. ** executed.
  42426. */
  42427. if( NEVER(
  42428. rc==SQLITE_OK && pPg->pgno>pPager->dbSize && subjRequiresPage(pPg)
  42429. ) ){
  42430. rc = subjournalPage(pPg);
  42431. }
  42432. /* Write the contents of the page out to the database file. */
  42433. if( rc==SQLITE_OK ){
  42434. assert( (pPg->flags&PGHDR_NEED_SYNC)==0 );
  42435. rc = pager_write_pagelist(pPager, pPg);
  42436. }
  42437. }
  42438. /* Mark the page as clean. */
  42439. if( rc==SQLITE_OK ){
  42440. PAGERTRACE(("STRESS %d page %d\n", PAGERID(pPager), pPg->pgno));
  42441. sqlite3PcacheMakeClean(pPg);
  42442. }
  42443. return pager_error(pPager, rc);
  42444. }
  42445. /*
  42446. ** Allocate and initialize a new Pager object and put a pointer to it
  42447. ** in *ppPager. The pager should eventually be freed by passing it
  42448. ** to sqlite3PagerClose().
  42449. **
  42450. ** The zFilename argument is the path to the database file to open.
  42451. ** If zFilename is NULL then a randomly-named temporary file is created
  42452. ** and used as the file to be cached. Temporary files are be deleted
  42453. ** automatically when they are closed. If zFilename is ":memory:" then
  42454. ** all information is held in cache. It is never written to disk.
  42455. ** This can be used to implement an in-memory database.
  42456. **
  42457. ** The nExtra parameter specifies the number of bytes of space allocated
  42458. ** along with each page reference. This space is available to the user
  42459. ** via the sqlite3PagerGetExtra() API.
  42460. **
  42461. ** The flags argument is used to specify properties that affect the
  42462. ** operation of the pager. It should be passed some bitwise combination
  42463. ** of the PAGER_* flags.
  42464. **
  42465. ** The vfsFlags parameter is a bitmask to pass to the flags parameter
  42466. ** of the xOpen() method of the supplied VFS when opening files.
  42467. **
  42468. ** If the pager object is allocated and the specified file opened
  42469. ** successfully, SQLITE_OK is returned and *ppPager set to point to
  42470. ** the new pager object. If an error occurs, *ppPager is set to NULL
  42471. ** and error code returned. This function may return SQLITE_NOMEM
  42472. ** (sqlite3Malloc() is used to allocate memory), SQLITE_CANTOPEN or
  42473. ** various SQLITE_IO_XXX errors.
  42474. */
  42475. SQLITE_PRIVATE int sqlite3PagerOpen(
  42476. sqlite3_vfs *pVfs, /* The virtual file system to use */
  42477. Pager **ppPager, /* OUT: Return the Pager structure here */
  42478. const char *zFilename, /* Name of the database file to open */
  42479. int nExtra, /* Extra bytes append to each in-memory page */
  42480. int flags, /* flags controlling this file */
  42481. int vfsFlags, /* flags passed through to sqlite3_vfs.xOpen() */
  42482. void (*xReinit)(DbPage*) /* Function to reinitialize pages */
  42483. ){
  42484. u8 *pPtr;
  42485. Pager *pPager = 0; /* Pager object to allocate and return */
  42486. int rc = SQLITE_OK; /* Return code */
  42487. int tempFile = 0; /* True for temp files (incl. in-memory files) */
  42488. int memDb = 0; /* True if this is an in-memory file */
  42489. int readOnly = 0; /* True if this is a read-only file */
  42490. int journalFileSize; /* Bytes to allocate for each journal fd */
  42491. char *zPathname = 0; /* Full path to database file */
  42492. int nPathname = 0; /* Number of bytes in zPathname */
  42493. int useJournal = (flags & PAGER_OMIT_JOURNAL)==0; /* False to omit journal */
  42494. int pcacheSize = sqlite3PcacheSize(); /* Bytes to allocate for PCache */
  42495. u32 szPageDflt = SQLITE_DEFAULT_PAGE_SIZE; /* Default page size */
  42496. const char *zUri = 0; /* URI args to copy */
  42497. int nUri = 0; /* Number of bytes of URI args at *zUri */
  42498. /* Figure out how much space is required for each journal file-handle
  42499. ** (there are two of them, the main journal and the sub-journal). This
  42500. ** is the maximum space required for an in-memory journal file handle
  42501. ** and a regular journal file-handle. Note that a "regular journal-handle"
  42502. ** may be a wrapper capable of caching the first portion of the journal
  42503. ** file in memory to implement the atomic-write optimization (see
  42504. ** source file journal.c).
  42505. */
  42506. if( sqlite3JournalSize(pVfs)>sqlite3MemJournalSize() ){
  42507. journalFileSize = ROUND8(sqlite3JournalSize(pVfs));
  42508. }else{
  42509. journalFileSize = ROUND8(sqlite3MemJournalSize());
  42510. }
  42511. /* Set the output variable to NULL in case an error occurs. */
  42512. *ppPager = 0;
  42513. #ifndef SQLITE_OMIT_MEMORYDB
  42514. if( flags & PAGER_MEMORY ){
  42515. memDb = 1;
  42516. if( zFilename && zFilename[0] ){
  42517. zPathname = sqlite3DbStrDup(0, zFilename);
  42518. if( zPathname==0 ) return SQLITE_NOMEM;
  42519. nPathname = sqlite3Strlen30(zPathname);
  42520. zFilename = 0;
  42521. }
  42522. }
  42523. #endif
  42524. /* Compute and store the full pathname in an allocated buffer pointed
  42525. ** to by zPathname, length nPathname. Or, if this is a temporary file,
  42526. ** leave both nPathname and zPathname set to 0.
  42527. */
  42528. if( zFilename && zFilename[0] ){
  42529. const char *z;
  42530. nPathname = pVfs->mxPathname+1;
  42531. zPathname = sqlite3DbMallocRaw(0, nPathname*2);
  42532. if( zPathname==0 ){
  42533. return SQLITE_NOMEM;
  42534. }
  42535. zPathname[0] = 0; /* Make sure initialized even if FullPathname() fails */
  42536. rc = sqlite3OsFullPathname(pVfs, zFilename, nPathname, zPathname);
  42537. nPathname = sqlite3Strlen30(zPathname);
  42538. z = zUri = &zFilename[sqlite3Strlen30(zFilename)+1];
  42539. while( *z ){
  42540. z += sqlite3Strlen30(z)+1;
  42541. z += sqlite3Strlen30(z)+1;
  42542. }
  42543. nUri = (int)(&z[1] - zUri);
  42544. assert( nUri>=0 );
  42545. if( rc==SQLITE_OK && nPathname+8>pVfs->mxPathname ){
  42546. /* This branch is taken when the journal path required by
  42547. ** the database being opened will be more than pVfs->mxPathname
  42548. ** bytes in length. This means the database cannot be opened,
  42549. ** as it will not be possible to open the journal file or even
  42550. ** check for a hot-journal before reading.
  42551. */
  42552. rc = SQLITE_CANTOPEN_BKPT;
  42553. }
  42554. if( rc!=SQLITE_OK ){
  42555. sqlite3DbFree(0, zPathname);
  42556. return rc;
  42557. }
  42558. }
  42559. /* Allocate memory for the Pager structure, PCache object, the
  42560. ** three file descriptors, the database file name and the journal
  42561. ** file name. The layout in memory is as follows:
  42562. **
  42563. ** Pager object (sizeof(Pager) bytes)
  42564. ** PCache object (sqlite3PcacheSize() bytes)
  42565. ** Database file handle (pVfs->szOsFile bytes)
  42566. ** Sub-journal file handle (journalFileSize bytes)
  42567. ** Main journal file handle (journalFileSize bytes)
  42568. ** Database file name (nPathname+1 bytes)
  42569. ** Journal file name (nPathname+8+1 bytes)
  42570. */
  42571. pPtr = (u8 *)sqlite3MallocZero(
  42572. ROUND8(sizeof(*pPager)) + /* Pager structure */
  42573. ROUND8(pcacheSize) + /* PCache object */
  42574. ROUND8(pVfs->szOsFile) + /* The main db file */
  42575. journalFileSize * 2 + /* The two journal files */
  42576. nPathname + 1 + nUri + /* zFilename */
  42577. nPathname + 8 + 2 /* zJournal */
  42578. #ifndef SQLITE_OMIT_WAL
  42579. + nPathname + 4 + 2 /* zWal */
  42580. #endif
  42581. );
  42582. assert( EIGHT_BYTE_ALIGNMENT(SQLITE_INT_TO_PTR(journalFileSize)) );
  42583. if( !pPtr ){
  42584. sqlite3DbFree(0, zPathname);
  42585. return SQLITE_NOMEM;
  42586. }
  42587. pPager = (Pager*)(pPtr);
  42588. pPager->pPCache = (PCache*)(pPtr += ROUND8(sizeof(*pPager)));
  42589. pPager->fd = (sqlite3_file*)(pPtr += ROUND8(pcacheSize));
  42590. pPager->sjfd = (sqlite3_file*)(pPtr += ROUND8(pVfs->szOsFile));
  42591. pPager->jfd = (sqlite3_file*)(pPtr += journalFileSize);
  42592. pPager->zFilename = (char*)(pPtr += journalFileSize);
  42593. assert( EIGHT_BYTE_ALIGNMENT(pPager->jfd) );
  42594. /* Fill in the Pager.zFilename and Pager.zJournal buffers, if required. */
  42595. if( zPathname ){
  42596. assert( nPathname>0 );
  42597. pPager->zJournal = (char*)(pPtr += nPathname + 1 + nUri);
  42598. memcpy(pPager->zFilename, zPathname, nPathname);
  42599. if( nUri ) memcpy(&pPager->zFilename[nPathname+1], zUri, nUri);
  42600. memcpy(pPager->zJournal, zPathname, nPathname);
  42601. memcpy(&pPager->zJournal[nPathname], "-journal\000", 8+2);
  42602. sqlite3FileSuffix3(pPager->zFilename, pPager->zJournal);
  42603. #ifndef SQLITE_OMIT_WAL
  42604. pPager->zWal = &pPager->zJournal[nPathname+8+1];
  42605. memcpy(pPager->zWal, zPathname, nPathname);
  42606. memcpy(&pPager->zWal[nPathname], "-wal\000", 4+1);
  42607. sqlite3FileSuffix3(pPager->zFilename, pPager->zWal);
  42608. #endif
  42609. sqlite3DbFree(0, zPathname);
  42610. }
  42611. pPager->pVfs = pVfs;
  42612. pPager->vfsFlags = vfsFlags;
  42613. /* Open the pager file.
  42614. */
  42615. if( zFilename && zFilename[0] ){
  42616. int fout = 0; /* VFS flags returned by xOpen() */
  42617. rc = sqlite3OsOpen(pVfs, pPager->zFilename, pPager->fd, vfsFlags, &fout);
  42618. assert( !memDb );
  42619. readOnly = (fout&SQLITE_OPEN_READONLY);
  42620. /* If the file was successfully opened for read/write access,
  42621. ** choose a default page size in case we have to create the
  42622. ** database file. The default page size is the maximum of:
  42623. **
  42624. ** + SQLITE_DEFAULT_PAGE_SIZE,
  42625. ** + The value returned by sqlite3OsSectorSize()
  42626. ** + The largest page size that can be written atomically.
  42627. */
  42628. if( rc==SQLITE_OK ){
  42629. int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
  42630. if( !readOnly ){
  42631. setSectorSize(pPager);
  42632. assert(SQLITE_DEFAULT_PAGE_SIZE<=SQLITE_MAX_DEFAULT_PAGE_SIZE);
  42633. if( szPageDflt<pPager->sectorSize ){
  42634. if( pPager->sectorSize>SQLITE_MAX_DEFAULT_PAGE_SIZE ){
  42635. szPageDflt = SQLITE_MAX_DEFAULT_PAGE_SIZE;
  42636. }else{
  42637. szPageDflt = (u32)pPager->sectorSize;
  42638. }
  42639. }
  42640. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  42641. {
  42642. int ii;
  42643. assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
  42644. assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
  42645. assert(SQLITE_MAX_DEFAULT_PAGE_SIZE<=65536);
  42646. for(ii=szPageDflt; ii<=SQLITE_MAX_DEFAULT_PAGE_SIZE; ii=ii*2){
  42647. if( iDc&(SQLITE_IOCAP_ATOMIC|(ii>>8)) ){
  42648. szPageDflt = ii;
  42649. }
  42650. }
  42651. }
  42652. #endif
  42653. }
  42654. pPager->noLock = sqlite3_uri_boolean(zFilename, "nolock", 0);
  42655. if( (iDc & SQLITE_IOCAP_IMMUTABLE)!=0
  42656. || sqlite3_uri_boolean(zFilename, "immutable", 0) ){
  42657. vfsFlags |= SQLITE_OPEN_READONLY;
  42658. goto act_like_temp_file;
  42659. }
  42660. }
  42661. }else{
  42662. /* If a temporary file is requested, it is not opened immediately.
  42663. ** In this case we accept the default page size and delay actually
  42664. ** opening the file until the first call to OsWrite().
  42665. **
  42666. ** This branch is also run for an in-memory database. An in-memory
  42667. ** database is the same as a temp-file that is never written out to
  42668. ** disk and uses an in-memory rollback journal.
  42669. **
  42670. ** This branch also runs for files marked as immutable.
  42671. */
  42672. act_like_temp_file:
  42673. tempFile = 1;
  42674. pPager->eState = PAGER_READER; /* Pretend we already have a lock */
  42675. pPager->eLock = EXCLUSIVE_LOCK; /* Pretend we are in EXCLUSIVE locking mode */
  42676. pPager->noLock = 1; /* Do no locking */
  42677. readOnly = (vfsFlags&SQLITE_OPEN_READONLY);
  42678. }
  42679. /* The following call to PagerSetPagesize() serves to set the value of
  42680. ** Pager.pageSize and to allocate the Pager.pTmpSpace buffer.
  42681. */
  42682. if( rc==SQLITE_OK ){
  42683. assert( pPager->memDb==0 );
  42684. rc = sqlite3PagerSetPagesize(pPager, &szPageDflt, -1);
  42685. testcase( rc!=SQLITE_OK );
  42686. }
  42687. /* Initialize the PCache object. */
  42688. if( rc==SQLITE_OK ){
  42689. assert( nExtra<1000 );
  42690. nExtra = ROUND8(nExtra);
  42691. rc = sqlite3PcacheOpen(szPageDflt, nExtra, !memDb,
  42692. !memDb?pagerStress:0, (void *)pPager, pPager->pPCache);
  42693. }
  42694. /* If an error occurred above, free the Pager structure and close the file.
  42695. */
  42696. if( rc!=SQLITE_OK ){
  42697. sqlite3OsClose(pPager->fd);
  42698. sqlite3PageFree(pPager->pTmpSpace);
  42699. sqlite3_free(pPager);
  42700. return rc;
  42701. }
  42702. PAGERTRACE(("OPEN %d %s\n", FILEHANDLEID(pPager->fd), pPager->zFilename));
  42703. IOTRACE(("OPEN %p %s\n", pPager, pPager->zFilename))
  42704. pPager->useJournal = (u8)useJournal;
  42705. /* pPager->stmtOpen = 0; */
  42706. /* pPager->stmtInUse = 0; */
  42707. /* pPager->nRef = 0; */
  42708. /* pPager->stmtSize = 0; */
  42709. /* pPager->stmtJSize = 0; */
  42710. /* pPager->nPage = 0; */
  42711. pPager->mxPgno = SQLITE_MAX_PAGE_COUNT;
  42712. /* pPager->state = PAGER_UNLOCK; */
  42713. /* pPager->errMask = 0; */
  42714. pPager->tempFile = (u8)tempFile;
  42715. assert( tempFile==PAGER_LOCKINGMODE_NORMAL
  42716. || tempFile==PAGER_LOCKINGMODE_EXCLUSIVE );
  42717. assert( PAGER_LOCKINGMODE_EXCLUSIVE==1 );
  42718. pPager->exclusiveMode = (u8)tempFile;
  42719. pPager->changeCountDone = pPager->tempFile;
  42720. pPager->memDb = (u8)memDb;
  42721. pPager->readOnly = (u8)readOnly;
  42722. assert( useJournal || pPager->tempFile );
  42723. pPager->noSync = pPager->tempFile;
  42724. if( pPager->noSync ){
  42725. assert( pPager->fullSync==0 );
  42726. assert( pPager->syncFlags==0 );
  42727. assert( pPager->walSyncFlags==0 );
  42728. assert( pPager->ckptSyncFlags==0 );
  42729. }else{
  42730. pPager->fullSync = 1;
  42731. pPager->syncFlags = SQLITE_SYNC_NORMAL;
  42732. pPager->walSyncFlags = SQLITE_SYNC_NORMAL | WAL_SYNC_TRANSACTIONS;
  42733. pPager->ckptSyncFlags = SQLITE_SYNC_NORMAL;
  42734. }
  42735. /* pPager->pFirst = 0; */
  42736. /* pPager->pFirstSynced = 0; */
  42737. /* pPager->pLast = 0; */
  42738. pPager->nExtra = (u16)nExtra;
  42739. pPager->journalSizeLimit = SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT;
  42740. assert( isOpen(pPager->fd) || tempFile );
  42741. setSectorSize(pPager);
  42742. if( !useJournal ){
  42743. pPager->journalMode = PAGER_JOURNALMODE_OFF;
  42744. }else if( memDb ){
  42745. pPager->journalMode = PAGER_JOURNALMODE_MEMORY;
  42746. }
  42747. /* pPager->xBusyHandler = 0; */
  42748. /* pPager->pBusyHandlerArg = 0; */
  42749. pPager->xReiniter = xReinit;
  42750. /* memset(pPager->aHash, 0, sizeof(pPager->aHash)); */
  42751. /* pPager->szMmap = SQLITE_DEFAULT_MMAP_SIZE // will be set by btree.c */
  42752. *ppPager = pPager;
  42753. return SQLITE_OK;
  42754. }
  42755. /* Verify that the database file has not be deleted or renamed out from
  42756. ** under the pager. Return SQLITE_OK if the database is still were it ought
  42757. ** to be on disk. Return non-zero (SQLITE_READONLY_DBMOVED or some other error
  42758. ** code from sqlite3OsAccess()) if the database has gone missing.
  42759. */
  42760. static int databaseIsUnmoved(Pager *pPager){
  42761. int bHasMoved = 0;
  42762. int rc;
  42763. if( pPager->tempFile ) return SQLITE_OK;
  42764. if( pPager->dbSize==0 ) return SQLITE_OK;
  42765. assert( pPager->zFilename && pPager->zFilename[0] );
  42766. rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_HAS_MOVED, &bHasMoved);
  42767. if( rc==SQLITE_NOTFOUND ){
  42768. /* If the HAS_MOVED file-control is unimplemented, assume that the file
  42769. ** has not been moved. That is the historical behavior of SQLite: prior to
  42770. ** version 3.8.3, it never checked */
  42771. rc = SQLITE_OK;
  42772. }else if( rc==SQLITE_OK && bHasMoved ){
  42773. rc = SQLITE_READONLY_DBMOVED;
  42774. }
  42775. return rc;
  42776. }
  42777. /*
  42778. ** This function is called after transitioning from PAGER_UNLOCK to
  42779. ** PAGER_SHARED state. It tests if there is a hot journal present in
  42780. ** the file-system for the given pager. A hot journal is one that
  42781. ** needs to be played back. According to this function, a hot-journal
  42782. ** file exists if the following criteria are met:
  42783. **
  42784. ** * The journal file exists in the file system, and
  42785. ** * No process holds a RESERVED or greater lock on the database file, and
  42786. ** * The database file itself is greater than 0 bytes in size, and
  42787. ** * The first byte of the journal file exists and is not 0x00.
  42788. **
  42789. ** If the current size of the database file is 0 but a journal file
  42790. ** exists, that is probably an old journal left over from a prior
  42791. ** database with the same name. In this case the journal file is
  42792. ** just deleted using OsDelete, *pExists is set to 0 and SQLITE_OK
  42793. ** is returned.
  42794. **
  42795. ** This routine does not check if there is a master journal filename
  42796. ** at the end of the file. If there is, and that master journal file
  42797. ** does not exist, then the journal file is not really hot. In this
  42798. ** case this routine will return a false-positive. The pager_playback()
  42799. ** routine will discover that the journal file is not really hot and
  42800. ** will not roll it back.
  42801. **
  42802. ** If a hot-journal file is found to exist, *pExists is set to 1 and
  42803. ** SQLITE_OK returned. If no hot-journal file is present, *pExists is
  42804. ** set to 0 and SQLITE_OK returned. If an IO error occurs while trying
  42805. ** to determine whether or not a hot-journal file exists, the IO error
  42806. ** code is returned and the value of *pExists is undefined.
  42807. */
  42808. static int hasHotJournal(Pager *pPager, int *pExists){
  42809. sqlite3_vfs * const pVfs = pPager->pVfs;
  42810. int rc = SQLITE_OK; /* Return code */
  42811. int exists = 1; /* True if a journal file is present */
  42812. int jrnlOpen = !!isOpen(pPager->jfd);
  42813. assert( pPager->useJournal );
  42814. assert( isOpen(pPager->fd) );
  42815. assert( pPager->eState==PAGER_OPEN );
  42816. assert( jrnlOpen==0 || ( sqlite3OsDeviceCharacteristics(pPager->jfd) &
  42817. SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN
  42818. ));
  42819. *pExists = 0;
  42820. if( !jrnlOpen ){
  42821. rc = sqlite3OsAccess(pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &exists);
  42822. }
  42823. if( rc==SQLITE_OK && exists ){
  42824. int locked = 0; /* True if some process holds a RESERVED lock */
  42825. /* Race condition here: Another process might have been holding the
  42826. ** the RESERVED lock and have a journal open at the sqlite3OsAccess()
  42827. ** call above, but then delete the journal and drop the lock before
  42828. ** we get to the following sqlite3OsCheckReservedLock() call. If that
  42829. ** is the case, this routine might think there is a hot journal when
  42830. ** in fact there is none. This results in a false-positive which will
  42831. ** be dealt with by the playback routine. Ticket #3883.
  42832. */
  42833. rc = sqlite3OsCheckReservedLock(pPager->fd, &locked);
  42834. if( rc==SQLITE_OK && !locked ){
  42835. Pgno nPage; /* Number of pages in database file */
  42836. rc = pagerPagecount(pPager, &nPage);
  42837. if( rc==SQLITE_OK ){
  42838. /* If the database is zero pages in size, that means that either (1) the
  42839. ** journal is a remnant from a prior database with the same name where
  42840. ** the database file but not the journal was deleted, or (2) the initial
  42841. ** transaction that populates a new database is being rolled back.
  42842. ** In either case, the journal file can be deleted. However, take care
  42843. ** not to delete the journal file if it is already open due to
  42844. ** journal_mode=PERSIST.
  42845. */
  42846. if( nPage==0 && !jrnlOpen ){
  42847. sqlite3BeginBenignMalloc();
  42848. if( pagerLockDb(pPager, RESERVED_LOCK)==SQLITE_OK ){
  42849. sqlite3OsDelete(pVfs, pPager->zJournal, 0);
  42850. if( !pPager->exclusiveMode ) pagerUnlockDb(pPager, SHARED_LOCK);
  42851. }
  42852. sqlite3EndBenignMalloc();
  42853. }else{
  42854. /* The journal file exists and no other connection has a reserved
  42855. ** or greater lock on the database file. Now check that there is
  42856. ** at least one non-zero bytes at the start of the journal file.
  42857. ** If there is, then we consider this journal to be hot. If not,
  42858. ** it can be ignored.
  42859. */
  42860. if( !jrnlOpen ){
  42861. int f = SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL;
  42862. rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &f);
  42863. }
  42864. if( rc==SQLITE_OK ){
  42865. u8 first = 0;
  42866. rc = sqlite3OsRead(pPager->jfd, (void *)&first, 1, 0);
  42867. if( rc==SQLITE_IOERR_SHORT_READ ){
  42868. rc = SQLITE_OK;
  42869. }
  42870. if( !jrnlOpen ){
  42871. sqlite3OsClose(pPager->jfd);
  42872. }
  42873. *pExists = (first!=0);
  42874. }else if( rc==SQLITE_CANTOPEN ){
  42875. /* If we cannot open the rollback journal file in order to see if
  42876. ** it has a zero header, that might be due to an I/O error, or
  42877. ** it might be due to the race condition described above and in
  42878. ** ticket #3883. Either way, assume that the journal is hot.
  42879. ** This might be a false positive. But if it is, then the
  42880. ** automatic journal playback and recovery mechanism will deal
  42881. ** with it under an EXCLUSIVE lock where we do not need to
  42882. ** worry so much with race conditions.
  42883. */
  42884. *pExists = 1;
  42885. rc = SQLITE_OK;
  42886. }
  42887. }
  42888. }
  42889. }
  42890. }
  42891. return rc;
  42892. }
  42893. /*
  42894. ** This function is called to obtain a shared lock on the database file.
  42895. ** It is illegal to call sqlite3PagerAcquire() until after this function
  42896. ** has been successfully called. If a shared-lock is already held when
  42897. ** this function is called, it is a no-op.
  42898. **
  42899. ** The following operations are also performed by this function.
  42900. **
  42901. ** 1) If the pager is currently in PAGER_OPEN state (no lock held
  42902. ** on the database file), then an attempt is made to obtain a
  42903. ** SHARED lock on the database file. Immediately after obtaining
  42904. ** the SHARED lock, the file-system is checked for a hot-journal,
  42905. ** which is played back if present. Following any hot-journal
  42906. ** rollback, the contents of the cache are validated by checking
  42907. ** the 'change-counter' field of the database file header and
  42908. ** discarded if they are found to be invalid.
  42909. **
  42910. ** 2) If the pager is running in exclusive-mode, and there are currently
  42911. ** no outstanding references to any pages, and is in the error state,
  42912. ** then an attempt is made to clear the error state by discarding
  42913. ** the contents of the page cache and rolling back any open journal
  42914. ** file.
  42915. **
  42916. ** If everything is successful, SQLITE_OK is returned. If an IO error
  42917. ** occurs while locking the database, checking for a hot-journal file or
  42918. ** rolling back a journal file, the IO error code is returned.
  42919. */
  42920. SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager){
  42921. int rc = SQLITE_OK; /* Return code */
  42922. /* This routine is only called from b-tree and only when there are no
  42923. ** outstanding pages. This implies that the pager state should either
  42924. ** be OPEN or READER. READER is only possible if the pager is or was in
  42925. ** exclusive access mode.
  42926. */
  42927. assert( sqlite3PcacheRefCount(pPager->pPCache)==0 );
  42928. assert( assert_pager_state(pPager) );
  42929. assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
  42930. if( NEVER(MEMDB && pPager->errCode) ){ return pPager->errCode; }
  42931. if( !pagerUseWal(pPager) && pPager->eState==PAGER_OPEN ){
  42932. int bHotJournal = 1; /* True if there exists a hot journal-file */
  42933. assert( !MEMDB );
  42934. rc = pager_wait_on_lock(pPager, SHARED_LOCK);
  42935. if( rc!=SQLITE_OK ){
  42936. assert( pPager->eLock==NO_LOCK || pPager->eLock==UNKNOWN_LOCK );
  42937. goto failed;
  42938. }
  42939. /* If a journal file exists, and there is no RESERVED lock on the
  42940. ** database file, then it either needs to be played back or deleted.
  42941. */
  42942. if( pPager->eLock<=SHARED_LOCK ){
  42943. rc = hasHotJournal(pPager, &bHotJournal);
  42944. }
  42945. if( rc!=SQLITE_OK ){
  42946. goto failed;
  42947. }
  42948. if( bHotJournal ){
  42949. if( pPager->readOnly ){
  42950. rc = SQLITE_READONLY_ROLLBACK;
  42951. goto failed;
  42952. }
  42953. /* Get an EXCLUSIVE lock on the database file. At this point it is
  42954. ** important that a RESERVED lock is not obtained on the way to the
  42955. ** EXCLUSIVE lock. If it were, another process might open the
  42956. ** database file, detect the RESERVED lock, and conclude that the
  42957. ** database is safe to read while this process is still rolling the
  42958. ** hot-journal back.
  42959. **
  42960. ** Because the intermediate RESERVED lock is not requested, any
  42961. ** other process attempting to access the database file will get to
  42962. ** this point in the code and fail to obtain its own EXCLUSIVE lock
  42963. ** on the database file.
  42964. **
  42965. ** Unless the pager is in locking_mode=exclusive mode, the lock is
  42966. ** downgraded to SHARED_LOCK before this function returns.
  42967. */
  42968. rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
  42969. if( rc!=SQLITE_OK ){
  42970. goto failed;
  42971. }
  42972. /* If it is not already open and the file exists on disk, open the
  42973. ** journal for read/write access. Write access is required because
  42974. ** in exclusive-access mode the file descriptor will be kept open
  42975. ** and possibly used for a transaction later on. Also, write-access
  42976. ** is usually required to finalize the journal in journal_mode=persist
  42977. ** mode (and also for journal_mode=truncate on some systems).
  42978. **
  42979. ** If the journal does not exist, it usually means that some
  42980. ** other connection managed to get in and roll it back before
  42981. ** this connection obtained the exclusive lock above. Or, it
  42982. ** may mean that the pager was in the error-state when this
  42983. ** function was called and the journal file does not exist.
  42984. */
  42985. if( !isOpen(pPager->jfd) ){
  42986. sqlite3_vfs * const pVfs = pPager->pVfs;
  42987. int bExists; /* True if journal file exists */
  42988. rc = sqlite3OsAccess(
  42989. pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &bExists);
  42990. if( rc==SQLITE_OK && bExists ){
  42991. int fout = 0;
  42992. int f = SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_JOURNAL;
  42993. assert( !pPager->tempFile );
  42994. rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &fout);
  42995. assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
  42996. if( rc==SQLITE_OK && fout&SQLITE_OPEN_READONLY ){
  42997. rc = SQLITE_CANTOPEN_BKPT;
  42998. sqlite3OsClose(pPager->jfd);
  42999. }
  43000. }
  43001. }
  43002. /* Playback and delete the journal. Drop the database write
  43003. ** lock and reacquire the read lock. Purge the cache before
  43004. ** playing back the hot-journal so that we don't end up with
  43005. ** an inconsistent cache. Sync the hot journal before playing
  43006. ** it back since the process that crashed and left the hot journal
  43007. ** probably did not sync it and we are required to always sync
  43008. ** the journal before playing it back.
  43009. */
  43010. if( isOpen(pPager->jfd) ){
  43011. assert( rc==SQLITE_OK );
  43012. rc = pagerSyncHotJournal(pPager);
  43013. if( rc==SQLITE_OK ){
  43014. rc = pager_playback(pPager, 1);
  43015. pPager->eState = PAGER_OPEN;
  43016. }
  43017. }else if( !pPager->exclusiveMode ){
  43018. pagerUnlockDb(pPager, SHARED_LOCK);
  43019. }
  43020. if( rc!=SQLITE_OK ){
  43021. /* This branch is taken if an error occurs while trying to open
  43022. ** or roll back a hot-journal while holding an EXCLUSIVE lock. The
  43023. ** pager_unlock() routine will be called before returning to unlock
  43024. ** the file. If the unlock attempt fails, then Pager.eLock must be
  43025. ** set to UNKNOWN_LOCK (see the comment above the #define for
  43026. ** UNKNOWN_LOCK above for an explanation).
  43027. **
  43028. ** In order to get pager_unlock() to do this, set Pager.eState to
  43029. ** PAGER_ERROR now. This is not actually counted as a transition
  43030. ** to ERROR state in the state diagram at the top of this file,
  43031. ** since we know that the same call to pager_unlock() will very
  43032. ** shortly transition the pager object to the OPEN state. Calling
  43033. ** assert_pager_state() would fail now, as it should not be possible
  43034. ** to be in ERROR state when there are zero outstanding page
  43035. ** references.
  43036. */
  43037. pager_error(pPager, rc);
  43038. goto failed;
  43039. }
  43040. assert( pPager->eState==PAGER_OPEN );
  43041. assert( (pPager->eLock==SHARED_LOCK)
  43042. || (pPager->exclusiveMode && pPager->eLock>SHARED_LOCK)
  43043. );
  43044. }
  43045. if( !pPager->tempFile && (
  43046. pPager->pBackup
  43047. || sqlite3PcachePagecount(pPager->pPCache)>0
  43048. || USEFETCH(pPager)
  43049. )){
  43050. /* The shared-lock has just been acquired on the database file
  43051. ** and there are already pages in the cache (from a previous
  43052. ** read or write transaction). Check to see if the database
  43053. ** has been modified. If the database has changed, flush the
  43054. ** cache.
  43055. **
  43056. ** Database changes is detected by looking at 15 bytes beginning
  43057. ** at offset 24 into the file. The first 4 of these 16 bytes are
  43058. ** a 32-bit counter that is incremented with each change. The
  43059. ** other bytes change randomly with each file change when
  43060. ** a codec is in use.
  43061. **
  43062. ** There is a vanishingly small chance that a change will not be
  43063. ** detected. The chance of an undetected change is so small that
  43064. ** it can be neglected.
  43065. */
  43066. Pgno nPage = 0;
  43067. char dbFileVers[sizeof(pPager->dbFileVers)];
  43068. rc = pagerPagecount(pPager, &nPage);
  43069. if( rc ) goto failed;
  43070. if( nPage>0 ){
  43071. IOTRACE(("CKVERS %p %d\n", pPager, sizeof(dbFileVers)));
  43072. rc = sqlite3OsRead(pPager->fd, &dbFileVers, sizeof(dbFileVers), 24);
  43073. if( rc!=SQLITE_OK && rc!=SQLITE_IOERR_SHORT_READ ){
  43074. goto failed;
  43075. }
  43076. }else{
  43077. memset(dbFileVers, 0, sizeof(dbFileVers));
  43078. }
  43079. if( memcmp(pPager->dbFileVers, dbFileVers, sizeof(dbFileVers))!=0 ){
  43080. pager_reset(pPager);
  43081. /* Unmap the database file. It is possible that external processes
  43082. ** may have truncated the database file and then extended it back
  43083. ** to its original size while this process was not holding a lock.
  43084. ** In this case there may exist a Pager.pMap mapping that appears
  43085. ** to be the right size but is not actually valid. Avoid this
  43086. ** possibility by unmapping the db here. */
  43087. if( USEFETCH(pPager) ){
  43088. sqlite3OsUnfetch(pPager->fd, 0, 0);
  43089. }
  43090. }
  43091. }
  43092. /* If there is a WAL file in the file-system, open this database in WAL
  43093. ** mode. Otherwise, the following function call is a no-op.
  43094. */
  43095. rc = pagerOpenWalIfPresent(pPager);
  43096. #ifndef SQLITE_OMIT_WAL
  43097. assert( pPager->pWal==0 || rc==SQLITE_OK );
  43098. #endif
  43099. }
  43100. if( pagerUseWal(pPager) ){
  43101. assert( rc==SQLITE_OK );
  43102. rc = pagerBeginReadTransaction(pPager);
  43103. }
  43104. if( pPager->eState==PAGER_OPEN && rc==SQLITE_OK ){
  43105. rc = pagerPagecount(pPager, &pPager->dbSize);
  43106. }
  43107. failed:
  43108. if( rc!=SQLITE_OK ){
  43109. assert( !MEMDB );
  43110. pager_unlock(pPager);
  43111. assert( pPager->eState==PAGER_OPEN );
  43112. }else{
  43113. pPager->eState = PAGER_READER;
  43114. }
  43115. return rc;
  43116. }
  43117. /*
  43118. ** If the reference count has reached zero, rollback any active
  43119. ** transaction and unlock the pager.
  43120. **
  43121. ** Except, in locking_mode=EXCLUSIVE when there is nothing to in
  43122. ** the rollback journal, the unlock is not performed and there is
  43123. ** nothing to rollback, so this routine is a no-op.
  43124. */
  43125. static void pagerUnlockIfUnused(Pager *pPager){
  43126. if( pPager->nMmapOut==0 && (sqlite3PcacheRefCount(pPager->pPCache)==0) ){
  43127. pagerUnlockAndRollback(pPager);
  43128. }
  43129. }
  43130. /*
  43131. ** Acquire a reference to page number pgno in pager pPager (a page
  43132. ** reference has type DbPage*). If the requested reference is
  43133. ** successfully obtained, it is copied to *ppPage and SQLITE_OK returned.
  43134. **
  43135. ** If the requested page is already in the cache, it is returned.
  43136. ** Otherwise, a new page object is allocated and populated with data
  43137. ** read from the database file. In some cases, the pcache module may
  43138. ** choose not to allocate a new page object and may reuse an existing
  43139. ** object with no outstanding references.
  43140. **
  43141. ** The extra data appended to a page is always initialized to zeros the
  43142. ** first time a page is loaded into memory. If the page requested is
  43143. ** already in the cache when this function is called, then the extra
  43144. ** data is left as it was when the page object was last used.
  43145. **
  43146. ** If the database image is smaller than the requested page or if a
  43147. ** non-zero value is passed as the noContent parameter and the
  43148. ** requested page is not already stored in the cache, then no
  43149. ** actual disk read occurs. In this case the memory image of the
  43150. ** page is initialized to all zeros.
  43151. **
  43152. ** If noContent is true, it means that we do not care about the contents
  43153. ** of the page. This occurs in two scenarios:
  43154. **
  43155. ** a) When reading a free-list leaf page from the database, and
  43156. **
  43157. ** b) When a savepoint is being rolled back and we need to load
  43158. ** a new page into the cache to be filled with the data read
  43159. ** from the savepoint journal.
  43160. **
  43161. ** If noContent is true, then the data returned is zeroed instead of
  43162. ** being read from the database. Additionally, the bits corresponding
  43163. ** to pgno in Pager.pInJournal (bitvec of pages already written to the
  43164. ** journal file) and the PagerSavepoint.pInSavepoint bitvecs of any open
  43165. ** savepoints are set. This means if the page is made writable at any
  43166. ** point in the future, using a call to sqlite3PagerWrite(), its contents
  43167. ** will not be journaled. This saves IO.
  43168. **
  43169. ** The acquisition might fail for several reasons. In all cases,
  43170. ** an appropriate error code is returned and *ppPage is set to NULL.
  43171. **
  43172. ** See also sqlite3PagerLookup(). Both this routine and Lookup() attempt
  43173. ** to find a page in the in-memory cache first. If the page is not already
  43174. ** in memory, this routine goes to disk to read it in whereas Lookup()
  43175. ** just returns 0. This routine acquires a read-lock the first time it
  43176. ** has to go to disk, and could also playback an old journal if necessary.
  43177. ** Since Lookup() never goes to disk, it never has to deal with locks
  43178. ** or journal files.
  43179. */
  43180. SQLITE_PRIVATE int sqlite3PagerAcquire(
  43181. Pager *pPager, /* The pager open on the database file */
  43182. Pgno pgno, /* Page number to fetch */
  43183. DbPage **ppPage, /* Write a pointer to the page here */
  43184. int flags /* PAGER_GET_XXX flags */
  43185. ){
  43186. int rc = SQLITE_OK;
  43187. PgHdr *pPg = 0;
  43188. u32 iFrame = 0; /* Frame to read from WAL file */
  43189. const int noContent = (flags & PAGER_GET_NOCONTENT);
  43190. /* It is acceptable to use a read-only (mmap) page for any page except
  43191. ** page 1 if there is no write-transaction open or the ACQUIRE_READONLY
  43192. ** flag was specified by the caller. And so long as the db is not a
  43193. ** temporary or in-memory database. */
  43194. const int bMmapOk = (pgno!=1 && USEFETCH(pPager)
  43195. && (pPager->eState==PAGER_READER || (flags & PAGER_GET_READONLY))
  43196. #ifdef SQLITE_HAS_CODEC
  43197. && pPager->xCodec==0
  43198. #endif
  43199. );
  43200. assert( pPager->eState>=PAGER_READER );
  43201. assert( assert_pager_state(pPager) );
  43202. assert( noContent==0 || bMmapOk==0 );
  43203. if( pgno==0 ){
  43204. return SQLITE_CORRUPT_BKPT;
  43205. }
  43206. /* If the pager is in the error state, return an error immediately.
  43207. ** Otherwise, request the page from the PCache layer. */
  43208. if( pPager->errCode!=SQLITE_OK ){
  43209. rc = pPager->errCode;
  43210. }else{
  43211. if( bMmapOk && pagerUseWal(pPager) ){
  43212. rc = sqlite3WalFindFrame(pPager->pWal, pgno, &iFrame);
  43213. if( rc!=SQLITE_OK ) goto pager_acquire_err;
  43214. }
  43215. if( bMmapOk && iFrame==0 ){
  43216. void *pData = 0;
  43217. rc = sqlite3OsFetch(pPager->fd,
  43218. (i64)(pgno-1) * pPager->pageSize, pPager->pageSize, &pData
  43219. );
  43220. if( rc==SQLITE_OK && pData ){
  43221. if( pPager->eState>PAGER_READER ){
  43222. pPg = sqlite3PagerLookup(pPager, pgno);
  43223. }
  43224. if( pPg==0 ){
  43225. rc = pagerAcquireMapPage(pPager, pgno, pData, &pPg);
  43226. }else{
  43227. sqlite3OsUnfetch(pPager->fd, (i64)(pgno-1)*pPager->pageSize, pData);
  43228. }
  43229. if( pPg ){
  43230. assert( rc==SQLITE_OK );
  43231. *ppPage = pPg;
  43232. return SQLITE_OK;
  43233. }
  43234. }
  43235. if( rc!=SQLITE_OK ){
  43236. goto pager_acquire_err;
  43237. }
  43238. }
  43239. {
  43240. sqlite3_pcache_page *pBase;
  43241. pBase = sqlite3PcacheFetch(pPager->pPCache, pgno, 3);
  43242. if( pBase==0 ){
  43243. rc = sqlite3PcacheFetchStress(pPager->pPCache, pgno, &pBase);
  43244. if( rc!=SQLITE_OK ) goto pager_acquire_err;
  43245. }
  43246. pPg = *ppPage = sqlite3PcacheFetchFinish(pPager->pPCache, pgno, pBase);
  43247. if( pPg==0 ) rc = SQLITE_NOMEM;
  43248. }
  43249. }
  43250. if( rc!=SQLITE_OK ){
  43251. /* Either the call to sqlite3PcacheFetch() returned an error or the
  43252. ** pager was already in the error-state when this function was called.
  43253. ** Set pPg to 0 and jump to the exception handler. */
  43254. pPg = 0;
  43255. goto pager_acquire_err;
  43256. }
  43257. assert( (*ppPage)->pgno==pgno );
  43258. assert( (*ppPage)->pPager==pPager || (*ppPage)->pPager==0 );
  43259. if( (*ppPage)->pPager && !noContent ){
  43260. /* In this case the pcache already contains an initialized copy of
  43261. ** the page. Return without further ado. */
  43262. assert( pgno<=PAGER_MAX_PGNO && pgno!=PAGER_MJ_PGNO(pPager) );
  43263. pPager->aStat[PAGER_STAT_HIT]++;
  43264. return SQLITE_OK;
  43265. }else{
  43266. /* The pager cache has created a new page. Its content needs to
  43267. ** be initialized. */
  43268. pPg = *ppPage;
  43269. pPg->pPager = pPager;
  43270. /* The maximum page number is 2^31. Return SQLITE_CORRUPT if a page
  43271. ** number greater than this, or the unused locking-page, is requested. */
  43272. if( pgno>PAGER_MAX_PGNO || pgno==PAGER_MJ_PGNO(pPager) ){
  43273. rc = SQLITE_CORRUPT_BKPT;
  43274. goto pager_acquire_err;
  43275. }
  43276. if( MEMDB || pPager->dbSize<pgno || noContent || !isOpen(pPager->fd) ){
  43277. if( pgno>pPager->mxPgno ){
  43278. rc = SQLITE_FULL;
  43279. goto pager_acquire_err;
  43280. }
  43281. if( noContent ){
  43282. /* Failure to set the bits in the InJournal bit-vectors is benign.
  43283. ** It merely means that we might do some extra work to journal a
  43284. ** page that does not need to be journaled. Nevertheless, be sure
  43285. ** to test the case where a malloc error occurs while trying to set
  43286. ** a bit in a bit vector.
  43287. */
  43288. sqlite3BeginBenignMalloc();
  43289. if( pgno<=pPager->dbOrigSize ){
  43290. TESTONLY( rc = ) sqlite3BitvecSet(pPager->pInJournal, pgno);
  43291. testcase( rc==SQLITE_NOMEM );
  43292. }
  43293. TESTONLY( rc = ) addToSavepointBitvecs(pPager, pgno);
  43294. testcase( rc==SQLITE_NOMEM );
  43295. sqlite3EndBenignMalloc();
  43296. }
  43297. memset(pPg->pData, 0, pPager->pageSize);
  43298. IOTRACE(("ZERO %p %d\n", pPager, pgno));
  43299. }else{
  43300. if( pagerUseWal(pPager) && bMmapOk==0 ){
  43301. rc = sqlite3WalFindFrame(pPager->pWal, pgno, &iFrame);
  43302. if( rc!=SQLITE_OK ) goto pager_acquire_err;
  43303. }
  43304. assert( pPg->pPager==pPager );
  43305. pPager->aStat[PAGER_STAT_MISS]++;
  43306. rc = readDbPage(pPg, iFrame);
  43307. if( rc!=SQLITE_OK ){
  43308. goto pager_acquire_err;
  43309. }
  43310. }
  43311. pager_set_pagehash(pPg);
  43312. }
  43313. return SQLITE_OK;
  43314. pager_acquire_err:
  43315. assert( rc!=SQLITE_OK );
  43316. if( pPg ){
  43317. sqlite3PcacheDrop(pPg);
  43318. }
  43319. pagerUnlockIfUnused(pPager);
  43320. *ppPage = 0;
  43321. return rc;
  43322. }
  43323. /*
  43324. ** Acquire a page if it is already in the in-memory cache. Do
  43325. ** not read the page from disk. Return a pointer to the page,
  43326. ** or 0 if the page is not in cache.
  43327. **
  43328. ** See also sqlite3PagerGet(). The difference between this routine
  43329. ** and sqlite3PagerGet() is that _get() will go to the disk and read
  43330. ** in the page if the page is not already in cache. This routine
  43331. ** returns NULL if the page is not in cache or if a disk I/O error
  43332. ** has ever happened.
  43333. */
  43334. SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno){
  43335. sqlite3_pcache_page *pPage;
  43336. assert( pPager!=0 );
  43337. assert( pgno!=0 );
  43338. assert( pPager->pPCache!=0 );
  43339. pPage = sqlite3PcacheFetch(pPager->pPCache, pgno, 0);
  43340. return sqlite3PcacheFetchFinish(pPager->pPCache, pgno, pPage);
  43341. }
  43342. /*
  43343. ** Release a page reference.
  43344. **
  43345. ** If the number of references to the page drop to zero, then the
  43346. ** page is added to the LRU list. When all references to all pages
  43347. ** are released, a rollback occurs and the lock on the database is
  43348. ** removed.
  43349. */
  43350. SQLITE_PRIVATE void sqlite3PagerUnrefNotNull(DbPage *pPg){
  43351. Pager *pPager;
  43352. assert( pPg!=0 );
  43353. pPager = pPg->pPager;
  43354. if( pPg->flags & PGHDR_MMAP ){
  43355. pagerReleaseMapPage(pPg);
  43356. }else{
  43357. sqlite3PcacheRelease(pPg);
  43358. }
  43359. pagerUnlockIfUnused(pPager);
  43360. }
  43361. SQLITE_PRIVATE void sqlite3PagerUnref(DbPage *pPg){
  43362. if( pPg ) sqlite3PagerUnrefNotNull(pPg);
  43363. }
  43364. /*
  43365. ** This function is called at the start of every write transaction.
  43366. ** There must already be a RESERVED or EXCLUSIVE lock on the database
  43367. ** file when this routine is called.
  43368. **
  43369. ** Open the journal file for pager pPager and write a journal header
  43370. ** to the start of it. If there are active savepoints, open the sub-journal
  43371. ** as well. This function is only used when the journal file is being
  43372. ** opened to write a rollback log for a transaction. It is not used
  43373. ** when opening a hot journal file to roll it back.
  43374. **
  43375. ** If the journal file is already open (as it may be in exclusive mode),
  43376. ** then this function just writes a journal header to the start of the
  43377. ** already open file.
  43378. **
  43379. ** Whether or not the journal file is opened by this function, the
  43380. ** Pager.pInJournal bitvec structure is allocated.
  43381. **
  43382. ** Return SQLITE_OK if everything is successful. Otherwise, return
  43383. ** SQLITE_NOMEM if the attempt to allocate Pager.pInJournal fails, or
  43384. ** an IO error code if opening or writing the journal file fails.
  43385. */
  43386. static int pager_open_journal(Pager *pPager){
  43387. int rc = SQLITE_OK; /* Return code */
  43388. sqlite3_vfs * const pVfs = pPager->pVfs; /* Local cache of vfs pointer */
  43389. assert( pPager->eState==PAGER_WRITER_LOCKED );
  43390. assert( assert_pager_state(pPager) );
  43391. assert( pPager->pInJournal==0 );
  43392. /* If already in the error state, this function is a no-op. But on
  43393. ** the other hand, this routine is never called if we are already in
  43394. ** an error state. */
  43395. if( NEVER(pPager->errCode) ) return pPager->errCode;
  43396. if( !pagerUseWal(pPager) && pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
  43397. pPager->pInJournal = sqlite3BitvecCreate(pPager->dbSize);
  43398. if( pPager->pInJournal==0 ){
  43399. return SQLITE_NOMEM;
  43400. }
  43401. /* Open the journal file if it is not already open. */
  43402. if( !isOpen(pPager->jfd) ){
  43403. if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ){
  43404. sqlite3MemJournalOpen(pPager->jfd);
  43405. }else{
  43406. const int flags = /* VFS flags to open journal file */
  43407. SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
  43408. (pPager->tempFile ?
  43409. (SQLITE_OPEN_DELETEONCLOSE|SQLITE_OPEN_TEMP_JOURNAL):
  43410. (SQLITE_OPEN_MAIN_JOURNAL)
  43411. );
  43412. /* Verify that the database still has the same name as it did when
  43413. ** it was originally opened. */
  43414. rc = databaseIsUnmoved(pPager);
  43415. if( rc==SQLITE_OK ){
  43416. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  43417. rc = sqlite3JournalOpen(
  43418. pVfs, pPager->zJournal, pPager->jfd, flags, jrnlBufferSize(pPager)
  43419. );
  43420. #else
  43421. rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, flags, 0);
  43422. #endif
  43423. }
  43424. }
  43425. assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
  43426. }
  43427. /* Write the first journal header to the journal file and open
  43428. ** the sub-journal if necessary.
  43429. */
  43430. if( rc==SQLITE_OK ){
  43431. /* TODO: Check if all of these are really required. */
  43432. pPager->nRec = 0;
  43433. pPager->journalOff = 0;
  43434. pPager->setMaster = 0;
  43435. pPager->journalHdr = 0;
  43436. rc = writeJournalHdr(pPager);
  43437. }
  43438. }
  43439. if( rc!=SQLITE_OK ){
  43440. sqlite3BitvecDestroy(pPager->pInJournal);
  43441. pPager->pInJournal = 0;
  43442. }else{
  43443. assert( pPager->eState==PAGER_WRITER_LOCKED );
  43444. pPager->eState = PAGER_WRITER_CACHEMOD;
  43445. }
  43446. return rc;
  43447. }
  43448. /*
  43449. ** Begin a write-transaction on the specified pager object. If a
  43450. ** write-transaction has already been opened, this function is a no-op.
  43451. **
  43452. ** If the exFlag argument is false, then acquire at least a RESERVED
  43453. ** lock on the database file. If exFlag is true, then acquire at least
  43454. ** an EXCLUSIVE lock. If such a lock is already held, no locking
  43455. ** functions need be called.
  43456. **
  43457. ** If the subjInMemory argument is non-zero, then any sub-journal opened
  43458. ** within this transaction will be opened as an in-memory file. This
  43459. ** has no effect if the sub-journal is already opened (as it may be when
  43460. ** running in exclusive mode) or if the transaction does not require a
  43461. ** sub-journal. If the subjInMemory argument is zero, then any required
  43462. ** sub-journal is implemented in-memory if pPager is an in-memory database,
  43463. ** or using a temporary file otherwise.
  43464. */
  43465. SQLITE_PRIVATE int sqlite3PagerBegin(Pager *pPager, int exFlag, int subjInMemory){
  43466. int rc = SQLITE_OK;
  43467. if( pPager->errCode ) return pPager->errCode;
  43468. assert( pPager->eState>=PAGER_READER && pPager->eState<PAGER_ERROR );
  43469. pPager->subjInMemory = (u8)subjInMemory;
  43470. if( ALWAYS(pPager->eState==PAGER_READER) ){
  43471. assert( pPager->pInJournal==0 );
  43472. if( pagerUseWal(pPager) ){
  43473. /* If the pager is configured to use locking_mode=exclusive, and an
  43474. ** exclusive lock on the database is not already held, obtain it now.
  43475. */
  43476. if( pPager->exclusiveMode && sqlite3WalExclusiveMode(pPager->pWal, -1) ){
  43477. rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
  43478. if( rc!=SQLITE_OK ){
  43479. return rc;
  43480. }
  43481. sqlite3WalExclusiveMode(pPager->pWal, 1);
  43482. }
  43483. /* Grab the write lock on the log file. If successful, upgrade to
  43484. ** PAGER_RESERVED state. Otherwise, return an error code to the caller.
  43485. ** The busy-handler is not invoked if another connection already
  43486. ** holds the write-lock. If possible, the upper layer will call it.
  43487. */
  43488. rc = sqlite3WalBeginWriteTransaction(pPager->pWal);
  43489. }else{
  43490. /* Obtain a RESERVED lock on the database file. If the exFlag parameter
  43491. ** is true, then immediately upgrade this to an EXCLUSIVE lock. The
  43492. ** busy-handler callback can be used when upgrading to the EXCLUSIVE
  43493. ** lock, but not when obtaining the RESERVED lock.
  43494. */
  43495. rc = pagerLockDb(pPager, RESERVED_LOCK);
  43496. if( rc==SQLITE_OK && exFlag ){
  43497. rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
  43498. }
  43499. }
  43500. if( rc==SQLITE_OK ){
  43501. /* Change to WRITER_LOCKED state.
  43502. **
  43503. ** WAL mode sets Pager.eState to PAGER_WRITER_LOCKED or CACHEMOD
  43504. ** when it has an open transaction, but never to DBMOD or FINISHED.
  43505. ** This is because in those states the code to roll back savepoint
  43506. ** transactions may copy data from the sub-journal into the database
  43507. ** file as well as into the page cache. Which would be incorrect in
  43508. ** WAL mode.
  43509. */
  43510. pPager->eState = PAGER_WRITER_LOCKED;
  43511. pPager->dbHintSize = pPager->dbSize;
  43512. pPager->dbFileSize = pPager->dbSize;
  43513. pPager->dbOrigSize = pPager->dbSize;
  43514. pPager->journalOff = 0;
  43515. }
  43516. assert( rc==SQLITE_OK || pPager->eState==PAGER_READER );
  43517. assert( rc!=SQLITE_OK || pPager->eState==PAGER_WRITER_LOCKED );
  43518. assert( assert_pager_state(pPager) );
  43519. }
  43520. PAGERTRACE(("TRANSACTION %d\n", PAGERID(pPager)));
  43521. return rc;
  43522. }
  43523. /*
  43524. ** Mark a single data page as writeable. The page is written into the
  43525. ** main journal or sub-journal as required. If the page is written into
  43526. ** one of the journals, the corresponding bit is set in the
  43527. ** Pager.pInJournal bitvec and the PagerSavepoint.pInSavepoint bitvecs
  43528. ** of any open savepoints as appropriate.
  43529. */
  43530. static int pager_write(PgHdr *pPg){
  43531. Pager *pPager = pPg->pPager;
  43532. int rc = SQLITE_OK;
  43533. int inJournal;
  43534. /* This routine is not called unless a write-transaction has already
  43535. ** been started. The journal file may or may not be open at this point.
  43536. ** It is never called in the ERROR state.
  43537. */
  43538. assert( pPager->eState==PAGER_WRITER_LOCKED
  43539. || pPager->eState==PAGER_WRITER_CACHEMOD
  43540. || pPager->eState==PAGER_WRITER_DBMOD
  43541. );
  43542. assert( assert_pager_state(pPager) );
  43543. assert( pPager->errCode==0 );
  43544. assert( pPager->readOnly==0 );
  43545. CHECK_PAGE(pPg);
  43546. /* The journal file needs to be opened. Higher level routines have already
  43547. ** obtained the necessary locks to begin the write-transaction, but the
  43548. ** rollback journal might not yet be open. Open it now if this is the case.
  43549. **
  43550. ** This is done before calling sqlite3PcacheMakeDirty() on the page.
  43551. ** Otherwise, if it were done after calling sqlite3PcacheMakeDirty(), then
  43552. ** an error might occur and the pager would end up in WRITER_LOCKED state
  43553. ** with pages marked as dirty in the cache.
  43554. */
  43555. if( pPager->eState==PAGER_WRITER_LOCKED ){
  43556. rc = pager_open_journal(pPager);
  43557. if( rc!=SQLITE_OK ) return rc;
  43558. }
  43559. assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
  43560. assert( assert_pager_state(pPager) );
  43561. /* Mark the page as dirty. If the page has already been written
  43562. ** to the journal then we can return right away.
  43563. */
  43564. sqlite3PcacheMakeDirty(pPg);
  43565. inJournal = pageInJournal(pPager, pPg);
  43566. if( inJournal && (pPager->nSavepoint==0 || !subjRequiresPage(pPg)) ){
  43567. assert( !pagerUseWal(pPager) );
  43568. }else{
  43569. /* The transaction journal now exists and we have a RESERVED or an
  43570. ** EXCLUSIVE lock on the main database file. Write the current page to
  43571. ** the transaction journal if it is not there already.
  43572. */
  43573. if( !inJournal && !pagerUseWal(pPager) ){
  43574. assert( pagerUseWal(pPager)==0 );
  43575. if( pPg->pgno<=pPager->dbOrigSize && isOpen(pPager->jfd) ){
  43576. u32 cksum;
  43577. char *pData2;
  43578. i64 iOff = pPager->journalOff;
  43579. /* We should never write to the journal file the page that
  43580. ** contains the database locks. The following assert verifies
  43581. ** that we do not. */
  43582. assert( pPg->pgno!=PAGER_MJ_PGNO(pPager) );
  43583. assert( pPager->journalHdr<=pPager->journalOff );
  43584. CODEC2(pPager, pPg->pData, pPg->pgno, 7, return SQLITE_NOMEM, pData2);
  43585. cksum = pager_cksum(pPager, (u8*)pData2);
  43586. /* Even if an IO or diskfull error occurs while journalling the
  43587. ** page in the block above, set the need-sync flag for the page.
  43588. ** Otherwise, when the transaction is rolled back, the logic in
  43589. ** playback_one_page() will think that the page needs to be restored
  43590. ** in the database file. And if an IO error occurs while doing so,
  43591. ** then corruption may follow.
  43592. */
  43593. pPg->flags |= PGHDR_NEED_SYNC;
  43594. rc = write32bits(pPager->jfd, iOff, pPg->pgno);
  43595. if( rc!=SQLITE_OK ) return rc;
  43596. rc = sqlite3OsWrite(pPager->jfd, pData2, pPager->pageSize, iOff+4);
  43597. if( rc!=SQLITE_OK ) return rc;
  43598. rc = write32bits(pPager->jfd, iOff+pPager->pageSize+4, cksum);
  43599. if( rc!=SQLITE_OK ) return rc;
  43600. IOTRACE(("JOUT %p %d %lld %d\n", pPager, pPg->pgno,
  43601. pPager->journalOff, pPager->pageSize));
  43602. PAGER_INCR(sqlite3_pager_writej_count);
  43603. PAGERTRACE(("JOURNAL %d page %d needSync=%d hash(%08x)\n",
  43604. PAGERID(pPager), pPg->pgno,
  43605. ((pPg->flags&PGHDR_NEED_SYNC)?1:0), pager_pagehash(pPg)));
  43606. pPager->journalOff += 8 + pPager->pageSize;
  43607. pPager->nRec++;
  43608. assert( pPager->pInJournal!=0 );
  43609. rc = sqlite3BitvecSet(pPager->pInJournal, pPg->pgno);
  43610. testcase( rc==SQLITE_NOMEM );
  43611. assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
  43612. rc |= addToSavepointBitvecs(pPager, pPg->pgno);
  43613. if( rc!=SQLITE_OK ){
  43614. assert( rc==SQLITE_NOMEM );
  43615. return rc;
  43616. }
  43617. }else{
  43618. if( pPager->eState!=PAGER_WRITER_DBMOD ){
  43619. pPg->flags |= PGHDR_NEED_SYNC;
  43620. }
  43621. PAGERTRACE(("APPEND %d page %d needSync=%d\n",
  43622. PAGERID(pPager), pPg->pgno,
  43623. ((pPg->flags&PGHDR_NEED_SYNC)?1:0)));
  43624. }
  43625. }
  43626. /* If the statement journal is open and the page is not in it,
  43627. ** then write the current page to the statement journal. Note that
  43628. ** the statement journal format differs from the standard journal format
  43629. ** in that it omits the checksums and the header.
  43630. */
  43631. if( pPager->nSavepoint>0 && subjRequiresPage(pPg) ){
  43632. rc = subjournalPage(pPg);
  43633. }
  43634. }
  43635. /* Update the database size and return.
  43636. */
  43637. if( pPager->dbSize<pPg->pgno ){
  43638. pPager->dbSize = pPg->pgno;
  43639. }
  43640. return rc;
  43641. }
  43642. /*
  43643. ** This is a variant of sqlite3PagerWrite() that runs when the sector size
  43644. ** is larger than the page size. SQLite makes the (reasonable) assumption that
  43645. ** all bytes of a sector are written together by hardware. Hence, all bytes of
  43646. ** a sector need to be journalled in case of a power loss in the middle of
  43647. ** a write.
  43648. **
  43649. ** Usually, the sector size is less than or equal to the page size, in which
  43650. ** case pages can be individually written. This routine only runs in the exceptional
  43651. ** case where the page size is smaller than the sector size.
  43652. */
  43653. static SQLITE_NOINLINE int pagerWriteLargeSector(PgHdr *pPg){
  43654. int rc = SQLITE_OK; /* Return code */
  43655. Pgno nPageCount; /* Total number of pages in database file */
  43656. Pgno pg1; /* First page of the sector pPg is located on. */
  43657. int nPage = 0; /* Number of pages starting at pg1 to journal */
  43658. int ii; /* Loop counter */
  43659. int needSync = 0; /* True if any page has PGHDR_NEED_SYNC */
  43660. Pager *pPager = pPg->pPager; /* The pager that owns pPg */
  43661. Pgno nPagePerSector = (pPager->sectorSize/pPager->pageSize);
  43662. /* Set the doNotSpill NOSYNC bit to 1. This is because we cannot allow
  43663. ** a journal header to be written between the pages journaled by
  43664. ** this function.
  43665. */
  43666. assert( !MEMDB );
  43667. assert( (pPager->doNotSpill & SPILLFLAG_NOSYNC)==0 );
  43668. pPager->doNotSpill |= SPILLFLAG_NOSYNC;
  43669. /* This trick assumes that both the page-size and sector-size are
  43670. ** an integer power of 2. It sets variable pg1 to the identifier
  43671. ** of the first page of the sector pPg is located on.
  43672. */
  43673. pg1 = ((pPg->pgno-1) & ~(nPagePerSector-1)) + 1;
  43674. nPageCount = pPager->dbSize;
  43675. if( pPg->pgno>nPageCount ){
  43676. nPage = (pPg->pgno - pg1)+1;
  43677. }else if( (pg1+nPagePerSector-1)>nPageCount ){
  43678. nPage = nPageCount+1-pg1;
  43679. }else{
  43680. nPage = nPagePerSector;
  43681. }
  43682. assert(nPage>0);
  43683. assert(pg1<=pPg->pgno);
  43684. assert((pg1+nPage)>pPg->pgno);
  43685. for(ii=0; ii<nPage && rc==SQLITE_OK; ii++){
  43686. Pgno pg = pg1+ii;
  43687. PgHdr *pPage;
  43688. if( pg==pPg->pgno || !sqlite3BitvecTest(pPager->pInJournal, pg) ){
  43689. if( pg!=PAGER_MJ_PGNO(pPager) ){
  43690. rc = sqlite3PagerGet(pPager, pg, &pPage);
  43691. if( rc==SQLITE_OK ){
  43692. rc = pager_write(pPage);
  43693. if( pPage->flags&PGHDR_NEED_SYNC ){
  43694. needSync = 1;
  43695. }
  43696. sqlite3PagerUnrefNotNull(pPage);
  43697. }
  43698. }
  43699. }else if( (pPage = sqlite3PagerLookup(pPager, pg))!=0 ){
  43700. if( pPage->flags&PGHDR_NEED_SYNC ){
  43701. needSync = 1;
  43702. }
  43703. sqlite3PagerUnrefNotNull(pPage);
  43704. }
  43705. }
  43706. /* If the PGHDR_NEED_SYNC flag is set for any of the nPage pages
  43707. ** starting at pg1, then it needs to be set for all of them. Because
  43708. ** writing to any of these nPage pages may damage the others, the
  43709. ** journal file must contain sync()ed copies of all of them
  43710. ** before any of them can be written out to the database file.
  43711. */
  43712. if( rc==SQLITE_OK && needSync ){
  43713. assert( !MEMDB );
  43714. for(ii=0; ii<nPage; ii++){
  43715. PgHdr *pPage = sqlite3PagerLookup(pPager, pg1+ii);
  43716. if( pPage ){
  43717. pPage->flags |= PGHDR_NEED_SYNC;
  43718. sqlite3PagerUnrefNotNull(pPage);
  43719. }
  43720. }
  43721. }
  43722. assert( (pPager->doNotSpill & SPILLFLAG_NOSYNC)!=0 );
  43723. pPager->doNotSpill &= ~SPILLFLAG_NOSYNC;
  43724. return rc;
  43725. }
  43726. /*
  43727. ** Mark a data page as writeable. This routine must be called before
  43728. ** making changes to a page. The caller must check the return value
  43729. ** of this function and be careful not to change any page data unless
  43730. ** this routine returns SQLITE_OK.
  43731. **
  43732. ** The difference between this function and pager_write() is that this
  43733. ** function also deals with the special case where 2 or more pages
  43734. ** fit on a single disk sector. In this case all co-resident pages
  43735. ** must have been written to the journal file before returning.
  43736. **
  43737. ** If an error occurs, SQLITE_NOMEM or an IO error code is returned
  43738. ** as appropriate. Otherwise, SQLITE_OK.
  43739. */
  43740. SQLITE_PRIVATE int sqlite3PagerWrite(PgHdr *pPg){
  43741. assert( (pPg->flags & PGHDR_MMAP)==0 );
  43742. assert( pPg->pPager->eState>=PAGER_WRITER_LOCKED );
  43743. assert( pPg->pPager->eState!=PAGER_ERROR );
  43744. assert( assert_pager_state(pPg->pPager) );
  43745. if( pPg->pPager->sectorSize > (u32)pPg->pPager->pageSize ){
  43746. return pagerWriteLargeSector(pPg);
  43747. }else{
  43748. return pager_write(pPg);
  43749. }
  43750. }
  43751. /*
  43752. ** Return TRUE if the page given in the argument was previously passed
  43753. ** to sqlite3PagerWrite(). In other words, return TRUE if it is ok
  43754. ** to change the content of the page.
  43755. */
  43756. #ifndef NDEBUG
  43757. SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage *pPg){
  43758. return pPg->flags&PGHDR_DIRTY;
  43759. }
  43760. #endif
  43761. /*
  43762. ** A call to this routine tells the pager that it is not necessary to
  43763. ** write the information on page pPg back to the disk, even though
  43764. ** that page might be marked as dirty. This happens, for example, when
  43765. ** the page has been added as a leaf of the freelist and so its
  43766. ** content no longer matters.
  43767. **
  43768. ** The overlying software layer calls this routine when all of the data
  43769. ** on the given page is unused. The pager marks the page as clean so
  43770. ** that it does not get written to disk.
  43771. **
  43772. ** Tests show that this optimization can quadruple the speed of large
  43773. ** DELETE operations.
  43774. */
  43775. SQLITE_PRIVATE void sqlite3PagerDontWrite(PgHdr *pPg){
  43776. Pager *pPager = pPg->pPager;
  43777. if( (pPg->flags&PGHDR_DIRTY) && pPager->nSavepoint==0 ){
  43778. PAGERTRACE(("DONT_WRITE page %d of %d\n", pPg->pgno, PAGERID(pPager)));
  43779. IOTRACE(("CLEAN %p %d\n", pPager, pPg->pgno))
  43780. pPg->flags |= PGHDR_DONT_WRITE;
  43781. pager_set_pagehash(pPg);
  43782. }
  43783. }
  43784. /*
  43785. ** This routine is called to increment the value of the database file
  43786. ** change-counter, stored as a 4-byte big-endian integer starting at
  43787. ** byte offset 24 of the pager file. The secondary change counter at
  43788. ** 92 is also updated, as is the SQLite version number at offset 96.
  43789. **
  43790. ** But this only happens if the pPager->changeCountDone flag is false.
  43791. ** To avoid excess churning of page 1, the update only happens once.
  43792. ** See also the pager_write_changecounter() routine that does an
  43793. ** unconditional update of the change counters.
  43794. **
  43795. ** If the isDirectMode flag is zero, then this is done by calling
  43796. ** sqlite3PagerWrite() on page 1, then modifying the contents of the
  43797. ** page data. In this case the file will be updated when the current
  43798. ** transaction is committed.
  43799. **
  43800. ** The isDirectMode flag may only be non-zero if the library was compiled
  43801. ** with the SQLITE_ENABLE_ATOMIC_WRITE macro defined. In this case,
  43802. ** if isDirect is non-zero, then the database file is updated directly
  43803. ** by writing an updated version of page 1 using a call to the
  43804. ** sqlite3OsWrite() function.
  43805. */
  43806. static int pager_incr_changecounter(Pager *pPager, int isDirectMode){
  43807. int rc = SQLITE_OK;
  43808. assert( pPager->eState==PAGER_WRITER_CACHEMOD
  43809. || pPager->eState==PAGER_WRITER_DBMOD
  43810. );
  43811. assert( assert_pager_state(pPager) );
  43812. /* Declare and initialize constant integer 'isDirect'. If the
  43813. ** atomic-write optimization is enabled in this build, then isDirect
  43814. ** is initialized to the value passed as the isDirectMode parameter
  43815. ** to this function. Otherwise, it is always set to zero.
  43816. **
  43817. ** The idea is that if the atomic-write optimization is not
  43818. ** enabled at compile time, the compiler can omit the tests of
  43819. ** 'isDirect' below, as well as the block enclosed in the
  43820. ** "if( isDirect )" condition.
  43821. */
  43822. #ifndef SQLITE_ENABLE_ATOMIC_WRITE
  43823. # define DIRECT_MODE 0
  43824. assert( isDirectMode==0 );
  43825. UNUSED_PARAMETER(isDirectMode);
  43826. #else
  43827. # define DIRECT_MODE isDirectMode
  43828. #endif
  43829. if( !pPager->changeCountDone && ALWAYS(pPager->dbSize>0) ){
  43830. PgHdr *pPgHdr; /* Reference to page 1 */
  43831. assert( !pPager->tempFile && isOpen(pPager->fd) );
  43832. /* Open page 1 of the file for writing. */
  43833. rc = sqlite3PagerGet(pPager, 1, &pPgHdr);
  43834. assert( pPgHdr==0 || rc==SQLITE_OK );
  43835. /* If page one was fetched successfully, and this function is not
  43836. ** operating in direct-mode, make page 1 writable. When not in
  43837. ** direct mode, page 1 is always held in cache and hence the PagerGet()
  43838. ** above is always successful - hence the ALWAYS on rc==SQLITE_OK.
  43839. */
  43840. if( !DIRECT_MODE && ALWAYS(rc==SQLITE_OK) ){
  43841. rc = sqlite3PagerWrite(pPgHdr);
  43842. }
  43843. if( rc==SQLITE_OK ){
  43844. /* Actually do the update of the change counter */
  43845. pager_write_changecounter(pPgHdr);
  43846. /* If running in direct mode, write the contents of page 1 to the file. */
  43847. if( DIRECT_MODE ){
  43848. const void *zBuf;
  43849. assert( pPager->dbFileSize>0 );
  43850. CODEC2(pPager, pPgHdr->pData, 1, 6, rc=SQLITE_NOMEM, zBuf);
  43851. if( rc==SQLITE_OK ){
  43852. rc = sqlite3OsWrite(pPager->fd, zBuf, pPager->pageSize, 0);
  43853. pPager->aStat[PAGER_STAT_WRITE]++;
  43854. }
  43855. if( rc==SQLITE_OK ){
  43856. /* Update the pager's copy of the change-counter. Otherwise, the
  43857. ** next time a read transaction is opened the cache will be
  43858. ** flushed (as the change-counter values will not match). */
  43859. const void *pCopy = (const void *)&((const char *)zBuf)[24];
  43860. memcpy(&pPager->dbFileVers, pCopy, sizeof(pPager->dbFileVers));
  43861. pPager->changeCountDone = 1;
  43862. }
  43863. }else{
  43864. pPager->changeCountDone = 1;
  43865. }
  43866. }
  43867. /* Release the page reference. */
  43868. sqlite3PagerUnref(pPgHdr);
  43869. }
  43870. return rc;
  43871. }
  43872. /*
  43873. ** Sync the database file to disk. This is a no-op for in-memory databases
  43874. ** or pages with the Pager.noSync flag set.
  43875. **
  43876. ** If successful, or if called on a pager for which it is a no-op, this
  43877. ** function returns SQLITE_OK. Otherwise, an IO error code is returned.
  43878. */
  43879. SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager, const char *zMaster){
  43880. int rc = SQLITE_OK;
  43881. if( isOpen(pPager->fd) ){
  43882. void *pArg = (void*)zMaster;
  43883. rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_SYNC, pArg);
  43884. if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
  43885. }
  43886. if( rc==SQLITE_OK && !pPager->noSync ){
  43887. assert( !MEMDB );
  43888. rc = sqlite3OsSync(pPager->fd, pPager->syncFlags);
  43889. }
  43890. return rc;
  43891. }
  43892. /*
  43893. ** This function may only be called while a write-transaction is active in
  43894. ** rollback. If the connection is in WAL mode, this call is a no-op.
  43895. ** Otherwise, if the connection does not already have an EXCLUSIVE lock on
  43896. ** the database file, an attempt is made to obtain one.
  43897. **
  43898. ** If the EXCLUSIVE lock is already held or the attempt to obtain it is
  43899. ** successful, or the connection is in WAL mode, SQLITE_OK is returned.
  43900. ** Otherwise, either SQLITE_BUSY or an SQLITE_IOERR_XXX error code is
  43901. ** returned.
  43902. */
  43903. SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager *pPager){
  43904. int rc = SQLITE_OK;
  43905. assert( pPager->eState==PAGER_WRITER_CACHEMOD
  43906. || pPager->eState==PAGER_WRITER_DBMOD
  43907. || pPager->eState==PAGER_WRITER_LOCKED
  43908. );
  43909. assert( assert_pager_state(pPager) );
  43910. if( 0==pagerUseWal(pPager) ){
  43911. rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
  43912. }
  43913. return rc;
  43914. }
  43915. /*
  43916. ** Sync the database file for the pager pPager. zMaster points to the name
  43917. ** of a master journal file that should be written into the individual
  43918. ** journal file. zMaster may be NULL, which is interpreted as no master
  43919. ** journal (a single database transaction).
  43920. **
  43921. ** This routine ensures that:
  43922. **
  43923. ** * The database file change-counter is updated,
  43924. ** * the journal is synced (unless the atomic-write optimization is used),
  43925. ** * all dirty pages are written to the database file,
  43926. ** * the database file is truncated (if required), and
  43927. ** * the database file synced.
  43928. **
  43929. ** The only thing that remains to commit the transaction is to finalize
  43930. ** (delete, truncate or zero the first part of) the journal file (or
  43931. ** delete the master journal file if specified).
  43932. **
  43933. ** Note that if zMaster==NULL, this does not overwrite a previous value
  43934. ** passed to an sqlite3PagerCommitPhaseOne() call.
  43935. **
  43936. ** If the final parameter - noSync - is true, then the database file itself
  43937. ** is not synced. The caller must call sqlite3PagerSync() directly to
  43938. ** sync the database file before calling CommitPhaseTwo() to delete the
  43939. ** journal file in this case.
  43940. */
  43941. SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(
  43942. Pager *pPager, /* Pager object */
  43943. const char *zMaster, /* If not NULL, the master journal name */
  43944. int noSync /* True to omit the xSync on the db file */
  43945. ){
  43946. int rc = SQLITE_OK; /* Return code */
  43947. assert( pPager->eState==PAGER_WRITER_LOCKED
  43948. || pPager->eState==PAGER_WRITER_CACHEMOD
  43949. || pPager->eState==PAGER_WRITER_DBMOD
  43950. || pPager->eState==PAGER_ERROR
  43951. );
  43952. assert( assert_pager_state(pPager) );
  43953. /* If a prior error occurred, report that error again. */
  43954. if( NEVER(pPager->errCode) ) return pPager->errCode;
  43955. PAGERTRACE(("DATABASE SYNC: File=%s zMaster=%s nSize=%d\n",
  43956. pPager->zFilename, zMaster, pPager->dbSize));
  43957. /* If no database changes have been made, return early. */
  43958. if( pPager->eState<PAGER_WRITER_CACHEMOD ) return SQLITE_OK;
  43959. if( MEMDB ){
  43960. /* If this is an in-memory db, or no pages have been written to, or this
  43961. ** function has already been called, it is mostly a no-op. However, any
  43962. ** backup in progress needs to be restarted.
  43963. */
  43964. sqlite3BackupRestart(pPager->pBackup);
  43965. }else{
  43966. if( pagerUseWal(pPager) ){
  43967. PgHdr *pList = sqlite3PcacheDirtyList(pPager->pPCache);
  43968. PgHdr *pPageOne = 0;
  43969. if( pList==0 ){
  43970. /* Must have at least one page for the WAL commit flag.
  43971. ** Ticket [2d1a5c67dfc2363e44f29d9bbd57f] 2011-05-18 */
  43972. rc = sqlite3PagerGet(pPager, 1, &pPageOne);
  43973. pList = pPageOne;
  43974. pList->pDirty = 0;
  43975. }
  43976. assert( rc==SQLITE_OK );
  43977. if( ALWAYS(pList) ){
  43978. rc = pagerWalFrames(pPager, pList, pPager->dbSize, 1);
  43979. }
  43980. sqlite3PagerUnref(pPageOne);
  43981. if( rc==SQLITE_OK ){
  43982. sqlite3PcacheCleanAll(pPager->pPCache);
  43983. }
  43984. }else{
  43985. /* The following block updates the change-counter. Exactly how it
  43986. ** does this depends on whether or not the atomic-update optimization
  43987. ** was enabled at compile time, and if this transaction meets the
  43988. ** runtime criteria to use the operation:
  43989. **
  43990. ** * The file-system supports the atomic-write property for
  43991. ** blocks of size page-size, and
  43992. ** * This commit is not part of a multi-file transaction, and
  43993. ** * Exactly one page has been modified and store in the journal file.
  43994. **
  43995. ** If the optimization was not enabled at compile time, then the
  43996. ** pager_incr_changecounter() function is called to update the change
  43997. ** counter in 'indirect-mode'. If the optimization is compiled in but
  43998. ** is not applicable to this transaction, call sqlite3JournalCreate()
  43999. ** to make sure the journal file has actually been created, then call
  44000. ** pager_incr_changecounter() to update the change-counter in indirect
  44001. ** mode.
  44002. **
  44003. ** Otherwise, if the optimization is both enabled and applicable,
  44004. ** then call pager_incr_changecounter() to update the change-counter
  44005. ** in 'direct' mode. In this case the journal file will never be
  44006. ** created for this transaction.
  44007. */
  44008. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  44009. PgHdr *pPg;
  44010. assert( isOpen(pPager->jfd)
  44011. || pPager->journalMode==PAGER_JOURNALMODE_OFF
  44012. || pPager->journalMode==PAGER_JOURNALMODE_WAL
  44013. );
  44014. if( !zMaster && isOpen(pPager->jfd)
  44015. && pPager->journalOff==jrnlBufferSize(pPager)
  44016. && pPager->dbSize>=pPager->dbOrigSize
  44017. && (0==(pPg = sqlite3PcacheDirtyList(pPager->pPCache)) || 0==pPg->pDirty)
  44018. ){
  44019. /* Update the db file change counter via the direct-write method. The
  44020. ** following call will modify the in-memory representation of page 1
  44021. ** to include the updated change counter and then write page 1
  44022. ** directly to the database file. Because of the atomic-write
  44023. ** property of the host file-system, this is safe.
  44024. */
  44025. rc = pager_incr_changecounter(pPager, 1);
  44026. }else{
  44027. rc = sqlite3JournalCreate(pPager->jfd);
  44028. if( rc==SQLITE_OK ){
  44029. rc = pager_incr_changecounter(pPager, 0);
  44030. }
  44031. }
  44032. #else
  44033. rc = pager_incr_changecounter(pPager, 0);
  44034. #endif
  44035. if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
  44036. /* Write the master journal name into the journal file. If a master
  44037. ** journal file name has already been written to the journal file,
  44038. ** or if zMaster is NULL (no master journal), then this call is a no-op.
  44039. */
  44040. rc = writeMasterJournal(pPager, zMaster);
  44041. if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
  44042. /* Sync the journal file and write all dirty pages to the database.
  44043. ** If the atomic-update optimization is being used, this sync will not
  44044. ** create the journal file or perform any real IO.
  44045. **
  44046. ** Because the change-counter page was just modified, unless the
  44047. ** atomic-update optimization is used it is almost certain that the
  44048. ** journal requires a sync here. However, in locking_mode=exclusive
  44049. ** on a system under memory pressure it is just possible that this is
  44050. ** not the case. In this case it is likely enough that the redundant
  44051. ** xSync() call will be changed to a no-op by the OS anyhow.
  44052. */
  44053. rc = syncJournal(pPager, 0);
  44054. if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
  44055. rc = pager_write_pagelist(pPager,sqlite3PcacheDirtyList(pPager->pPCache));
  44056. if( rc!=SQLITE_OK ){
  44057. assert( rc!=SQLITE_IOERR_BLOCKED );
  44058. goto commit_phase_one_exit;
  44059. }
  44060. sqlite3PcacheCleanAll(pPager->pPCache);
  44061. /* If the file on disk is smaller than the database image, use
  44062. ** pager_truncate to grow the file here. This can happen if the database
  44063. ** image was extended as part of the current transaction and then the
  44064. ** last page in the db image moved to the free-list. In this case the
  44065. ** last page is never written out to disk, leaving the database file
  44066. ** undersized. Fix this now if it is the case. */
  44067. if( pPager->dbSize>pPager->dbFileSize ){
  44068. Pgno nNew = pPager->dbSize - (pPager->dbSize==PAGER_MJ_PGNO(pPager));
  44069. assert( pPager->eState==PAGER_WRITER_DBMOD );
  44070. rc = pager_truncate(pPager, nNew);
  44071. if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
  44072. }
  44073. /* Finally, sync the database file. */
  44074. if( !noSync ){
  44075. rc = sqlite3PagerSync(pPager, zMaster);
  44076. }
  44077. IOTRACE(("DBSYNC %p\n", pPager))
  44078. }
  44079. }
  44080. commit_phase_one_exit:
  44081. if( rc==SQLITE_OK && !pagerUseWal(pPager) ){
  44082. pPager->eState = PAGER_WRITER_FINISHED;
  44083. }
  44084. return rc;
  44085. }
  44086. /*
  44087. ** When this function is called, the database file has been completely
  44088. ** updated to reflect the changes made by the current transaction and
  44089. ** synced to disk. The journal file still exists in the file-system
  44090. ** though, and if a failure occurs at this point it will eventually
  44091. ** be used as a hot-journal and the current transaction rolled back.
  44092. **
  44093. ** This function finalizes the journal file, either by deleting,
  44094. ** truncating or partially zeroing it, so that it cannot be used
  44095. ** for hot-journal rollback. Once this is done the transaction is
  44096. ** irrevocably committed.
  44097. **
  44098. ** If an error occurs, an IO error code is returned and the pager
  44099. ** moves into the error state. Otherwise, SQLITE_OK is returned.
  44100. */
  44101. SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager *pPager){
  44102. int rc = SQLITE_OK; /* Return code */
  44103. /* This routine should not be called if a prior error has occurred.
  44104. ** But if (due to a coding error elsewhere in the system) it does get
  44105. ** called, just return the same error code without doing anything. */
  44106. if( NEVER(pPager->errCode) ) return pPager->errCode;
  44107. assert( pPager->eState==PAGER_WRITER_LOCKED
  44108. || pPager->eState==PAGER_WRITER_FINISHED
  44109. || (pagerUseWal(pPager) && pPager->eState==PAGER_WRITER_CACHEMOD)
  44110. );
  44111. assert( assert_pager_state(pPager) );
  44112. /* An optimization. If the database was not actually modified during
  44113. ** this transaction, the pager is running in exclusive-mode and is
  44114. ** using persistent journals, then this function is a no-op.
  44115. **
  44116. ** The start of the journal file currently contains a single journal
  44117. ** header with the nRec field set to 0. If such a journal is used as
  44118. ** a hot-journal during hot-journal rollback, 0 changes will be made
  44119. ** to the database file. So there is no need to zero the journal
  44120. ** header. Since the pager is in exclusive mode, there is no need
  44121. ** to drop any locks either.
  44122. */
  44123. if( pPager->eState==PAGER_WRITER_LOCKED
  44124. && pPager->exclusiveMode
  44125. && pPager->journalMode==PAGER_JOURNALMODE_PERSIST
  44126. ){
  44127. assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) || !pPager->journalOff );
  44128. pPager->eState = PAGER_READER;
  44129. return SQLITE_OK;
  44130. }
  44131. PAGERTRACE(("COMMIT %d\n", PAGERID(pPager)));
  44132. rc = pager_end_transaction(pPager, pPager->setMaster, 1);
  44133. return pager_error(pPager, rc);
  44134. }
  44135. /*
  44136. ** If a write transaction is open, then all changes made within the
  44137. ** transaction are reverted and the current write-transaction is closed.
  44138. ** The pager falls back to PAGER_READER state if successful, or PAGER_ERROR
  44139. ** state if an error occurs.
  44140. **
  44141. ** If the pager is already in PAGER_ERROR state when this function is called,
  44142. ** it returns Pager.errCode immediately. No work is performed in this case.
  44143. **
  44144. ** Otherwise, in rollback mode, this function performs two functions:
  44145. **
  44146. ** 1) It rolls back the journal file, restoring all database file and
  44147. ** in-memory cache pages to the state they were in when the transaction
  44148. ** was opened, and
  44149. **
  44150. ** 2) It finalizes the journal file, so that it is not used for hot
  44151. ** rollback at any point in the future.
  44152. **
  44153. ** Finalization of the journal file (task 2) is only performed if the
  44154. ** rollback is successful.
  44155. **
  44156. ** In WAL mode, all cache-entries containing data modified within the
  44157. ** current transaction are either expelled from the cache or reverted to
  44158. ** their pre-transaction state by re-reading data from the database or
  44159. ** WAL files. The WAL transaction is then closed.
  44160. */
  44161. SQLITE_PRIVATE int sqlite3PagerRollback(Pager *pPager){
  44162. int rc = SQLITE_OK; /* Return code */
  44163. PAGERTRACE(("ROLLBACK %d\n", PAGERID(pPager)));
  44164. /* PagerRollback() is a no-op if called in READER or OPEN state. If
  44165. ** the pager is already in the ERROR state, the rollback is not
  44166. ** attempted here. Instead, the error code is returned to the caller.
  44167. */
  44168. assert( assert_pager_state(pPager) );
  44169. if( pPager->eState==PAGER_ERROR ) return pPager->errCode;
  44170. if( pPager->eState<=PAGER_READER ) return SQLITE_OK;
  44171. if( pagerUseWal(pPager) ){
  44172. int rc2;
  44173. rc = sqlite3PagerSavepoint(pPager, SAVEPOINT_ROLLBACK, -1);
  44174. rc2 = pager_end_transaction(pPager, pPager->setMaster, 0);
  44175. if( rc==SQLITE_OK ) rc = rc2;
  44176. }else if( !isOpen(pPager->jfd) || pPager->eState==PAGER_WRITER_LOCKED ){
  44177. int eState = pPager->eState;
  44178. rc = pager_end_transaction(pPager, 0, 0);
  44179. if( !MEMDB && eState>PAGER_WRITER_LOCKED ){
  44180. /* This can happen using journal_mode=off. Move the pager to the error
  44181. ** state to indicate that the contents of the cache may not be trusted.
  44182. ** Any active readers will get SQLITE_ABORT.
  44183. */
  44184. pPager->errCode = SQLITE_ABORT;
  44185. pPager->eState = PAGER_ERROR;
  44186. return rc;
  44187. }
  44188. }else{
  44189. rc = pager_playback(pPager, 0);
  44190. }
  44191. assert( pPager->eState==PAGER_READER || rc!=SQLITE_OK );
  44192. assert( rc==SQLITE_OK || rc==SQLITE_FULL || rc==SQLITE_CORRUPT
  44193. || rc==SQLITE_NOMEM || (rc&0xFF)==SQLITE_IOERR
  44194. || rc==SQLITE_CANTOPEN
  44195. );
  44196. /* If an error occurs during a ROLLBACK, we can no longer trust the pager
  44197. ** cache. So call pager_error() on the way out to make any error persistent.
  44198. */
  44199. return pager_error(pPager, rc);
  44200. }
  44201. /*
  44202. ** Return TRUE if the database file is opened read-only. Return FALSE
  44203. ** if the database is (in theory) writable.
  44204. */
  44205. SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager *pPager){
  44206. return pPager->readOnly;
  44207. }
  44208. /*
  44209. ** Return the number of references to the pager.
  44210. */
  44211. SQLITE_PRIVATE int sqlite3PagerRefcount(Pager *pPager){
  44212. return sqlite3PcacheRefCount(pPager->pPCache);
  44213. }
  44214. /*
  44215. ** Return the approximate number of bytes of memory currently
  44216. ** used by the pager and its associated cache.
  44217. */
  44218. SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager *pPager){
  44219. int perPageSize = pPager->pageSize + pPager->nExtra + sizeof(PgHdr)
  44220. + 5*sizeof(void*);
  44221. return perPageSize*sqlite3PcachePagecount(pPager->pPCache)
  44222. + sqlite3MallocSize(pPager)
  44223. + pPager->pageSize;
  44224. }
  44225. /*
  44226. ** Return the number of references to the specified page.
  44227. */
  44228. SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage *pPage){
  44229. return sqlite3PcachePageRefcount(pPage);
  44230. }
  44231. #ifdef SQLITE_TEST
  44232. /*
  44233. ** This routine is used for testing and analysis only.
  44234. */
  44235. SQLITE_PRIVATE int *sqlite3PagerStats(Pager *pPager){
  44236. static int a[11];
  44237. a[0] = sqlite3PcacheRefCount(pPager->pPCache);
  44238. a[1] = sqlite3PcachePagecount(pPager->pPCache);
  44239. a[2] = sqlite3PcacheGetCachesize(pPager->pPCache);
  44240. a[3] = pPager->eState==PAGER_OPEN ? -1 : (int) pPager->dbSize;
  44241. a[4] = pPager->eState;
  44242. a[5] = pPager->errCode;
  44243. a[6] = pPager->aStat[PAGER_STAT_HIT];
  44244. a[7] = pPager->aStat[PAGER_STAT_MISS];
  44245. a[8] = 0; /* Used to be pPager->nOvfl */
  44246. a[9] = pPager->nRead;
  44247. a[10] = pPager->aStat[PAGER_STAT_WRITE];
  44248. return a;
  44249. }
  44250. #endif
  44251. /*
  44252. ** Parameter eStat must be either SQLITE_DBSTATUS_CACHE_HIT or
  44253. ** SQLITE_DBSTATUS_CACHE_MISS. Before returning, *pnVal is incremented by the
  44254. ** current cache hit or miss count, according to the value of eStat. If the
  44255. ** reset parameter is non-zero, the cache hit or miss count is zeroed before
  44256. ** returning.
  44257. */
  44258. SQLITE_PRIVATE void sqlite3PagerCacheStat(Pager *pPager, int eStat, int reset, int *pnVal){
  44259. assert( eStat==SQLITE_DBSTATUS_CACHE_HIT
  44260. || eStat==SQLITE_DBSTATUS_CACHE_MISS
  44261. || eStat==SQLITE_DBSTATUS_CACHE_WRITE
  44262. );
  44263. assert( SQLITE_DBSTATUS_CACHE_HIT+1==SQLITE_DBSTATUS_CACHE_MISS );
  44264. assert( SQLITE_DBSTATUS_CACHE_HIT+2==SQLITE_DBSTATUS_CACHE_WRITE );
  44265. assert( PAGER_STAT_HIT==0 && PAGER_STAT_MISS==1 && PAGER_STAT_WRITE==2 );
  44266. *pnVal += pPager->aStat[eStat - SQLITE_DBSTATUS_CACHE_HIT];
  44267. if( reset ){
  44268. pPager->aStat[eStat - SQLITE_DBSTATUS_CACHE_HIT] = 0;
  44269. }
  44270. }
  44271. /*
  44272. ** Return true if this is an in-memory pager.
  44273. */
  44274. SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager *pPager){
  44275. return MEMDB;
  44276. }
  44277. /*
  44278. ** Check that there are at least nSavepoint savepoints open. If there are
  44279. ** currently less than nSavepoints open, then open one or more savepoints
  44280. ** to make up the difference. If the number of savepoints is already
  44281. ** equal to nSavepoint, then this function is a no-op.
  44282. **
  44283. ** If a memory allocation fails, SQLITE_NOMEM is returned. If an error
  44284. ** occurs while opening the sub-journal file, then an IO error code is
  44285. ** returned. Otherwise, SQLITE_OK.
  44286. */
  44287. SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int nSavepoint){
  44288. int rc = SQLITE_OK; /* Return code */
  44289. int nCurrent = pPager->nSavepoint; /* Current number of savepoints */
  44290. assert( pPager->eState>=PAGER_WRITER_LOCKED );
  44291. assert( assert_pager_state(pPager) );
  44292. if( nSavepoint>nCurrent && pPager->useJournal ){
  44293. int ii; /* Iterator variable */
  44294. PagerSavepoint *aNew; /* New Pager.aSavepoint array */
  44295. /* Grow the Pager.aSavepoint array using realloc(). Return SQLITE_NOMEM
  44296. ** if the allocation fails. Otherwise, zero the new portion in case a
  44297. ** malloc failure occurs while populating it in the for(...) loop below.
  44298. */
  44299. aNew = (PagerSavepoint *)sqlite3Realloc(
  44300. pPager->aSavepoint, sizeof(PagerSavepoint)*nSavepoint
  44301. );
  44302. if( !aNew ){
  44303. return SQLITE_NOMEM;
  44304. }
  44305. memset(&aNew[nCurrent], 0, (nSavepoint-nCurrent) * sizeof(PagerSavepoint));
  44306. pPager->aSavepoint = aNew;
  44307. /* Populate the PagerSavepoint structures just allocated. */
  44308. for(ii=nCurrent; ii<nSavepoint; ii++){
  44309. aNew[ii].nOrig = pPager->dbSize;
  44310. if( isOpen(pPager->jfd) && pPager->journalOff>0 ){
  44311. aNew[ii].iOffset = pPager->journalOff;
  44312. }else{
  44313. aNew[ii].iOffset = JOURNAL_HDR_SZ(pPager);
  44314. }
  44315. aNew[ii].iSubRec = pPager->nSubRec;
  44316. aNew[ii].pInSavepoint = sqlite3BitvecCreate(pPager->dbSize);
  44317. if( !aNew[ii].pInSavepoint ){
  44318. return SQLITE_NOMEM;
  44319. }
  44320. if( pagerUseWal(pPager) ){
  44321. sqlite3WalSavepoint(pPager->pWal, aNew[ii].aWalData);
  44322. }
  44323. pPager->nSavepoint = ii+1;
  44324. }
  44325. assert( pPager->nSavepoint==nSavepoint );
  44326. assertTruncateConstraint(pPager);
  44327. }
  44328. return rc;
  44329. }
  44330. /*
  44331. ** This function is called to rollback or release (commit) a savepoint.
  44332. ** The savepoint to release or rollback need not be the most recently
  44333. ** created savepoint.
  44334. **
  44335. ** Parameter op is always either SAVEPOINT_ROLLBACK or SAVEPOINT_RELEASE.
  44336. ** If it is SAVEPOINT_RELEASE, then release and destroy the savepoint with
  44337. ** index iSavepoint. If it is SAVEPOINT_ROLLBACK, then rollback all changes
  44338. ** that have occurred since the specified savepoint was created.
  44339. **
  44340. ** The savepoint to rollback or release is identified by parameter
  44341. ** iSavepoint. A value of 0 means to operate on the outermost savepoint
  44342. ** (the first created). A value of (Pager.nSavepoint-1) means operate
  44343. ** on the most recently created savepoint. If iSavepoint is greater than
  44344. ** (Pager.nSavepoint-1), then this function is a no-op.
  44345. **
  44346. ** If a negative value is passed to this function, then the current
  44347. ** transaction is rolled back. This is different to calling
  44348. ** sqlite3PagerRollback() because this function does not terminate
  44349. ** the transaction or unlock the database, it just restores the
  44350. ** contents of the database to its original state.
  44351. **
  44352. ** In any case, all savepoints with an index greater than iSavepoint
  44353. ** are destroyed. If this is a release operation (op==SAVEPOINT_RELEASE),
  44354. ** then savepoint iSavepoint is also destroyed.
  44355. **
  44356. ** This function may return SQLITE_NOMEM if a memory allocation fails,
  44357. ** or an IO error code if an IO error occurs while rolling back a
  44358. ** savepoint. If no errors occur, SQLITE_OK is returned.
  44359. */
  44360. SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint){
  44361. int rc = pPager->errCode; /* Return code */
  44362. assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
  44363. assert( iSavepoint>=0 || op==SAVEPOINT_ROLLBACK );
  44364. if( rc==SQLITE_OK && iSavepoint<pPager->nSavepoint ){
  44365. int ii; /* Iterator variable */
  44366. int nNew; /* Number of remaining savepoints after this op. */
  44367. /* Figure out how many savepoints will still be active after this
  44368. ** operation. Store this value in nNew. Then free resources associated
  44369. ** with any savepoints that are destroyed by this operation.
  44370. */
  44371. nNew = iSavepoint + (( op==SAVEPOINT_RELEASE ) ? 0 : 1);
  44372. for(ii=nNew; ii<pPager->nSavepoint; ii++){
  44373. sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
  44374. }
  44375. pPager->nSavepoint = nNew;
  44376. /* If this is a release of the outermost savepoint, truncate
  44377. ** the sub-journal to zero bytes in size. */
  44378. if( op==SAVEPOINT_RELEASE ){
  44379. if( nNew==0 && isOpen(pPager->sjfd) ){
  44380. /* Only truncate if it is an in-memory sub-journal. */
  44381. if( sqlite3IsMemJournal(pPager->sjfd) ){
  44382. rc = sqlite3OsTruncate(pPager->sjfd, 0);
  44383. assert( rc==SQLITE_OK );
  44384. }
  44385. pPager->nSubRec = 0;
  44386. }
  44387. }
  44388. /* Else this is a rollback operation, playback the specified savepoint.
  44389. ** If this is a temp-file, it is possible that the journal file has
  44390. ** not yet been opened. In this case there have been no changes to
  44391. ** the database file, so the playback operation can be skipped.
  44392. */
  44393. else if( pagerUseWal(pPager) || isOpen(pPager->jfd) ){
  44394. PagerSavepoint *pSavepoint = (nNew==0)?0:&pPager->aSavepoint[nNew-1];
  44395. rc = pagerPlaybackSavepoint(pPager, pSavepoint);
  44396. assert(rc!=SQLITE_DONE);
  44397. }
  44398. }
  44399. return rc;
  44400. }
  44401. /*
  44402. ** Return the full pathname of the database file.
  44403. **
  44404. ** Except, if the pager is in-memory only, then return an empty string if
  44405. ** nullIfMemDb is true. This routine is called with nullIfMemDb==1 when
  44406. ** used to report the filename to the user, for compatibility with legacy
  44407. ** behavior. But when the Btree needs to know the filename for matching to
  44408. ** shared cache, it uses nullIfMemDb==0 so that in-memory databases can
  44409. ** participate in shared-cache.
  44410. */
  44411. SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager *pPager, int nullIfMemDb){
  44412. return (nullIfMemDb && pPager->memDb) ? "" : pPager->zFilename;
  44413. }
  44414. /*
  44415. ** Return the VFS structure for the pager.
  44416. */
  44417. SQLITE_PRIVATE const sqlite3_vfs *sqlite3PagerVfs(Pager *pPager){
  44418. return pPager->pVfs;
  44419. }
  44420. /*
  44421. ** Return the file handle for the database file associated
  44422. ** with the pager. This might return NULL if the file has
  44423. ** not yet been opened.
  44424. */
  44425. SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager *pPager){
  44426. return pPager->fd;
  44427. }
  44428. /*
  44429. ** Return the full pathname of the journal file.
  44430. */
  44431. SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager *pPager){
  44432. return pPager->zJournal;
  44433. }
  44434. /*
  44435. ** Return true if fsync() calls are disabled for this pager. Return FALSE
  44436. ** if fsync()s are executed normally.
  44437. */
  44438. SQLITE_PRIVATE int sqlite3PagerNosync(Pager *pPager){
  44439. return pPager->noSync;
  44440. }
  44441. #ifdef SQLITE_HAS_CODEC
  44442. /*
  44443. ** Set or retrieve the codec for this pager
  44444. */
  44445. SQLITE_PRIVATE void sqlite3PagerSetCodec(
  44446. Pager *pPager,
  44447. void *(*xCodec)(void*,void*,Pgno,int),
  44448. void (*xCodecSizeChng)(void*,int,int),
  44449. void (*xCodecFree)(void*),
  44450. void *pCodec
  44451. ){
  44452. if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
  44453. pPager->xCodec = pPager->memDb ? 0 : xCodec;
  44454. pPager->xCodecSizeChng = xCodecSizeChng;
  44455. pPager->xCodecFree = xCodecFree;
  44456. pPager->pCodec = pCodec;
  44457. pagerReportSize(pPager);
  44458. }
  44459. SQLITE_PRIVATE void *sqlite3PagerGetCodec(Pager *pPager){
  44460. return pPager->pCodec;
  44461. }
  44462. /*
  44463. ** This function is called by the wal module when writing page content
  44464. ** into the log file.
  44465. **
  44466. ** This function returns a pointer to a buffer containing the encrypted
  44467. ** page content. If a malloc fails, this function may return NULL.
  44468. */
  44469. SQLITE_PRIVATE void *sqlite3PagerCodec(PgHdr *pPg){
  44470. void *aData = 0;
  44471. CODEC2(pPg->pPager, pPg->pData, pPg->pgno, 6, return 0, aData);
  44472. return aData;
  44473. }
  44474. /*
  44475. ** Return the current pager state
  44476. */
  44477. SQLITE_PRIVATE int sqlite3PagerState(Pager *pPager){
  44478. return pPager->eState;
  44479. }
  44480. #endif /* SQLITE_HAS_CODEC */
  44481. #ifndef SQLITE_OMIT_AUTOVACUUM
  44482. /*
  44483. ** Move the page pPg to location pgno in the file.
  44484. **
  44485. ** There must be no references to the page previously located at
  44486. ** pgno (which we call pPgOld) though that page is allowed to be
  44487. ** in cache. If the page previously located at pgno is not already
  44488. ** in the rollback journal, it is not put there by by this routine.
  44489. **
  44490. ** References to the page pPg remain valid. Updating any
  44491. ** meta-data associated with pPg (i.e. data stored in the nExtra bytes
  44492. ** allocated along with the page) is the responsibility of the caller.
  44493. **
  44494. ** A transaction must be active when this routine is called. It used to be
  44495. ** required that a statement transaction was not active, but this restriction
  44496. ** has been removed (CREATE INDEX needs to move a page when a statement
  44497. ** transaction is active).
  44498. **
  44499. ** If the fourth argument, isCommit, is non-zero, then this page is being
  44500. ** moved as part of a database reorganization just before the transaction
  44501. ** is being committed. In this case, it is guaranteed that the database page
  44502. ** pPg refers to will not be written to again within this transaction.
  44503. **
  44504. ** This function may return SQLITE_NOMEM or an IO error code if an error
  44505. ** occurs. Otherwise, it returns SQLITE_OK.
  44506. */
  44507. SQLITE_PRIVATE int sqlite3PagerMovepage(Pager *pPager, DbPage *pPg, Pgno pgno, int isCommit){
  44508. PgHdr *pPgOld; /* The page being overwritten. */
  44509. Pgno needSyncPgno = 0; /* Old value of pPg->pgno, if sync is required */
  44510. int rc; /* Return code */
  44511. Pgno origPgno; /* The original page number */
  44512. assert( pPg->nRef>0 );
  44513. assert( pPager->eState==PAGER_WRITER_CACHEMOD
  44514. || pPager->eState==PAGER_WRITER_DBMOD
  44515. );
  44516. assert( assert_pager_state(pPager) );
  44517. /* In order to be able to rollback, an in-memory database must journal
  44518. ** the page we are moving from.
  44519. */
  44520. if( MEMDB ){
  44521. rc = sqlite3PagerWrite(pPg);
  44522. if( rc ) return rc;
  44523. }
  44524. /* If the page being moved is dirty and has not been saved by the latest
  44525. ** savepoint, then save the current contents of the page into the
  44526. ** sub-journal now. This is required to handle the following scenario:
  44527. **
  44528. ** BEGIN;
  44529. ** <journal page X, then modify it in memory>
  44530. ** SAVEPOINT one;
  44531. ** <Move page X to location Y>
  44532. ** ROLLBACK TO one;
  44533. **
  44534. ** If page X were not written to the sub-journal here, it would not
  44535. ** be possible to restore its contents when the "ROLLBACK TO one"
  44536. ** statement were is processed.
  44537. **
  44538. ** subjournalPage() may need to allocate space to store pPg->pgno into
  44539. ** one or more savepoint bitvecs. This is the reason this function
  44540. ** may return SQLITE_NOMEM.
  44541. */
  44542. if( pPg->flags&PGHDR_DIRTY
  44543. && subjRequiresPage(pPg)
  44544. && SQLITE_OK!=(rc = subjournalPage(pPg))
  44545. ){
  44546. return rc;
  44547. }
  44548. PAGERTRACE(("MOVE %d page %d (needSync=%d) moves to %d\n",
  44549. PAGERID(pPager), pPg->pgno, (pPg->flags&PGHDR_NEED_SYNC)?1:0, pgno));
  44550. IOTRACE(("MOVE %p %d %d\n", pPager, pPg->pgno, pgno))
  44551. /* If the journal needs to be sync()ed before page pPg->pgno can
  44552. ** be written to, store pPg->pgno in local variable needSyncPgno.
  44553. **
  44554. ** If the isCommit flag is set, there is no need to remember that
  44555. ** the journal needs to be sync()ed before database page pPg->pgno
  44556. ** can be written to. The caller has already promised not to write to it.
  44557. */
  44558. if( (pPg->flags&PGHDR_NEED_SYNC) && !isCommit ){
  44559. needSyncPgno = pPg->pgno;
  44560. assert( pPager->journalMode==PAGER_JOURNALMODE_OFF ||
  44561. pageInJournal(pPager, pPg) || pPg->pgno>pPager->dbOrigSize );
  44562. assert( pPg->flags&PGHDR_DIRTY );
  44563. }
  44564. /* If the cache contains a page with page-number pgno, remove it
  44565. ** from its hash chain. Also, if the PGHDR_NEED_SYNC flag was set for
  44566. ** page pgno before the 'move' operation, it needs to be retained
  44567. ** for the page moved there.
  44568. */
  44569. pPg->flags &= ~PGHDR_NEED_SYNC;
  44570. pPgOld = sqlite3PagerLookup(pPager, pgno);
  44571. assert( !pPgOld || pPgOld->nRef==1 );
  44572. if( pPgOld ){
  44573. pPg->flags |= (pPgOld->flags&PGHDR_NEED_SYNC);
  44574. if( MEMDB ){
  44575. /* Do not discard pages from an in-memory database since we might
  44576. ** need to rollback later. Just move the page out of the way. */
  44577. sqlite3PcacheMove(pPgOld, pPager->dbSize+1);
  44578. }else{
  44579. sqlite3PcacheDrop(pPgOld);
  44580. }
  44581. }
  44582. origPgno = pPg->pgno;
  44583. sqlite3PcacheMove(pPg, pgno);
  44584. sqlite3PcacheMakeDirty(pPg);
  44585. /* For an in-memory database, make sure the original page continues
  44586. ** to exist, in case the transaction needs to roll back. Use pPgOld
  44587. ** as the original page since it has already been allocated.
  44588. */
  44589. if( MEMDB ){
  44590. assert( pPgOld );
  44591. sqlite3PcacheMove(pPgOld, origPgno);
  44592. sqlite3PagerUnrefNotNull(pPgOld);
  44593. }
  44594. if( needSyncPgno ){
  44595. /* If needSyncPgno is non-zero, then the journal file needs to be
  44596. ** sync()ed before any data is written to database file page needSyncPgno.
  44597. ** Currently, no such page exists in the page-cache and the
  44598. ** "is journaled" bitvec flag has been set. This needs to be remedied by
  44599. ** loading the page into the pager-cache and setting the PGHDR_NEED_SYNC
  44600. ** flag.
  44601. **
  44602. ** If the attempt to load the page into the page-cache fails, (due
  44603. ** to a malloc() or IO failure), clear the bit in the pInJournal[]
  44604. ** array. Otherwise, if the page is loaded and written again in
  44605. ** this transaction, it may be written to the database file before
  44606. ** it is synced into the journal file. This way, it may end up in
  44607. ** the journal file twice, but that is not a problem.
  44608. */
  44609. PgHdr *pPgHdr;
  44610. rc = sqlite3PagerGet(pPager, needSyncPgno, &pPgHdr);
  44611. if( rc!=SQLITE_OK ){
  44612. if( needSyncPgno<=pPager->dbOrigSize ){
  44613. assert( pPager->pTmpSpace!=0 );
  44614. sqlite3BitvecClear(pPager->pInJournal, needSyncPgno, pPager->pTmpSpace);
  44615. }
  44616. return rc;
  44617. }
  44618. pPgHdr->flags |= PGHDR_NEED_SYNC;
  44619. sqlite3PcacheMakeDirty(pPgHdr);
  44620. sqlite3PagerUnrefNotNull(pPgHdr);
  44621. }
  44622. return SQLITE_OK;
  44623. }
  44624. #endif
  44625. /*
  44626. ** The page handle passed as the first argument refers to a dirty page
  44627. ** with a page number other than iNew. This function changes the page's
  44628. ** page number to iNew and sets the value of the PgHdr.flags field to
  44629. ** the value passed as the third parameter.
  44630. */
  44631. SQLITE_PRIVATE void sqlite3PagerRekey(DbPage *pPg, Pgno iNew, u16 flags){
  44632. assert( pPg->pgno!=iNew );
  44633. pPg->flags = flags;
  44634. sqlite3PcacheMove(pPg, iNew);
  44635. }
  44636. /*
  44637. ** Return a pointer to the data for the specified page.
  44638. */
  44639. SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *pPg){
  44640. assert( pPg->nRef>0 || pPg->pPager->memDb );
  44641. return pPg->pData;
  44642. }
  44643. /*
  44644. ** Return a pointer to the Pager.nExtra bytes of "extra" space
  44645. ** allocated along with the specified page.
  44646. */
  44647. SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *pPg){
  44648. return pPg->pExtra;
  44649. }
  44650. /*
  44651. ** Get/set the locking-mode for this pager. Parameter eMode must be one
  44652. ** of PAGER_LOCKINGMODE_QUERY, PAGER_LOCKINGMODE_NORMAL or
  44653. ** PAGER_LOCKINGMODE_EXCLUSIVE. If the parameter is not _QUERY, then
  44654. ** the locking-mode is set to the value specified.
  44655. **
  44656. ** The returned value is either PAGER_LOCKINGMODE_NORMAL or
  44657. ** PAGER_LOCKINGMODE_EXCLUSIVE, indicating the current (possibly updated)
  44658. ** locking-mode.
  44659. */
  44660. SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *pPager, int eMode){
  44661. assert( eMode==PAGER_LOCKINGMODE_QUERY
  44662. || eMode==PAGER_LOCKINGMODE_NORMAL
  44663. || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
  44664. assert( PAGER_LOCKINGMODE_QUERY<0 );
  44665. assert( PAGER_LOCKINGMODE_NORMAL>=0 && PAGER_LOCKINGMODE_EXCLUSIVE>=0 );
  44666. assert( pPager->exclusiveMode || 0==sqlite3WalHeapMemory(pPager->pWal) );
  44667. if( eMode>=0 && !pPager->tempFile && !sqlite3WalHeapMemory(pPager->pWal) ){
  44668. pPager->exclusiveMode = (u8)eMode;
  44669. }
  44670. return (int)pPager->exclusiveMode;
  44671. }
  44672. /*
  44673. ** Set the journal-mode for this pager. Parameter eMode must be one of:
  44674. **
  44675. ** PAGER_JOURNALMODE_DELETE
  44676. ** PAGER_JOURNALMODE_TRUNCATE
  44677. ** PAGER_JOURNALMODE_PERSIST
  44678. ** PAGER_JOURNALMODE_OFF
  44679. ** PAGER_JOURNALMODE_MEMORY
  44680. ** PAGER_JOURNALMODE_WAL
  44681. **
  44682. ** The journalmode is set to the value specified if the change is allowed.
  44683. ** The change may be disallowed for the following reasons:
  44684. **
  44685. ** * An in-memory database can only have its journal_mode set to _OFF
  44686. ** or _MEMORY.
  44687. **
  44688. ** * Temporary databases cannot have _WAL journalmode.
  44689. **
  44690. ** The returned indicate the current (possibly updated) journal-mode.
  44691. */
  44692. SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *pPager, int eMode){
  44693. u8 eOld = pPager->journalMode; /* Prior journalmode */
  44694. #ifdef SQLITE_DEBUG
  44695. /* The print_pager_state() routine is intended to be used by the debugger
  44696. ** only. We invoke it once here to suppress a compiler warning. */
  44697. print_pager_state(pPager);
  44698. #endif
  44699. /* The eMode parameter is always valid */
  44700. assert( eMode==PAGER_JOURNALMODE_DELETE
  44701. || eMode==PAGER_JOURNALMODE_TRUNCATE
  44702. || eMode==PAGER_JOURNALMODE_PERSIST
  44703. || eMode==PAGER_JOURNALMODE_OFF
  44704. || eMode==PAGER_JOURNALMODE_WAL
  44705. || eMode==PAGER_JOURNALMODE_MEMORY );
  44706. /* This routine is only called from the OP_JournalMode opcode, and
  44707. ** the logic there will never allow a temporary file to be changed
  44708. ** to WAL mode.
  44709. */
  44710. assert( pPager->tempFile==0 || eMode!=PAGER_JOURNALMODE_WAL );
  44711. /* Do allow the journalmode of an in-memory database to be set to
  44712. ** anything other than MEMORY or OFF
  44713. */
  44714. if( MEMDB ){
  44715. assert( eOld==PAGER_JOURNALMODE_MEMORY || eOld==PAGER_JOURNALMODE_OFF );
  44716. if( eMode!=PAGER_JOURNALMODE_MEMORY && eMode!=PAGER_JOURNALMODE_OFF ){
  44717. eMode = eOld;
  44718. }
  44719. }
  44720. if( eMode!=eOld ){
  44721. /* Change the journal mode. */
  44722. assert( pPager->eState!=PAGER_ERROR );
  44723. pPager->journalMode = (u8)eMode;
  44724. /* When transistioning from TRUNCATE or PERSIST to any other journal
  44725. ** mode except WAL, unless the pager is in locking_mode=exclusive mode,
  44726. ** delete the journal file.
  44727. */
  44728. assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
  44729. assert( (PAGER_JOURNALMODE_PERSIST & 5)==1 );
  44730. assert( (PAGER_JOURNALMODE_DELETE & 5)==0 );
  44731. assert( (PAGER_JOURNALMODE_MEMORY & 5)==4 );
  44732. assert( (PAGER_JOURNALMODE_OFF & 5)==0 );
  44733. assert( (PAGER_JOURNALMODE_WAL & 5)==5 );
  44734. assert( isOpen(pPager->fd) || pPager->exclusiveMode );
  44735. if( !pPager->exclusiveMode && (eOld & 5)==1 && (eMode & 1)==0 ){
  44736. /* In this case we would like to delete the journal file. If it is
  44737. ** not possible, then that is not a problem. Deleting the journal file
  44738. ** here is an optimization only.
  44739. **
  44740. ** Before deleting the journal file, obtain a RESERVED lock on the
  44741. ** database file. This ensures that the journal file is not deleted
  44742. ** while it is in use by some other client.
  44743. */
  44744. sqlite3OsClose(pPager->jfd);
  44745. if( pPager->eLock>=RESERVED_LOCK ){
  44746. sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
  44747. }else{
  44748. int rc = SQLITE_OK;
  44749. int state = pPager->eState;
  44750. assert( state==PAGER_OPEN || state==PAGER_READER );
  44751. if( state==PAGER_OPEN ){
  44752. rc = sqlite3PagerSharedLock(pPager);
  44753. }
  44754. if( pPager->eState==PAGER_READER ){
  44755. assert( rc==SQLITE_OK );
  44756. rc = pagerLockDb(pPager, RESERVED_LOCK);
  44757. }
  44758. if( rc==SQLITE_OK ){
  44759. sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
  44760. }
  44761. if( rc==SQLITE_OK && state==PAGER_READER ){
  44762. pagerUnlockDb(pPager, SHARED_LOCK);
  44763. }else if( state==PAGER_OPEN ){
  44764. pager_unlock(pPager);
  44765. }
  44766. assert( state==pPager->eState );
  44767. }
  44768. }
  44769. }
  44770. /* Return the new journal mode */
  44771. return (int)pPager->journalMode;
  44772. }
  44773. /*
  44774. ** Return the current journal mode.
  44775. */
  44776. SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager *pPager){
  44777. return (int)pPager->journalMode;
  44778. }
  44779. /*
  44780. ** Return TRUE if the pager is in a state where it is OK to change the
  44781. ** journalmode. Journalmode changes can only happen when the database
  44782. ** is unmodified.
  44783. */
  44784. SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager *pPager){
  44785. assert( assert_pager_state(pPager) );
  44786. if( pPager->eState>=PAGER_WRITER_CACHEMOD ) return 0;
  44787. if( NEVER(isOpen(pPager->jfd) && pPager->journalOff>0) ) return 0;
  44788. return 1;
  44789. }
  44790. /*
  44791. ** Get/set the size-limit used for persistent journal files.
  44792. **
  44793. ** Setting the size limit to -1 means no limit is enforced.
  44794. ** An attempt to set a limit smaller than -1 is a no-op.
  44795. */
  44796. SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *pPager, i64 iLimit){
  44797. if( iLimit>=-1 ){
  44798. pPager->journalSizeLimit = iLimit;
  44799. sqlite3WalLimit(pPager->pWal, iLimit);
  44800. }
  44801. return pPager->journalSizeLimit;
  44802. }
  44803. /*
  44804. ** Return a pointer to the pPager->pBackup variable. The backup module
  44805. ** in backup.c maintains the content of this variable. This module
  44806. ** uses it opaquely as an argument to sqlite3BackupRestart() and
  44807. ** sqlite3BackupUpdate() only.
  44808. */
  44809. SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager *pPager){
  44810. return &pPager->pBackup;
  44811. }
  44812. #ifndef SQLITE_OMIT_VACUUM
  44813. /*
  44814. ** Unless this is an in-memory or temporary database, clear the pager cache.
  44815. */
  44816. SQLITE_PRIVATE void sqlite3PagerClearCache(Pager *pPager){
  44817. if( !MEMDB && pPager->tempFile==0 ) pager_reset(pPager);
  44818. }
  44819. #endif
  44820. #ifndef SQLITE_OMIT_WAL
  44821. /*
  44822. ** This function is called when the user invokes "PRAGMA wal_checkpoint",
  44823. ** "PRAGMA wal_blocking_checkpoint" or calls the sqlite3_wal_checkpoint()
  44824. ** or wal_blocking_checkpoint() API functions.
  44825. **
  44826. ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
  44827. */
  44828. SQLITE_PRIVATE int sqlite3PagerCheckpoint(Pager *pPager, int eMode, int *pnLog, int *pnCkpt){
  44829. int rc = SQLITE_OK;
  44830. if( pPager->pWal ){
  44831. rc = sqlite3WalCheckpoint(pPager->pWal, eMode,
  44832. pPager->xBusyHandler, pPager->pBusyHandlerArg,
  44833. pPager->ckptSyncFlags, pPager->pageSize, (u8 *)pPager->pTmpSpace,
  44834. pnLog, pnCkpt
  44835. );
  44836. }
  44837. return rc;
  44838. }
  44839. SQLITE_PRIVATE int sqlite3PagerWalCallback(Pager *pPager){
  44840. return sqlite3WalCallback(pPager->pWal);
  44841. }
  44842. /*
  44843. ** Return true if the underlying VFS for the given pager supports the
  44844. ** primitives necessary for write-ahead logging.
  44845. */
  44846. SQLITE_PRIVATE int sqlite3PagerWalSupported(Pager *pPager){
  44847. const sqlite3_io_methods *pMethods = pPager->fd->pMethods;
  44848. return pPager->exclusiveMode || (pMethods->iVersion>=2 && pMethods->xShmMap);
  44849. }
  44850. /*
  44851. ** Attempt to take an exclusive lock on the database file. If a PENDING lock
  44852. ** is obtained instead, immediately release it.
  44853. */
  44854. static int pagerExclusiveLock(Pager *pPager){
  44855. int rc; /* Return code */
  44856. assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK );
  44857. rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
  44858. if( rc!=SQLITE_OK ){
  44859. /* If the attempt to grab the exclusive lock failed, release the
  44860. ** pending lock that may have been obtained instead. */
  44861. pagerUnlockDb(pPager, SHARED_LOCK);
  44862. }
  44863. return rc;
  44864. }
  44865. /*
  44866. ** Call sqlite3WalOpen() to open the WAL handle. If the pager is in
  44867. ** exclusive-locking mode when this function is called, take an EXCLUSIVE
  44868. ** lock on the database file and use heap-memory to store the wal-index
  44869. ** in. Otherwise, use the normal shared-memory.
  44870. */
  44871. static int pagerOpenWal(Pager *pPager){
  44872. int rc = SQLITE_OK;
  44873. assert( pPager->pWal==0 && pPager->tempFile==0 );
  44874. assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK );
  44875. /* If the pager is already in exclusive-mode, the WAL module will use
  44876. ** heap-memory for the wal-index instead of the VFS shared-memory
  44877. ** implementation. Take the exclusive lock now, before opening the WAL
  44878. ** file, to make sure this is safe.
  44879. */
  44880. if( pPager->exclusiveMode ){
  44881. rc = pagerExclusiveLock(pPager);
  44882. }
  44883. /* Open the connection to the log file. If this operation fails,
  44884. ** (e.g. due to malloc() failure), return an error code.
  44885. */
  44886. if( rc==SQLITE_OK ){
  44887. rc = sqlite3WalOpen(pPager->pVfs,
  44888. pPager->fd, pPager->zWal, pPager->exclusiveMode,
  44889. pPager->journalSizeLimit, &pPager->pWal
  44890. );
  44891. }
  44892. pagerFixMaplimit(pPager);
  44893. return rc;
  44894. }
  44895. /*
  44896. ** The caller must be holding a SHARED lock on the database file to call
  44897. ** this function.
  44898. **
  44899. ** If the pager passed as the first argument is open on a real database
  44900. ** file (not a temp file or an in-memory database), and the WAL file
  44901. ** is not already open, make an attempt to open it now. If successful,
  44902. ** return SQLITE_OK. If an error occurs or the VFS used by the pager does
  44903. ** not support the xShmXXX() methods, return an error code. *pbOpen is
  44904. ** not modified in either case.
  44905. **
  44906. ** If the pager is open on a temp-file (or in-memory database), or if
  44907. ** the WAL file is already open, set *pbOpen to 1 and return SQLITE_OK
  44908. ** without doing anything.
  44909. */
  44910. SQLITE_PRIVATE int sqlite3PagerOpenWal(
  44911. Pager *pPager, /* Pager object */
  44912. int *pbOpen /* OUT: Set to true if call is a no-op */
  44913. ){
  44914. int rc = SQLITE_OK; /* Return code */
  44915. assert( assert_pager_state(pPager) );
  44916. assert( pPager->eState==PAGER_OPEN || pbOpen );
  44917. assert( pPager->eState==PAGER_READER || !pbOpen );
  44918. assert( pbOpen==0 || *pbOpen==0 );
  44919. assert( pbOpen!=0 || (!pPager->tempFile && !pPager->pWal) );
  44920. if( !pPager->tempFile && !pPager->pWal ){
  44921. if( !sqlite3PagerWalSupported(pPager) ) return SQLITE_CANTOPEN;
  44922. /* Close any rollback journal previously open */
  44923. sqlite3OsClose(pPager->jfd);
  44924. rc = pagerOpenWal(pPager);
  44925. if( rc==SQLITE_OK ){
  44926. pPager->journalMode = PAGER_JOURNALMODE_WAL;
  44927. pPager->eState = PAGER_OPEN;
  44928. }
  44929. }else{
  44930. *pbOpen = 1;
  44931. }
  44932. return rc;
  44933. }
  44934. /*
  44935. ** This function is called to close the connection to the log file prior
  44936. ** to switching from WAL to rollback mode.
  44937. **
  44938. ** Before closing the log file, this function attempts to take an
  44939. ** EXCLUSIVE lock on the database file. If this cannot be obtained, an
  44940. ** error (SQLITE_BUSY) is returned and the log connection is not closed.
  44941. ** If successful, the EXCLUSIVE lock is not released before returning.
  44942. */
  44943. SQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager){
  44944. int rc = SQLITE_OK;
  44945. assert( pPager->journalMode==PAGER_JOURNALMODE_WAL );
  44946. /* If the log file is not already open, but does exist in the file-system,
  44947. ** it may need to be checkpointed before the connection can switch to
  44948. ** rollback mode. Open it now so this can happen.
  44949. */
  44950. if( !pPager->pWal ){
  44951. int logexists = 0;
  44952. rc = pagerLockDb(pPager, SHARED_LOCK);
  44953. if( rc==SQLITE_OK ){
  44954. rc = sqlite3OsAccess(
  44955. pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &logexists
  44956. );
  44957. }
  44958. if( rc==SQLITE_OK && logexists ){
  44959. rc = pagerOpenWal(pPager);
  44960. }
  44961. }
  44962. /* Checkpoint and close the log. Because an EXCLUSIVE lock is held on
  44963. ** the database file, the log and log-summary files will be deleted.
  44964. */
  44965. if( rc==SQLITE_OK && pPager->pWal ){
  44966. rc = pagerExclusiveLock(pPager);
  44967. if( rc==SQLITE_OK ){
  44968. rc = sqlite3WalClose(pPager->pWal, pPager->ckptSyncFlags,
  44969. pPager->pageSize, (u8*)pPager->pTmpSpace);
  44970. pPager->pWal = 0;
  44971. pagerFixMaplimit(pPager);
  44972. }
  44973. }
  44974. return rc;
  44975. }
  44976. #endif /* !SQLITE_OMIT_WAL */
  44977. #ifdef SQLITE_ENABLE_ZIPVFS
  44978. /*
  44979. ** A read-lock must be held on the pager when this function is called. If
  44980. ** the pager is in WAL mode and the WAL file currently contains one or more
  44981. ** frames, return the size in bytes of the page images stored within the
  44982. ** WAL frames. Otherwise, if this is not a WAL database or the WAL file
  44983. ** is empty, return 0.
  44984. */
  44985. SQLITE_PRIVATE int sqlite3PagerWalFramesize(Pager *pPager){
  44986. assert( pPager->eState>=PAGER_READER );
  44987. return sqlite3WalFramesize(pPager->pWal);
  44988. }
  44989. #endif
  44990. #endif /* SQLITE_OMIT_DISKIO */
  44991. /************** End of pager.c ***********************************************/
  44992. /************** Begin file wal.c *********************************************/
  44993. /*
  44994. ** 2010 February 1
  44995. **
  44996. ** The author disclaims copyright to this source code. In place of
  44997. ** a legal notice, here is a blessing:
  44998. **
  44999. ** May you do good and not evil.
  45000. ** May you find forgiveness for yourself and forgive others.
  45001. ** May you share freely, never taking more than you give.
  45002. **
  45003. *************************************************************************
  45004. **
  45005. ** This file contains the implementation of a write-ahead log (WAL) used in
  45006. ** "journal_mode=WAL" mode.
  45007. **
  45008. ** WRITE-AHEAD LOG (WAL) FILE FORMAT
  45009. **
  45010. ** A WAL file consists of a header followed by zero or more "frames".
  45011. ** Each frame records the revised content of a single page from the
  45012. ** database file. All changes to the database are recorded by writing
  45013. ** frames into the WAL. Transactions commit when a frame is written that
  45014. ** contains a commit marker. A single WAL can and usually does record
  45015. ** multiple transactions. Periodically, the content of the WAL is
  45016. ** transferred back into the database file in an operation called a
  45017. ** "checkpoint".
  45018. **
  45019. ** A single WAL file can be used multiple times. In other words, the
  45020. ** WAL can fill up with frames and then be checkpointed and then new
  45021. ** frames can overwrite the old ones. A WAL always grows from beginning
  45022. ** toward the end. Checksums and counters attached to each frame are
  45023. ** used to determine which frames within the WAL are valid and which
  45024. ** are leftovers from prior checkpoints.
  45025. **
  45026. ** The WAL header is 32 bytes in size and consists of the following eight
  45027. ** big-endian 32-bit unsigned integer values:
  45028. **
  45029. ** 0: Magic number. 0x377f0682 or 0x377f0683
  45030. ** 4: File format version. Currently 3007000
  45031. ** 8: Database page size. Example: 1024
  45032. ** 12: Checkpoint sequence number
  45033. ** 16: Salt-1, random integer incremented with each checkpoint
  45034. ** 20: Salt-2, a different random integer changing with each ckpt
  45035. ** 24: Checksum-1 (first part of checksum for first 24 bytes of header).
  45036. ** 28: Checksum-2 (second part of checksum for first 24 bytes of header).
  45037. **
  45038. ** Immediately following the wal-header are zero or more frames. Each
  45039. ** frame consists of a 24-byte frame-header followed by a <page-size> bytes
  45040. ** of page data. The frame-header is six big-endian 32-bit unsigned
  45041. ** integer values, as follows:
  45042. **
  45043. ** 0: Page number.
  45044. ** 4: For commit records, the size of the database image in pages
  45045. ** after the commit. For all other records, zero.
  45046. ** 8: Salt-1 (copied from the header)
  45047. ** 12: Salt-2 (copied from the header)
  45048. ** 16: Checksum-1.
  45049. ** 20: Checksum-2.
  45050. **
  45051. ** A frame is considered valid if and only if the following conditions are
  45052. ** true:
  45053. **
  45054. ** (1) The salt-1 and salt-2 values in the frame-header match
  45055. ** salt values in the wal-header
  45056. **
  45057. ** (2) The checksum values in the final 8 bytes of the frame-header
  45058. ** exactly match the checksum computed consecutively on the
  45059. ** WAL header and the first 8 bytes and the content of all frames
  45060. ** up to and including the current frame.
  45061. **
  45062. ** The checksum is computed using 32-bit big-endian integers if the
  45063. ** magic number in the first 4 bytes of the WAL is 0x377f0683 and it
  45064. ** is computed using little-endian if the magic number is 0x377f0682.
  45065. ** The checksum values are always stored in the frame header in a
  45066. ** big-endian format regardless of which byte order is used to compute
  45067. ** the checksum. The checksum is computed by interpreting the input as
  45068. ** an even number of unsigned 32-bit integers: x[0] through x[N]. The
  45069. ** algorithm used for the checksum is as follows:
  45070. **
  45071. ** for i from 0 to n-1 step 2:
  45072. ** s0 += x[i] + s1;
  45073. ** s1 += x[i+1] + s0;
  45074. ** endfor
  45075. **
  45076. ** Note that s0 and s1 are both weighted checksums using fibonacci weights
  45077. ** in reverse order (the largest fibonacci weight occurs on the first element
  45078. ** of the sequence being summed.) The s1 value spans all 32-bit
  45079. ** terms of the sequence whereas s0 omits the final term.
  45080. **
  45081. ** On a checkpoint, the WAL is first VFS.xSync-ed, then valid content of the
  45082. ** WAL is transferred into the database, then the database is VFS.xSync-ed.
  45083. ** The VFS.xSync operations serve as write barriers - all writes launched
  45084. ** before the xSync must complete before any write that launches after the
  45085. ** xSync begins.
  45086. **
  45087. ** After each checkpoint, the salt-1 value is incremented and the salt-2
  45088. ** value is randomized. This prevents old and new frames in the WAL from
  45089. ** being considered valid at the same time and being checkpointing together
  45090. ** following a crash.
  45091. **
  45092. ** READER ALGORITHM
  45093. **
  45094. ** To read a page from the database (call it page number P), a reader
  45095. ** first checks the WAL to see if it contains page P. If so, then the
  45096. ** last valid instance of page P that is a followed by a commit frame
  45097. ** or is a commit frame itself becomes the value read. If the WAL
  45098. ** contains no copies of page P that are valid and which are a commit
  45099. ** frame or are followed by a commit frame, then page P is read from
  45100. ** the database file.
  45101. **
  45102. ** To start a read transaction, the reader records the index of the last
  45103. ** valid frame in the WAL. The reader uses this recorded "mxFrame" value
  45104. ** for all subsequent read operations. New transactions can be appended
  45105. ** to the WAL, but as long as the reader uses its original mxFrame value
  45106. ** and ignores the newly appended content, it will see a consistent snapshot
  45107. ** of the database from a single point in time. This technique allows
  45108. ** multiple concurrent readers to view different versions of the database
  45109. ** content simultaneously.
  45110. **
  45111. ** The reader algorithm in the previous paragraphs works correctly, but
  45112. ** because frames for page P can appear anywhere within the WAL, the
  45113. ** reader has to scan the entire WAL looking for page P frames. If the
  45114. ** WAL is large (multiple megabytes is typical) that scan can be slow,
  45115. ** and read performance suffers. To overcome this problem, a separate
  45116. ** data structure called the wal-index is maintained to expedite the
  45117. ** search for frames of a particular page.
  45118. **
  45119. ** WAL-INDEX FORMAT
  45120. **
  45121. ** Conceptually, the wal-index is shared memory, though VFS implementations
  45122. ** might choose to implement the wal-index using a mmapped file. Because
  45123. ** the wal-index is shared memory, SQLite does not support journal_mode=WAL
  45124. ** on a network filesystem. All users of the database must be able to
  45125. ** share memory.
  45126. **
  45127. ** The wal-index is transient. After a crash, the wal-index can (and should
  45128. ** be) reconstructed from the original WAL file. In fact, the VFS is required
  45129. ** to either truncate or zero the header of the wal-index when the last
  45130. ** connection to it closes. Because the wal-index is transient, it can
  45131. ** use an architecture-specific format; it does not have to be cross-platform.
  45132. ** Hence, unlike the database and WAL file formats which store all values
  45133. ** as big endian, the wal-index can store multi-byte values in the native
  45134. ** byte order of the host computer.
  45135. **
  45136. ** The purpose of the wal-index is to answer this question quickly: Given
  45137. ** a page number P and a maximum frame index M, return the index of the
  45138. ** last frame in the wal before frame M for page P in the WAL, or return
  45139. ** NULL if there are no frames for page P in the WAL prior to M.
  45140. **
  45141. ** The wal-index consists of a header region, followed by an one or
  45142. ** more index blocks.
  45143. **
  45144. ** The wal-index header contains the total number of frames within the WAL
  45145. ** in the mxFrame field.
  45146. **
  45147. ** Each index block except for the first contains information on
  45148. ** HASHTABLE_NPAGE frames. The first index block contains information on
  45149. ** HASHTABLE_NPAGE_ONE frames. The values of HASHTABLE_NPAGE_ONE and
  45150. ** HASHTABLE_NPAGE are selected so that together the wal-index header and
  45151. ** first index block are the same size as all other index blocks in the
  45152. ** wal-index.
  45153. **
  45154. ** Each index block contains two sections, a page-mapping that contains the
  45155. ** database page number associated with each wal frame, and a hash-table
  45156. ** that allows readers to query an index block for a specific page number.
  45157. ** The page-mapping is an array of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE
  45158. ** for the first index block) 32-bit page numbers. The first entry in the
  45159. ** first index-block contains the database page number corresponding to the
  45160. ** first frame in the WAL file. The first entry in the second index block
  45161. ** in the WAL file corresponds to the (HASHTABLE_NPAGE_ONE+1)th frame in
  45162. ** the log, and so on.
  45163. **
  45164. ** The last index block in a wal-index usually contains less than the full
  45165. ** complement of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE) page-numbers,
  45166. ** depending on the contents of the WAL file. This does not change the
  45167. ** allocated size of the page-mapping array - the page-mapping array merely
  45168. ** contains unused entries.
  45169. **
  45170. ** Even without using the hash table, the last frame for page P
  45171. ** can be found by scanning the page-mapping sections of each index block
  45172. ** starting with the last index block and moving toward the first, and
  45173. ** within each index block, starting at the end and moving toward the
  45174. ** beginning. The first entry that equals P corresponds to the frame
  45175. ** holding the content for that page.
  45176. **
  45177. ** The hash table consists of HASHTABLE_NSLOT 16-bit unsigned integers.
  45178. ** HASHTABLE_NSLOT = 2*HASHTABLE_NPAGE, and there is one entry in the
  45179. ** hash table for each page number in the mapping section, so the hash
  45180. ** table is never more than half full. The expected number of collisions
  45181. ** prior to finding a match is 1. Each entry of the hash table is an
  45182. ** 1-based index of an entry in the mapping section of the same
  45183. ** index block. Let K be the 1-based index of the largest entry in
  45184. ** the mapping section. (For index blocks other than the last, K will
  45185. ** always be exactly HASHTABLE_NPAGE (4096) and for the last index block
  45186. ** K will be (mxFrame%HASHTABLE_NPAGE).) Unused slots of the hash table
  45187. ** contain a value of 0.
  45188. **
  45189. ** To look for page P in the hash table, first compute a hash iKey on
  45190. ** P as follows:
  45191. **
  45192. ** iKey = (P * 383) % HASHTABLE_NSLOT
  45193. **
  45194. ** Then start scanning entries of the hash table, starting with iKey
  45195. ** (wrapping around to the beginning when the end of the hash table is
  45196. ** reached) until an unused hash slot is found. Let the first unused slot
  45197. ** be at index iUnused. (iUnused might be less than iKey if there was
  45198. ** wrap-around.) Because the hash table is never more than half full,
  45199. ** the search is guaranteed to eventually hit an unused entry. Let
  45200. ** iMax be the value between iKey and iUnused, closest to iUnused,
  45201. ** where aHash[iMax]==P. If there is no iMax entry (if there exists
  45202. ** no hash slot such that aHash[i]==p) then page P is not in the
  45203. ** current index block. Otherwise the iMax-th mapping entry of the
  45204. ** current index block corresponds to the last entry that references
  45205. ** page P.
  45206. **
  45207. ** A hash search begins with the last index block and moves toward the
  45208. ** first index block, looking for entries corresponding to page P. On
  45209. ** average, only two or three slots in each index block need to be
  45210. ** examined in order to either find the last entry for page P, or to
  45211. ** establish that no such entry exists in the block. Each index block
  45212. ** holds over 4000 entries. So two or three index blocks are sufficient
  45213. ** to cover a typical 10 megabyte WAL file, assuming 1K pages. 8 or 10
  45214. ** comparisons (on average) suffice to either locate a frame in the
  45215. ** WAL or to establish that the frame does not exist in the WAL. This
  45216. ** is much faster than scanning the entire 10MB WAL.
  45217. **
  45218. ** Note that entries are added in order of increasing K. Hence, one
  45219. ** reader might be using some value K0 and a second reader that started
  45220. ** at a later time (after additional transactions were added to the WAL
  45221. ** and to the wal-index) might be using a different value K1, where K1>K0.
  45222. ** Both readers can use the same hash table and mapping section to get
  45223. ** the correct result. There may be entries in the hash table with
  45224. ** K>K0 but to the first reader, those entries will appear to be unused
  45225. ** slots in the hash table and so the first reader will get an answer as
  45226. ** if no values greater than K0 had ever been inserted into the hash table
  45227. ** in the first place - which is what reader one wants. Meanwhile, the
  45228. ** second reader using K1 will see additional values that were inserted
  45229. ** later, which is exactly what reader two wants.
  45230. **
  45231. ** When a rollback occurs, the value of K is decreased. Hash table entries
  45232. ** that correspond to frames greater than the new K value are removed
  45233. ** from the hash table at this point.
  45234. */
  45235. #ifndef SQLITE_OMIT_WAL
  45236. /*
  45237. ** Trace output macros
  45238. */
  45239. #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
  45240. SQLITE_PRIVATE int sqlite3WalTrace = 0;
  45241. # define WALTRACE(X) if(sqlite3WalTrace) sqlite3DebugPrintf X
  45242. #else
  45243. # define WALTRACE(X)
  45244. #endif
  45245. /*
  45246. ** The maximum (and only) versions of the wal and wal-index formats
  45247. ** that may be interpreted by this version of SQLite.
  45248. **
  45249. ** If a client begins recovering a WAL file and finds that (a) the checksum
  45250. ** values in the wal-header are correct and (b) the version field is not
  45251. ** WAL_MAX_VERSION, recovery fails and SQLite returns SQLITE_CANTOPEN.
  45252. **
  45253. ** Similarly, if a client successfully reads a wal-index header (i.e. the
  45254. ** checksum test is successful) and finds that the version field is not
  45255. ** WALINDEX_MAX_VERSION, then no read-transaction is opened and SQLite
  45256. ** returns SQLITE_CANTOPEN.
  45257. */
  45258. #define WAL_MAX_VERSION 3007000
  45259. #define WALINDEX_MAX_VERSION 3007000
  45260. /*
  45261. ** Indices of various locking bytes. WAL_NREADER is the number
  45262. ** of available reader locks and should be at least 3.
  45263. */
  45264. #define WAL_WRITE_LOCK 0
  45265. #define WAL_ALL_BUT_WRITE 1
  45266. #define WAL_CKPT_LOCK 1
  45267. #define WAL_RECOVER_LOCK 2
  45268. #define WAL_READ_LOCK(I) (3+(I))
  45269. #define WAL_NREADER (SQLITE_SHM_NLOCK-3)
  45270. /* Object declarations */
  45271. typedef struct WalIndexHdr WalIndexHdr;
  45272. typedef struct WalIterator WalIterator;
  45273. typedef struct WalCkptInfo WalCkptInfo;
  45274. /*
  45275. ** The following object holds a copy of the wal-index header content.
  45276. **
  45277. ** The actual header in the wal-index consists of two copies of this
  45278. ** object.
  45279. **
  45280. ** The szPage value can be any power of 2 between 512 and 32768, inclusive.
  45281. ** Or it can be 1 to represent a 65536-byte page. The latter case was
  45282. ** added in 3.7.1 when support for 64K pages was added.
  45283. */
  45284. struct WalIndexHdr {
  45285. u32 iVersion; /* Wal-index version */
  45286. u32 unused; /* Unused (padding) field */
  45287. u32 iChange; /* Counter incremented each transaction */
  45288. u8 isInit; /* 1 when initialized */
  45289. u8 bigEndCksum; /* True if checksums in WAL are big-endian */
  45290. u16 szPage; /* Database page size in bytes. 1==64K */
  45291. u32 mxFrame; /* Index of last valid frame in the WAL */
  45292. u32 nPage; /* Size of database in pages */
  45293. u32 aFrameCksum[2]; /* Checksum of last frame in log */
  45294. u32 aSalt[2]; /* Two salt values copied from WAL header */
  45295. u32 aCksum[2]; /* Checksum over all prior fields */
  45296. };
  45297. /*
  45298. ** A copy of the following object occurs in the wal-index immediately
  45299. ** following the second copy of the WalIndexHdr. This object stores
  45300. ** information used by checkpoint.
  45301. **
  45302. ** nBackfill is the number of frames in the WAL that have been written
  45303. ** back into the database. (We call the act of moving content from WAL to
  45304. ** database "backfilling".) The nBackfill number is never greater than
  45305. ** WalIndexHdr.mxFrame. nBackfill can only be increased by threads
  45306. ** holding the WAL_CKPT_LOCK lock (which includes a recovery thread).
  45307. ** However, a WAL_WRITE_LOCK thread can move the value of nBackfill from
  45308. ** mxFrame back to zero when the WAL is reset.
  45309. **
  45310. ** There is one entry in aReadMark[] for each reader lock. If a reader
  45311. ** holds read-lock K, then the value in aReadMark[K] is no greater than
  45312. ** the mxFrame for that reader. The value READMARK_NOT_USED (0xffffffff)
  45313. ** for any aReadMark[] means that entry is unused. aReadMark[0] is
  45314. ** a special case; its value is never used and it exists as a place-holder
  45315. ** to avoid having to offset aReadMark[] indexs by one. Readers holding
  45316. ** WAL_READ_LOCK(0) always ignore the entire WAL and read all content
  45317. ** directly from the database.
  45318. **
  45319. ** The value of aReadMark[K] may only be changed by a thread that
  45320. ** is holding an exclusive lock on WAL_READ_LOCK(K). Thus, the value of
  45321. ** aReadMark[K] cannot changed while there is a reader is using that mark
  45322. ** since the reader will be holding a shared lock on WAL_READ_LOCK(K).
  45323. **
  45324. ** The checkpointer may only transfer frames from WAL to database where
  45325. ** the frame numbers are less than or equal to every aReadMark[] that is
  45326. ** in use (that is, every aReadMark[j] for which there is a corresponding
  45327. ** WAL_READ_LOCK(j)). New readers (usually) pick the aReadMark[] with the
  45328. ** largest value and will increase an unused aReadMark[] to mxFrame if there
  45329. ** is not already an aReadMark[] equal to mxFrame. The exception to the
  45330. ** previous sentence is when nBackfill equals mxFrame (meaning that everything
  45331. ** in the WAL has been backfilled into the database) then new readers
  45332. ** will choose aReadMark[0] which has value 0 and hence such reader will
  45333. ** get all their all content directly from the database file and ignore
  45334. ** the WAL.
  45335. **
  45336. ** Writers normally append new frames to the end of the WAL. However,
  45337. ** if nBackfill equals mxFrame (meaning that all WAL content has been
  45338. ** written back into the database) and if no readers are using the WAL
  45339. ** (in other words, if there are no WAL_READ_LOCK(i) where i>0) then
  45340. ** the writer will first "reset" the WAL back to the beginning and start
  45341. ** writing new content beginning at frame 1.
  45342. **
  45343. ** We assume that 32-bit loads are atomic and so no locks are needed in
  45344. ** order to read from any aReadMark[] entries.
  45345. */
  45346. struct WalCkptInfo {
  45347. u32 nBackfill; /* Number of WAL frames backfilled into DB */
  45348. u32 aReadMark[WAL_NREADER]; /* Reader marks */
  45349. };
  45350. #define READMARK_NOT_USED 0xffffffff
  45351. /* A block of WALINDEX_LOCK_RESERVED bytes beginning at
  45352. ** WALINDEX_LOCK_OFFSET is reserved for locks. Since some systems
  45353. ** only support mandatory file-locks, we do not read or write data
  45354. ** from the region of the file on which locks are applied.
  45355. */
  45356. #define WALINDEX_LOCK_OFFSET (sizeof(WalIndexHdr)*2 + sizeof(WalCkptInfo))
  45357. #define WALINDEX_LOCK_RESERVED 16
  45358. #define WALINDEX_HDR_SIZE (WALINDEX_LOCK_OFFSET+WALINDEX_LOCK_RESERVED)
  45359. /* Size of header before each frame in wal */
  45360. #define WAL_FRAME_HDRSIZE 24
  45361. /* Size of write ahead log header, including checksum. */
  45362. /* #define WAL_HDRSIZE 24 */
  45363. #define WAL_HDRSIZE 32
  45364. /* WAL magic value. Either this value, or the same value with the least
  45365. ** significant bit also set (WAL_MAGIC | 0x00000001) is stored in 32-bit
  45366. ** big-endian format in the first 4 bytes of a WAL file.
  45367. **
  45368. ** If the LSB is set, then the checksums for each frame within the WAL
  45369. ** file are calculated by treating all data as an array of 32-bit
  45370. ** big-endian words. Otherwise, they are calculated by interpreting
  45371. ** all data as 32-bit little-endian words.
  45372. */
  45373. #define WAL_MAGIC 0x377f0682
  45374. /*
  45375. ** Return the offset of frame iFrame in the write-ahead log file,
  45376. ** assuming a database page size of szPage bytes. The offset returned
  45377. ** is to the start of the write-ahead log frame-header.
  45378. */
  45379. #define walFrameOffset(iFrame, szPage) ( \
  45380. WAL_HDRSIZE + ((iFrame)-1)*(i64)((szPage)+WAL_FRAME_HDRSIZE) \
  45381. )
  45382. /*
  45383. ** An open write-ahead log file is represented by an instance of the
  45384. ** following object.
  45385. */
  45386. struct Wal {
  45387. sqlite3_vfs *pVfs; /* The VFS used to create pDbFd */
  45388. sqlite3_file *pDbFd; /* File handle for the database file */
  45389. sqlite3_file *pWalFd; /* File handle for WAL file */
  45390. u32 iCallback; /* Value to pass to log callback (or 0) */
  45391. i64 mxWalSize; /* Truncate WAL to this size upon reset */
  45392. int nWiData; /* Size of array apWiData */
  45393. int szFirstBlock; /* Size of first block written to WAL file */
  45394. volatile u32 **apWiData; /* Pointer to wal-index content in memory */
  45395. u32 szPage; /* Database page size */
  45396. i16 readLock; /* Which read lock is being held. -1 for none */
  45397. u8 syncFlags; /* Flags to use to sync header writes */
  45398. u8 exclusiveMode; /* Non-zero if connection is in exclusive mode */
  45399. u8 writeLock; /* True if in a write transaction */
  45400. u8 ckptLock; /* True if holding a checkpoint lock */
  45401. u8 readOnly; /* WAL_RDWR, WAL_RDONLY, or WAL_SHM_RDONLY */
  45402. u8 truncateOnCommit; /* True to truncate WAL file on commit */
  45403. u8 syncHeader; /* Fsync the WAL header if true */
  45404. u8 padToSectorBoundary; /* Pad transactions out to the next sector */
  45405. WalIndexHdr hdr; /* Wal-index header for current transaction */
  45406. const char *zWalName; /* Name of WAL file */
  45407. u32 nCkpt; /* Checkpoint sequence counter in the wal-header */
  45408. #ifdef SQLITE_DEBUG
  45409. u8 lockError; /* True if a locking error has occurred */
  45410. #endif
  45411. };
  45412. /*
  45413. ** Candidate values for Wal.exclusiveMode.
  45414. */
  45415. #define WAL_NORMAL_MODE 0
  45416. #define WAL_EXCLUSIVE_MODE 1
  45417. #define WAL_HEAPMEMORY_MODE 2
  45418. /*
  45419. ** Possible values for WAL.readOnly
  45420. */
  45421. #define WAL_RDWR 0 /* Normal read/write connection */
  45422. #define WAL_RDONLY 1 /* The WAL file is readonly */
  45423. #define WAL_SHM_RDONLY 2 /* The SHM file is readonly */
  45424. /*
  45425. ** Each page of the wal-index mapping contains a hash-table made up of
  45426. ** an array of HASHTABLE_NSLOT elements of the following type.
  45427. */
  45428. typedef u16 ht_slot;
  45429. /*
  45430. ** This structure is used to implement an iterator that loops through
  45431. ** all frames in the WAL in database page order. Where two or more frames
  45432. ** correspond to the same database page, the iterator visits only the
  45433. ** frame most recently written to the WAL (in other words, the frame with
  45434. ** the largest index).
  45435. **
  45436. ** The internals of this structure are only accessed by:
  45437. **
  45438. ** walIteratorInit() - Create a new iterator,
  45439. ** walIteratorNext() - Step an iterator,
  45440. ** walIteratorFree() - Free an iterator.
  45441. **
  45442. ** This functionality is used by the checkpoint code (see walCheckpoint()).
  45443. */
  45444. struct WalIterator {
  45445. int iPrior; /* Last result returned from the iterator */
  45446. int nSegment; /* Number of entries in aSegment[] */
  45447. struct WalSegment {
  45448. int iNext; /* Next slot in aIndex[] not yet returned */
  45449. ht_slot *aIndex; /* i0, i1, i2... such that aPgno[iN] ascend */
  45450. u32 *aPgno; /* Array of page numbers. */
  45451. int nEntry; /* Nr. of entries in aPgno[] and aIndex[] */
  45452. int iZero; /* Frame number associated with aPgno[0] */
  45453. } aSegment[1]; /* One for every 32KB page in the wal-index */
  45454. };
  45455. /*
  45456. ** Define the parameters of the hash tables in the wal-index file. There
  45457. ** is a hash-table following every HASHTABLE_NPAGE page numbers in the
  45458. ** wal-index.
  45459. **
  45460. ** Changing any of these constants will alter the wal-index format and
  45461. ** create incompatibilities.
  45462. */
  45463. #define HASHTABLE_NPAGE 4096 /* Must be power of 2 */
  45464. #define HASHTABLE_HASH_1 383 /* Should be prime */
  45465. #define HASHTABLE_NSLOT (HASHTABLE_NPAGE*2) /* Must be a power of 2 */
  45466. /*
  45467. ** The block of page numbers associated with the first hash-table in a
  45468. ** wal-index is smaller than usual. This is so that there is a complete
  45469. ** hash-table on each aligned 32KB page of the wal-index.
  45470. */
  45471. #define HASHTABLE_NPAGE_ONE (HASHTABLE_NPAGE - (WALINDEX_HDR_SIZE/sizeof(u32)))
  45472. /* The wal-index is divided into pages of WALINDEX_PGSZ bytes each. */
  45473. #define WALINDEX_PGSZ ( \
  45474. sizeof(ht_slot)*HASHTABLE_NSLOT + HASHTABLE_NPAGE*sizeof(u32) \
  45475. )
  45476. /*
  45477. ** Obtain a pointer to the iPage'th page of the wal-index. The wal-index
  45478. ** is broken into pages of WALINDEX_PGSZ bytes. Wal-index pages are
  45479. ** numbered from zero.
  45480. **
  45481. ** If this call is successful, *ppPage is set to point to the wal-index
  45482. ** page and SQLITE_OK is returned. If an error (an OOM or VFS error) occurs,
  45483. ** then an SQLite error code is returned and *ppPage is set to 0.
  45484. */
  45485. static int walIndexPage(Wal *pWal, int iPage, volatile u32 **ppPage){
  45486. int rc = SQLITE_OK;
  45487. /* Enlarge the pWal->apWiData[] array if required */
  45488. if( pWal->nWiData<=iPage ){
  45489. int nByte = sizeof(u32*)*(iPage+1);
  45490. volatile u32 **apNew;
  45491. apNew = (volatile u32 **)sqlite3_realloc((void *)pWal->apWiData, nByte);
  45492. if( !apNew ){
  45493. *ppPage = 0;
  45494. return SQLITE_NOMEM;
  45495. }
  45496. memset((void*)&apNew[pWal->nWiData], 0,
  45497. sizeof(u32*)*(iPage+1-pWal->nWiData));
  45498. pWal->apWiData = apNew;
  45499. pWal->nWiData = iPage+1;
  45500. }
  45501. /* Request a pointer to the required page from the VFS */
  45502. if( pWal->apWiData[iPage]==0 ){
  45503. if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){
  45504. pWal->apWiData[iPage] = (u32 volatile *)sqlite3MallocZero(WALINDEX_PGSZ);
  45505. if( !pWal->apWiData[iPage] ) rc = SQLITE_NOMEM;
  45506. }else{
  45507. rc = sqlite3OsShmMap(pWal->pDbFd, iPage, WALINDEX_PGSZ,
  45508. pWal->writeLock, (void volatile **)&pWal->apWiData[iPage]
  45509. );
  45510. if( rc==SQLITE_READONLY ){
  45511. pWal->readOnly |= WAL_SHM_RDONLY;
  45512. rc = SQLITE_OK;
  45513. }
  45514. }
  45515. }
  45516. *ppPage = pWal->apWiData[iPage];
  45517. assert( iPage==0 || *ppPage || rc!=SQLITE_OK );
  45518. return rc;
  45519. }
  45520. /*
  45521. ** Return a pointer to the WalCkptInfo structure in the wal-index.
  45522. */
  45523. static volatile WalCkptInfo *walCkptInfo(Wal *pWal){
  45524. assert( pWal->nWiData>0 && pWal->apWiData[0] );
  45525. return (volatile WalCkptInfo*)&(pWal->apWiData[0][sizeof(WalIndexHdr)/2]);
  45526. }
  45527. /*
  45528. ** Return a pointer to the WalIndexHdr structure in the wal-index.
  45529. */
  45530. static volatile WalIndexHdr *walIndexHdr(Wal *pWal){
  45531. assert( pWal->nWiData>0 && pWal->apWiData[0] );
  45532. return (volatile WalIndexHdr*)pWal->apWiData[0];
  45533. }
  45534. /*
  45535. ** The argument to this macro must be of type u32. On a little-endian
  45536. ** architecture, it returns the u32 value that results from interpreting
  45537. ** the 4 bytes as a big-endian value. On a big-endian architecture, it
  45538. ** returns the value that would be produced by interpreting the 4 bytes
  45539. ** of the input value as a little-endian integer.
  45540. */
  45541. #define BYTESWAP32(x) ( \
  45542. (((x)&0x000000FF)<<24) + (((x)&0x0000FF00)<<8) \
  45543. + (((x)&0x00FF0000)>>8) + (((x)&0xFF000000)>>24) \
  45544. )
  45545. /*
  45546. ** Generate or extend an 8 byte checksum based on the data in
  45547. ** array aByte[] and the initial values of aIn[0] and aIn[1] (or
  45548. ** initial values of 0 and 0 if aIn==NULL).
  45549. **
  45550. ** The checksum is written back into aOut[] before returning.
  45551. **
  45552. ** nByte must be a positive multiple of 8.
  45553. */
  45554. static void walChecksumBytes(
  45555. int nativeCksum, /* True for native byte-order, false for non-native */
  45556. u8 *a, /* Content to be checksummed */
  45557. int nByte, /* Bytes of content in a[]. Must be a multiple of 8. */
  45558. const u32 *aIn, /* Initial checksum value input */
  45559. u32 *aOut /* OUT: Final checksum value output */
  45560. ){
  45561. u32 s1, s2;
  45562. u32 *aData = (u32 *)a;
  45563. u32 *aEnd = (u32 *)&a[nByte];
  45564. if( aIn ){
  45565. s1 = aIn[0];
  45566. s2 = aIn[1];
  45567. }else{
  45568. s1 = s2 = 0;
  45569. }
  45570. assert( nByte>=8 );
  45571. assert( (nByte&0x00000007)==0 );
  45572. if( nativeCksum ){
  45573. do {
  45574. s1 += *aData++ + s2;
  45575. s2 += *aData++ + s1;
  45576. }while( aData<aEnd );
  45577. }else{
  45578. do {
  45579. s1 += BYTESWAP32(aData[0]) + s2;
  45580. s2 += BYTESWAP32(aData[1]) + s1;
  45581. aData += 2;
  45582. }while( aData<aEnd );
  45583. }
  45584. aOut[0] = s1;
  45585. aOut[1] = s2;
  45586. }
  45587. static void walShmBarrier(Wal *pWal){
  45588. if( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE ){
  45589. sqlite3OsShmBarrier(pWal->pDbFd);
  45590. }
  45591. }
  45592. /*
  45593. ** Write the header information in pWal->hdr into the wal-index.
  45594. **
  45595. ** The checksum on pWal->hdr is updated before it is written.
  45596. */
  45597. static void walIndexWriteHdr(Wal *pWal){
  45598. volatile WalIndexHdr *aHdr = walIndexHdr(pWal);
  45599. const int nCksum = offsetof(WalIndexHdr, aCksum);
  45600. assert( pWal->writeLock );
  45601. pWal->hdr.isInit = 1;
  45602. pWal->hdr.iVersion = WALINDEX_MAX_VERSION;
  45603. walChecksumBytes(1, (u8*)&pWal->hdr, nCksum, 0, pWal->hdr.aCksum);
  45604. memcpy((void *)&aHdr[1], (void *)&pWal->hdr, sizeof(WalIndexHdr));
  45605. walShmBarrier(pWal);
  45606. memcpy((void *)&aHdr[0], (void *)&pWal->hdr, sizeof(WalIndexHdr));
  45607. }
  45608. /*
  45609. ** This function encodes a single frame header and writes it to a buffer
  45610. ** supplied by the caller. A frame-header is made up of a series of
  45611. ** 4-byte big-endian integers, as follows:
  45612. **
  45613. ** 0: Page number.
  45614. ** 4: For commit records, the size of the database image in pages
  45615. ** after the commit. For all other records, zero.
  45616. ** 8: Salt-1 (copied from the wal-header)
  45617. ** 12: Salt-2 (copied from the wal-header)
  45618. ** 16: Checksum-1.
  45619. ** 20: Checksum-2.
  45620. */
  45621. static void walEncodeFrame(
  45622. Wal *pWal, /* The write-ahead log */
  45623. u32 iPage, /* Database page number for frame */
  45624. u32 nTruncate, /* New db size (or 0 for non-commit frames) */
  45625. u8 *aData, /* Pointer to page data */
  45626. u8 *aFrame /* OUT: Write encoded frame here */
  45627. ){
  45628. int nativeCksum; /* True for native byte-order checksums */
  45629. u32 *aCksum = pWal->hdr.aFrameCksum;
  45630. assert( WAL_FRAME_HDRSIZE==24 );
  45631. sqlite3Put4byte(&aFrame[0], iPage);
  45632. sqlite3Put4byte(&aFrame[4], nTruncate);
  45633. memcpy(&aFrame[8], pWal->hdr.aSalt, 8);
  45634. nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
  45635. walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
  45636. walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
  45637. sqlite3Put4byte(&aFrame[16], aCksum[0]);
  45638. sqlite3Put4byte(&aFrame[20], aCksum[1]);
  45639. }
  45640. /*
  45641. ** Check to see if the frame with header in aFrame[] and content
  45642. ** in aData[] is valid. If it is a valid frame, fill *piPage and
  45643. ** *pnTruncate and return true. Return if the frame is not valid.
  45644. */
  45645. static int walDecodeFrame(
  45646. Wal *pWal, /* The write-ahead log */
  45647. u32 *piPage, /* OUT: Database page number for frame */
  45648. u32 *pnTruncate, /* OUT: New db size (or 0 if not commit) */
  45649. u8 *aData, /* Pointer to page data (for checksum) */
  45650. u8 *aFrame /* Frame data */
  45651. ){
  45652. int nativeCksum; /* True for native byte-order checksums */
  45653. u32 *aCksum = pWal->hdr.aFrameCksum;
  45654. u32 pgno; /* Page number of the frame */
  45655. assert( WAL_FRAME_HDRSIZE==24 );
  45656. /* A frame is only valid if the salt values in the frame-header
  45657. ** match the salt values in the wal-header.
  45658. */
  45659. if( memcmp(&pWal->hdr.aSalt, &aFrame[8], 8)!=0 ){
  45660. return 0;
  45661. }
  45662. /* A frame is only valid if the page number is creater than zero.
  45663. */
  45664. pgno = sqlite3Get4byte(&aFrame[0]);
  45665. if( pgno==0 ){
  45666. return 0;
  45667. }
  45668. /* A frame is only valid if a checksum of the WAL header,
  45669. ** all prior frams, the first 16 bytes of this frame-header,
  45670. ** and the frame-data matches the checksum in the last 8
  45671. ** bytes of this frame-header.
  45672. */
  45673. nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
  45674. walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
  45675. walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
  45676. if( aCksum[0]!=sqlite3Get4byte(&aFrame[16])
  45677. || aCksum[1]!=sqlite3Get4byte(&aFrame[20])
  45678. ){
  45679. /* Checksum failed. */
  45680. return 0;
  45681. }
  45682. /* If we reach this point, the frame is valid. Return the page number
  45683. ** and the new database size.
  45684. */
  45685. *piPage = pgno;
  45686. *pnTruncate = sqlite3Get4byte(&aFrame[4]);
  45687. return 1;
  45688. }
  45689. #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
  45690. /*
  45691. ** Names of locks. This routine is used to provide debugging output and is not
  45692. ** a part of an ordinary build.
  45693. */
  45694. static const char *walLockName(int lockIdx){
  45695. if( lockIdx==WAL_WRITE_LOCK ){
  45696. return "WRITE-LOCK";
  45697. }else if( lockIdx==WAL_CKPT_LOCK ){
  45698. return "CKPT-LOCK";
  45699. }else if( lockIdx==WAL_RECOVER_LOCK ){
  45700. return "RECOVER-LOCK";
  45701. }else{
  45702. static char zName[15];
  45703. sqlite3_snprintf(sizeof(zName), zName, "READ-LOCK[%d]",
  45704. lockIdx-WAL_READ_LOCK(0));
  45705. return zName;
  45706. }
  45707. }
  45708. #endif /*defined(SQLITE_TEST) || defined(SQLITE_DEBUG) */
  45709. /*
  45710. ** Set or release locks on the WAL. Locks are either shared or exclusive.
  45711. ** A lock cannot be moved directly between shared and exclusive - it must go
  45712. ** through the unlocked state first.
  45713. **
  45714. ** In locking_mode=EXCLUSIVE, all of these routines become no-ops.
  45715. */
  45716. static int walLockShared(Wal *pWal, int lockIdx){
  45717. int rc;
  45718. if( pWal->exclusiveMode ) return SQLITE_OK;
  45719. rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
  45720. SQLITE_SHM_LOCK | SQLITE_SHM_SHARED);
  45721. WALTRACE(("WAL%p: acquire SHARED-%s %s\n", pWal,
  45722. walLockName(lockIdx), rc ? "failed" : "ok"));
  45723. VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); )
  45724. return rc;
  45725. }
  45726. static void walUnlockShared(Wal *pWal, int lockIdx){
  45727. if( pWal->exclusiveMode ) return;
  45728. (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
  45729. SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED);
  45730. WALTRACE(("WAL%p: release SHARED-%s\n", pWal, walLockName(lockIdx)));
  45731. }
  45732. static int walLockExclusive(Wal *pWal, int lockIdx, int n){
  45733. int rc;
  45734. if( pWal->exclusiveMode ) return SQLITE_OK;
  45735. rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
  45736. SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE);
  45737. WALTRACE(("WAL%p: acquire EXCLUSIVE-%s cnt=%d %s\n", pWal,
  45738. walLockName(lockIdx), n, rc ? "failed" : "ok"));
  45739. VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); )
  45740. return rc;
  45741. }
  45742. static void walUnlockExclusive(Wal *pWal, int lockIdx, int n){
  45743. if( pWal->exclusiveMode ) return;
  45744. (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
  45745. SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE);
  45746. WALTRACE(("WAL%p: release EXCLUSIVE-%s cnt=%d\n", pWal,
  45747. walLockName(lockIdx), n));
  45748. }
  45749. /*
  45750. ** Compute a hash on a page number. The resulting hash value must land
  45751. ** between 0 and (HASHTABLE_NSLOT-1). The walHashNext() function advances
  45752. ** the hash to the next value in the event of a collision.
  45753. */
  45754. static int walHash(u32 iPage){
  45755. assert( iPage>0 );
  45756. assert( (HASHTABLE_NSLOT & (HASHTABLE_NSLOT-1))==0 );
  45757. return (iPage*HASHTABLE_HASH_1) & (HASHTABLE_NSLOT-1);
  45758. }
  45759. static int walNextHash(int iPriorHash){
  45760. return (iPriorHash+1)&(HASHTABLE_NSLOT-1);
  45761. }
  45762. /*
  45763. ** Return pointers to the hash table and page number array stored on
  45764. ** page iHash of the wal-index. The wal-index is broken into 32KB pages
  45765. ** numbered starting from 0.
  45766. **
  45767. ** Set output variable *paHash to point to the start of the hash table
  45768. ** in the wal-index file. Set *piZero to one less than the frame
  45769. ** number of the first frame indexed by this hash table. If a
  45770. ** slot in the hash table is set to N, it refers to frame number
  45771. ** (*piZero+N) in the log.
  45772. **
  45773. ** Finally, set *paPgno so that *paPgno[1] is the page number of the
  45774. ** first frame indexed by the hash table, frame (*piZero+1).
  45775. */
  45776. static int walHashGet(
  45777. Wal *pWal, /* WAL handle */
  45778. int iHash, /* Find the iHash'th table */
  45779. volatile ht_slot **paHash, /* OUT: Pointer to hash index */
  45780. volatile u32 **paPgno, /* OUT: Pointer to page number array */
  45781. u32 *piZero /* OUT: Frame associated with *paPgno[0] */
  45782. ){
  45783. int rc; /* Return code */
  45784. volatile u32 *aPgno;
  45785. rc = walIndexPage(pWal, iHash, &aPgno);
  45786. assert( rc==SQLITE_OK || iHash>0 );
  45787. if( rc==SQLITE_OK ){
  45788. u32 iZero;
  45789. volatile ht_slot *aHash;
  45790. aHash = (volatile ht_slot *)&aPgno[HASHTABLE_NPAGE];
  45791. if( iHash==0 ){
  45792. aPgno = &aPgno[WALINDEX_HDR_SIZE/sizeof(u32)];
  45793. iZero = 0;
  45794. }else{
  45795. iZero = HASHTABLE_NPAGE_ONE + (iHash-1)*HASHTABLE_NPAGE;
  45796. }
  45797. *paPgno = &aPgno[-1];
  45798. *paHash = aHash;
  45799. *piZero = iZero;
  45800. }
  45801. return rc;
  45802. }
  45803. /*
  45804. ** Return the number of the wal-index page that contains the hash-table
  45805. ** and page-number array that contain entries corresponding to WAL frame
  45806. ** iFrame. The wal-index is broken up into 32KB pages. Wal-index pages
  45807. ** are numbered starting from 0.
  45808. */
  45809. static int walFramePage(u32 iFrame){
  45810. int iHash = (iFrame+HASHTABLE_NPAGE-HASHTABLE_NPAGE_ONE-1) / HASHTABLE_NPAGE;
  45811. assert( (iHash==0 || iFrame>HASHTABLE_NPAGE_ONE)
  45812. && (iHash>=1 || iFrame<=HASHTABLE_NPAGE_ONE)
  45813. && (iHash<=1 || iFrame>(HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE))
  45814. && (iHash>=2 || iFrame<=HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE)
  45815. && (iHash<=2 || iFrame>(HASHTABLE_NPAGE_ONE+2*HASHTABLE_NPAGE))
  45816. );
  45817. return iHash;
  45818. }
  45819. /*
  45820. ** Return the page number associated with frame iFrame in this WAL.
  45821. */
  45822. static u32 walFramePgno(Wal *pWal, u32 iFrame){
  45823. int iHash = walFramePage(iFrame);
  45824. if( iHash==0 ){
  45825. return pWal->apWiData[0][WALINDEX_HDR_SIZE/sizeof(u32) + iFrame - 1];
  45826. }
  45827. return pWal->apWiData[iHash][(iFrame-1-HASHTABLE_NPAGE_ONE)%HASHTABLE_NPAGE];
  45828. }
  45829. /*
  45830. ** Remove entries from the hash table that point to WAL slots greater
  45831. ** than pWal->hdr.mxFrame.
  45832. **
  45833. ** This function is called whenever pWal->hdr.mxFrame is decreased due
  45834. ** to a rollback or savepoint.
  45835. **
  45836. ** At most only the hash table containing pWal->hdr.mxFrame needs to be
  45837. ** updated. Any later hash tables will be automatically cleared when
  45838. ** pWal->hdr.mxFrame advances to the point where those hash tables are
  45839. ** actually needed.
  45840. */
  45841. static void walCleanupHash(Wal *pWal){
  45842. volatile ht_slot *aHash = 0; /* Pointer to hash table to clear */
  45843. volatile u32 *aPgno = 0; /* Page number array for hash table */
  45844. u32 iZero = 0; /* frame == (aHash[x]+iZero) */
  45845. int iLimit = 0; /* Zero values greater than this */
  45846. int nByte; /* Number of bytes to zero in aPgno[] */
  45847. int i; /* Used to iterate through aHash[] */
  45848. assert( pWal->writeLock );
  45849. testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE-1 );
  45850. testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE );
  45851. testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE+1 );
  45852. if( pWal->hdr.mxFrame==0 ) return;
  45853. /* Obtain pointers to the hash-table and page-number array containing
  45854. ** the entry that corresponds to frame pWal->hdr.mxFrame. It is guaranteed
  45855. ** that the page said hash-table and array reside on is already mapped.
  45856. */
  45857. assert( pWal->nWiData>walFramePage(pWal->hdr.mxFrame) );
  45858. assert( pWal->apWiData[walFramePage(pWal->hdr.mxFrame)] );
  45859. walHashGet(pWal, walFramePage(pWal->hdr.mxFrame), &aHash, &aPgno, &iZero);
  45860. /* Zero all hash-table entries that correspond to frame numbers greater
  45861. ** than pWal->hdr.mxFrame.
  45862. */
  45863. iLimit = pWal->hdr.mxFrame - iZero;
  45864. assert( iLimit>0 );
  45865. for(i=0; i<HASHTABLE_NSLOT; i++){
  45866. if( aHash[i]>iLimit ){
  45867. aHash[i] = 0;
  45868. }
  45869. }
  45870. /* Zero the entries in the aPgno array that correspond to frames with
  45871. ** frame numbers greater than pWal->hdr.mxFrame.
  45872. */
  45873. nByte = (int)((char *)aHash - (char *)&aPgno[iLimit+1]);
  45874. memset((void *)&aPgno[iLimit+1], 0, nByte);
  45875. #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
  45876. /* Verify that the every entry in the mapping region is still reachable
  45877. ** via the hash table even after the cleanup.
  45878. */
  45879. if( iLimit ){
  45880. int i; /* Loop counter */
  45881. int iKey; /* Hash key */
  45882. for(i=1; i<=iLimit; i++){
  45883. for(iKey=walHash(aPgno[i]); aHash[iKey]; iKey=walNextHash(iKey)){
  45884. if( aHash[iKey]==i ) break;
  45885. }
  45886. assert( aHash[iKey]==i );
  45887. }
  45888. }
  45889. #endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
  45890. }
  45891. /*
  45892. ** Set an entry in the wal-index that will map database page number
  45893. ** pPage into WAL frame iFrame.
  45894. */
  45895. static int walIndexAppend(Wal *pWal, u32 iFrame, u32 iPage){
  45896. int rc; /* Return code */
  45897. u32 iZero = 0; /* One less than frame number of aPgno[1] */
  45898. volatile u32 *aPgno = 0; /* Page number array */
  45899. volatile ht_slot *aHash = 0; /* Hash table */
  45900. rc = walHashGet(pWal, walFramePage(iFrame), &aHash, &aPgno, &iZero);
  45901. /* Assuming the wal-index file was successfully mapped, populate the
  45902. ** page number array and hash table entry.
  45903. */
  45904. if( rc==SQLITE_OK ){
  45905. int iKey; /* Hash table key */
  45906. int idx; /* Value to write to hash-table slot */
  45907. int nCollide; /* Number of hash collisions */
  45908. idx = iFrame - iZero;
  45909. assert( idx <= HASHTABLE_NSLOT/2 + 1 );
  45910. /* If this is the first entry to be added to this hash-table, zero the
  45911. ** entire hash table and aPgno[] array before proceeding.
  45912. */
  45913. if( idx==1 ){
  45914. int nByte = (int)((u8 *)&aHash[HASHTABLE_NSLOT] - (u8 *)&aPgno[1]);
  45915. memset((void*)&aPgno[1], 0, nByte);
  45916. }
  45917. /* If the entry in aPgno[] is already set, then the previous writer
  45918. ** must have exited unexpectedly in the middle of a transaction (after
  45919. ** writing one or more dirty pages to the WAL to free up memory).
  45920. ** Remove the remnants of that writers uncommitted transaction from
  45921. ** the hash-table before writing any new entries.
  45922. */
  45923. if( aPgno[idx] ){
  45924. walCleanupHash(pWal);
  45925. assert( !aPgno[idx] );
  45926. }
  45927. /* Write the aPgno[] array entry and the hash-table slot. */
  45928. nCollide = idx;
  45929. for(iKey=walHash(iPage); aHash[iKey]; iKey=walNextHash(iKey)){
  45930. if( (nCollide--)==0 ) return SQLITE_CORRUPT_BKPT;
  45931. }
  45932. aPgno[idx] = iPage;
  45933. aHash[iKey] = (ht_slot)idx;
  45934. #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
  45935. /* Verify that the number of entries in the hash table exactly equals
  45936. ** the number of entries in the mapping region.
  45937. */
  45938. {
  45939. int i; /* Loop counter */
  45940. int nEntry = 0; /* Number of entries in the hash table */
  45941. for(i=0; i<HASHTABLE_NSLOT; i++){ if( aHash[i] ) nEntry++; }
  45942. assert( nEntry==idx );
  45943. }
  45944. /* Verify that the every entry in the mapping region is reachable
  45945. ** via the hash table. This turns out to be a really, really expensive
  45946. ** thing to check, so only do this occasionally - not on every
  45947. ** iteration.
  45948. */
  45949. if( (idx&0x3ff)==0 ){
  45950. int i; /* Loop counter */
  45951. for(i=1; i<=idx; i++){
  45952. for(iKey=walHash(aPgno[i]); aHash[iKey]; iKey=walNextHash(iKey)){
  45953. if( aHash[iKey]==i ) break;
  45954. }
  45955. assert( aHash[iKey]==i );
  45956. }
  45957. }
  45958. #endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
  45959. }
  45960. return rc;
  45961. }
  45962. /*
  45963. ** Recover the wal-index by reading the write-ahead log file.
  45964. **
  45965. ** This routine first tries to establish an exclusive lock on the
  45966. ** wal-index to prevent other threads/processes from doing anything
  45967. ** with the WAL or wal-index while recovery is running. The
  45968. ** WAL_RECOVER_LOCK is also held so that other threads will know
  45969. ** that this thread is running recovery. If unable to establish
  45970. ** the necessary locks, this routine returns SQLITE_BUSY.
  45971. */
  45972. static int walIndexRecover(Wal *pWal){
  45973. int rc; /* Return Code */
  45974. i64 nSize; /* Size of log file */
  45975. u32 aFrameCksum[2] = {0, 0};
  45976. int iLock; /* Lock offset to lock for checkpoint */
  45977. int nLock; /* Number of locks to hold */
  45978. /* Obtain an exclusive lock on all byte in the locking range not already
  45979. ** locked by the caller. The caller is guaranteed to have locked the
  45980. ** WAL_WRITE_LOCK byte, and may have also locked the WAL_CKPT_LOCK byte.
  45981. ** If successful, the same bytes that are locked here are unlocked before
  45982. ** this function returns.
  45983. */
  45984. assert( pWal->ckptLock==1 || pWal->ckptLock==0 );
  45985. assert( WAL_ALL_BUT_WRITE==WAL_WRITE_LOCK+1 );
  45986. assert( WAL_CKPT_LOCK==WAL_ALL_BUT_WRITE );
  45987. assert( pWal->writeLock );
  45988. iLock = WAL_ALL_BUT_WRITE + pWal->ckptLock;
  45989. nLock = SQLITE_SHM_NLOCK - iLock;
  45990. rc = walLockExclusive(pWal, iLock, nLock);
  45991. if( rc ){
  45992. return rc;
  45993. }
  45994. WALTRACE(("WAL%p: recovery begin...\n", pWal));
  45995. memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
  45996. rc = sqlite3OsFileSize(pWal->pWalFd, &nSize);
  45997. if( rc!=SQLITE_OK ){
  45998. goto recovery_error;
  45999. }
  46000. if( nSize>WAL_HDRSIZE ){
  46001. u8 aBuf[WAL_HDRSIZE]; /* Buffer to load WAL header into */
  46002. u8 *aFrame = 0; /* Malloc'd buffer to load entire frame */
  46003. int szFrame; /* Number of bytes in buffer aFrame[] */
  46004. u8 *aData; /* Pointer to data part of aFrame buffer */
  46005. int iFrame; /* Index of last frame read */
  46006. i64 iOffset; /* Next offset to read from log file */
  46007. int szPage; /* Page size according to the log */
  46008. u32 magic; /* Magic value read from WAL header */
  46009. u32 version; /* Magic value read from WAL header */
  46010. int isValid; /* True if this frame is valid */
  46011. /* Read in the WAL header. */
  46012. rc = sqlite3OsRead(pWal->pWalFd, aBuf, WAL_HDRSIZE, 0);
  46013. if( rc!=SQLITE_OK ){
  46014. goto recovery_error;
  46015. }
  46016. /* If the database page size is not a power of two, or is greater than
  46017. ** SQLITE_MAX_PAGE_SIZE, conclude that the WAL file contains no valid
  46018. ** data. Similarly, if the 'magic' value is invalid, ignore the whole
  46019. ** WAL file.
  46020. */
  46021. magic = sqlite3Get4byte(&aBuf[0]);
  46022. szPage = sqlite3Get4byte(&aBuf[8]);
  46023. if( (magic&0xFFFFFFFE)!=WAL_MAGIC
  46024. || szPage&(szPage-1)
  46025. || szPage>SQLITE_MAX_PAGE_SIZE
  46026. || szPage<512
  46027. ){
  46028. goto finished;
  46029. }
  46030. pWal->hdr.bigEndCksum = (u8)(magic&0x00000001);
  46031. pWal->szPage = szPage;
  46032. pWal->nCkpt = sqlite3Get4byte(&aBuf[12]);
  46033. memcpy(&pWal->hdr.aSalt, &aBuf[16], 8);
  46034. /* Verify that the WAL header checksum is correct */
  46035. walChecksumBytes(pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN,
  46036. aBuf, WAL_HDRSIZE-2*4, 0, pWal->hdr.aFrameCksum
  46037. );
  46038. if( pWal->hdr.aFrameCksum[0]!=sqlite3Get4byte(&aBuf[24])
  46039. || pWal->hdr.aFrameCksum[1]!=sqlite3Get4byte(&aBuf[28])
  46040. ){
  46041. goto finished;
  46042. }
  46043. /* Verify that the version number on the WAL format is one that
  46044. ** are able to understand */
  46045. version = sqlite3Get4byte(&aBuf[4]);
  46046. if( version!=WAL_MAX_VERSION ){
  46047. rc = SQLITE_CANTOPEN_BKPT;
  46048. goto finished;
  46049. }
  46050. /* Malloc a buffer to read frames into. */
  46051. szFrame = szPage + WAL_FRAME_HDRSIZE;
  46052. aFrame = (u8 *)sqlite3_malloc(szFrame);
  46053. if( !aFrame ){
  46054. rc = SQLITE_NOMEM;
  46055. goto recovery_error;
  46056. }
  46057. aData = &aFrame[WAL_FRAME_HDRSIZE];
  46058. /* Read all frames from the log file. */
  46059. iFrame = 0;
  46060. for(iOffset=WAL_HDRSIZE; (iOffset+szFrame)<=nSize; iOffset+=szFrame){
  46061. u32 pgno; /* Database page number for frame */
  46062. u32 nTruncate; /* dbsize field from frame header */
  46063. /* Read and decode the next log frame. */
  46064. iFrame++;
  46065. rc = sqlite3OsRead(pWal->pWalFd, aFrame, szFrame, iOffset);
  46066. if( rc!=SQLITE_OK ) break;
  46067. isValid = walDecodeFrame(pWal, &pgno, &nTruncate, aData, aFrame);
  46068. if( !isValid ) break;
  46069. rc = walIndexAppend(pWal, iFrame, pgno);
  46070. if( rc!=SQLITE_OK ) break;
  46071. /* If nTruncate is non-zero, this is a commit record. */
  46072. if( nTruncate ){
  46073. pWal->hdr.mxFrame = iFrame;
  46074. pWal->hdr.nPage = nTruncate;
  46075. pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
  46076. testcase( szPage<=32768 );
  46077. testcase( szPage>=65536 );
  46078. aFrameCksum[0] = pWal->hdr.aFrameCksum[0];
  46079. aFrameCksum[1] = pWal->hdr.aFrameCksum[1];
  46080. }
  46081. }
  46082. sqlite3_free(aFrame);
  46083. }
  46084. finished:
  46085. if( rc==SQLITE_OK ){
  46086. volatile WalCkptInfo *pInfo;
  46087. int i;
  46088. pWal->hdr.aFrameCksum[0] = aFrameCksum[0];
  46089. pWal->hdr.aFrameCksum[1] = aFrameCksum[1];
  46090. walIndexWriteHdr(pWal);
  46091. /* Reset the checkpoint-header. This is safe because this thread is
  46092. ** currently holding locks that exclude all other readers, writers and
  46093. ** checkpointers.
  46094. */
  46095. pInfo = walCkptInfo(pWal);
  46096. pInfo->nBackfill = 0;
  46097. pInfo->aReadMark[0] = 0;
  46098. for(i=1; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
  46099. if( pWal->hdr.mxFrame ) pInfo->aReadMark[1] = pWal->hdr.mxFrame;
  46100. /* If more than one frame was recovered from the log file, report an
  46101. ** event via sqlite3_log(). This is to help with identifying performance
  46102. ** problems caused by applications routinely shutting down without
  46103. ** checkpointing the log file.
  46104. */
  46105. if( pWal->hdr.nPage ){
  46106. sqlite3_log(SQLITE_NOTICE_RECOVER_WAL,
  46107. "recovered %d frames from WAL file %s",
  46108. pWal->hdr.mxFrame, pWal->zWalName
  46109. );
  46110. }
  46111. }
  46112. recovery_error:
  46113. WALTRACE(("WAL%p: recovery %s\n", pWal, rc ? "failed" : "ok"));
  46114. walUnlockExclusive(pWal, iLock, nLock);
  46115. return rc;
  46116. }
  46117. /*
  46118. ** Close an open wal-index.
  46119. */
  46120. static void walIndexClose(Wal *pWal, int isDelete){
  46121. if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){
  46122. int i;
  46123. for(i=0; i<pWal->nWiData; i++){
  46124. sqlite3_free((void *)pWal->apWiData[i]);
  46125. pWal->apWiData[i] = 0;
  46126. }
  46127. }else{
  46128. sqlite3OsShmUnmap(pWal->pDbFd, isDelete);
  46129. }
  46130. }
  46131. /*
  46132. ** Open a connection to the WAL file zWalName. The database file must
  46133. ** already be opened on connection pDbFd. The buffer that zWalName points
  46134. ** to must remain valid for the lifetime of the returned Wal* handle.
  46135. **
  46136. ** A SHARED lock should be held on the database file when this function
  46137. ** is called. The purpose of this SHARED lock is to prevent any other
  46138. ** client from unlinking the WAL or wal-index file. If another process
  46139. ** were to do this just after this client opened one of these files, the
  46140. ** system would be badly broken.
  46141. **
  46142. ** If the log file is successfully opened, SQLITE_OK is returned and
  46143. ** *ppWal is set to point to a new WAL handle. If an error occurs,
  46144. ** an SQLite error code is returned and *ppWal is left unmodified.
  46145. */
  46146. SQLITE_PRIVATE int sqlite3WalOpen(
  46147. sqlite3_vfs *pVfs, /* vfs module to open wal and wal-index */
  46148. sqlite3_file *pDbFd, /* The open database file */
  46149. const char *zWalName, /* Name of the WAL file */
  46150. int bNoShm, /* True to run in heap-memory mode */
  46151. i64 mxWalSize, /* Truncate WAL to this size on reset */
  46152. Wal **ppWal /* OUT: Allocated Wal handle */
  46153. ){
  46154. int rc; /* Return Code */
  46155. Wal *pRet; /* Object to allocate and return */
  46156. int flags; /* Flags passed to OsOpen() */
  46157. assert( zWalName && zWalName[0] );
  46158. assert( pDbFd );
  46159. /* In the amalgamation, the os_unix.c and os_win.c source files come before
  46160. ** this source file. Verify that the #defines of the locking byte offsets
  46161. ** in os_unix.c and os_win.c agree with the WALINDEX_LOCK_OFFSET value.
  46162. */
  46163. #ifdef WIN_SHM_BASE
  46164. assert( WIN_SHM_BASE==WALINDEX_LOCK_OFFSET );
  46165. #endif
  46166. #ifdef UNIX_SHM_BASE
  46167. assert( UNIX_SHM_BASE==WALINDEX_LOCK_OFFSET );
  46168. #endif
  46169. /* Allocate an instance of struct Wal to return. */
  46170. *ppWal = 0;
  46171. pRet = (Wal*)sqlite3MallocZero(sizeof(Wal) + pVfs->szOsFile);
  46172. if( !pRet ){
  46173. return SQLITE_NOMEM;
  46174. }
  46175. pRet->pVfs = pVfs;
  46176. pRet->pWalFd = (sqlite3_file *)&pRet[1];
  46177. pRet->pDbFd = pDbFd;
  46178. pRet->readLock = -1;
  46179. pRet->mxWalSize = mxWalSize;
  46180. pRet->zWalName = zWalName;
  46181. pRet->syncHeader = 1;
  46182. pRet->padToSectorBoundary = 1;
  46183. pRet->exclusiveMode = (bNoShm ? WAL_HEAPMEMORY_MODE: WAL_NORMAL_MODE);
  46184. /* Open file handle on the write-ahead log file. */
  46185. flags = (SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|SQLITE_OPEN_WAL);
  46186. rc = sqlite3OsOpen(pVfs, zWalName, pRet->pWalFd, flags, &flags);
  46187. if( rc==SQLITE_OK && flags&SQLITE_OPEN_READONLY ){
  46188. pRet->readOnly = WAL_RDONLY;
  46189. }
  46190. if( rc!=SQLITE_OK ){
  46191. walIndexClose(pRet, 0);
  46192. sqlite3OsClose(pRet->pWalFd);
  46193. sqlite3_free(pRet);
  46194. }else{
  46195. int iDC = sqlite3OsDeviceCharacteristics(pDbFd);
  46196. if( iDC & SQLITE_IOCAP_SEQUENTIAL ){ pRet->syncHeader = 0; }
  46197. if( iDC & SQLITE_IOCAP_POWERSAFE_OVERWRITE ){
  46198. pRet->padToSectorBoundary = 0;
  46199. }
  46200. *ppWal = pRet;
  46201. WALTRACE(("WAL%d: opened\n", pRet));
  46202. }
  46203. return rc;
  46204. }
  46205. /*
  46206. ** Change the size to which the WAL file is trucated on each reset.
  46207. */
  46208. SQLITE_PRIVATE void sqlite3WalLimit(Wal *pWal, i64 iLimit){
  46209. if( pWal ) pWal->mxWalSize = iLimit;
  46210. }
  46211. /*
  46212. ** Find the smallest page number out of all pages held in the WAL that
  46213. ** has not been returned by any prior invocation of this method on the
  46214. ** same WalIterator object. Write into *piFrame the frame index where
  46215. ** that page was last written into the WAL. Write into *piPage the page
  46216. ** number.
  46217. **
  46218. ** Return 0 on success. If there are no pages in the WAL with a page
  46219. ** number larger than *piPage, then return 1.
  46220. */
  46221. static int walIteratorNext(
  46222. WalIterator *p, /* Iterator */
  46223. u32 *piPage, /* OUT: The page number of the next page */
  46224. u32 *piFrame /* OUT: Wal frame index of next page */
  46225. ){
  46226. u32 iMin; /* Result pgno must be greater than iMin */
  46227. u32 iRet = 0xFFFFFFFF; /* 0xffffffff is never a valid page number */
  46228. int i; /* For looping through segments */
  46229. iMin = p->iPrior;
  46230. assert( iMin<0xffffffff );
  46231. for(i=p->nSegment-1; i>=0; i--){
  46232. struct WalSegment *pSegment = &p->aSegment[i];
  46233. while( pSegment->iNext<pSegment->nEntry ){
  46234. u32 iPg = pSegment->aPgno[pSegment->aIndex[pSegment->iNext]];
  46235. if( iPg>iMin ){
  46236. if( iPg<iRet ){
  46237. iRet = iPg;
  46238. *piFrame = pSegment->iZero + pSegment->aIndex[pSegment->iNext];
  46239. }
  46240. break;
  46241. }
  46242. pSegment->iNext++;
  46243. }
  46244. }
  46245. *piPage = p->iPrior = iRet;
  46246. return (iRet==0xFFFFFFFF);
  46247. }
  46248. /*
  46249. ** This function merges two sorted lists into a single sorted list.
  46250. **
  46251. ** aLeft[] and aRight[] are arrays of indices. The sort key is
  46252. ** aContent[aLeft[]] and aContent[aRight[]]. Upon entry, the following
  46253. ** is guaranteed for all J<K:
  46254. **
  46255. ** aContent[aLeft[J]] < aContent[aLeft[K]]
  46256. ** aContent[aRight[J]] < aContent[aRight[K]]
  46257. **
  46258. ** This routine overwrites aRight[] with a new (probably longer) sequence
  46259. ** of indices such that the aRight[] contains every index that appears in
  46260. ** either aLeft[] or the old aRight[] and such that the second condition
  46261. ** above is still met.
  46262. **
  46263. ** The aContent[aLeft[X]] values will be unique for all X. And the
  46264. ** aContent[aRight[X]] values will be unique too. But there might be
  46265. ** one or more combinations of X and Y such that
  46266. **
  46267. ** aLeft[X]!=aRight[Y] && aContent[aLeft[X]] == aContent[aRight[Y]]
  46268. **
  46269. ** When that happens, omit the aLeft[X] and use the aRight[Y] index.
  46270. */
  46271. static void walMerge(
  46272. const u32 *aContent, /* Pages in wal - keys for the sort */
  46273. ht_slot *aLeft, /* IN: Left hand input list */
  46274. int nLeft, /* IN: Elements in array *paLeft */
  46275. ht_slot **paRight, /* IN/OUT: Right hand input list */
  46276. int *pnRight, /* IN/OUT: Elements in *paRight */
  46277. ht_slot *aTmp /* Temporary buffer */
  46278. ){
  46279. int iLeft = 0; /* Current index in aLeft */
  46280. int iRight = 0; /* Current index in aRight */
  46281. int iOut = 0; /* Current index in output buffer */
  46282. int nRight = *pnRight;
  46283. ht_slot *aRight = *paRight;
  46284. assert( nLeft>0 && nRight>0 );
  46285. while( iRight<nRight || iLeft<nLeft ){
  46286. ht_slot logpage;
  46287. Pgno dbpage;
  46288. if( (iLeft<nLeft)
  46289. && (iRight>=nRight || aContent[aLeft[iLeft]]<aContent[aRight[iRight]])
  46290. ){
  46291. logpage = aLeft[iLeft++];
  46292. }else{
  46293. logpage = aRight[iRight++];
  46294. }
  46295. dbpage = aContent[logpage];
  46296. aTmp[iOut++] = logpage;
  46297. if( iLeft<nLeft && aContent[aLeft[iLeft]]==dbpage ) iLeft++;
  46298. assert( iLeft>=nLeft || aContent[aLeft[iLeft]]>dbpage );
  46299. assert( iRight>=nRight || aContent[aRight[iRight]]>dbpage );
  46300. }
  46301. *paRight = aLeft;
  46302. *pnRight = iOut;
  46303. memcpy(aLeft, aTmp, sizeof(aTmp[0])*iOut);
  46304. }
  46305. /*
  46306. ** Sort the elements in list aList using aContent[] as the sort key.
  46307. ** Remove elements with duplicate keys, preferring to keep the
  46308. ** larger aList[] values.
  46309. **
  46310. ** The aList[] entries are indices into aContent[]. The values in
  46311. ** aList[] are to be sorted so that for all J<K:
  46312. **
  46313. ** aContent[aList[J]] < aContent[aList[K]]
  46314. **
  46315. ** For any X and Y such that
  46316. **
  46317. ** aContent[aList[X]] == aContent[aList[Y]]
  46318. **
  46319. ** Keep the larger of the two values aList[X] and aList[Y] and discard
  46320. ** the smaller.
  46321. */
  46322. static void walMergesort(
  46323. const u32 *aContent, /* Pages in wal */
  46324. ht_slot *aBuffer, /* Buffer of at least *pnList items to use */
  46325. ht_slot *aList, /* IN/OUT: List to sort */
  46326. int *pnList /* IN/OUT: Number of elements in aList[] */
  46327. ){
  46328. struct Sublist {
  46329. int nList; /* Number of elements in aList */
  46330. ht_slot *aList; /* Pointer to sub-list content */
  46331. };
  46332. const int nList = *pnList; /* Size of input list */
  46333. int nMerge = 0; /* Number of elements in list aMerge */
  46334. ht_slot *aMerge = 0; /* List to be merged */
  46335. int iList; /* Index into input list */
  46336. int iSub = 0; /* Index into aSub array */
  46337. struct Sublist aSub[13]; /* Array of sub-lists */
  46338. memset(aSub, 0, sizeof(aSub));
  46339. assert( nList<=HASHTABLE_NPAGE && nList>0 );
  46340. assert( HASHTABLE_NPAGE==(1<<(ArraySize(aSub)-1)) );
  46341. for(iList=0; iList<nList; iList++){
  46342. nMerge = 1;
  46343. aMerge = &aList[iList];
  46344. for(iSub=0; iList & (1<<iSub); iSub++){
  46345. struct Sublist *p = &aSub[iSub];
  46346. assert( p->aList && p->nList<=(1<<iSub) );
  46347. assert( p->aList==&aList[iList&~((2<<iSub)-1)] );
  46348. walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
  46349. }
  46350. aSub[iSub].aList = aMerge;
  46351. aSub[iSub].nList = nMerge;
  46352. }
  46353. for(iSub++; iSub<ArraySize(aSub); iSub++){
  46354. if( nList & (1<<iSub) ){
  46355. struct Sublist *p = &aSub[iSub];
  46356. assert( p->nList<=(1<<iSub) );
  46357. assert( p->aList==&aList[nList&~((2<<iSub)-1)] );
  46358. walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
  46359. }
  46360. }
  46361. assert( aMerge==aList );
  46362. *pnList = nMerge;
  46363. #ifdef SQLITE_DEBUG
  46364. {
  46365. int i;
  46366. for(i=1; i<*pnList; i++){
  46367. assert( aContent[aList[i]] > aContent[aList[i-1]] );
  46368. }
  46369. }
  46370. #endif
  46371. }
  46372. /*
  46373. ** Free an iterator allocated by walIteratorInit().
  46374. */
  46375. static void walIteratorFree(WalIterator *p){
  46376. sqlite3ScratchFree(p);
  46377. }
  46378. /*
  46379. ** Construct a WalInterator object that can be used to loop over all
  46380. ** pages in the WAL in ascending order. The caller must hold the checkpoint
  46381. ** lock.
  46382. **
  46383. ** On success, make *pp point to the newly allocated WalInterator object
  46384. ** return SQLITE_OK. Otherwise, return an error code. If this routine
  46385. ** returns an error, the value of *pp is undefined.
  46386. **
  46387. ** The calling routine should invoke walIteratorFree() to destroy the
  46388. ** WalIterator object when it has finished with it.
  46389. */
  46390. static int walIteratorInit(Wal *pWal, WalIterator **pp){
  46391. WalIterator *p; /* Return value */
  46392. int nSegment; /* Number of segments to merge */
  46393. u32 iLast; /* Last frame in log */
  46394. int nByte; /* Number of bytes to allocate */
  46395. int i; /* Iterator variable */
  46396. ht_slot *aTmp; /* Temp space used by merge-sort */
  46397. int rc = SQLITE_OK; /* Return Code */
  46398. /* This routine only runs while holding the checkpoint lock. And
  46399. ** it only runs if there is actually content in the log (mxFrame>0).
  46400. */
  46401. assert( pWal->ckptLock && pWal->hdr.mxFrame>0 );
  46402. iLast = pWal->hdr.mxFrame;
  46403. /* Allocate space for the WalIterator object. */
  46404. nSegment = walFramePage(iLast) + 1;
  46405. nByte = sizeof(WalIterator)
  46406. + (nSegment-1)*sizeof(struct WalSegment)
  46407. + iLast*sizeof(ht_slot);
  46408. p = (WalIterator *)sqlite3ScratchMalloc(nByte);
  46409. if( !p ){
  46410. return SQLITE_NOMEM;
  46411. }
  46412. memset(p, 0, nByte);
  46413. p->nSegment = nSegment;
  46414. /* Allocate temporary space used by the merge-sort routine. This block
  46415. ** of memory will be freed before this function returns.
  46416. */
  46417. aTmp = (ht_slot *)sqlite3ScratchMalloc(
  46418. sizeof(ht_slot) * (iLast>HASHTABLE_NPAGE?HASHTABLE_NPAGE:iLast)
  46419. );
  46420. if( !aTmp ){
  46421. rc = SQLITE_NOMEM;
  46422. }
  46423. for(i=0; rc==SQLITE_OK && i<nSegment; i++){
  46424. volatile ht_slot *aHash;
  46425. u32 iZero;
  46426. volatile u32 *aPgno;
  46427. rc = walHashGet(pWal, i, &aHash, &aPgno, &iZero);
  46428. if( rc==SQLITE_OK ){
  46429. int j; /* Counter variable */
  46430. int nEntry; /* Number of entries in this segment */
  46431. ht_slot *aIndex; /* Sorted index for this segment */
  46432. aPgno++;
  46433. if( (i+1)==nSegment ){
  46434. nEntry = (int)(iLast - iZero);
  46435. }else{
  46436. nEntry = (int)((u32*)aHash - (u32*)aPgno);
  46437. }
  46438. aIndex = &((ht_slot *)&p->aSegment[p->nSegment])[iZero];
  46439. iZero++;
  46440. for(j=0; j<nEntry; j++){
  46441. aIndex[j] = (ht_slot)j;
  46442. }
  46443. walMergesort((u32 *)aPgno, aTmp, aIndex, &nEntry);
  46444. p->aSegment[i].iZero = iZero;
  46445. p->aSegment[i].nEntry = nEntry;
  46446. p->aSegment[i].aIndex = aIndex;
  46447. p->aSegment[i].aPgno = (u32 *)aPgno;
  46448. }
  46449. }
  46450. sqlite3ScratchFree(aTmp);
  46451. if( rc!=SQLITE_OK ){
  46452. walIteratorFree(p);
  46453. }
  46454. *pp = p;
  46455. return rc;
  46456. }
  46457. /*
  46458. ** Attempt to obtain the exclusive WAL lock defined by parameters lockIdx and
  46459. ** n. If the attempt fails and parameter xBusy is not NULL, then it is a
  46460. ** busy-handler function. Invoke it and retry the lock until either the
  46461. ** lock is successfully obtained or the busy-handler returns 0.
  46462. */
  46463. static int walBusyLock(
  46464. Wal *pWal, /* WAL connection */
  46465. int (*xBusy)(void*), /* Function to call when busy */
  46466. void *pBusyArg, /* Context argument for xBusyHandler */
  46467. int lockIdx, /* Offset of first byte to lock */
  46468. int n /* Number of bytes to lock */
  46469. ){
  46470. int rc;
  46471. do {
  46472. rc = walLockExclusive(pWal, lockIdx, n);
  46473. }while( xBusy && rc==SQLITE_BUSY && xBusy(pBusyArg) );
  46474. return rc;
  46475. }
  46476. /*
  46477. ** The cache of the wal-index header must be valid to call this function.
  46478. ** Return the page-size in bytes used by the database.
  46479. */
  46480. static int walPagesize(Wal *pWal){
  46481. return (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
  46482. }
  46483. /*
  46484. ** Copy as much content as we can from the WAL back into the database file
  46485. ** in response to an sqlite3_wal_checkpoint() request or the equivalent.
  46486. **
  46487. ** The amount of information copies from WAL to database might be limited
  46488. ** by active readers. This routine will never overwrite a database page
  46489. ** that a concurrent reader might be using.
  46490. **
  46491. ** All I/O barrier operations (a.k.a fsyncs) occur in this routine when
  46492. ** SQLite is in WAL-mode in synchronous=NORMAL. That means that if
  46493. ** checkpoints are always run by a background thread or background
  46494. ** process, foreground threads will never block on a lengthy fsync call.
  46495. **
  46496. ** Fsync is called on the WAL before writing content out of the WAL and
  46497. ** into the database. This ensures that if the new content is persistent
  46498. ** in the WAL and can be recovered following a power-loss or hard reset.
  46499. **
  46500. ** Fsync is also called on the database file if (and only if) the entire
  46501. ** WAL content is copied into the database file. This second fsync makes
  46502. ** it safe to delete the WAL since the new content will persist in the
  46503. ** database file.
  46504. **
  46505. ** This routine uses and updates the nBackfill field of the wal-index header.
  46506. ** This is the only routine that will increase the value of nBackfill.
  46507. ** (A WAL reset or recovery will revert nBackfill to zero, but not increase
  46508. ** its value.)
  46509. **
  46510. ** The caller must be holding sufficient locks to ensure that no other
  46511. ** checkpoint is running (in any other thread or process) at the same
  46512. ** time.
  46513. */
  46514. static int walCheckpoint(
  46515. Wal *pWal, /* Wal connection */
  46516. int eMode, /* One of PASSIVE, FULL or RESTART */
  46517. int (*xBusyCall)(void*), /* Function to call when busy */
  46518. void *pBusyArg, /* Context argument for xBusyHandler */
  46519. int sync_flags, /* Flags for OsSync() (or 0) */
  46520. u8 *zBuf /* Temporary buffer to use */
  46521. ){
  46522. int rc; /* Return code */
  46523. int szPage; /* Database page-size */
  46524. WalIterator *pIter = 0; /* Wal iterator context */
  46525. u32 iDbpage = 0; /* Next database page to write */
  46526. u32 iFrame = 0; /* Wal frame containing data for iDbpage */
  46527. u32 mxSafeFrame; /* Max frame that can be backfilled */
  46528. u32 mxPage; /* Max database page to write */
  46529. int i; /* Loop counter */
  46530. volatile WalCkptInfo *pInfo; /* The checkpoint status information */
  46531. int (*xBusy)(void*) = 0; /* Function to call when waiting for locks */
  46532. szPage = walPagesize(pWal);
  46533. testcase( szPage<=32768 );
  46534. testcase( szPage>=65536 );
  46535. pInfo = walCkptInfo(pWal);
  46536. if( pInfo->nBackfill>=pWal->hdr.mxFrame ) return SQLITE_OK;
  46537. /* Allocate the iterator */
  46538. rc = walIteratorInit(pWal, &pIter);
  46539. if( rc!=SQLITE_OK ){
  46540. return rc;
  46541. }
  46542. assert( pIter );
  46543. if( eMode!=SQLITE_CHECKPOINT_PASSIVE ) xBusy = xBusyCall;
  46544. /* Compute in mxSafeFrame the index of the last frame of the WAL that is
  46545. ** safe to write into the database. Frames beyond mxSafeFrame might
  46546. ** overwrite database pages that are in use by active readers and thus
  46547. ** cannot be backfilled from the WAL.
  46548. */
  46549. mxSafeFrame = pWal->hdr.mxFrame;
  46550. mxPage = pWal->hdr.nPage;
  46551. for(i=1; i<WAL_NREADER; i++){
  46552. u32 y = pInfo->aReadMark[i];
  46553. if( mxSafeFrame>y ){
  46554. assert( y<=pWal->hdr.mxFrame );
  46555. rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(i), 1);
  46556. if( rc==SQLITE_OK ){
  46557. pInfo->aReadMark[i] = (i==1 ? mxSafeFrame : READMARK_NOT_USED);
  46558. walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
  46559. }else if( rc==SQLITE_BUSY ){
  46560. mxSafeFrame = y;
  46561. xBusy = 0;
  46562. }else{
  46563. goto walcheckpoint_out;
  46564. }
  46565. }
  46566. }
  46567. if( pInfo->nBackfill<mxSafeFrame
  46568. && (rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(0), 1))==SQLITE_OK
  46569. ){
  46570. i64 nSize; /* Current size of database file */
  46571. u32 nBackfill = pInfo->nBackfill;
  46572. /* Sync the WAL to disk */
  46573. if( sync_flags ){
  46574. rc = sqlite3OsSync(pWal->pWalFd, sync_flags);
  46575. }
  46576. /* If the database may grow as a result of this checkpoint, hint
  46577. ** about the eventual size of the db file to the VFS layer.
  46578. */
  46579. if( rc==SQLITE_OK ){
  46580. i64 nReq = ((i64)mxPage * szPage);
  46581. rc = sqlite3OsFileSize(pWal->pDbFd, &nSize);
  46582. if( rc==SQLITE_OK && nSize<nReq ){
  46583. sqlite3OsFileControlHint(pWal->pDbFd, SQLITE_FCNTL_SIZE_HINT, &nReq);
  46584. }
  46585. }
  46586. /* Iterate through the contents of the WAL, copying data to the db file. */
  46587. while( rc==SQLITE_OK && 0==walIteratorNext(pIter, &iDbpage, &iFrame) ){
  46588. i64 iOffset;
  46589. assert( walFramePgno(pWal, iFrame)==iDbpage );
  46590. if( iFrame<=nBackfill || iFrame>mxSafeFrame || iDbpage>mxPage ) continue;
  46591. iOffset = walFrameOffset(iFrame, szPage) + WAL_FRAME_HDRSIZE;
  46592. /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL file */
  46593. rc = sqlite3OsRead(pWal->pWalFd, zBuf, szPage, iOffset);
  46594. if( rc!=SQLITE_OK ) break;
  46595. iOffset = (iDbpage-1)*(i64)szPage;
  46596. testcase( IS_BIG_INT(iOffset) );
  46597. rc = sqlite3OsWrite(pWal->pDbFd, zBuf, szPage, iOffset);
  46598. if( rc!=SQLITE_OK ) break;
  46599. }
  46600. /* If work was actually accomplished... */
  46601. if( rc==SQLITE_OK ){
  46602. if( mxSafeFrame==walIndexHdr(pWal)->mxFrame ){
  46603. i64 szDb = pWal->hdr.nPage*(i64)szPage;
  46604. testcase( IS_BIG_INT(szDb) );
  46605. rc = sqlite3OsTruncate(pWal->pDbFd, szDb);
  46606. if( rc==SQLITE_OK && sync_flags ){
  46607. rc = sqlite3OsSync(pWal->pDbFd, sync_flags);
  46608. }
  46609. }
  46610. if( rc==SQLITE_OK ){
  46611. pInfo->nBackfill = mxSafeFrame;
  46612. }
  46613. }
  46614. /* Release the reader lock held while backfilling */
  46615. walUnlockExclusive(pWal, WAL_READ_LOCK(0), 1);
  46616. }
  46617. if( rc==SQLITE_BUSY ){
  46618. /* Reset the return code so as not to report a checkpoint failure
  46619. ** just because there are active readers. */
  46620. rc = SQLITE_OK;
  46621. }
  46622. /* If this is an SQLITE_CHECKPOINT_RESTART operation, and the entire wal
  46623. ** file has been copied into the database file, then block until all
  46624. ** readers have finished using the wal file. This ensures that the next
  46625. ** process to write to the database restarts the wal file.
  46626. */
  46627. if( rc==SQLITE_OK && eMode!=SQLITE_CHECKPOINT_PASSIVE ){
  46628. assert( pWal->writeLock );
  46629. if( pInfo->nBackfill<pWal->hdr.mxFrame ){
  46630. rc = SQLITE_BUSY;
  46631. }else if( eMode==SQLITE_CHECKPOINT_RESTART ){
  46632. assert( mxSafeFrame==pWal->hdr.mxFrame );
  46633. rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(1), WAL_NREADER-1);
  46634. if( rc==SQLITE_OK ){
  46635. walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
  46636. }
  46637. }
  46638. }
  46639. walcheckpoint_out:
  46640. walIteratorFree(pIter);
  46641. return rc;
  46642. }
  46643. /*
  46644. ** If the WAL file is currently larger than nMax bytes in size, truncate
  46645. ** it to exactly nMax bytes. If an error occurs while doing so, ignore it.
  46646. */
  46647. static void walLimitSize(Wal *pWal, i64 nMax){
  46648. i64 sz;
  46649. int rx;
  46650. sqlite3BeginBenignMalloc();
  46651. rx = sqlite3OsFileSize(pWal->pWalFd, &sz);
  46652. if( rx==SQLITE_OK && (sz > nMax ) ){
  46653. rx = sqlite3OsTruncate(pWal->pWalFd, nMax);
  46654. }
  46655. sqlite3EndBenignMalloc();
  46656. if( rx ){
  46657. sqlite3_log(rx, "cannot limit WAL size: %s", pWal->zWalName);
  46658. }
  46659. }
  46660. /*
  46661. ** Close a connection to a log file.
  46662. */
  46663. SQLITE_PRIVATE int sqlite3WalClose(
  46664. Wal *pWal, /* Wal to close */
  46665. int sync_flags, /* Flags to pass to OsSync() (or 0) */
  46666. int nBuf,
  46667. u8 *zBuf /* Buffer of at least nBuf bytes */
  46668. ){
  46669. int rc = SQLITE_OK;
  46670. if( pWal ){
  46671. int isDelete = 0; /* True to unlink wal and wal-index files */
  46672. /* If an EXCLUSIVE lock can be obtained on the database file (using the
  46673. ** ordinary, rollback-mode locking methods, this guarantees that the
  46674. ** connection associated with this log file is the only connection to
  46675. ** the database. In this case checkpoint the database and unlink both
  46676. ** the wal and wal-index files.
  46677. **
  46678. ** The EXCLUSIVE lock is not released before returning.
  46679. */
  46680. rc = sqlite3OsLock(pWal->pDbFd, SQLITE_LOCK_EXCLUSIVE);
  46681. if( rc==SQLITE_OK ){
  46682. if( pWal->exclusiveMode==WAL_NORMAL_MODE ){
  46683. pWal->exclusiveMode = WAL_EXCLUSIVE_MODE;
  46684. }
  46685. rc = sqlite3WalCheckpoint(
  46686. pWal, SQLITE_CHECKPOINT_PASSIVE, 0, 0, sync_flags, nBuf, zBuf, 0, 0
  46687. );
  46688. if( rc==SQLITE_OK ){
  46689. int bPersist = -1;
  46690. sqlite3OsFileControlHint(
  46691. pWal->pDbFd, SQLITE_FCNTL_PERSIST_WAL, &bPersist
  46692. );
  46693. if( bPersist!=1 ){
  46694. /* Try to delete the WAL file if the checkpoint completed and
  46695. ** fsyned (rc==SQLITE_OK) and if we are not in persistent-wal
  46696. ** mode (!bPersist) */
  46697. isDelete = 1;
  46698. }else if( pWal->mxWalSize>=0 ){
  46699. /* Try to truncate the WAL file to zero bytes if the checkpoint
  46700. ** completed and fsynced (rc==SQLITE_OK) and we are in persistent
  46701. ** WAL mode (bPersist) and if the PRAGMA journal_size_limit is a
  46702. ** non-negative value (pWal->mxWalSize>=0). Note that we truncate
  46703. ** to zero bytes as truncating to the journal_size_limit might
  46704. ** leave a corrupt WAL file on disk. */
  46705. walLimitSize(pWal, 0);
  46706. }
  46707. }
  46708. }
  46709. walIndexClose(pWal, isDelete);
  46710. sqlite3OsClose(pWal->pWalFd);
  46711. if( isDelete ){
  46712. sqlite3BeginBenignMalloc();
  46713. sqlite3OsDelete(pWal->pVfs, pWal->zWalName, 0);
  46714. sqlite3EndBenignMalloc();
  46715. }
  46716. WALTRACE(("WAL%p: closed\n", pWal));
  46717. sqlite3_free((void *)pWal->apWiData);
  46718. sqlite3_free(pWal);
  46719. }
  46720. return rc;
  46721. }
  46722. /*
  46723. ** Try to read the wal-index header. Return 0 on success and 1 if
  46724. ** there is a problem.
  46725. **
  46726. ** The wal-index is in shared memory. Another thread or process might
  46727. ** be writing the header at the same time this procedure is trying to
  46728. ** read it, which might result in inconsistency. A dirty read is detected
  46729. ** by verifying that both copies of the header are the same and also by
  46730. ** a checksum on the header.
  46731. **
  46732. ** If and only if the read is consistent and the header is different from
  46733. ** pWal->hdr, then pWal->hdr is updated to the content of the new header
  46734. ** and *pChanged is set to 1.
  46735. **
  46736. ** If the checksum cannot be verified return non-zero. If the header
  46737. ** is read successfully and the checksum verified, return zero.
  46738. */
  46739. static int walIndexTryHdr(Wal *pWal, int *pChanged){
  46740. u32 aCksum[2]; /* Checksum on the header content */
  46741. WalIndexHdr h1, h2; /* Two copies of the header content */
  46742. WalIndexHdr volatile *aHdr; /* Header in shared memory */
  46743. /* The first page of the wal-index must be mapped at this point. */
  46744. assert( pWal->nWiData>0 && pWal->apWiData[0] );
  46745. /* Read the header. This might happen concurrently with a write to the
  46746. ** same area of shared memory on a different CPU in a SMP,
  46747. ** meaning it is possible that an inconsistent snapshot is read
  46748. ** from the file. If this happens, return non-zero.
  46749. **
  46750. ** There are two copies of the header at the beginning of the wal-index.
  46751. ** When reading, read [0] first then [1]. Writes are in the reverse order.
  46752. ** Memory barriers are used to prevent the compiler or the hardware from
  46753. ** reordering the reads and writes.
  46754. */
  46755. aHdr = walIndexHdr(pWal);
  46756. memcpy(&h1, (void *)&aHdr[0], sizeof(h1));
  46757. walShmBarrier(pWal);
  46758. memcpy(&h2, (void *)&aHdr[1], sizeof(h2));
  46759. if( memcmp(&h1, &h2, sizeof(h1))!=0 ){
  46760. return 1; /* Dirty read */
  46761. }
  46762. if( h1.isInit==0 ){
  46763. return 1; /* Malformed header - probably all zeros */
  46764. }
  46765. walChecksumBytes(1, (u8*)&h1, sizeof(h1)-sizeof(h1.aCksum), 0, aCksum);
  46766. if( aCksum[0]!=h1.aCksum[0] || aCksum[1]!=h1.aCksum[1] ){
  46767. return 1; /* Checksum does not match */
  46768. }
  46769. if( memcmp(&pWal->hdr, &h1, sizeof(WalIndexHdr)) ){
  46770. *pChanged = 1;
  46771. memcpy(&pWal->hdr, &h1, sizeof(WalIndexHdr));
  46772. pWal->szPage = (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
  46773. testcase( pWal->szPage<=32768 );
  46774. testcase( pWal->szPage>=65536 );
  46775. }
  46776. /* The header was successfully read. Return zero. */
  46777. return 0;
  46778. }
  46779. /*
  46780. ** Read the wal-index header from the wal-index and into pWal->hdr.
  46781. ** If the wal-header appears to be corrupt, try to reconstruct the
  46782. ** wal-index from the WAL before returning.
  46783. **
  46784. ** Set *pChanged to 1 if the wal-index header value in pWal->hdr is
  46785. ** changed by this operation. If pWal->hdr is unchanged, set *pChanged
  46786. ** to 0.
  46787. **
  46788. ** If the wal-index header is successfully read, return SQLITE_OK.
  46789. ** Otherwise an SQLite error code.
  46790. */
  46791. static int walIndexReadHdr(Wal *pWal, int *pChanged){
  46792. int rc; /* Return code */
  46793. int badHdr; /* True if a header read failed */
  46794. volatile u32 *page0; /* Chunk of wal-index containing header */
  46795. /* Ensure that page 0 of the wal-index (the page that contains the
  46796. ** wal-index header) is mapped. Return early if an error occurs here.
  46797. */
  46798. assert( pChanged );
  46799. rc = walIndexPage(pWal, 0, &page0);
  46800. if( rc!=SQLITE_OK ){
  46801. return rc;
  46802. };
  46803. assert( page0 || pWal->writeLock==0 );
  46804. /* If the first page of the wal-index has been mapped, try to read the
  46805. ** wal-index header immediately, without holding any lock. This usually
  46806. ** works, but may fail if the wal-index header is corrupt or currently
  46807. ** being modified by another thread or process.
  46808. */
  46809. badHdr = (page0 ? walIndexTryHdr(pWal, pChanged) : 1);
  46810. /* If the first attempt failed, it might have been due to a race
  46811. ** with a writer. So get a WRITE lock and try again.
  46812. */
  46813. assert( badHdr==0 || pWal->writeLock==0 );
  46814. if( badHdr ){
  46815. if( pWal->readOnly & WAL_SHM_RDONLY ){
  46816. if( SQLITE_OK==(rc = walLockShared(pWal, WAL_WRITE_LOCK)) ){
  46817. walUnlockShared(pWal, WAL_WRITE_LOCK);
  46818. rc = SQLITE_READONLY_RECOVERY;
  46819. }
  46820. }else if( SQLITE_OK==(rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1)) ){
  46821. pWal->writeLock = 1;
  46822. if( SQLITE_OK==(rc = walIndexPage(pWal, 0, &page0)) ){
  46823. badHdr = walIndexTryHdr(pWal, pChanged);
  46824. if( badHdr ){
  46825. /* If the wal-index header is still malformed even while holding
  46826. ** a WRITE lock, it can only mean that the header is corrupted and
  46827. ** needs to be reconstructed. So run recovery to do exactly that.
  46828. */
  46829. rc = walIndexRecover(pWal);
  46830. *pChanged = 1;
  46831. }
  46832. }
  46833. pWal->writeLock = 0;
  46834. walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
  46835. }
  46836. }
  46837. /* If the header is read successfully, check the version number to make
  46838. ** sure the wal-index was not constructed with some future format that
  46839. ** this version of SQLite cannot understand.
  46840. */
  46841. if( badHdr==0 && pWal->hdr.iVersion!=WALINDEX_MAX_VERSION ){
  46842. rc = SQLITE_CANTOPEN_BKPT;
  46843. }
  46844. return rc;
  46845. }
  46846. /*
  46847. ** This is the value that walTryBeginRead returns when it needs to
  46848. ** be retried.
  46849. */
  46850. #define WAL_RETRY (-1)
  46851. /*
  46852. ** Attempt to start a read transaction. This might fail due to a race or
  46853. ** other transient condition. When that happens, it returns WAL_RETRY to
  46854. ** indicate to the caller that it is safe to retry immediately.
  46855. **
  46856. ** On success return SQLITE_OK. On a permanent failure (such an
  46857. ** I/O error or an SQLITE_BUSY because another process is running
  46858. ** recovery) return a positive error code.
  46859. **
  46860. ** The useWal parameter is true to force the use of the WAL and disable
  46861. ** the case where the WAL is bypassed because it has been completely
  46862. ** checkpointed. If useWal==0 then this routine calls walIndexReadHdr()
  46863. ** to make a copy of the wal-index header into pWal->hdr. If the
  46864. ** wal-index header has changed, *pChanged is set to 1 (as an indication
  46865. ** to the caller that the local paget cache is obsolete and needs to be
  46866. ** flushed.) When useWal==1, the wal-index header is assumed to already
  46867. ** be loaded and the pChanged parameter is unused.
  46868. **
  46869. ** The caller must set the cnt parameter to the number of prior calls to
  46870. ** this routine during the current read attempt that returned WAL_RETRY.
  46871. ** This routine will start taking more aggressive measures to clear the
  46872. ** race conditions after multiple WAL_RETRY returns, and after an excessive
  46873. ** number of errors will ultimately return SQLITE_PROTOCOL. The
  46874. ** SQLITE_PROTOCOL return indicates that some other process has gone rogue
  46875. ** and is not honoring the locking protocol. There is a vanishingly small
  46876. ** chance that SQLITE_PROTOCOL could be returned because of a run of really
  46877. ** bad luck when there is lots of contention for the wal-index, but that
  46878. ** possibility is so small that it can be safely neglected, we believe.
  46879. **
  46880. ** On success, this routine obtains a read lock on
  46881. ** WAL_READ_LOCK(pWal->readLock). The pWal->readLock integer is
  46882. ** in the range 0 <= pWal->readLock < WAL_NREADER. If pWal->readLock==(-1)
  46883. ** that means the Wal does not hold any read lock. The reader must not
  46884. ** access any database page that is modified by a WAL frame up to and
  46885. ** including frame number aReadMark[pWal->readLock]. The reader will
  46886. ** use WAL frames up to and including pWal->hdr.mxFrame if pWal->readLock>0
  46887. ** Or if pWal->readLock==0, then the reader will ignore the WAL
  46888. ** completely and get all content directly from the database file.
  46889. ** If the useWal parameter is 1 then the WAL will never be ignored and
  46890. ** this routine will always set pWal->readLock>0 on success.
  46891. ** When the read transaction is completed, the caller must release the
  46892. ** lock on WAL_READ_LOCK(pWal->readLock) and set pWal->readLock to -1.
  46893. **
  46894. ** This routine uses the nBackfill and aReadMark[] fields of the header
  46895. ** to select a particular WAL_READ_LOCK() that strives to let the
  46896. ** checkpoint process do as much work as possible. This routine might
  46897. ** update values of the aReadMark[] array in the header, but if it does
  46898. ** so it takes care to hold an exclusive lock on the corresponding
  46899. ** WAL_READ_LOCK() while changing values.
  46900. */
  46901. static int walTryBeginRead(Wal *pWal, int *pChanged, int useWal, int cnt){
  46902. volatile WalCkptInfo *pInfo; /* Checkpoint information in wal-index */
  46903. u32 mxReadMark; /* Largest aReadMark[] value */
  46904. int mxI; /* Index of largest aReadMark[] value */
  46905. int i; /* Loop counter */
  46906. int rc = SQLITE_OK; /* Return code */
  46907. assert( pWal->readLock<0 ); /* Not currently locked */
  46908. /* Take steps to avoid spinning forever if there is a protocol error.
  46909. **
  46910. ** Circumstances that cause a RETRY should only last for the briefest
  46911. ** instances of time. No I/O or other system calls are done while the
  46912. ** locks are held, so the locks should not be held for very long. But
  46913. ** if we are unlucky, another process that is holding a lock might get
  46914. ** paged out or take a page-fault that is time-consuming to resolve,
  46915. ** during the few nanoseconds that it is holding the lock. In that case,
  46916. ** it might take longer than normal for the lock to free.
  46917. **
  46918. ** After 5 RETRYs, we begin calling sqlite3OsSleep(). The first few
  46919. ** calls to sqlite3OsSleep() have a delay of 1 microsecond. Really this
  46920. ** is more of a scheduler yield than an actual delay. But on the 10th
  46921. ** an subsequent retries, the delays start becoming longer and longer,
  46922. ** so that on the 100th (and last) RETRY we delay for 323 milliseconds.
  46923. ** The total delay time before giving up is less than 10 seconds.
  46924. */
  46925. if( cnt>5 ){
  46926. int nDelay = 1; /* Pause time in microseconds */
  46927. if( cnt>100 ){
  46928. VVA_ONLY( pWal->lockError = 1; )
  46929. return SQLITE_PROTOCOL;
  46930. }
  46931. if( cnt>=10 ) nDelay = (cnt-9)*(cnt-9)*39;
  46932. sqlite3OsSleep(pWal->pVfs, nDelay);
  46933. }
  46934. if( !useWal ){
  46935. rc = walIndexReadHdr(pWal, pChanged);
  46936. if( rc==SQLITE_BUSY ){
  46937. /* If there is not a recovery running in another thread or process
  46938. ** then convert BUSY errors to WAL_RETRY. If recovery is known to
  46939. ** be running, convert BUSY to BUSY_RECOVERY. There is a race here
  46940. ** which might cause WAL_RETRY to be returned even if BUSY_RECOVERY
  46941. ** would be technically correct. But the race is benign since with
  46942. ** WAL_RETRY this routine will be called again and will probably be
  46943. ** right on the second iteration.
  46944. */
  46945. if( pWal->apWiData[0]==0 ){
  46946. /* This branch is taken when the xShmMap() method returns SQLITE_BUSY.
  46947. ** We assume this is a transient condition, so return WAL_RETRY. The
  46948. ** xShmMap() implementation used by the default unix and win32 VFS
  46949. ** modules may return SQLITE_BUSY due to a race condition in the
  46950. ** code that determines whether or not the shared-memory region
  46951. ** must be zeroed before the requested page is returned.
  46952. */
  46953. rc = WAL_RETRY;
  46954. }else if( SQLITE_OK==(rc = walLockShared(pWal, WAL_RECOVER_LOCK)) ){
  46955. walUnlockShared(pWal, WAL_RECOVER_LOCK);
  46956. rc = WAL_RETRY;
  46957. }else if( rc==SQLITE_BUSY ){
  46958. rc = SQLITE_BUSY_RECOVERY;
  46959. }
  46960. }
  46961. if( rc!=SQLITE_OK ){
  46962. return rc;
  46963. }
  46964. }
  46965. pInfo = walCkptInfo(pWal);
  46966. if( !useWal && pInfo->nBackfill==pWal->hdr.mxFrame ){
  46967. /* The WAL has been completely backfilled (or it is empty).
  46968. ** and can be safely ignored.
  46969. */
  46970. rc = walLockShared(pWal, WAL_READ_LOCK(0));
  46971. walShmBarrier(pWal);
  46972. if( rc==SQLITE_OK ){
  46973. if( memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr)) ){
  46974. /* It is not safe to allow the reader to continue here if frames
  46975. ** may have been appended to the log before READ_LOCK(0) was obtained.
  46976. ** When holding READ_LOCK(0), the reader ignores the entire log file,
  46977. ** which implies that the database file contains a trustworthy
  46978. ** snapshot. Since holding READ_LOCK(0) prevents a checkpoint from
  46979. ** happening, this is usually correct.
  46980. **
  46981. ** However, if frames have been appended to the log (or if the log
  46982. ** is wrapped and written for that matter) before the READ_LOCK(0)
  46983. ** is obtained, that is not necessarily true. A checkpointer may
  46984. ** have started to backfill the appended frames but crashed before
  46985. ** it finished. Leaving a corrupt image in the database file.
  46986. */
  46987. walUnlockShared(pWal, WAL_READ_LOCK(0));
  46988. return WAL_RETRY;
  46989. }
  46990. pWal->readLock = 0;
  46991. return SQLITE_OK;
  46992. }else if( rc!=SQLITE_BUSY ){
  46993. return rc;
  46994. }
  46995. }
  46996. /* If we get this far, it means that the reader will want to use
  46997. ** the WAL to get at content from recent commits. The job now is
  46998. ** to select one of the aReadMark[] entries that is closest to
  46999. ** but not exceeding pWal->hdr.mxFrame and lock that entry.
  47000. */
  47001. mxReadMark = 0;
  47002. mxI = 0;
  47003. for(i=1; i<WAL_NREADER; i++){
  47004. u32 thisMark = pInfo->aReadMark[i];
  47005. if( mxReadMark<=thisMark && thisMark<=pWal->hdr.mxFrame ){
  47006. assert( thisMark!=READMARK_NOT_USED );
  47007. mxReadMark = thisMark;
  47008. mxI = i;
  47009. }
  47010. }
  47011. /* There was once an "if" here. The extra "{" is to preserve indentation. */
  47012. {
  47013. if( (pWal->readOnly & WAL_SHM_RDONLY)==0
  47014. && (mxReadMark<pWal->hdr.mxFrame || mxI==0)
  47015. ){
  47016. for(i=1; i<WAL_NREADER; i++){
  47017. rc = walLockExclusive(pWal, WAL_READ_LOCK(i), 1);
  47018. if( rc==SQLITE_OK ){
  47019. mxReadMark = pInfo->aReadMark[i] = pWal->hdr.mxFrame;
  47020. mxI = i;
  47021. walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
  47022. break;
  47023. }else if( rc!=SQLITE_BUSY ){
  47024. return rc;
  47025. }
  47026. }
  47027. }
  47028. if( mxI==0 ){
  47029. assert( rc==SQLITE_BUSY || (pWal->readOnly & WAL_SHM_RDONLY)!=0 );
  47030. return rc==SQLITE_BUSY ? WAL_RETRY : SQLITE_READONLY_CANTLOCK;
  47031. }
  47032. rc = walLockShared(pWal, WAL_READ_LOCK(mxI));
  47033. if( rc ){
  47034. return rc==SQLITE_BUSY ? WAL_RETRY : rc;
  47035. }
  47036. /* Now that the read-lock has been obtained, check that neither the
  47037. ** value in the aReadMark[] array or the contents of the wal-index
  47038. ** header have changed.
  47039. **
  47040. ** It is necessary to check that the wal-index header did not change
  47041. ** between the time it was read and when the shared-lock was obtained
  47042. ** on WAL_READ_LOCK(mxI) was obtained to account for the possibility
  47043. ** that the log file may have been wrapped by a writer, or that frames
  47044. ** that occur later in the log than pWal->hdr.mxFrame may have been
  47045. ** copied into the database by a checkpointer. If either of these things
  47046. ** happened, then reading the database with the current value of
  47047. ** pWal->hdr.mxFrame risks reading a corrupted snapshot. So, retry
  47048. ** instead.
  47049. **
  47050. ** This does not guarantee that the copy of the wal-index header is up to
  47051. ** date before proceeding. That would not be possible without somehow
  47052. ** blocking writers. It only guarantees that a dangerous checkpoint or
  47053. ** log-wrap (either of which would require an exclusive lock on
  47054. ** WAL_READ_LOCK(mxI)) has not occurred since the snapshot was valid.
  47055. */
  47056. walShmBarrier(pWal);
  47057. if( pInfo->aReadMark[mxI]!=mxReadMark
  47058. || memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr))
  47059. ){
  47060. walUnlockShared(pWal, WAL_READ_LOCK(mxI));
  47061. return WAL_RETRY;
  47062. }else{
  47063. assert( mxReadMark<=pWal->hdr.mxFrame );
  47064. pWal->readLock = (i16)mxI;
  47065. }
  47066. }
  47067. return rc;
  47068. }
  47069. /*
  47070. ** Begin a read transaction on the database.
  47071. **
  47072. ** This routine used to be called sqlite3OpenSnapshot() and with good reason:
  47073. ** it takes a snapshot of the state of the WAL and wal-index for the current
  47074. ** instant in time. The current thread will continue to use this snapshot.
  47075. ** Other threads might append new content to the WAL and wal-index but
  47076. ** that extra content is ignored by the current thread.
  47077. **
  47078. ** If the database contents have changes since the previous read
  47079. ** transaction, then *pChanged is set to 1 before returning. The
  47080. ** Pager layer will use this to know that is cache is stale and
  47081. ** needs to be flushed.
  47082. */
  47083. SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *pChanged){
  47084. int rc; /* Return code */
  47085. int cnt = 0; /* Number of TryBeginRead attempts */
  47086. do{
  47087. rc = walTryBeginRead(pWal, pChanged, 0, ++cnt);
  47088. }while( rc==WAL_RETRY );
  47089. testcase( (rc&0xff)==SQLITE_BUSY );
  47090. testcase( (rc&0xff)==SQLITE_IOERR );
  47091. testcase( rc==SQLITE_PROTOCOL );
  47092. testcase( rc==SQLITE_OK );
  47093. return rc;
  47094. }
  47095. /*
  47096. ** Finish with a read transaction. All this does is release the
  47097. ** read-lock.
  47098. */
  47099. SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal){
  47100. sqlite3WalEndWriteTransaction(pWal);
  47101. if( pWal->readLock>=0 ){
  47102. walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
  47103. pWal->readLock = -1;
  47104. }
  47105. }
  47106. /*
  47107. ** Search the wal file for page pgno. If found, set *piRead to the frame that
  47108. ** contains the page. Otherwise, if pgno is not in the wal file, set *piRead
  47109. ** to zero.
  47110. **
  47111. ** Return SQLITE_OK if successful, or an error code if an error occurs. If an
  47112. ** error does occur, the final value of *piRead is undefined.
  47113. */
  47114. SQLITE_PRIVATE int sqlite3WalFindFrame(
  47115. Wal *pWal, /* WAL handle */
  47116. Pgno pgno, /* Database page number to read data for */
  47117. u32 *piRead /* OUT: Frame number (or zero) */
  47118. ){
  47119. u32 iRead = 0; /* If !=0, WAL frame to return data from */
  47120. u32 iLast = pWal->hdr.mxFrame; /* Last page in WAL for this reader */
  47121. int iHash; /* Used to loop through N hash tables */
  47122. /* This routine is only be called from within a read transaction. */
  47123. assert( pWal->readLock>=0 || pWal->lockError );
  47124. /* If the "last page" field of the wal-index header snapshot is 0, then
  47125. ** no data will be read from the wal under any circumstances. Return early
  47126. ** in this case as an optimization. Likewise, if pWal->readLock==0,
  47127. ** then the WAL is ignored by the reader so return early, as if the
  47128. ** WAL were empty.
  47129. */
  47130. if( iLast==0 || pWal->readLock==0 ){
  47131. *piRead = 0;
  47132. return SQLITE_OK;
  47133. }
  47134. /* Search the hash table or tables for an entry matching page number
  47135. ** pgno. Each iteration of the following for() loop searches one
  47136. ** hash table (each hash table indexes up to HASHTABLE_NPAGE frames).
  47137. **
  47138. ** This code might run concurrently to the code in walIndexAppend()
  47139. ** that adds entries to the wal-index (and possibly to this hash
  47140. ** table). This means the value just read from the hash
  47141. ** slot (aHash[iKey]) may have been added before or after the
  47142. ** current read transaction was opened. Values added after the
  47143. ** read transaction was opened may have been written incorrectly -
  47144. ** i.e. these slots may contain garbage data. However, we assume
  47145. ** that any slots written before the current read transaction was
  47146. ** opened remain unmodified.
  47147. **
  47148. ** For the reasons above, the if(...) condition featured in the inner
  47149. ** loop of the following block is more stringent that would be required
  47150. ** if we had exclusive access to the hash-table:
  47151. **
  47152. ** (aPgno[iFrame]==pgno):
  47153. ** This condition filters out normal hash-table collisions.
  47154. **
  47155. ** (iFrame<=iLast):
  47156. ** This condition filters out entries that were added to the hash
  47157. ** table after the current read-transaction had started.
  47158. */
  47159. for(iHash=walFramePage(iLast); iHash>=0 && iRead==0; iHash--){
  47160. volatile ht_slot *aHash; /* Pointer to hash table */
  47161. volatile u32 *aPgno; /* Pointer to array of page numbers */
  47162. u32 iZero; /* Frame number corresponding to aPgno[0] */
  47163. int iKey; /* Hash slot index */
  47164. int nCollide; /* Number of hash collisions remaining */
  47165. int rc; /* Error code */
  47166. rc = walHashGet(pWal, iHash, &aHash, &aPgno, &iZero);
  47167. if( rc!=SQLITE_OK ){
  47168. return rc;
  47169. }
  47170. nCollide = HASHTABLE_NSLOT;
  47171. for(iKey=walHash(pgno); aHash[iKey]; iKey=walNextHash(iKey)){
  47172. u32 iFrame = aHash[iKey] + iZero;
  47173. if( iFrame<=iLast && aPgno[aHash[iKey]]==pgno ){
  47174. /* assert( iFrame>iRead ); -- not true if there is corruption */
  47175. iRead = iFrame;
  47176. }
  47177. if( (nCollide--)==0 ){
  47178. return SQLITE_CORRUPT_BKPT;
  47179. }
  47180. }
  47181. }
  47182. #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
  47183. /* If expensive assert() statements are available, do a linear search
  47184. ** of the wal-index file content. Make sure the results agree with the
  47185. ** result obtained using the hash indexes above. */
  47186. {
  47187. u32 iRead2 = 0;
  47188. u32 iTest;
  47189. for(iTest=iLast; iTest>0; iTest--){
  47190. if( walFramePgno(pWal, iTest)==pgno ){
  47191. iRead2 = iTest;
  47192. break;
  47193. }
  47194. }
  47195. assert( iRead==iRead2 );
  47196. }
  47197. #endif
  47198. *piRead = iRead;
  47199. return SQLITE_OK;
  47200. }
  47201. /*
  47202. ** Read the contents of frame iRead from the wal file into buffer pOut
  47203. ** (which is nOut bytes in size). Return SQLITE_OK if successful, or an
  47204. ** error code otherwise.
  47205. */
  47206. SQLITE_PRIVATE int sqlite3WalReadFrame(
  47207. Wal *pWal, /* WAL handle */
  47208. u32 iRead, /* Frame to read */
  47209. int nOut, /* Size of buffer pOut in bytes */
  47210. u8 *pOut /* Buffer to write page data to */
  47211. ){
  47212. int sz;
  47213. i64 iOffset;
  47214. sz = pWal->hdr.szPage;
  47215. sz = (sz&0xfe00) + ((sz&0x0001)<<16);
  47216. testcase( sz<=32768 );
  47217. testcase( sz>=65536 );
  47218. iOffset = walFrameOffset(iRead, sz) + WAL_FRAME_HDRSIZE;
  47219. /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL */
  47220. return sqlite3OsRead(pWal->pWalFd, pOut, (nOut>sz ? sz : nOut), iOffset);
  47221. }
  47222. /*
  47223. ** Return the size of the database in pages (or zero, if unknown).
  47224. */
  47225. SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal){
  47226. if( pWal && ALWAYS(pWal->readLock>=0) ){
  47227. return pWal->hdr.nPage;
  47228. }
  47229. return 0;
  47230. }
  47231. /*
  47232. ** This function starts a write transaction on the WAL.
  47233. **
  47234. ** A read transaction must have already been started by a prior call
  47235. ** to sqlite3WalBeginReadTransaction().
  47236. **
  47237. ** If another thread or process has written into the database since
  47238. ** the read transaction was started, then it is not possible for this
  47239. ** thread to write as doing so would cause a fork. So this routine
  47240. ** returns SQLITE_BUSY in that case and no write transaction is started.
  47241. **
  47242. ** There can only be a single writer active at a time.
  47243. */
  47244. SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal){
  47245. int rc;
  47246. /* Cannot start a write transaction without first holding a read
  47247. ** transaction. */
  47248. assert( pWal->readLock>=0 );
  47249. if( pWal->readOnly ){
  47250. return SQLITE_READONLY;
  47251. }
  47252. /* Only one writer allowed at a time. Get the write lock. Return
  47253. ** SQLITE_BUSY if unable.
  47254. */
  47255. rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1);
  47256. if( rc ){
  47257. return rc;
  47258. }
  47259. pWal->writeLock = 1;
  47260. /* If another connection has written to the database file since the
  47261. ** time the read transaction on this connection was started, then
  47262. ** the write is disallowed.
  47263. */
  47264. if( memcmp(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr))!=0 ){
  47265. walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
  47266. pWal->writeLock = 0;
  47267. rc = SQLITE_BUSY_SNAPSHOT;
  47268. }
  47269. return rc;
  47270. }
  47271. /*
  47272. ** End a write transaction. The commit has already been done. This
  47273. ** routine merely releases the lock.
  47274. */
  47275. SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal){
  47276. if( pWal->writeLock ){
  47277. walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
  47278. pWal->writeLock = 0;
  47279. pWal->truncateOnCommit = 0;
  47280. }
  47281. return SQLITE_OK;
  47282. }
  47283. /*
  47284. ** If any data has been written (but not committed) to the log file, this
  47285. ** function moves the write-pointer back to the start of the transaction.
  47286. **
  47287. ** Additionally, the callback function is invoked for each frame written
  47288. ** to the WAL since the start of the transaction. If the callback returns
  47289. ** other than SQLITE_OK, it is not invoked again and the error code is
  47290. ** returned to the caller.
  47291. **
  47292. ** Otherwise, if the callback function does not return an error, this
  47293. ** function returns SQLITE_OK.
  47294. */
  47295. SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx){
  47296. int rc = SQLITE_OK;
  47297. if( ALWAYS(pWal->writeLock) ){
  47298. Pgno iMax = pWal->hdr.mxFrame;
  47299. Pgno iFrame;
  47300. /* Restore the clients cache of the wal-index header to the state it
  47301. ** was in before the client began writing to the database.
  47302. */
  47303. memcpy(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr));
  47304. for(iFrame=pWal->hdr.mxFrame+1;
  47305. ALWAYS(rc==SQLITE_OK) && iFrame<=iMax;
  47306. iFrame++
  47307. ){
  47308. /* This call cannot fail. Unless the page for which the page number
  47309. ** is passed as the second argument is (a) in the cache and
  47310. ** (b) has an outstanding reference, then xUndo is either a no-op
  47311. ** (if (a) is false) or simply expels the page from the cache (if (b)
  47312. ** is false).
  47313. **
  47314. ** If the upper layer is doing a rollback, it is guaranteed that there
  47315. ** are no outstanding references to any page other than page 1. And
  47316. ** page 1 is never written to the log until the transaction is
  47317. ** committed. As a result, the call to xUndo may not fail.
  47318. */
  47319. assert( walFramePgno(pWal, iFrame)!=1 );
  47320. rc = xUndo(pUndoCtx, walFramePgno(pWal, iFrame));
  47321. }
  47322. if( iMax!=pWal->hdr.mxFrame ) walCleanupHash(pWal);
  47323. }
  47324. assert( rc==SQLITE_OK );
  47325. return rc;
  47326. }
  47327. /*
  47328. ** Argument aWalData must point to an array of WAL_SAVEPOINT_NDATA u32
  47329. ** values. This function populates the array with values required to
  47330. ** "rollback" the write position of the WAL handle back to the current
  47331. ** point in the event of a savepoint rollback (via WalSavepointUndo()).
  47332. */
  47333. SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData){
  47334. assert( pWal->writeLock );
  47335. aWalData[0] = pWal->hdr.mxFrame;
  47336. aWalData[1] = pWal->hdr.aFrameCksum[0];
  47337. aWalData[2] = pWal->hdr.aFrameCksum[1];
  47338. aWalData[3] = pWal->nCkpt;
  47339. }
  47340. /*
  47341. ** Move the write position of the WAL back to the point identified by
  47342. ** the values in the aWalData[] array. aWalData must point to an array
  47343. ** of WAL_SAVEPOINT_NDATA u32 values that has been previously populated
  47344. ** by a call to WalSavepoint().
  47345. */
  47346. SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData){
  47347. int rc = SQLITE_OK;
  47348. assert( pWal->writeLock );
  47349. assert( aWalData[3]!=pWal->nCkpt || aWalData[0]<=pWal->hdr.mxFrame );
  47350. if( aWalData[3]!=pWal->nCkpt ){
  47351. /* This savepoint was opened immediately after the write-transaction
  47352. ** was started. Right after that, the writer decided to wrap around
  47353. ** to the start of the log. Update the savepoint values to match.
  47354. */
  47355. aWalData[0] = 0;
  47356. aWalData[3] = pWal->nCkpt;
  47357. }
  47358. if( aWalData[0]<pWal->hdr.mxFrame ){
  47359. pWal->hdr.mxFrame = aWalData[0];
  47360. pWal->hdr.aFrameCksum[0] = aWalData[1];
  47361. pWal->hdr.aFrameCksum[1] = aWalData[2];
  47362. walCleanupHash(pWal);
  47363. }
  47364. return rc;
  47365. }
  47366. /*
  47367. ** This function is called just before writing a set of frames to the log
  47368. ** file (see sqlite3WalFrames()). It checks to see if, instead of appending
  47369. ** to the current log file, it is possible to overwrite the start of the
  47370. ** existing log file with the new frames (i.e. "reset" the log). If so,
  47371. ** it sets pWal->hdr.mxFrame to 0. Otherwise, pWal->hdr.mxFrame is left
  47372. ** unchanged.
  47373. **
  47374. ** SQLITE_OK is returned if no error is encountered (regardless of whether
  47375. ** or not pWal->hdr.mxFrame is modified). An SQLite error code is returned
  47376. ** if an error occurs.
  47377. */
  47378. static int walRestartLog(Wal *pWal){
  47379. int rc = SQLITE_OK;
  47380. int cnt;
  47381. if( pWal->readLock==0 ){
  47382. volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
  47383. assert( pInfo->nBackfill==pWal->hdr.mxFrame );
  47384. if( pInfo->nBackfill>0 ){
  47385. u32 salt1;
  47386. sqlite3_randomness(4, &salt1);
  47387. rc = walLockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
  47388. if( rc==SQLITE_OK ){
  47389. /* If all readers are using WAL_READ_LOCK(0) (in other words if no
  47390. ** readers are currently using the WAL), then the transactions
  47391. ** frames will overwrite the start of the existing log. Update the
  47392. ** wal-index header to reflect this.
  47393. **
  47394. ** In theory it would be Ok to update the cache of the header only
  47395. ** at this point. But updating the actual wal-index header is also
  47396. ** safe and means there is no special case for sqlite3WalUndo()
  47397. ** to handle if this transaction is rolled back.
  47398. */
  47399. int i; /* Loop counter */
  47400. u32 *aSalt = pWal->hdr.aSalt; /* Big-endian salt values */
  47401. pWal->nCkpt++;
  47402. pWal->hdr.mxFrame = 0;
  47403. sqlite3Put4byte((u8*)&aSalt[0], 1 + sqlite3Get4byte((u8*)&aSalt[0]));
  47404. aSalt[1] = salt1;
  47405. walIndexWriteHdr(pWal);
  47406. pInfo->nBackfill = 0;
  47407. pInfo->aReadMark[1] = 0;
  47408. for(i=2; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
  47409. assert( pInfo->aReadMark[0]==0 );
  47410. walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
  47411. }else if( rc!=SQLITE_BUSY ){
  47412. return rc;
  47413. }
  47414. }
  47415. walUnlockShared(pWal, WAL_READ_LOCK(0));
  47416. pWal->readLock = -1;
  47417. cnt = 0;
  47418. do{
  47419. int notUsed;
  47420. rc = walTryBeginRead(pWal, &notUsed, 1, ++cnt);
  47421. }while( rc==WAL_RETRY );
  47422. assert( (rc&0xff)!=SQLITE_BUSY ); /* BUSY not possible when useWal==1 */
  47423. testcase( (rc&0xff)==SQLITE_IOERR );
  47424. testcase( rc==SQLITE_PROTOCOL );
  47425. testcase( rc==SQLITE_OK );
  47426. }
  47427. return rc;
  47428. }
  47429. /*
  47430. ** Information about the current state of the WAL file and where
  47431. ** the next fsync should occur - passed from sqlite3WalFrames() into
  47432. ** walWriteToLog().
  47433. */
  47434. typedef struct WalWriter {
  47435. Wal *pWal; /* The complete WAL information */
  47436. sqlite3_file *pFd; /* The WAL file to which we write */
  47437. sqlite3_int64 iSyncPoint; /* Fsync at this offset */
  47438. int syncFlags; /* Flags for the fsync */
  47439. int szPage; /* Size of one page */
  47440. } WalWriter;
  47441. /*
  47442. ** Write iAmt bytes of content into the WAL file beginning at iOffset.
  47443. ** Do a sync when crossing the p->iSyncPoint boundary.
  47444. **
  47445. ** In other words, if iSyncPoint is in between iOffset and iOffset+iAmt,
  47446. ** first write the part before iSyncPoint, then sync, then write the
  47447. ** rest.
  47448. */
  47449. static int walWriteToLog(
  47450. WalWriter *p, /* WAL to write to */
  47451. void *pContent, /* Content to be written */
  47452. int iAmt, /* Number of bytes to write */
  47453. sqlite3_int64 iOffset /* Start writing at this offset */
  47454. ){
  47455. int rc;
  47456. if( iOffset<p->iSyncPoint && iOffset+iAmt>=p->iSyncPoint ){
  47457. int iFirstAmt = (int)(p->iSyncPoint - iOffset);
  47458. rc = sqlite3OsWrite(p->pFd, pContent, iFirstAmt, iOffset);
  47459. if( rc ) return rc;
  47460. iOffset += iFirstAmt;
  47461. iAmt -= iFirstAmt;
  47462. pContent = (void*)(iFirstAmt + (char*)pContent);
  47463. assert( p->syncFlags & (SQLITE_SYNC_NORMAL|SQLITE_SYNC_FULL) );
  47464. rc = sqlite3OsSync(p->pFd, p->syncFlags & SQLITE_SYNC_MASK);
  47465. if( iAmt==0 || rc ) return rc;
  47466. }
  47467. rc = sqlite3OsWrite(p->pFd, pContent, iAmt, iOffset);
  47468. return rc;
  47469. }
  47470. /*
  47471. ** Write out a single frame of the WAL
  47472. */
  47473. static int walWriteOneFrame(
  47474. WalWriter *p, /* Where to write the frame */
  47475. PgHdr *pPage, /* The page of the frame to be written */
  47476. int nTruncate, /* The commit flag. Usually 0. >0 for commit */
  47477. sqlite3_int64 iOffset /* Byte offset at which to write */
  47478. ){
  47479. int rc; /* Result code from subfunctions */
  47480. void *pData; /* Data actually written */
  47481. u8 aFrame[WAL_FRAME_HDRSIZE]; /* Buffer to assemble frame-header in */
  47482. #if defined(SQLITE_HAS_CODEC)
  47483. if( (pData = sqlite3PagerCodec(pPage))==0 ) return SQLITE_NOMEM;
  47484. #else
  47485. pData = pPage->pData;
  47486. #endif
  47487. walEncodeFrame(p->pWal, pPage->pgno, nTruncate, pData, aFrame);
  47488. rc = walWriteToLog(p, aFrame, sizeof(aFrame), iOffset);
  47489. if( rc ) return rc;
  47490. /* Write the page data */
  47491. rc = walWriteToLog(p, pData, p->szPage, iOffset+sizeof(aFrame));
  47492. return rc;
  47493. }
  47494. /*
  47495. ** Write a set of frames to the log. The caller must hold the write-lock
  47496. ** on the log file (obtained using sqlite3WalBeginWriteTransaction()).
  47497. */
  47498. SQLITE_PRIVATE int sqlite3WalFrames(
  47499. Wal *pWal, /* Wal handle to write to */
  47500. int szPage, /* Database page-size in bytes */
  47501. PgHdr *pList, /* List of dirty pages to write */
  47502. Pgno nTruncate, /* Database size after this commit */
  47503. int isCommit, /* True if this is a commit */
  47504. int sync_flags /* Flags to pass to OsSync() (or 0) */
  47505. ){
  47506. int rc; /* Used to catch return codes */
  47507. u32 iFrame; /* Next frame address */
  47508. PgHdr *p; /* Iterator to run through pList with. */
  47509. PgHdr *pLast = 0; /* Last frame in list */
  47510. int nExtra = 0; /* Number of extra copies of last page */
  47511. int szFrame; /* The size of a single frame */
  47512. i64 iOffset; /* Next byte to write in WAL file */
  47513. WalWriter w; /* The writer */
  47514. assert( pList );
  47515. assert( pWal->writeLock );
  47516. /* If this frame set completes a transaction, then nTruncate>0. If
  47517. ** nTruncate==0 then this frame set does not complete the transaction. */
  47518. assert( (isCommit!=0)==(nTruncate!=0) );
  47519. #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
  47520. { int cnt; for(cnt=0, p=pList; p; p=p->pDirty, cnt++){}
  47521. WALTRACE(("WAL%p: frame write begin. %d frames. mxFrame=%d. %s\n",
  47522. pWal, cnt, pWal->hdr.mxFrame, isCommit ? "Commit" : "Spill"));
  47523. }
  47524. #endif
  47525. /* See if it is possible to write these frames into the start of the
  47526. ** log file, instead of appending to it at pWal->hdr.mxFrame.
  47527. */
  47528. if( SQLITE_OK!=(rc = walRestartLog(pWal)) ){
  47529. return rc;
  47530. }
  47531. /* If this is the first frame written into the log, write the WAL
  47532. ** header to the start of the WAL file. See comments at the top of
  47533. ** this source file for a description of the WAL header format.
  47534. */
  47535. iFrame = pWal->hdr.mxFrame;
  47536. if( iFrame==0 ){
  47537. u8 aWalHdr[WAL_HDRSIZE]; /* Buffer to assemble wal-header in */
  47538. u32 aCksum[2]; /* Checksum for wal-header */
  47539. sqlite3Put4byte(&aWalHdr[0], (WAL_MAGIC | SQLITE_BIGENDIAN));
  47540. sqlite3Put4byte(&aWalHdr[4], WAL_MAX_VERSION);
  47541. sqlite3Put4byte(&aWalHdr[8], szPage);
  47542. sqlite3Put4byte(&aWalHdr[12], pWal->nCkpt);
  47543. if( pWal->nCkpt==0 ) sqlite3_randomness(8, pWal->hdr.aSalt);
  47544. memcpy(&aWalHdr[16], pWal->hdr.aSalt, 8);
  47545. walChecksumBytes(1, aWalHdr, WAL_HDRSIZE-2*4, 0, aCksum);
  47546. sqlite3Put4byte(&aWalHdr[24], aCksum[0]);
  47547. sqlite3Put4byte(&aWalHdr[28], aCksum[1]);
  47548. pWal->szPage = szPage;
  47549. pWal->hdr.bigEndCksum = SQLITE_BIGENDIAN;
  47550. pWal->hdr.aFrameCksum[0] = aCksum[0];
  47551. pWal->hdr.aFrameCksum[1] = aCksum[1];
  47552. pWal->truncateOnCommit = 1;
  47553. rc = sqlite3OsWrite(pWal->pWalFd, aWalHdr, sizeof(aWalHdr), 0);
  47554. WALTRACE(("WAL%p: wal-header write %s\n", pWal, rc ? "failed" : "ok"));
  47555. if( rc!=SQLITE_OK ){
  47556. return rc;
  47557. }
  47558. /* Sync the header (unless SQLITE_IOCAP_SEQUENTIAL is true or unless
  47559. ** all syncing is turned off by PRAGMA synchronous=OFF). Otherwise
  47560. ** an out-of-order write following a WAL restart could result in
  47561. ** database corruption. See the ticket:
  47562. **
  47563. ** http://localhost:591/sqlite/info/ff5be73dee
  47564. */
  47565. if( pWal->syncHeader && sync_flags ){
  47566. rc = sqlite3OsSync(pWal->pWalFd, sync_flags & SQLITE_SYNC_MASK);
  47567. if( rc ) return rc;
  47568. }
  47569. }
  47570. assert( (int)pWal->szPage==szPage );
  47571. /* Setup information needed to write frames into the WAL */
  47572. w.pWal = pWal;
  47573. w.pFd = pWal->pWalFd;
  47574. w.iSyncPoint = 0;
  47575. w.syncFlags = sync_flags;
  47576. w.szPage = szPage;
  47577. iOffset = walFrameOffset(iFrame+1, szPage);
  47578. szFrame = szPage + WAL_FRAME_HDRSIZE;
  47579. /* Write all frames into the log file exactly once */
  47580. for(p=pList; p; p=p->pDirty){
  47581. int nDbSize; /* 0 normally. Positive == commit flag */
  47582. iFrame++;
  47583. assert( iOffset==walFrameOffset(iFrame, szPage) );
  47584. nDbSize = (isCommit && p->pDirty==0) ? nTruncate : 0;
  47585. rc = walWriteOneFrame(&w, p, nDbSize, iOffset);
  47586. if( rc ) return rc;
  47587. pLast = p;
  47588. iOffset += szFrame;
  47589. }
  47590. /* If this is the end of a transaction, then we might need to pad
  47591. ** the transaction and/or sync the WAL file.
  47592. **
  47593. ** Padding and syncing only occur if this set of frames complete a
  47594. ** transaction and if PRAGMA synchronous=FULL. If synchronous==NORMAL
  47595. ** or synchronous==OFF, then no padding or syncing are needed.
  47596. **
  47597. ** If SQLITE_IOCAP_POWERSAFE_OVERWRITE is defined, then padding is not
  47598. ** needed and only the sync is done. If padding is needed, then the
  47599. ** final frame is repeated (with its commit mark) until the next sector
  47600. ** boundary is crossed. Only the part of the WAL prior to the last
  47601. ** sector boundary is synced; the part of the last frame that extends
  47602. ** past the sector boundary is written after the sync.
  47603. */
  47604. if( isCommit && (sync_flags & WAL_SYNC_TRANSACTIONS)!=0 ){
  47605. if( pWal->padToSectorBoundary ){
  47606. int sectorSize = sqlite3SectorSize(pWal->pWalFd);
  47607. w.iSyncPoint = ((iOffset+sectorSize-1)/sectorSize)*sectorSize;
  47608. while( iOffset<w.iSyncPoint ){
  47609. rc = walWriteOneFrame(&w, pLast, nTruncate, iOffset);
  47610. if( rc ) return rc;
  47611. iOffset += szFrame;
  47612. nExtra++;
  47613. }
  47614. }else{
  47615. rc = sqlite3OsSync(w.pFd, sync_flags & SQLITE_SYNC_MASK);
  47616. }
  47617. }
  47618. /* If this frame set completes the first transaction in the WAL and
  47619. ** if PRAGMA journal_size_limit is set, then truncate the WAL to the
  47620. ** journal size limit, if possible.
  47621. */
  47622. if( isCommit && pWal->truncateOnCommit && pWal->mxWalSize>=0 ){
  47623. i64 sz = pWal->mxWalSize;
  47624. if( walFrameOffset(iFrame+nExtra+1, szPage)>pWal->mxWalSize ){
  47625. sz = walFrameOffset(iFrame+nExtra+1, szPage);
  47626. }
  47627. walLimitSize(pWal, sz);
  47628. pWal->truncateOnCommit = 0;
  47629. }
  47630. /* Append data to the wal-index. It is not necessary to lock the
  47631. ** wal-index to do this as the SQLITE_SHM_WRITE lock held on the wal-index
  47632. ** guarantees that there are no other writers, and no data that may
  47633. ** be in use by existing readers is being overwritten.
  47634. */
  47635. iFrame = pWal->hdr.mxFrame;
  47636. for(p=pList; p && rc==SQLITE_OK; p=p->pDirty){
  47637. iFrame++;
  47638. rc = walIndexAppend(pWal, iFrame, p->pgno);
  47639. }
  47640. while( rc==SQLITE_OK && nExtra>0 ){
  47641. iFrame++;
  47642. nExtra--;
  47643. rc = walIndexAppend(pWal, iFrame, pLast->pgno);
  47644. }
  47645. if( rc==SQLITE_OK ){
  47646. /* Update the private copy of the header. */
  47647. pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
  47648. testcase( szPage<=32768 );
  47649. testcase( szPage>=65536 );
  47650. pWal->hdr.mxFrame = iFrame;
  47651. if( isCommit ){
  47652. pWal->hdr.iChange++;
  47653. pWal->hdr.nPage = nTruncate;
  47654. }
  47655. /* If this is a commit, update the wal-index header too. */
  47656. if( isCommit ){
  47657. walIndexWriteHdr(pWal);
  47658. pWal->iCallback = iFrame;
  47659. }
  47660. }
  47661. WALTRACE(("WAL%p: frame write %s\n", pWal, rc ? "failed" : "ok"));
  47662. return rc;
  47663. }
  47664. /*
  47665. ** This routine is called to implement sqlite3_wal_checkpoint() and
  47666. ** related interfaces.
  47667. **
  47668. ** Obtain a CHECKPOINT lock and then backfill as much information as
  47669. ** we can from WAL into the database.
  47670. **
  47671. ** If parameter xBusy is not NULL, it is a pointer to a busy-handler
  47672. ** callback. In this case this function runs a blocking checkpoint.
  47673. */
  47674. SQLITE_PRIVATE int sqlite3WalCheckpoint(
  47675. Wal *pWal, /* Wal connection */
  47676. int eMode, /* PASSIVE, FULL or RESTART */
  47677. int (*xBusy)(void*), /* Function to call when busy */
  47678. void *pBusyArg, /* Context argument for xBusyHandler */
  47679. int sync_flags, /* Flags to sync db file with (or 0) */
  47680. int nBuf, /* Size of temporary buffer */
  47681. u8 *zBuf, /* Temporary buffer to use */
  47682. int *pnLog, /* OUT: Number of frames in WAL */
  47683. int *pnCkpt /* OUT: Number of backfilled frames in WAL */
  47684. ){
  47685. int rc; /* Return code */
  47686. int isChanged = 0; /* True if a new wal-index header is loaded */
  47687. int eMode2 = eMode; /* Mode to pass to walCheckpoint() */
  47688. assert( pWal->ckptLock==0 );
  47689. assert( pWal->writeLock==0 );
  47690. if( pWal->readOnly ) return SQLITE_READONLY;
  47691. WALTRACE(("WAL%p: checkpoint begins\n", pWal));
  47692. rc = walLockExclusive(pWal, WAL_CKPT_LOCK, 1);
  47693. if( rc ){
  47694. /* Usually this is SQLITE_BUSY meaning that another thread or process
  47695. ** is already running a checkpoint, or maybe a recovery. But it might
  47696. ** also be SQLITE_IOERR. */
  47697. return rc;
  47698. }
  47699. pWal->ckptLock = 1;
  47700. /* If this is a blocking-checkpoint, then obtain the write-lock as well
  47701. ** to prevent any writers from running while the checkpoint is underway.
  47702. ** This has to be done before the call to walIndexReadHdr() below.
  47703. **
  47704. ** If the writer lock cannot be obtained, then a passive checkpoint is
  47705. ** run instead. Since the checkpointer is not holding the writer lock,
  47706. ** there is no point in blocking waiting for any readers. Assuming no
  47707. ** other error occurs, this function will return SQLITE_BUSY to the caller.
  47708. */
  47709. if( eMode!=SQLITE_CHECKPOINT_PASSIVE ){
  47710. rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_WRITE_LOCK, 1);
  47711. if( rc==SQLITE_OK ){
  47712. pWal->writeLock = 1;
  47713. }else if( rc==SQLITE_BUSY ){
  47714. eMode2 = SQLITE_CHECKPOINT_PASSIVE;
  47715. rc = SQLITE_OK;
  47716. }
  47717. }
  47718. /* Read the wal-index header. */
  47719. if( rc==SQLITE_OK ){
  47720. rc = walIndexReadHdr(pWal, &isChanged);
  47721. if( isChanged && pWal->pDbFd->pMethods->iVersion>=3 ){
  47722. sqlite3OsUnfetch(pWal->pDbFd, 0, 0);
  47723. }
  47724. }
  47725. /* Copy data from the log to the database file. */
  47726. if( rc==SQLITE_OK ){
  47727. if( pWal->hdr.mxFrame && walPagesize(pWal)!=nBuf ){
  47728. rc = SQLITE_CORRUPT_BKPT;
  47729. }else{
  47730. rc = walCheckpoint(pWal, eMode2, xBusy, pBusyArg, sync_flags, zBuf);
  47731. }
  47732. /* If no error occurred, set the output variables. */
  47733. if( rc==SQLITE_OK || rc==SQLITE_BUSY ){
  47734. if( pnLog ) *pnLog = (int)pWal->hdr.mxFrame;
  47735. if( pnCkpt ) *pnCkpt = (int)(walCkptInfo(pWal)->nBackfill);
  47736. }
  47737. }
  47738. if( isChanged ){
  47739. /* If a new wal-index header was loaded before the checkpoint was
  47740. ** performed, then the pager-cache associated with pWal is now
  47741. ** out of date. So zero the cached wal-index header to ensure that
  47742. ** next time the pager opens a snapshot on this database it knows that
  47743. ** the cache needs to be reset.
  47744. */
  47745. memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
  47746. }
  47747. /* Release the locks. */
  47748. sqlite3WalEndWriteTransaction(pWal);
  47749. walUnlockExclusive(pWal, WAL_CKPT_LOCK, 1);
  47750. pWal->ckptLock = 0;
  47751. WALTRACE(("WAL%p: checkpoint %s\n", pWal, rc ? "failed" : "ok"));
  47752. return (rc==SQLITE_OK && eMode!=eMode2 ? SQLITE_BUSY : rc);
  47753. }
  47754. /* Return the value to pass to a sqlite3_wal_hook callback, the
  47755. ** number of frames in the WAL at the point of the last commit since
  47756. ** sqlite3WalCallback() was called. If no commits have occurred since
  47757. ** the last call, then return 0.
  47758. */
  47759. SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal){
  47760. u32 ret = 0;
  47761. if( pWal ){
  47762. ret = pWal->iCallback;
  47763. pWal->iCallback = 0;
  47764. }
  47765. return (int)ret;
  47766. }
  47767. /*
  47768. ** This function is called to change the WAL subsystem into or out
  47769. ** of locking_mode=EXCLUSIVE.
  47770. **
  47771. ** If op is zero, then attempt to change from locking_mode=EXCLUSIVE
  47772. ** into locking_mode=NORMAL. This means that we must acquire a lock
  47773. ** on the pWal->readLock byte. If the WAL is already in locking_mode=NORMAL
  47774. ** or if the acquisition of the lock fails, then return 0. If the
  47775. ** transition out of exclusive-mode is successful, return 1. This
  47776. ** operation must occur while the pager is still holding the exclusive
  47777. ** lock on the main database file.
  47778. **
  47779. ** If op is one, then change from locking_mode=NORMAL into
  47780. ** locking_mode=EXCLUSIVE. This means that the pWal->readLock must
  47781. ** be released. Return 1 if the transition is made and 0 if the
  47782. ** WAL is already in exclusive-locking mode - meaning that this
  47783. ** routine is a no-op. The pager must already hold the exclusive lock
  47784. ** on the main database file before invoking this operation.
  47785. **
  47786. ** If op is negative, then do a dry-run of the op==1 case but do
  47787. ** not actually change anything. The pager uses this to see if it
  47788. ** should acquire the database exclusive lock prior to invoking
  47789. ** the op==1 case.
  47790. */
  47791. SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op){
  47792. int rc;
  47793. assert( pWal->writeLock==0 );
  47794. assert( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE || op==-1 );
  47795. /* pWal->readLock is usually set, but might be -1 if there was a
  47796. ** prior error while attempting to acquire are read-lock. This cannot
  47797. ** happen if the connection is actually in exclusive mode (as no xShmLock
  47798. ** locks are taken in this case). Nor should the pager attempt to
  47799. ** upgrade to exclusive-mode following such an error.
  47800. */
  47801. assert( pWal->readLock>=0 || pWal->lockError );
  47802. assert( pWal->readLock>=0 || (op<=0 && pWal->exclusiveMode==0) );
  47803. if( op==0 ){
  47804. if( pWal->exclusiveMode ){
  47805. pWal->exclusiveMode = 0;
  47806. if( walLockShared(pWal, WAL_READ_LOCK(pWal->readLock))!=SQLITE_OK ){
  47807. pWal->exclusiveMode = 1;
  47808. }
  47809. rc = pWal->exclusiveMode==0;
  47810. }else{
  47811. /* Already in locking_mode=NORMAL */
  47812. rc = 0;
  47813. }
  47814. }else if( op>0 ){
  47815. assert( pWal->exclusiveMode==0 );
  47816. assert( pWal->readLock>=0 );
  47817. walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
  47818. pWal->exclusiveMode = 1;
  47819. rc = 1;
  47820. }else{
  47821. rc = pWal->exclusiveMode==0;
  47822. }
  47823. return rc;
  47824. }
  47825. /*
  47826. ** Return true if the argument is non-NULL and the WAL module is using
  47827. ** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
  47828. ** WAL module is using shared-memory, return false.
  47829. */
  47830. SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal){
  47831. return (pWal && pWal->exclusiveMode==WAL_HEAPMEMORY_MODE );
  47832. }
  47833. #ifdef SQLITE_ENABLE_ZIPVFS
  47834. /*
  47835. ** If the argument is not NULL, it points to a Wal object that holds a
  47836. ** read-lock. This function returns the database page-size if it is known,
  47837. ** or zero if it is not (or if pWal is NULL).
  47838. */
  47839. SQLITE_PRIVATE int sqlite3WalFramesize(Wal *pWal){
  47840. assert( pWal==0 || pWal->readLock>=0 );
  47841. return (pWal ? pWal->szPage : 0);
  47842. }
  47843. #endif
  47844. #endif /* #ifndef SQLITE_OMIT_WAL */
  47845. /************** End of wal.c *************************************************/
  47846. /************** Begin file btmutex.c *****************************************/
  47847. /*
  47848. ** 2007 August 27
  47849. **
  47850. ** The author disclaims copyright to this source code. In place of
  47851. ** a legal notice, here is a blessing:
  47852. **
  47853. ** May you do good and not evil.
  47854. ** May you find forgiveness for yourself and forgive others.
  47855. ** May you share freely, never taking more than you give.
  47856. **
  47857. *************************************************************************
  47858. **
  47859. ** This file contains code used to implement mutexes on Btree objects.
  47860. ** This code really belongs in btree.c. But btree.c is getting too
  47861. ** big and we want to break it down some. This packaged seemed like
  47862. ** a good breakout.
  47863. */
  47864. /************** Include btreeInt.h in the middle of btmutex.c ****************/
  47865. /************** Begin file btreeInt.h ****************************************/
  47866. /*
  47867. ** 2004 April 6
  47868. **
  47869. ** The author disclaims copyright to this source code. In place of
  47870. ** a legal notice, here is a blessing:
  47871. **
  47872. ** May you do good and not evil.
  47873. ** May you find forgiveness for yourself and forgive others.
  47874. ** May you share freely, never taking more than you give.
  47875. **
  47876. *************************************************************************
  47877. ** This file implements an external (disk-based) database using BTrees.
  47878. ** For a detailed discussion of BTrees, refer to
  47879. **
  47880. ** Donald E. Knuth, THE ART OF COMPUTER PROGRAMMING, Volume 3:
  47881. ** "Sorting And Searching", pages 473-480. Addison-Wesley
  47882. ** Publishing Company, Reading, Massachusetts.
  47883. **
  47884. ** The basic idea is that each page of the file contains N database
  47885. ** entries and N+1 pointers to subpages.
  47886. **
  47887. ** ----------------------------------------------------------------
  47888. ** | Ptr(0) | Key(0) | Ptr(1) | Key(1) | ... | Key(N-1) | Ptr(N) |
  47889. ** ----------------------------------------------------------------
  47890. **
  47891. ** All of the keys on the page that Ptr(0) points to have values less
  47892. ** than Key(0). All of the keys on page Ptr(1) and its subpages have
  47893. ** values greater than Key(0) and less than Key(1). All of the keys
  47894. ** on Ptr(N) and its subpages have values greater than Key(N-1). And
  47895. ** so forth.
  47896. **
  47897. ** Finding a particular key requires reading O(log(M)) pages from the
  47898. ** disk where M is the number of entries in the tree.
  47899. **
  47900. ** In this implementation, a single file can hold one or more separate
  47901. ** BTrees. Each BTree is identified by the index of its root page. The
  47902. ** key and data for any entry are combined to form the "payload". A
  47903. ** fixed amount of payload can be carried directly on the database
  47904. ** page. If the payload is larger than the preset amount then surplus
  47905. ** bytes are stored on overflow pages. The payload for an entry
  47906. ** and the preceding pointer are combined to form a "Cell". Each
  47907. ** page has a small header which contains the Ptr(N) pointer and other
  47908. ** information such as the size of key and data.
  47909. **
  47910. ** FORMAT DETAILS
  47911. **
  47912. ** The file is divided into pages. The first page is called page 1,
  47913. ** the second is page 2, and so forth. A page number of zero indicates
  47914. ** "no such page". The page size can be any power of 2 between 512 and 65536.
  47915. ** Each page can be either a btree page, a freelist page, an overflow
  47916. ** page, or a pointer-map page.
  47917. **
  47918. ** The first page is always a btree page. The first 100 bytes of the first
  47919. ** page contain a special header (the "file header") that describes the file.
  47920. ** The format of the file header is as follows:
  47921. **
  47922. ** OFFSET SIZE DESCRIPTION
  47923. ** 0 16 Header string: "SQLite format 3\000"
  47924. ** 16 2 Page size in bytes. (1 means 65536)
  47925. ** 18 1 File format write version
  47926. ** 19 1 File format read version
  47927. ** 20 1 Bytes of unused space at the end of each page
  47928. ** 21 1 Max embedded payload fraction (must be 64)
  47929. ** 22 1 Min embedded payload fraction (must be 32)
  47930. ** 23 1 Min leaf payload fraction (must be 32)
  47931. ** 24 4 File change counter
  47932. ** 28 4 Reserved for future use
  47933. ** 32 4 First freelist page
  47934. ** 36 4 Number of freelist pages in the file
  47935. ** 40 60 15 4-byte meta values passed to higher layers
  47936. **
  47937. ** 40 4 Schema cookie
  47938. ** 44 4 File format of schema layer
  47939. ** 48 4 Size of page cache
  47940. ** 52 4 Largest root-page (auto/incr_vacuum)
  47941. ** 56 4 1=UTF-8 2=UTF16le 3=UTF16be
  47942. ** 60 4 User version
  47943. ** 64 4 Incremental vacuum mode
  47944. ** 68 4 Application-ID
  47945. ** 72 20 unused
  47946. ** 92 4 The version-valid-for number
  47947. ** 96 4 SQLITE_VERSION_NUMBER
  47948. **
  47949. ** All of the integer values are big-endian (most significant byte first).
  47950. **
  47951. ** The file change counter is incremented when the database is changed
  47952. ** This counter allows other processes to know when the file has changed
  47953. ** and thus when they need to flush their cache.
  47954. **
  47955. ** The max embedded payload fraction is the amount of the total usable
  47956. ** space in a page that can be consumed by a single cell for standard
  47957. ** B-tree (non-LEAFDATA) tables. A value of 255 means 100%. The default
  47958. ** is to limit the maximum cell size so that at least 4 cells will fit
  47959. ** on one page. Thus the default max embedded payload fraction is 64.
  47960. **
  47961. ** If the payload for a cell is larger than the max payload, then extra
  47962. ** payload is spilled to overflow pages. Once an overflow page is allocated,
  47963. ** as many bytes as possible are moved into the overflow pages without letting
  47964. ** the cell size drop below the min embedded payload fraction.
  47965. **
  47966. ** The min leaf payload fraction is like the min embedded payload fraction
  47967. ** except that it applies to leaf nodes in a LEAFDATA tree. The maximum
  47968. ** payload fraction for a LEAFDATA tree is always 100% (or 255) and it
  47969. ** not specified in the header.
  47970. **
  47971. ** Each btree pages is divided into three sections: The header, the
  47972. ** cell pointer array, and the cell content area. Page 1 also has a 100-byte
  47973. ** file header that occurs before the page header.
  47974. **
  47975. ** |----------------|
  47976. ** | file header | 100 bytes. Page 1 only.
  47977. ** |----------------|
  47978. ** | page header | 8 bytes for leaves. 12 bytes for interior nodes
  47979. ** |----------------|
  47980. ** | cell pointer | | 2 bytes per cell. Sorted order.
  47981. ** | array | | Grows downward
  47982. ** | | v
  47983. ** |----------------|
  47984. ** | unallocated |
  47985. ** | space |
  47986. ** |----------------| ^ Grows upwards
  47987. ** | cell content | | Arbitrary order interspersed with freeblocks.
  47988. ** | area | | and free space fragments.
  47989. ** |----------------|
  47990. **
  47991. ** The page headers looks like this:
  47992. **
  47993. ** OFFSET SIZE DESCRIPTION
  47994. ** 0 1 Flags. 1: intkey, 2: zerodata, 4: leafdata, 8: leaf
  47995. ** 1 2 byte offset to the first freeblock
  47996. ** 3 2 number of cells on this page
  47997. ** 5 2 first byte of the cell content area
  47998. ** 7 1 number of fragmented free bytes
  47999. ** 8 4 Right child (the Ptr(N) value). Omitted on leaves.
  48000. **
  48001. ** The flags define the format of this btree page. The leaf flag means that
  48002. ** this page has no children. The zerodata flag means that this page carries
  48003. ** only keys and no data. The intkey flag means that the key is an integer
  48004. ** which is stored in the key size entry of the cell header rather than in
  48005. ** the payload area.
  48006. **
  48007. ** The cell pointer array begins on the first byte after the page header.
  48008. ** The cell pointer array contains zero or more 2-byte numbers which are
  48009. ** offsets from the beginning of the page to the cell content in the cell
  48010. ** content area. The cell pointers occur in sorted order. The system strives
  48011. ** to keep free space after the last cell pointer so that new cells can
  48012. ** be easily added without having to defragment the page.
  48013. **
  48014. ** Cell content is stored at the very end of the page and grows toward the
  48015. ** beginning of the page.
  48016. **
  48017. ** Unused space within the cell content area is collected into a linked list of
  48018. ** freeblocks. Each freeblock is at least 4 bytes in size. The byte offset
  48019. ** to the first freeblock is given in the header. Freeblocks occur in
  48020. ** increasing order. Because a freeblock must be at least 4 bytes in size,
  48021. ** any group of 3 or fewer unused bytes in the cell content area cannot
  48022. ** exist on the freeblock chain. A group of 3 or fewer free bytes is called
  48023. ** a fragment. The total number of bytes in all fragments is recorded.
  48024. ** in the page header at offset 7.
  48025. **
  48026. ** SIZE DESCRIPTION
  48027. ** 2 Byte offset of the next freeblock
  48028. ** 2 Bytes in this freeblock
  48029. **
  48030. ** Cells are of variable length. Cells are stored in the cell content area at
  48031. ** the end of the page. Pointers to the cells are in the cell pointer array
  48032. ** that immediately follows the page header. Cells is not necessarily
  48033. ** contiguous or in order, but cell pointers are contiguous and in order.
  48034. **
  48035. ** Cell content makes use of variable length integers. A variable
  48036. ** length integer is 1 to 9 bytes where the lower 7 bits of each
  48037. ** byte are used. The integer consists of all bytes that have bit 8 set and
  48038. ** the first byte with bit 8 clear. The most significant byte of the integer
  48039. ** appears first. A variable-length integer may not be more than 9 bytes long.
  48040. ** As a special case, all 8 bytes of the 9th byte are used as data. This
  48041. ** allows a 64-bit integer to be encoded in 9 bytes.
  48042. **
  48043. ** 0x00 becomes 0x00000000
  48044. ** 0x7f becomes 0x0000007f
  48045. ** 0x81 0x00 becomes 0x00000080
  48046. ** 0x82 0x00 becomes 0x00000100
  48047. ** 0x80 0x7f becomes 0x0000007f
  48048. ** 0x8a 0x91 0xd1 0xac 0x78 becomes 0x12345678
  48049. ** 0x81 0x81 0x81 0x81 0x01 becomes 0x10204081
  48050. **
  48051. ** Variable length integers are used for rowids and to hold the number of
  48052. ** bytes of key and data in a btree cell.
  48053. **
  48054. ** The content of a cell looks like this:
  48055. **
  48056. ** SIZE DESCRIPTION
  48057. ** 4 Page number of the left child. Omitted if leaf flag is set.
  48058. ** var Number of bytes of data. Omitted if the zerodata flag is set.
  48059. ** var Number of bytes of key. Or the key itself if intkey flag is set.
  48060. ** * Payload
  48061. ** 4 First page of the overflow chain. Omitted if no overflow
  48062. **
  48063. ** Overflow pages form a linked list. Each page except the last is completely
  48064. ** filled with data (pagesize - 4 bytes). The last page can have as little
  48065. ** as 1 byte of data.
  48066. **
  48067. ** SIZE DESCRIPTION
  48068. ** 4 Page number of next overflow page
  48069. ** * Data
  48070. **
  48071. ** Freelist pages come in two subtypes: trunk pages and leaf pages. The
  48072. ** file header points to the first in a linked list of trunk page. Each trunk
  48073. ** page points to multiple leaf pages. The content of a leaf page is
  48074. ** unspecified. A trunk page looks like this:
  48075. **
  48076. ** SIZE DESCRIPTION
  48077. ** 4 Page number of next trunk page
  48078. ** 4 Number of leaf pointers on this page
  48079. ** * zero or more pages numbers of leaves
  48080. */
  48081. /* The following value is the maximum cell size assuming a maximum page
  48082. ** size give above.
  48083. */
  48084. #define MX_CELL_SIZE(pBt) ((int)(pBt->pageSize-8))
  48085. /* The maximum number of cells on a single page of the database. This
  48086. ** assumes a minimum cell size of 6 bytes (4 bytes for the cell itself
  48087. ** plus 2 bytes for the index to the cell in the page header). Such
  48088. ** small cells will be rare, but they are possible.
  48089. */
  48090. #define MX_CELL(pBt) ((pBt->pageSize-8)/6)
  48091. /* Forward declarations */
  48092. typedef struct MemPage MemPage;
  48093. typedef struct BtLock BtLock;
  48094. /*
  48095. ** This is a magic string that appears at the beginning of every
  48096. ** SQLite database in order to identify the file as a real database.
  48097. **
  48098. ** You can change this value at compile-time by specifying a
  48099. ** -DSQLITE_FILE_HEADER="..." on the compiler command-line. The
  48100. ** header must be exactly 16 bytes including the zero-terminator so
  48101. ** the string itself should be 15 characters long. If you change
  48102. ** the header, then your custom library will not be able to read
  48103. ** databases generated by the standard tools and the standard tools
  48104. ** will not be able to read databases created by your custom library.
  48105. */
  48106. #ifndef SQLITE_FILE_HEADER /* 123456789 123456 */
  48107. # define SQLITE_FILE_HEADER "SQLite format 3"
  48108. #endif
  48109. /*
  48110. ** Page type flags. An ORed combination of these flags appear as the
  48111. ** first byte of on-disk image of every BTree page.
  48112. */
  48113. #define PTF_INTKEY 0x01
  48114. #define PTF_ZERODATA 0x02
  48115. #define PTF_LEAFDATA 0x04
  48116. #define PTF_LEAF 0x08
  48117. /*
  48118. ** As each page of the file is loaded into memory, an instance of the following
  48119. ** structure is appended and initialized to zero. This structure stores
  48120. ** information about the page that is decoded from the raw file page.
  48121. **
  48122. ** The pParent field points back to the parent page. This allows us to
  48123. ** walk up the BTree from any leaf to the root. Care must be taken to
  48124. ** unref() the parent page pointer when this page is no longer referenced.
  48125. ** The pageDestructor() routine handles that chore.
  48126. **
  48127. ** Access to all fields of this structure is controlled by the mutex
  48128. ** stored in MemPage.pBt->mutex.
  48129. */
  48130. struct MemPage {
  48131. u8 isInit; /* True if previously initialized. MUST BE FIRST! */
  48132. u8 nOverflow; /* Number of overflow cell bodies in aCell[] */
  48133. u8 intKey; /* True if table b-trees. False for index b-trees */
  48134. u8 intKeyLeaf; /* True if the leaf of an intKey table */
  48135. u8 noPayload; /* True if internal intKey page (thus w/o data) */
  48136. u8 leaf; /* True if a leaf page */
  48137. u8 hdrOffset; /* 100 for page 1. 0 otherwise */
  48138. u8 childPtrSize; /* 0 if leaf==1. 4 if leaf==0 */
  48139. u8 max1bytePayload; /* min(maxLocal,127) */
  48140. u16 maxLocal; /* Copy of BtShared.maxLocal or BtShared.maxLeaf */
  48141. u16 minLocal; /* Copy of BtShared.minLocal or BtShared.minLeaf */
  48142. u16 cellOffset; /* Index in aData of first cell pointer */
  48143. u16 nFree; /* Number of free bytes on the page */
  48144. u16 nCell; /* Number of cells on this page, local and ovfl */
  48145. u16 maskPage; /* Mask for page offset */
  48146. u16 aiOvfl[5]; /* Insert the i-th overflow cell before the aiOvfl-th
  48147. ** non-overflow cell */
  48148. u8 *apOvfl[5]; /* Pointers to the body of overflow cells */
  48149. BtShared *pBt; /* Pointer to BtShared that this page is part of */
  48150. u8 *aData; /* Pointer to disk image of the page data */
  48151. u8 *aDataEnd; /* One byte past the end of usable data */
  48152. u8 *aCellIdx; /* The cell index area */
  48153. DbPage *pDbPage; /* Pager page handle */
  48154. Pgno pgno; /* Page number for this page */
  48155. };
  48156. /*
  48157. ** The in-memory image of a disk page has the auxiliary information appended
  48158. ** to the end. EXTRA_SIZE is the number of bytes of space needed to hold
  48159. ** that extra information.
  48160. */
  48161. #define EXTRA_SIZE sizeof(MemPage)
  48162. /*
  48163. ** A linked list of the following structures is stored at BtShared.pLock.
  48164. ** Locks are added (or upgraded from READ_LOCK to WRITE_LOCK) when a cursor
  48165. ** is opened on the table with root page BtShared.iTable. Locks are removed
  48166. ** from this list when a transaction is committed or rolled back, or when
  48167. ** a btree handle is closed.
  48168. */
  48169. struct BtLock {
  48170. Btree *pBtree; /* Btree handle holding this lock */
  48171. Pgno iTable; /* Root page of table */
  48172. u8 eLock; /* READ_LOCK or WRITE_LOCK */
  48173. BtLock *pNext; /* Next in BtShared.pLock list */
  48174. };
  48175. /* Candidate values for BtLock.eLock */
  48176. #define READ_LOCK 1
  48177. #define WRITE_LOCK 2
  48178. /* A Btree handle
  48179. **
  48180. ** A database connection contains a pointer to an instance of
  48181. ** this object for every database file that it has open. This structure
  48182. ** is opaque to the database connection. The database connection cannot
  48183. ** see the internals of this structure and only deals with pointers to
  48184. ** this structure.
  48185. **
  48186. ** For some database files, the same underlying database cache might be
  48187. ** shared between multiple connections. In that case, each connection
  48188. ** has it own instance of this object. But each instance of this object
  48189. ** points to the same BtShared object. The database cache and the
  48190. ** schema associated with the database file are all contained within
  48191. ** the BtShared object.
  48192. **
  48193. ** All fields in this structure are accessed under sqlite3.mutex.
  48194. ** The pBt pointer itself may not be changed while there exists cursors
  48195. ** in the referenced BtShared that point back to this Btree since those
  48196. ** cursors have to go through this Btree to find their BtShared and
  48197. ** they often do so without holding sqlite3.mutex.
  48198. */
  48199. struct Btree {
  48200. sqlite3 *db; /* The database connection holding this btree */
  48201. BtShared *pBt; /* Sharable content of this btree */
  48202. u8 inTrans; /* TRANS_NONE, TRANS_READ or TRANS_WRITE */
  48203. u8 sharable; /* True if we can share pBt with another db */
  48204. u8 locked; /* True if db currently has pBt locked */
  48205. int wantToLock; /* Number of nested calls to sqlite3BtreeEnter() */
  48206. int nBackup; /* Number of backup operations reading this btree */
  48207. Btree *pNext; /* List of other sharable Btrees from the same db */
  48208. Btree *pPrev; /* Back pointer of the same list */
  48209. #ifndef SQLITE_OMIT_SHARED_CACHE
  48210. BtLock lock; /* Object used to lock page 1 */
  48211. #endif
  48212. };
  48213. /*
  48214. ** Btree.inTrans may take one of the following values.
  48215. **
  48216. ** If the shared-data extension is enabled, there may be multiple users
  48217. ** of the Btree structure. At most one of these may open a write transaction,
  48218. ** but any number may have active read transactions.
  48219. */
  48220. #define TRANS_NONE 0
  48221. #define TRANS_READ 1
  48222. #define TRANS_WRITE 2
  48223. /*
  48224. ** An instance of this object represents a single database file.
  48225. **
  48226. ** A single database file can be in use at the same time by two
  48227. ** or more database connections. When two or more connections are
  48228. ** sharing the same database file, each connection has it own
  48229. ** private Btree object for the file and each of those Btrees points
  48230. ** to this one BtShared object. BtShared.nRef is the number of
  48231. ** connections currently sharing this database file.
  48232. **
  48233. ** Fields in this structure are accessed under the BtShared.mutex
  48234. ** mutex, except for nRef and pNext which are accessed under the
  48235. ** global SQLITE_MUTEX_STATIC_MASTER mutex. The pPager field
  48236. ** may not be modified once it is initially set as long as nRef>0.
  48237. ** The pSchema field may be set once under BtShared.mutex and
  48238. ** thereafter is unchanged as long as nRef>0.
  48239. **
  48240. ** isPending:
  48241. **
  48242. ** If a BtShared client fails to obtain a write-lock on a database
  48243. ** table (because there exists one or more read-locks on the table),
  48244. ** the shared-cache enters 'pending-lock' state and isPending is
  48245. ** set to true.
  48246. **
  48247. ** The shared-cache leaves the 'pending lock' state when either of
  48248. ** the following occur:
  48249. **
  48250. ** 1) The current writer (BtShared.pWriter) concludes its transaction, OR
  48251. ** 2) The number of locks held by other connections drops to zero.
  48252. **
  48253. ** while in the 'pending-lock' state, no connection may start a new
  48254. ** transaction.
  48255. **
  48256. ** This feature is included to help prevent writer-starvation.
  48257. */
  48258. struct BtShared {
  48259. Pager *pPager; /* The page cache */
  48260. sqlite3 *db; /* Database connection currently using this Btree */
  48261. BtCursor *pCursor; /* A list of all open cursors */
  48262. MemPage *pPage1; /* First page of the database */
  48263. u8 openFlags; /* Flags to sqlite3BtreeOpen() */
  48264. #ifndef SQLITE_OMIT_AUTOVACUUM
  48265. u8 autoVacuum; /* True if auto-vacuum is enabled */
  48266. u8 incrVacuum; /* True if incr-vacuum is enabled */
  48267. u8 bDoTruncate; /* True to truncate db on commit */
  48268. #endif
  48269. u8 inTransaction; /* Transaction state */
  48270. u8 max1bytePayload; /* Maximum first byte of cell for a 1-byte payload */
  48271. u16 btsFlags; /* Boolean parameters. See BTS_* macros below */
  48272. u16 maxLocal; /* Maximum local payload in non-LEAFDATA tables */
  48273. u16 minLocal; /* Minimum local payload in non-LEAFDATA tables */
  48274. u16 maxLeaf; /* Maximum local payload in a LEAFDATA table */
  48275. u16 minLeaf; /* Minimum local payload in a LEAFDATA table */
  48276. u32 pageSize; /* Total number of bytes on a page */
  48277. u32 usableSize; /* Number of usable bytes on each page */
  48278. int nTransaction; /* Number of open transactions (read + write) */
  48279. u32 nPage; /* Number of pages in the database */
  48280. void *pSchema; /* Pointer to space allocated by sqlite3BtreeSchema() */
  48281. void (*xFreeSchema)(void*); /* Destructor for BtShared.pSchema */
  48282. sqlite3_mutex *mutex; /* Non-recursive mutex required to access this object */
  48283. Bitvec *pHasContent; /* Set of pages moved to free-list this transaction */
  48284. #ifndef SQLITE_OMIT_SHARED_CACHE
  48285. int nRef; /* Number of references to this structure */
  48286. BtShared *pNext; /* Next on a list of sharable BtShared structs */
  48287. BtLock *pLock; /* List of locks held on this shared-btree struct */
  48288. Btree *pWriter; /* Btree with currently open write transaction */
  48289. #endif
  48290. u8 *pTmpSpace; /* Temp space sufficient to hold a single cell */
  48291. };
  48292. /*
  48293. ** Allowed values for BtShared.btsFlags
  48294. */
  48295. #define BTS_READ_ONLY 0x0001 /* Underlying file is readonly */
  48296. #define BTS_PAGESIZE_FIXED 0x0002 /* Page size can no longer be changed */
  48297. #define BTS_SECURE_DELETE 0x0004 /* PRAGMA secure_delete is enabled */
  48298. #define BTS_INITIALLY_EMPTY 0x0008 /* Database was empty at trans start */
  48299. #define BTS_NO_WAL 0x0010 /* Do not open write-ahead-log files */
  48300. #define BTS_EXCLUSIVE 0x0020 /* pWriter has an exclusive lock */
  48301. #define BTS_PENDING 0x0040 /* Waiting for read-locks to clear */
  48302. /*
  48303. ** An instance of the following structure is used to hold information
  48304. ** about a cell. The parseCellPtr() function fills in this structure
  48305. ** based on information extract from the raw disk page.
  48306. */
  48307. typedef struct CellInfo CellInfo;
  48308. struct CellInfo {
  48309. i64 nKey; /* The key for INTKEY tables, or nPayload otherwise */
  48310. u8 *pPayload; /* Pointer to the start of payload */
  48311. u32 nPayload; /* Bytes of payload */
  48312. u16 nLocal; /* Amount of payload held locally, not on overflow */
  48313. u16 iOverflow; /* Offset to overflow page number. Zero if no overflow */
  48314. u16 nSize; /* Size of the cell content on the main b-tree page */
  48315. };
  48316. /*
  48317. ** Maximum depth of an SQLite B-Tree structure. Any B-Tree deeper than
  48318. ** this will be declared corrupt. This value is calculated based on a
  48319. ** maximum database size of 2^31 pages a minimum fanout of 2 for a
  48320. ** root-node and 3 for all other internal nodes.
  48321. **
  48322. ** If a tree that appears to be taller than this is encountered, it is
  48323. ** assumed that the database is corrupt.
  48324. */
  48325. #define BTCURSOR_MAX_DEPTH 20
  48326. /*
  48327. ** A cursor is a pointer to a particular entry within a particular
  48328. ** b-tree within a database file.
  48329. **
  48330. ** The entry is identified by its MemPage and the index in
  48331. ** MemPage.aCell[] of the entry.
  48332. **
  48333. ** A single database file can be shared by two more database connections,
  48334. ** but cursors cannot be shared. Each cursor is associated with a
  48335. ** particular database connection identified BtCursor.pBtree.db.
  48336. **
  48337. ** Fields in this structure are accessed under the BtShared.mutex
  48338. ** found at self->pBt->mutex.
  48339. */
  48340. struct BtCursor {
  48341. Btree *pBtree; /* The Btree to which this cursor belongs */
  48342. BtShared *pBt; /* The BtShared this cursor points to */
  48343. BtCursor *pNext, *pPrev; /* Forms a linked list of all cursors */
  48344. struct KeyInfo *pKeyInfo; /* Argument passed to comparison function */
  48345. Pgno *aOverflow; /* Cache of overflow page locations */
  48346. CellInfo info; /* A parse of the cell we are pointing at */
  48347. i64 nKey; /* Size of pKey, or last integer key */
  48348. void *pKey; /* Saved key that was cursor last known position */
  48349. Pgno pgnoRoot; /* The root page of this tree */
  48350. int nOvflAlloc; /* Allocated size of aOverflow[] array */
  48351. int skipNext; /* Prev() is noop if negative. Next() is noop if positive */
  48352. u8 curFlags; /* zero or more BTCF_* flags defined below */
  48353. u8 eState; /* One of the CURSOR_XXX constants (see below) */
  48354. u8 hints; /* As configured by CursorSetHints() */
  48355. i16 iPage; /* Index of current page in apPage */
  48356. u16 aiIdx[BTCURSOR_MAX_DEPTH]; /* Current index in apPage[i] */
  48357. MemPage *apPage[BTCURSOR_MAX_DEPTH]; /* Pages from root to current page */
  48358. };
  48359. /*
  48360. ** Legal values for BtCursor.curFlags
  48361. */
  48362. #define BTCF_WriteFlag 0x01 /* True if a write cursor */
  48363. #define BTCF_ValidNKey 0x02 /* True if info.nKey is valid */
  48364. #define BTCF_ValidOvfl 0x04 /* True if aOverflow is valid */
  48365. #define BTCF_AtLast 0x08 /* Cursor is pointing ot the last entry */
  48366. #define BTCF_Incrblob 0x10 /* True if an incremental I/O handle */
  48367. /*
  48368. ** Potential values for BtCursor.eState.
  48369. **
  48370. ** CURSOR_INVALID:
  48371. ** Cursor does not point to a valid entry. This can happen (for example)
  48372. ** because the table is empty or because BtreeCursorFirst() has not been
  48373. ** called.
  48374. **
  48375. ** CURSOR_VALID:
  48376. ** Cursor points to a valid entry. getPayload() etc. may be called.
  48377. **
  48378. ** CURSOR_SKIPNEXT:
  48379. ** Cursor is valid except that the Cursor.skipNext field is non-zero
  48380. ** indicating that the next sqlite3BtreeNext() or sqlite3BtreePrevious()
  48381. ** operation should be a no-op.
  48382. **
  48383. ** CURSOR_REQUIRESEEK:
  48384. ** The table that this cursor was opened on still exists, but has been
  48385. ** modified since the cursor was last used. The cursor position is saved
  48386. ** in variables BtCursor.pKey and BtCursor.nKey. When a cursor is in
  48387. ** this state, restoreCursorPosition() can be called to attempt to
  48388. ** seek the cursor to the saved position.
  48389. **
  48390. ** CURSOR_FAULT:
  48391. ** An unrecoverable error (an I/O error or a malloc failure) has occurred
  48392. ** on a different connection that shares the BtShared cache with this
  48393. ** cursor. The error has left the cache in an inconsistent state.
  48394. ** Do nothing else with this cursor. Any attempt to use the cursor
  48395. ** should return the error code stored in BtCursor.skip
  48396. */
  48397. #define CURSOR_INVALID 0
  48398. #define CURSOR_VALID 1
  48399. #define CURSOR_SKIPNEXT 2
  48400. #define CURSOR_REQUIRESEEK 3
  48401. #define CURSOR_FAULT 4
  48402. /*
  48403. ** The database page the PENDING_BYTE occupies. This page is never used.
  48404. */
  48405. # define PENDING_BYTE_PAGE(pBt) PAGER_MJ_PGNO(pBt)
  48406. /*
  48407. ** These macros define the location of the pointer-map entry for a
  48408. ** database page. The first argument to each is the number of usable
  48409. ** bytes on each page of the database (often 1024). The second is the
  48410. ** page number to look up in the pointer map.
  48411. **
  48412. ** PTRMAP_PAGENO returns the database page number of the pointer-map
  48413. ** page that stores the required pointer. PTRMAP_PTROFFSET returns
  48414. ** the offset of the requested map entry.
  48415. **
  48416. ** If the pgno argument passed to PTRMAP_PAGENO is a pointer-map page,
  48417. ** then pgno is returned. So (pgno==PTRMAP_PAGENO(pgsz, pgno)) can be
  48418. ** used to test if pgno is a pointer-map page. PTRMAP_ISPAGE implements
  48419. ** this test.
  48420. */
  48421. #define PTRMAP_PAGENO(pBt, pgno) ptrmapPageno(pBt, pgno)
  48422. #define PTRMAP_PTROFFSET(pgptrmap, pgno) (5*(pgno-pgptrmap-1))
  48423. #define PTRMAP_ISPAGE(pBt, pgno) (PTRMAP_PAGENO((pBt),(pgno))==(pgno))
  48424. /*
  48425. ** The pointer map is a lookup table that identifies the parent page for
  48426. ** each child page in the database file. The parent page is the page that
  48427. ** contains a pointer to the child. Every page in the database contains
  48428. ** 0 or 1 parent pages. (In this context 'database page' refers
  48429. ** to any page that is not part of the pointer map itself.) Each pointer map
  48430. ** entry consists of a single byte 'type' and a 4 byte parent page number.
  48431. ** The PTRMAP_XXX identifiers below are the valid types.
  48432. **
  48433. ** The purpose of the pointer map is to facility moving pages from one
  48434. ** position in the file to another as part of autovacuum. When a page
  48435. ** is moved, the pointer in its parent must be updated to point to the
  48436. ** new location. The pointer map is used to locate the parent page quickly.
  48437. **
  48438. ** PTRMAP_ROOTPAGE: The database page is a root-page. The page-number is not
  48439. ** used in this case.
  48440. **
  48441. ** PTRMAP_FREEPAGE: The database page is an unused (free) page. The page-number
  48442. ** is not used in this case.
  48443. **
  48444. ** PTRMAP_OVERFLOW1: The database page is the first page in a list of
  48445. ** overflow pages. The page number identifies the page that
  48446. ** contains the cell with a pointer to this overflow page.
  48447. **
  48448. ** PTRMAP_OVERFLOW2: The database page is the second or later page in a list of
  48449. ** overflow pages. The page-number identifies the previous
  48450. ** page in the overflow page list.
  48451. **
  48452. ** PTRMAP_BTREE: The database page is a non-root btree page. The page number
  48453. ** identifies the parent page in the btree.
  48454. */
  48455. #define PTRMAP_ROOTPAGE 1
  48456. #define PTRMAP_FREEPAGE 2
  48457. #define PTRMAP_OVERFLOW1 3
  48458. #define PTRMAP_OVERFLOW2 4
  48459. #define PTRMAP_BTREE 5
  48460. /* A bunch of assert() statements to check the transaction state variables
  48461. ** of handle p (type Btree*) are internally consistent.
  48462. */
  48463. #define btreeIntegrity(p) \
  48464. assert( p->pBt->inTransaction!=TRANS_NONE || p->pBt->nTransaction==0 ); \
  48465. assert( p->pBt->inTransaction>=p->inTrans );
  48466. /*
  48467. ** The ISAUTOVACUUM macro is used within balance_nonroot() to determine
  48468. ** if the database supports auto-vacuum or not. Because it is used
  48469. ** within an expression that is an argument to another macro
  48470. ** (sqliteMallocRaw), it is not possible to use conditional compilation.
  48471. ** So, this macro is defined instead.
  48472. */
  48473. #ifndef SQLITE_OMIT_AUTOVACUUM
  48474. #define ISAUTOVACUUM (pBt->autoVacuum)
  48475. #else
  48476. #define ISAUTOVACUUM 0
  48477. #endif
  48478. /*
  48479. ** This structure is passed around through all the sanity checking routines
  48480. ** in order to keep track of some global state information.
  48481. **
  48482. ** The aRef[] array is allocated so that there is 1 bit for each page in
  48483. ** the database. As the integrity-check proceeds, for each page used in
  48484. ** the database the corresponding bit is set. This allows integrity-check to
  48485. ** detect pages that are used twice and orphaned pages (both of which
  48486. ** indicate corruption).
  48487. */
  48488. typedef struct IntegrityCk IntegrityCk;
  48489. struct IntegrityCk {
  48490. BtShared *pBt; /* The tree being checked out */
  48491. Pager *pPager; /* The associated pager. Also accessible by pBt->pPager */
  48492. u8 *aPgRef; /* 1 bit per page in the db (see above) */
  48493. Pgno nPage; /* Number of pages in the database */
  48494. int mxErr; /* Stop accumulating errors when this reaches zero */
  48495. int nErr; /* Number of messages written to zErrMsg so far */
  48496. int mallocFailed; /* A memory allocation error has occurred */
  48497. const char *zPfx; /* Error message prefix */
  48498. int v1, v2; /* Values for up to two %d fields in zPfx */
  48499. StrAccum errMsg; /* Accumulate the error message text here */
  48500. };
  48501. /*
  48502. ** Routines to read or write a two- and four-byte big-endian integer values.
  48503. */
  48504. #define get2byte(x) ((x)[0]<<8 | (x)[1])
  48505. #define put2byte(p,v) ((p)[0] = (u8)((v)>>8), (p)[1] = (u8)(v))
  48506. #define get4byte sqlite3Get4byte
  48507. #define put4byte sqlite3Put4byte
  48508. /************** End of btreeInt.h ********************************************/
  48509. /************** Continuing where we left off in btmutex.c ********************/
  48510. #ifndef SQLITE_OMIT_SHARED_CACHE
  48511. #if SQLITE_THREADSAFE
  48512. /*
  48513. ** Obtain the BtShared mutex associated with B-Tree handle p. Also,
  48514. ** set BtShared.db to the database handle associated with p and the
  48515. ** p->locked boolean to true.
  48516. */
  48517. static void lockBtreeMutex(Btree *p){
  48518. assert( p->locked==0 );
  48519. assert( sqlite3_mutex_notheld(p->pBt->mutex) );
  48520. assert( sqlite3_mutex_held(p->db->mutex) );
  48521. sqlite3_mutex_enter(p->pBt->mutex);
  48522. p->pBt->db = p->db;
  48523. p->locked = 1;
  48524. }
  48525. /*
  48526. ** Release the BtShared mutex associated with B-Tree handle p and
  48527. ** clear the p->locked boolean.
  48528. */
  48529. static void SQLITE_NOINLINE unlockBtreeMutex(Btree *p){
  48530. BtShared *pBt = p->pBt;
  48531. assert( p->locked==1 );
  48532. assert( sqlite3_mutex_held(pBt->mutex) );
  48533. assert( sqlite3_mutex_held(p->db->mutex) );
  48534. assert( p->db==pBt->db );
  48535. sqlite3_mutex_leave(pBt->mutex);
  48536. p->locked = 0;
  48537. }
  48538. /* Forward reference */
  48539. static void SQLITE_NOINLINE btreeLockCarefully(Btree *p);
  48540. /*
  48541. ** Enter a mutex on the given BTree object.
  48542. **
  48543. ** If the object is not sharable, then no mutex is ever required
  48544. ** and this routine is a no-op. The underlying mutex is non-recursive.
  48545. ** But we keep a reference count in Btree.wantToLock so the behavior
  48546. ** of this interface is recursive.
  48547. **
  48548. ** To avoid deadlocks, multiple Btrees are locked in the same order
  48549. ** by all database connections. The p->pNext is a list of other
  48550. ** Btrees belonging to the same database connection as the p Btree
  48551. ** which need to be locked after p. If we cannot get a lock on
  48552. ** p, then first unlock all of the others on p->pNext, then wait
  48553. ** for the lock to become available on p, then relock all of the
  48554. ** subsequent Btrees that desire a lock.
  48555. */
  48556. SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
  48557. /* Some basic sanity checking on the Btree. The list of Btrees
  48558. ** connected by pNext and pPrev should be in sorted order by
  48559. ** Btree.pBt value. All elements of the list should belong to
  48560. ** the same connection. Only shared Btrees are on the list. */
  48561. assert( p->pNext==0 || p->pNext->pBt>p->pBt );
  48562. assert( p->pPrev==0 || p->pPrev->pBt<p->pBt );
  48563. assert( p->pNext==0 || p->pNext->db==p->db );
  48564. assert( p->pPrev==0 || p->pPrev->db==p->db );
  48565. assert( p->sharable || (p->pNext==0 && p->pPrev==0) );
  48566. /* Check for locking consistency */
  48567. assert( !p->locked || p->wantToLock>0 );
  48568. assert( p->sharable || p->wantToLock==0 );
  48569. /* We should already hold a lock on the database connection */
  48570. assert( sqlite3_mutex_held(p->db->mutex) );
  48571. /* Unless the database is sharable and unlocked, then BtShared.db
  48572. ** should already be set correctly. */
  48573. assert( (p->locked==0 && p->sharable) || p->pBt->db==p->db );
  48574. if( !p->sharable ) return;
  48575. p->wantToLock++;
  48576. if( p->locked ) return;
  48577. btreeLockCarefully(p);
  48578. }
  48579. /* This is a helper function for sqlite3BtreeLock(). By moving
  48580. ** complex, but seldom used logic, out of sqlite3BtreeLock() and
  48581. ** into this routine, we avoid unnecessary stack pointer changes
  48582. ** and thus help the sqlite3BtreeLock() routine to run much faster
  48583. ** in the common case.
  48584. */
  48585. static void SQLITE_NOINLINE btreeLockCarefully(Btree *p){
  48586. Btree *pLater;
  48587. /* In most cases, we should be able to acquire the lock we
  48588. ** want without having to go through the ascending lock
  48589. ** procedure that follows. Just be sure not to block.
  48590. */
  48591. if( sqlite3_mutex_try(p->pBt->mutex)==SQLITE_OK ){
  48592. p->pBt->db = p->db;
  48593. p->locked = 1;
  48594. return;
  48595. }
  48596. /* To avoid deadlock, first release all locks with a larger
  48597. ** BtShared address. Then acquire our lock. Then reacquire
  48598. ** the other BtShared locks that we used to hold in ascending
  48599. ** order.
  48600. */
  48601. for(pLater=p->pNext; pLater; pLater=pLater->pNext){
  48602. assert( pLater->sharable );
  48603. assert( pLater->pNext==0 || pLater->pNext->pBt>pLater->pBt );
  48604. assert( !pLater->locked || pLater->wantToLock>0 );
  48605. if( pLater->locked ){
  48606. unlockBtreeMutex(pLater);
  48607. }
  48608. }
  48609. lockBtreeMutex(p);
  48610. for(pLater=p->pNext; pLater; pLater=pLater->pNext){
  48611. if( pLater->wantToLock ){
  48612. lockBtreeMutex(pLater);
  48613. }
  48614. }
  48615. }
  48616. /*
  48617. ** Exit the recursive mutex on a Btree.
  48618. */
  48619. SQLITE_PRIVATE void sqlite3BtreeLeave(Btree *p){
  48620. if( p->sharable ){
  48621. assert( p->wantToLock>0 );
  48622. p->wantToLock--;
  48623. if( p->wantToLock==0 ){
  48624. unlockBtreeMutex(p);
  48625. }
  48626. }
  48627. }
  48628. #ifndef NDEBUG
  48629. /*
  48630. ** Return true if the BtShared mutex is held on the btree, or if the
  48631. ** B-Tree is not marked as sharable.
  48632. **
  48633. ** This routine is used only from within assert() statements.
  48634. */
  48635. SQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree *p){
  48636. assert( p->sharable==0 || p->locked==0 || p->wantToLock>0 );
  48637. assert( p->sharable==0 || p->locked==0 || p->db==p->pBt->db );
  48638. assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->pBt->mutex) );
  48639. assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->db->mutex) );
  48640. return (p->sharable==0 || p->locked);
  48641. }
  48642. #endif
  48643. #ifndef SQLITE_OMIT_INCRBLOB
  48644. /*
  48645. ** Enter and leave a mutex on a Btree given a cursor owned by that
  48646. ** Btree. These entry points are used by incremental I/O and can be
  48647. ** omitted if that module is not used.
  48648. */
  48649. SQLITE_PRIVATE void sqlite3BtreeEnterCursor(BtCursor *pCur){
  48650. sqlite3BtreeEnter(pCur->pBtree);
  48651. }
  48652. SQLITE_PRIVATE void sqlite3BtreeLeaveCursor(BtCursor *pCur){
  48653. sqlite3BtreeLeave(pCur->pBtree);
  48654. }
  48655. #endif /* SQLITE_OMIT_INCRBLOB */
  48656. /*
  48657. ** Enter the mutex on every Btree associated with a database
  48658. ** connection. This is needed (for example) prior to parsing
  48659. ** a statement since we will be comparing table and column names
  48660. ** against all schemas and we do not want those schemas being
  48661. ** reset out from under us.
  48662. **
  48663. ** There is a corresponding leave-all procedures.
  48664. **
  48665. ** Enter the mutexes in accending order by BtShared pointer address
  48666. ** to avoid the possibility of deadlock when two threads with
  48667. ** two or more btrees in common both try to lock all their btrees
  48668. ** at the same instant.
  48669. */
  48670. SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
  48671. int i;
  48672. Btree *p;
  48673. assert( sqlite3_mutex_held(db->mutex) );
  48674. for(i=0; i<db->nDb; i++){
  48675. p = db->aDb[i].pBt;
  48676. if( p ) sqlite3BtreeEnter(p);
  48677. }
  48678. }
  48679. SQLITE_PRIVATE void sqlite3BtreeLeaveAll(sqlite3 *db){
  48680. int i;
  48681. Btree *p;
  48682. assert( sqlite3_mutex_held(db->mutex) );
  48683. for(i=0; i<db->nDb; i++){
  48684. p = db->aDb[i].pBt;
  48685. if( p ) sqlite3BtreeLeave(p);
  48686. }
  48687. }
  48688. /*
  48689. ** Return true if a particular Btree requires a lock. Return FALSE if
  48690. ** no lock is ever required since it is not sharable.
  48691. */
  48692. SQLITE_PRIVATE int sqlite3BtreeSharable(Btree *p){
  48693. return p->sharable;
  48694. }
  48695. #ifndef NDEBUG
  48696. /*
  48697. ** Return true if the current thread holds the database connection
  48698. ** mutex and all required BtShared mutexes.
  48699. **
  48700. ** This routine is used inside assert() statements only.
  48701. */
  48702. SQLITE_PRIVATE int sqlite3BtreeHoldsAllMutexes(sqlite3 *db){
  48703. int i;
  48704. if( !sqlite3_mutex_held(db->mutex) ){
  48705. return 0;
  48706. }
  48707. for(i=0; i<db->nDb; i++){
  48708. Btree *p;
  48709. p = db->aDb[i].pBt;
  48710. if( p && p->sharable &&
  48711. (p->wantToLock==0 || !sqlite3_mutex_held(p->pBt->mutex)) ){
  48712. return 0;
  48713. }
  48714. }
  48715. return 1;
  48716. }
  48717. #endif /* NDEBUG */
  48718. #ifndef NDEBUG
  48719. /*
  48720. ** Return true if the correct mutexes are held for accessing the
  48721. ** db->aDb[iDb].pSchema structure. The mutexes required for schema
  48722. ** access are:
  48723. **
  48724. ** (1) The mutex on db
  48725. ** (2) if iDb!=1, then the mutex on db->aDb[iDb].pBt.
  48726. **
  48727. ** If pSchema is not NULL, then iDb is computed from pSchema and
  48728. ** db using sqlite3SchemaToIndex().
  48729. */
  48730. SQLITE_PRIVATE int sqlite3SchemaMutexHeld(sqlite3 *db, int iDb, Schema *pSchema){
  48731. Btree *p;
  48732. assert( db!=0 );
  48733. if( pSchema ) iDb = sqlite3SchemaToIndex(db, pSchema);
  48734. assert( iDb>=0 && iDb<db->nDb );
  48735. if( !sqlite3_mutex_held(db->mutex) ) return 0;
  48736. if( iDb==1 ) return 1;
  48737. p = db->aDb[iDb].pBt;
  48738. assert( p!=0 );
  48739. return p->sharable==0 || p->locked==1;
  48740. }
  48741. #endif /* NDEBUG */
  48742. #else /* SQLITE_THREADSAFE>0 above. SQLITE_THREADSAFE==0 below */
  48743. /*
  48744. ** The following are special cases for mutex enter routines for use
  48745. ** in single threaded applications that use shared cache. Except for
  48746. ** these two routines, all mutex operations are no-ops in that case and
  48747. ** are null #defines in btree.h.
  48748. **
  48749. ** If shared cache is disabled, then all btree mutex routines, including
  48750. ** the ones below, are no-ops and are null #defines in btree.h.
  48751. */
  48752. SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
  48753. p->pBt->db = p->db;
  48754. }
  48755. SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
  48756. int i;
  48757. for(i=0; i<db->nDb; i++){
  48758. Btree *p = db->aDb[i].pBt;
  48759. if( p ){
  48760. p->pBt->db = p->db;
  48761. }
  48762. }
  48763. }
  48764. #endif /* if SQLITE_THREADSAFE */
  48765. #endif /* ifndef SQLITE_OMIT_SHARED_CACHE */
  48766. /************** End of btmutex.c *********************************************/
  48767. /************** Begin file btree.c *******************************************/
  48768. /*
  48769. ** 2004 April 6
  48770. **
  48771. ** The author disclaims copyright to this source code. In place of
  48772. ** a legal notice, here is a blessing:
  48773. **
  48774. ** May you do good and not evil.
  48775. ** May you find forgiveness for yourself and forgive others.
  48776. ** May you share freely, never taking more than you give.
  48777. **
  48778. *************************************************************************
  48779. ** This file implements an external (disk-based) database using BTrees.
  48780. ** See the header comment on "btreeInt.h" for additional information.
  48781. ** Including a description of file format and an overview of operation.
  48782. */
  48783. /*
  48784. ** The header string that appears at the beginning of every
  48785. ** SQLite database.
  48786. */
  48787. static const char zMagicHeader[] = SQLITE_FILE_HEADER;
  48788. /*
  48789. ** Set this global variable to 1 to enable tracing using the TRACE
  48790. ** macro.
  48791. */
  48792. #if 0
  48793. int sqlite3BtreeTrace=1; /* True to enable tracing */
  48794. # define TRACE(X) if(sqlite3BtreeTrace){printf X;fflush(stdout);}
  48795. #else
  48796. # define TRACE(X)
  48797. #endif
  48798. /*
  48799. ** Extract a 2-byte big-endian integer from an array of unsigned bytes.
  48800. ** But if the value is zero, make it 65536.
  48801. **
  48802. ** This routine is used to extract the "offset to cell content area" value
  48803. ** from the header of a btree page. If the page size is 65536 and the page
  48804. ** is empty, the offset should be 65536, but the 2-byte value stores zero.
  48805. ** This routine makes the necessary adjustment to 65536.
  48806. */
  48807. #define get2byteNotZero(X) (((((int)get2byte(X))-1)&0xffff)+1)
  48808. /*
  48809. ** Values passed as the 5th argument to allocateBtreePage()
  48810. */
  48811. #define BTALLOC_ANY 0 /* Allocate any page */
  48812. #define BTALLOC_EXACT 1 /* Allocate exact page if possible */
  48813. #define BTALLOC_LE 2 /* Allocate any page <= the parameter */
  48814. /*
  48815. ** Macro IfNotOmitAV(x) returns (x) if SQLITE_OMIT_AUTOVACUUM is not
  48816. ** defined, or 0 if it is. For example:
  48817. **
  48818. ** bIncrVacuum = IfNotOmitAV(pBtShared->incrVacuum);
  48819. */
  48820. #ifndef SQLITE_OMIT_AUTOVACUUM
  48821. #define IfNotOmitAV(expr) (expr)
  48822. #else
  48823. #define IfNotOmitAV(expr) 0
  48824. #endif
  48825. #ifndef SQLITE_OMIT_SHARED_CACHE
  48826. /*
  48827. ** A list of BtShared objects that are eligible for participation
  48828. ** in shared cache. This variable has file scope during normal builds,
  48829. ** but the test harness needs to access it so we make it global for
  48830. ** test builds.
  48831. **
  48832. ** Access to this variable is protected by SQLITE_MUTEX_STATIC_MASTER.
  48833. */
  48834. #ifdef SQLITE_TEST
  48835. SQLITE_PRIVATE BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
  48836. #else
  48837. static BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
  48838. #endif
  48839. #endif /* SQLITE_OMIT_SHARED_CACHE */
  48840. #ifndef SQLITE_OMIT_SHARED_CACHE
  48841. /*
  48842. ** Enable or disable the shared pager and schema features.
  48843. **
  48844. ** This routine has no effect on existing database connections.
  48845. ** The shared cache setting effects only future calls to
  48846. ** sqlite3_open(), sqlite3_open16(), or sqlite3_open_v2().
  48847. */
  48848. SQLITE_API int sqlite3_enable_shared_cache(int enable){
  48849. sqlite3GlobalConfig.sharedCacheEnabled = enable;
  48850. return SQLITE_OK;
  48851. }
  48852. #endif
  48853. #ifdef SQLITE_OMIT_SHARED_CACHE
  48854. /*
  48855. ** The functions querySharedCacheTableLock(), setSharedCacheTableLock(),
  48856. ** and clearAllSharedCacheTableLocks()
  48857. ** manipulate entries in the BtShared.pLock linked list used to store
  48858. ** shared-cache table level locks. If the library is compiled with the
  48859. ** shared-cache feature disabled, then there is only ever one user
  48860. ** of each BtShared structure and so this locking is not necessary.
  48861. ** So define the lock related functions as no-ops.
  48862. */
  48863. #define querySharedCacheTableLock(a,b,c) SQLITE_OK
  48864. #define setSharedCacheTableLock(a,b,c) SQLITE_OK
  48865. #define clearAllSharedCacheTableLocks(a)
  48866. #define downgradeAllSharedCacheTableLocks(a)
  48867. #define hasSharedCacheTableLock(a,b,c,d) 1
  48868. #define hasReadConflicts(a, b) 0
  48869. #endif
  48870. #ifndef SQLITE_OMIT_SHARED_CACHE
  48871. #ifdef SQLITE_DEBUG
  48872. /*
  48873. **** This function is only used as part of an assert() statement. ***
  48874. **
  48875. ** Check to see if pBtree holds the required locks to read or write to the
  48876. ** table with root page iRoot. Return 1 if it does and 0 if not.
  48877. **
  48878. ** For example, when writing to a table with root-page iRoot via
  48879. ** Btree connection pBtree:
  48880. **
  48881. ** assert( hasSharedCacheTableLock(pBtree, iRoot, 0, WRITE_LOCK) );
  48882. **
  48883. ** When writing to an index that resides in a sharable database, the
  48884. ** caller should have first obtained a lock specifying the root page of
  48885. ** the corresponding table. This makes things a bit more complicated,
  48886. ** as this module treats each table as a separate structure. To determine
  48887. ** the table corresponding to the index being written, this
  48888. ** function has to search through the database schema.
  48889. **
  48890. ** Instead of a lock on the table/index rooted at page iRoot, the caller may
  48891. ** hold a write-lock on the schema table (root page 1). This is also
  48892. ** acceptable.
  48893. */
  48894. static int hasSharedCacheTableLock(
  48895. Btree *pBtree, /* Handle that must hold lock */
  48896. Pgno iRoot, /* Root page of b-tree */
  48897. int isIndex, /* True if iRoot is the root of an index b-tree */
  48898. int eLockType /* Required lock type (READ_LOCK or WRITE_LOCK) */
  48899. ){
  48900. Schema *pSchema = (Schema *)pBtree->pBt->pSchema;
  48901. Pgno iTab = 0;
  48902. BtLock *pLock;
  48903. /* If this database is not shareable, or if the client is reading
  48904. ** and has the read-uncommitted flag set, then no lock is required.
  48905. ** Return true immediately.
  48906. */
  48907. if( (pBtree->sharable==0)
  48908. || (eLockType==READ_LOCK && (pBtree->db->flags & SQLITE_ReadUncommitted))
  48909. ){
  48910. return 1;
  48911. }
  48912. /* If the client is reading or writing an index and the schema is
  48913. ** not loaded, then it is too difficult to actually check to see if
  48914. ** the correct locks are held. So do not bother - just return true.
  48915. ** This case does not come up very often anyhow.
  48916. */
  48917. if( isIndex && (!pSchema || (pSchema->schemaFlags&DB_SchemaLoaded)==0) ){
  48918. return 1;
  48919. }
  48920. /* Figure out the root-page that the lock should be held on. For table
  48921. ** b-trees, this is just the root page of the b-tree being read or
  48922. ** written. For index b-trees, it is the root page of the associated
  48923. ** table. */
  48924. if( isIndex ){
  48925. HashElem *p;
  48926. for(p=sqliteHashFirst(&pSchema->idxHash); p; p=sqliteHashNext(p)){
  48927. Index *pIdx = (Index *)sqliteHashData(p);
  48928. if( pIdx->tnum==(int)iRoot ){
  48929. iTab = pIdx->pTable->tnum;
  48930. }
  48931. }
  48932. }else{
  48933. iTab = iRoot;
  48934. }
  48935. /* Search for the required lock. Either a write-lock on root-page iTab, a
  48936. ** write-lock on the schema table, or (if the client is reading) a
  48937. ** read-lock on iTab will suffice. Return 1 if any of these are found. */
  48938. for(pLock=pBtree->pBt->pLock; pLock; pLock=pLock->pNext){
  48939. if( pLock->pBtree==pBtree
  48940. && (pLock->iTable==iTab || (pLock->eLock==WRITE_LOCK && pLock->iTable==1))
  48941. && pLock->eLock>=eLockType
  48942. ){
  48943. return 1;
  48944. }
  48945. }
  48946. /* Failed to find the required lock. */
  48947. return 0;
  48948. }
  48949. #endif /* SQLITE_DEBUG */
  48950. #ifdef SQLITE_DEBUG
  48951. /*
  48952. **** This function may be used as part of assert() statements only. ****
  48953. **
  48954. ** Return true if it would be illegal for pBtree to write into the
  48955. ** table or index rooted at iRoot because other shared connections are
  48956. ** simultaneously reading that same table or index.
  48957. **
  48958. ** It is illegal for pBtree to write if some other Btree object that
  48959. ** shares the same BtShared object is currently reading or writing
  48960. ** the iRoot table. Except, if the other Btree object has the
  48961. ** read-uncommitted flag set, then it is OK for the other object to
  48962. ** have a read cursor.
  48963. **
  48964. ** For example, before writing to any part of the table or index
  48965. ** rooted at page iRoot, one should call:
  48966. **
  48967. ** assert( !hasReadConflicts(pBtree, iRoot) );
  48968. */
  48969. static int hasReadConflicts(Btree *pBtree, Pgno iRoot){
  48970. BtCursor *p;
  48971. for(p=pBtree->pBt->pCursor; p; p=p->pNext){
  48972. if( p->pgnoRoot==iRoot
  48973. && p->pBtree!=pBtree
  48974. && 0==(p->pBtree->db->flags & SQLITE_ReadUncommitted)
  48975. ){
  48976. return 1;
  48977. }
  48978. }
  48979. return 0;
  48980. }
  48981. #endif /* #ifdef SQLITE_DEBUG */
  48982. /*
  48983. ** Query to see if Btree handle p may obtain a lock of type eLock
  48984. ** (READ_LOCK or WRITE_LOCK) on the table with root-page iTab. Return
  48985. ** SQLITE_OK if the lock may be obtained (by calling
  48986. ** setSharedCacheTableLock()), or SQLITE_LOCKED if not.
  48987. */
  48988. static int querySharedCacheTableLock(Btree *p, Pgno iTab, u8 eLock){
  48989. BtShared *pBt = p->pBt;
  48990. BtLock *pIter;
  48991. assert( sqlite3BtreeHoldsMutex(p) );
  48992. assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
  48993. assert( p->db!=0 );
  48994. assert( !(p->db->flags&SQLITE_ReadUncommitted)||eLock==WRITE_LOCK||iTab==1 );
  48995. /* If requesting a write-lock, then the Btree must have an open write
  48996. ** transaction on this file. And, obviously, for this to be so there
  48997. ** must be an open write transaction on the file itself.
  48998. */
  48999. assert( eLock==READ_LOCK || (p==pBt->pWriter && p->inTrans==TRANS_WRITE) );
  49000. assert( eLock==READ_LOCK || pBt->inTransaction==TRANS_WRITE );
  49001. /* This routine is a no-op if the shared-cache is not enabled */
  49002. if( !p->sharable ){
  49003. return SQLITE_OK;
  49004. }
  49005. /* If some other connection is holding an exclusive lock, the
  49006. ** requested lock may not be obtained.
  49007. */
  49008. if( pBt->pWriter!=p && (pBt->btsFlags & BTS_EXCLUSIVE)!=0 ){
  49009. sqlite3ConnectionBlocked(p->db, pBt->pWriter->db);
  49010. return SQLITE_LOCKED_SHAREDCACHE;
  49011. }
  49012. for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
  49013. /* The condition (pIter->eLock!=eLock) in the following if(...)
  49014. ** statement is a simplification of:
  49015. **
  49016. ** (eLock==WRITE_LOCK || pIter->eLock==WRITE_LOCK)
  49017. **
  49018. ** since we know that if eLock==WRITE_LOCK, then no other connection
  49019. ** may hold a WRITE_LOCK on any table in this file (since there can
  49020. ** only be a single writer).
  49021. */
  49022. assert( pIter->eLock==READ_LOCK || pIter->eLock==WRITE_LOCK );
  49023. assert( eLock==READ_LOCK || pIter->pBtree==p || pIter->eLock==READ_LOCK);
  49024. if( pIter->pBtree!=p && pIter->iTable==iTab && pIter->eLock!=eLock ){
  49025. sqlite3ConnectionBlocked(p->db, pIter->pBtree->db);
  49026. if( eLock==WRITE_LOCK ){
  49027. assert( p==pBt->pWriter );
  49028. pBt->btsFlags |= BTS_PENDING;
  49029. }
  49030. return SQLITE_LOCKED_SHAREDCACHE;
  49031. }
  49032. }
  49033. return SQLITE_OK;
  49034. }
  49035. #endif /* !SQLITE_OMIT_SHARED_CACHE */
  49036. #ifndef SQLITE_OMIT_SHARED_CACHE
  49037. /*
  49038. ** Add a lock on the table with root-page iTable to the shared-btree used
  49039. ** by Btree handle p. Parameter eLock must be either READ_LOCK or
  49040. ** WRITE_LOCK.
  49041. **
  49042. ** This function assumes the following:
  49043. **
  49044. ** (a) The specified Btree object p is connected to a sharable
  49045. ** database (one with the BtShared.sharable flag set), and
  49046. **
  49047. ** (b) No other Btree objects hold a lock that conflicts
  49048. ** with the requested lock (i.e. querySharedCacheTableLock() has
  49049. ** already been called and returned SQLITE_OK).
  49050. **
  49051. ** SQLITE_OK is returned if the lock is added successfully. SQLITE_NOMEM
  49052. ** is returned if a malloc attempt fails.
  49053. */
  49054. static int setSharedCacheTableLock(Btree *p, Pgno iTable, u8 eLock){
  49055. BtShared *pBt = p->pBt;
  49056. BtLock *pLock = 0;
  49057. BtLock *pIter;
  49058. assert( sqlite3BtreeHoldsMutex(p) );
  49059. assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
  49060. assert( p->db!=0 );
  49061. /* A connection with the read-uncommitted flag set will never try to
  49062. ** obtain a read-lock using this function. The only read-lock obtained
  49063. ** by a connection in read-uncommitted mode is on the sqlite_master
  49064. ** table, and that lock is obtained in BtreeBeginTrans(). */
  49065. assert( 0==(p->db->flags&SQLITE_ReadUncommitted) || eLock==WRITE_LOCK );
  49066. /* This function should only be called on a sharable b-tree after it
  49067. ** has been determined that no other b-tree holds a conflicting lock. */
  49068. assert( p->sharable );
  49069. assert( SQLITE_OK==querySharedCacheTableLock(p, iTable, eLock) );
  49070. /* First search the list for an existing lock on this table. */
  49071. for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
  49072. if( pIter->iTable==iTable && pIter->pBtree==p ){
  49073. pLock = pIter;
  49074. break;
  49075. }
  49076. }
  49077. /* If the above search did not find a BtLock struct associating Btree p
  49078. ** with table iTable, allocate one and link it into the list.
  49079. */
  49080. if( !pLock ){
  49081. pLock = (BtLock *)sqlite3MallocZero(sizeof(BtLock));
  49082. if( !pLock ){
  49083. return SQLITE_NOMEM;
  49084. }
  49085. pLock->iTable = iTable;
  49086. pLock->pBtree = p;
  49087. pLock->pNext = pBt->pLock;
  49088. pBt->pLock = pLock;
  49089. }
  49090. /* Set the BtLock.eLock variable to the maximum of the current lock
  49091. ** and the requested lock. This means if a write-lock was already held
  49092. ** and a read-lock requested, we don't incorrectly downgrade the lock.
  49093. */
  49094. assert( WRITE_LOCK>READ_LOCK );
  49095. if( eLock>pLock->eLock ){
  49096. pLock->eLock = eLock;
  49097. }
  49098. return SQLITE_OK;
  49099. }
  49100. #endif /* !SQLITE_OMIT_SHARED_CACHE */
  49101. #ifndef SQLITE_OMIT_SHARED_CACHE
  49102. /*
  49103. ** Release all the table locks (locks obtained via calls to
  49104. ** the setSharedCacheTableLock() procedure) held by Btree object p.
  49105. **
  49106. ** This function assumes that Btree p has an open read or write
  49107. ** transaction. If it does not, then the BTS_PENDING flag
  49108. ** may be incorrectly cleared.
  49109. */
  49110. static void clearAllSharedCacheTableLocks(Btree *p){
  49111. BtShared *pBt = p->pBt;
  49112. BtLock **ppIter = &pBt->pLock;
  49113. assert( sqlite3BtreeHoldsMutex(p) );
  49114. assert( p->sharable || 0==*ppIter );
  49115. assert( p->inTrans>0 );
  49116. while( *ppIter ){
  49117. BtLock *pLock = *ppIter;
  49118. assert( (pBt->btsFlags & BTS_EXCLUSIVE)==0 || pBt->pWriter==pLock->pBtree );
  49119. assert( pLock->pBtree->inTrans>=pLock->eLock );
  49120. if( pLock->pBtree==p ){
  49121. *ppIter = pLock->pNext;
  49122. assert( pLock->iTable!=1 || pLock==&p->lock );
  49123. if( pLock->iTable!=1 ){
  49124. sqlite3_free(pLock);
  49125. }
  49126. }else{
  49127. ppIter = &pLock->pNext;
  49128. }
  49129. }
  49130. assert( (pBt->btsFlags & BTS_PENDING)==0 || pBt->pWriter );
  49131. if( pBt->pWriter==p ){
  49132. pBt->pWriter = 0;
  49133. pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
  49134. }else if( pBt->nTransaction==2 ){
  49135. /* This function is called when Btree p is concluding its
  49136. ** transaction. If there currently exists a writer, and p is not
  49137. ** that writer, then the number of locks held by connections other
  49138. ** than the writer must be about to drop to zero. In this case
  49139. ** set the BTS_PENDING flag to 0.
  49140. **
  49141. ** If there is not currently a writer, then BTS_PENDING must
  49142. ** be zero already. So this next line is harmless in that case.
  49143. */
  49144. pBt->btsFlags &= ~BTS_PENDING;
  49145. }
  49146. }
  49147. /*
  49148. ** This function changes all write-locks held by Btree p into read-locks.
  49149. */
  49150. static void downgradeAllSharedCacheTableLocks(Btree *p){
  49151. BtShared *pBt = p->pBt;
  49152. if( pBt->pWriter==p ){
  49153. BtLock *pLock;
  49154. pBt->pWriter = 0;
  49155. pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
  49156. for(pLock=pBt->pLock; pLock; pLock=pLock->pNext){
  49157. assert( pLock->eLock==READ_LOCK || pLock->pBtree==p );
  49158. pLock->eLock = READ_LOCK;
  49159. }
  49160. }
  49161. }
  49162. #endif /* SQLITE_OMIT_SHARED_CACHE */
  49163. static void releasePage(MemPage *pPage); /* Forward reference */
  49164. /*
  49165. ***** This routine is used inside of assert() only ****
  49166. **
  49167. ** Verify that the cursor holds the mutex on its BtShared
  49168. */
  49169. #ifdef SQLITE_DEBUG
  49170. static int cursorHoldsMutex(BtCursor *p){
  49171. return sqlite3_mutex_held(p->pBt->mutex);
  49172. }
  49173. #endif
  49174. /*
  49175. ** Invalidate the overflow cache of the cursor passed as the first argument.
  49176. ** on the shared btree structure pBt.
  49177. */
  49178. #define invalidateOverflowCache(pCur) (pCur->curFlags &= ~BTCF_ValidOvfl)
  49179. /*
  49180. ** Invalidate the overflow page-list cache for all cursors opened
  49181. ** on the shared btree structure pBt.
  49182. */
  49183. static void invalidateAllOverflowCache(BtShared *pBt){
  49184. BtCursor *p;
  49185. assert( sqlite3_mutex_held(pBt->mutex) );
  49186. for(p=pBt->pCursor; p; p=p->pNext){
  49187. invalidateOverflowCache(p);
  49188. }
  49189. }
  49190. #ifndef SQLITE_OMIT_INCRBLOB
  49191. /*
  49192. ** This function is called before modifying the contents of a table
  49193. ** to invalidate any incrblob cursors that are open on the
  49194. ** row or one of the rows being modified.
  49195. **
  49196. ** If argument isClearTable is true, then the entire contents of the
  49197. ** table is about to be deleted. In this case invalidate all incrblob
  49198. ** cursors open on any row within the table with root-page pgnoRoot.
  49199. **
  49200. ** Otherwise, if argument isClearTable is false, then the row with
  49201. ** rowid iRow is being replaced or deleted. In this case invalidate
  49202. ** only those incrblob cursors open on that specific row.
  49203. */
  49204. static void invalidateIncrblobCursors(
  49205. Btree *pBtree, /* The database file to check */
  49206. i64 iRow, /* The rowid that might be changing */
  49207. int isClearTable /* True if all rows are being deleted */
  49208. ){
  49209. BtCursor *p;
  49210. BtShared *pBt = pBtree->pBt;
  49211. assert( sqlite3BtreeHoldsMutex(pBtree) );
  49212. for(p=pBt->pCursor; p; p=p->pNext){
  49213. if( (p->curFlags & BTCF_Incrblob)!=0
  49214. && (isClearTable || p->info.nKey==iRow)
  49215. ){
  49216. p->eState = CURSOR_INVALID;
  49217. }
  49218. }
  49219. }
  49220. #else
  49221. /* Stub function when INCRBLOB is omitted */
  49222. #define invalidateIncrblobCursors(x,y,z)
  49223. #endif /* SQLITE_OMIT_INCRBLOB */
  49224. /*
  49225. ** Set bit pgno of the BtShared.pHasContent bitvec. This is called
  49226. ** when a page that previously contained data becomes a free-list leaf
  49227. ** page.
  49228. **
  49229. ** The BtShared.pHasContent bitvec exists to work around an obscure
  49230. ** bug caused by the interaction of two useful IO optimizations surrounding
  49231. ** free-list leaf pages:
  49232. **
  49233. ** 1) When all data is deleted from a page and the page becomes
  49234. ** a free-list leaf page, the page is not written to the database
  49235. ** (as free-list leaf pages contain no meaningful data). Sometimes
  49236. ** such a page is not even journalled (as it will not be modified,
  49237. ** why bother journalling it?).
  49238. **
  49239. ** 2) When a free-list leaf page is reused, its content is not read
  49240. ** from the database or written to the journal file (why should it
  49241. ** be, if it is not at all meaningful?).
  49242. **
  49243. ** By themselves, these optimizations work fine and provide a handy
  49244. ** performance boost to bulk delete or insert operations. However, if
  49245. ** a page is moved to the free-list and then reused within the same
  49246. ** transaction, a problem comes up. If the page is not journalled when
  49247. ** it is moved to the free-list and it is also not journalled when it
  49248. ** is extracted from the free-list and reused, then the original data
  49249. ** may be lost. In the event of a rollback, it may not be possible
  49250. ** to restore the database to its original configuration.
  49251. **
  49252. ** The solution is the BtShared.pHasContent bitvec. Whenever a page is
  49253. ** moved to become a free-list leaf page, the corresponding bit is
  49254. ** set in the bitvec. Whenever a leaf page is extracted from the free-list,
  49255. ** optimization 2 above is omitted if the corresponding bit is already
  49256. ** set in BtShared.pHasContent. The contents of the bitvec are cleared
  49257. ** at the end of every transaction.
  49258. */
  49259. static int btreeSetHasContent(BtShared *pBt, Pgno pgno){
  49260. int rc = SQLITE_OK;
  49261. if( !pBt->pHasContent ){
  49262. assert( pgno<=pBt->nPage );
  49263. pBt->pHasContent = sqlite3BitvecCreate(pBt->nPage);
  49264. if( !pBt->pHasContent ){
  49265. rc = SQLITE_NOMEM;
  49266. }
  49267. }
  49268. if( rc==SQLITE_OK && pgno<=sqlite3BitvecSize(pBt->pHasContent) ){
  49269. rc = sqlite3BitvecSet(pBt->pHasContent, pgno);
  49270. }
  49271. return rc;
  49272. }
  49273. /*
  49274. ** Query the BtShared.pHasContent vector.
  49275. **
  49276. ** This function is called when a free-list leaf page is removed from the
  49277. ** free-list for reuse. It returns false if it is safe to retrieve the
  49278. ** page from the pager layer with the 'no-content' flag set. True otherwise.
  49279. */
  49280. static int btreeGetHasContent(BtShared *pBt, Pgno pgno){
  49281. Bitvec *p = pBt->pHasContent;
  49282. return (p && (pgno>sqlite3BitvecSize(p) || sqlite3BitvecTest(p, pgno)));
  49283. }
  49284. /*
  49285. ** Clear (destroy) the BtShared.pHasContent bitvec. This should be
  49286. ** invoked at the conclusion of each write-transaction.
  49287. */
  49288. static void btreeClearHasContent(BtShared *pBt){
  49289. sqlite3BitvecDestroy(pBt->pHasContent);
  49290. pBt->pHasContent = 0;
  49291. }
  49292. /*
  49293. ** Release all of the apPage[] pages for a cursor.
  49294. */
  49295. static void btreeReleaseAllCursorPages(BtCursor *pCur){
  49296. int i;
  49297. for(i=0; i<=pCur->iPage; i++){
  49298. releasePage(pCur->apPage[i]);
  49299. pCur->apPage[i] = 0;
  49300. }
  49301. pCur->iPage = -1;
  49302. }
  49303. /*
  49304. ** Save the current cursor position in the variables BtCursor.nKey
  49305. ** and BtCursor.pKey. The cursor's state is set to CURSOR_REQUIRESEEK.
  49306. **
  49307. ** The caller must ensure that the cursor is valid (has eState==CURSOR_VALID)
  49308. ** prior to calling this routine.
  49309. */
  49310. static int saveCursorPosition(BtCursor *pCur){
  49311. int rc;
  49312. assert( CURSOR_VALID==pCur->eState );
  49313. assert( 0==pCur->pKey );
  49314. assert( cursorHoldsMutex(pCur) );
  49315. rc = sqlite3BtreeKeySize(pCur, &pCur->nKey);
  49316. assert( rc==SQLITE_OK ); /* KeySize() cannot fail */
  49317. /* If this is an intKey table, then the above call to BtreeKeySize()
  49318. ** stores the integer key in pCur->nKey. In this case this value is
  49319. ** all that is required. Otherwise, if pCur is not open on an intKey
  49320. ** table, then malloc space for and store the pCur->nKey bytes of key
  49321. ** data.
  49322. */
  49323. if( 0==pCur->apPage[0]->intKey ){
  49324. void *pKey = sqlite3Malloc( pCur->nKey );
  49325. if( pKey ){
  49326. rc = sqlite3BtreeKey(pCur, 0, (int)pCur->nKey, pKey);
  49327. if( rc==SQLITE_OK ){
  49328. pCur->pKey = pKey;
  49329. }else{
  49330. sqlite3_free(pKey);
  49331. }
  49332. }else{
  49333. rc = SQLITE_NOMEM;
  49334. }
  49335. }
  49336. assert( !pCur->apPage[0]->intKey || !pCur->pKey );
  49337. if( rc==SQLITE_OK ){
  49338. btreeReleaseAllCursorPages(pCur);
  49339. pCur->eState = CURSOR_REQUIRESEEK;
  49340. }
  49341. invalidateOverflowCache(pCur);
  49342. return rc;
  49343. }
  49344. /* Forward reference */
  49345. static int SQLITE_NOINLINE saveCursorsOnList(BtCursor*,Pgno,BtCursor*);
  49346. /*
  49347. ** Save the positions of all cursors (except pExcept) that are open on
  49348. ** the table with root-page iRoot. "Saving the cursor position" means that
  49349. ** the location in the btree is remembered in such a way that it can be
  49350. ** moved back to the same spot after the btree has been modified. This
  49351. ** routine is called just before cursor pExcept is used to modify the
  49352. ** table, for example in BtreeDelete() or BtreeInsert().
  49353. **
  49354. ** Implementation note: This routine merely checks to see if any cursors
  49355. ** need to be saved. It calls out to saveCursorsOnList() in the (unusual)
  49356. ** event that cursors are in need to being saved.
  49357. */
  49358. static int saveAllCursors(BtShared *pBt, Pgno iRoot, BtCursor *pExcept){
  49359. BtCursor *p;
  49360. assert( sqlite3_mutex_held(pBt->mutex) );
  49361. assert( pExcept==0 || pExcept->pBt==pBt );
  49362. for(p=pBt->pCursor; p; p=p->pNext){
  49363. if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) ) break;
  49364. }
  49365. return p ? saveCursorsOnList(p, iRoot, pExcept) : SQLITE_OK;
  49366. }
  49367. /* This helper routine to saveAllCursors does the actual work of saving
  49368. ** the cursors if and when a cursor is found that actually requires saving.
  49369. ** The common case is that no cursors need to be saved, so this routine is
  49370. ** broken out from its caller to avoid unnecessary stack pointer movement.
  49371. */
  49372. static int SQLITE_NOINLINE saveCursorsOnList(
  49373. BtCursor *p, /* The first cursor that needs saving */
  49374. Pgno iRoot, /* Only save cursor with this iRoot. Save all if zero */
  49375. BtCursor *pExcept /* Do not save this cursor */
  49376. ){
  49377. do{
  49378. if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) ){
  49379. if( p->eState==CURSOR_VALID ){
  49380. int rc = saveCursorPosition(p);
  49381. if( SQLITE_OK!=rc ){
  49382. return rc;
  49383. }
  49384. }else{
  49385. testcase( p->iPage>0 );
  49386. btreeReleaseAllCursorPages(p);
  49387. }
  49388. }
  49389. p = p->pNext;
  49390. }while( p );
  49391. return SQLITE_OK;
  49392. }
  49393. /*
  49394. ** Clear the current cursor position.
  49395. */
  49396. SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *pCur){
  49397. assert( cursorHoldsMutex(pCur) );
  49398. sqlite3_free(pCur->pKey);
  49399. pCur->pKey = 0;
  49400. pCur->eState = CURSOR_INVALID;
  49401. }
  49402. /*
  49403. ** In this version of BtreeMoveto, pKey is a packed index record
  49404. ** such as is generated by the OP_MakeRecord opcode. Unpack the
  49405. ** record and then call BtreeMovetoUnpacked() to do the work.
  49406. */
  49407. static int btreeMoveto(
  49408. BtCursor *pCur, /* Cursor open on the btree to be searched */
  49409. const void *pKey, /* Packed key if the btree is an index */
  49410. i64 nKey, /* Integer key for tables. Size of pKey for indices */
  49411. int bias, /* Bias search to the high end */
  49412. int *pRes /* Write search results here */
  49413. ){
  49414. int rc; /* Status code */
  49415. UnpackedRecord *pIdxKey; /* Unpacked index key */
  49416. char aSpace[200]; /* Temp space for pIdxKey - to avoid a malloc */
  49417. char *pFree = 0;
  49418. if( pKey ){
  49419. assert( nKey==(i64)(int)nKey );
  49420. pIdxKey = sqlite3VdbeAllocUnpackedRecord(
  49421. pCur->pKeyInfo, aSpace, sizeof(aSpace), &pFree
  49422. );
  49423. if( pIdxKey==0 ) return SQLITE_NOMEM;
  49424. sqlite3VdbeRecordUnpack(pCur->pKeyInfo, (int)nKey, pKey, pIdxKey);
  49425. if( pIdxKey->nField==0 ){
  49426. sqlite3DbFree(pCur->pKeyInfo->db, pFree);
  49427. return SQLITE_CORRUPT_BKPT;
  49428. }
  49429. }else{
  49430. pIdxKey = 0;
  49431. }
  49432. rc = sqlite3BtreeMovetoUnpacked(pCur, pIdxKey, nKey, bias, pRes);
  49433. if( pFree ){
  49434. sqlite3DbFree(pCur->pKeyInfo->db, pFree);
  49435. }
  49436. return rc;
  49437. }
  49438. /*
  49439. ** Restore the cursor to the position it was in (or as close to as possible)
  49440. ** when saveCursorPosition() was called. Note that this call deletes the
  49441. ** saved position info stored by saveCursorPosition(), so there can be
  49442. ** at most one effective restoreCursorPosition() call after each
  49443. ** saveCursorPosition().
  49444. */
  49445. static int btreeRestoreCursorPosition(BtCursor *pCur){
  49446. int rc;
  49447. assert( cursorHoldsMutex(pCur) );
  49448. assert( pCur->eState>=CURSOR_REQUIRESEEK );
  49449. if( pCur->eState==CURSOR_FAULT ){
  49450. return pCur->skipNext;
  49451. }
  49452. pCur->eState = CURSOR_INVALID;
  49453. rc = btreeMoveto(pCur, pCur->pKey, pCur->nKey, 0, &pCur->skipNext);
  49454. if( rc==SQLITE_OK ){
  49455. sqlite3_free(pCur->pKey);
  49456. pCur->pKey = 0;
  49457. assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_INVALID );
  49458. if( pCur->skipNext && pCur->eState==CURSOR_VALID ){
  49459. pCur->eState = CURSOR_SKIPNEXT;
  49460. }
  49461. }
  49462. return rc;
  49463. }
  49464. #define restoreCursorPosition(p) \
  49465. (p->eState>=CURSOR_REQUIRESEEK ? \
  49466. btreeRestoreCursorPosition(p) : \
  49467. SQLITE_OK)
  49468. /*
  49469. ** Determine whether or not a cursor has moved from the position where
  49470. ** it was last placed, or has been invalidated for any other reason.
  49471. ** Cursors can move when the row they are pointing at is deleted out
  49472. ** from under them, for example. Cursor might also move if a btree
  49473. ** is rebalanced.
  49474. **
  49475. ** Calling this routine with a NULL cursor pointer returns false.
  49476. **
  49477. ** Use the separate sqlite3BtreeCursorRestore() routine to restore a cursor
  49478. ** back to where it ought to be if this routine returns true.
  49479. */
  49480. SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor *pCur){
  49481. return pCur->eState!=CURSOR_VALID;
  49482. }
  49483. /*
  49484. ** This routine restores a cursor back to its original position after it
  49485. ** has been moved by some outside activity (such as a btree rebalance or
  49486. ** a row having been deleted out from under the cursor).
  49487. **
  49488. ** On success, the *pDifferentRow parameter is false if the cursor is left
  49489. ** pointing at exactly the same row. *pDifferntRow is the row the cursor
  49490. ** was pointing to has been deleted, forcing the cursor to point to some
  49491. ** nearby row.
  49492. **
  49493. ** This routine should only be called for a cursor that just returned
  49494. ** TRUE from sqlite3BtreeCursorHasMoved().
  49495. */
  49496. SQLITE_PRIVATE int sqlite3BtreeCursorRestore(BtCursor *pCur, int *pDifferentRow){
  49497. int rc;
  49498. assert( pCur!=0 );
  49499. assert( pCur->eState!=CURSOR_VALID );
  49500. rc = restoreCursorPosition(pCur);
  49501. if( rc ){
  49502. *pDifferentRow = 1;
  49503. return rc;
  49504. }
  49505. if( pCur->eState!=CURSOR_VALID || NEVER(pCur->skipNext!=0) ){
  49506. *pDifferentRow = 1;
  49507. }else{
  49508. *pDifferentRow = 0;
  49509. }
  49510. return SQLITE_OK;
  49511. }
  49512. #ifndef SQLITE_OMIT_AUTOVACUUM
  49513. /*
  49514. ** Given a page number of a regular database page, return the page
  49515. ** number for the pointer-map page that contains the entry for the
  49516. ** input page number.
  49517. **
  49518. ** Return 0 (not a valid page) for pgno==1 since there is
  49519. ** no pointer map associated with page 1. The integrity_check logic
  49520. ** requires that ptrmapPageno(*,1)!=1.
  49521. */
  49522. static Pgno ptrmapPageno(BtShared *pBt, Pgno pgno){
  49523. int nPagesPerMapPage;
  49524. Pgno iPtrMap, ret;
  49525. assert( sqlite3_mutex_held(pBt->mutex) );
  49526. if( pgno<2 ) return 0;
  49527. nPagesPerMapPage = (pBt->usableSize/5)+1;
  49528. iPtrMap = (pgno-2)/nPagesPerMapPage;
  49529. ret = (iPtrMap*nPagesPerMapPage) + 2;
  49530. if( ret==PENDING_BYTE_PAGE(pBt) ){
  49531. ret++;
  49532. }
  49533. return ret;
  49534. }
  49535. /*
  49536. ** Write an entry into the pointer map.
  49537. **
  49538. ** This routine updates the pointer map entry for page number 'key'
  49539. ** so that it maps to type 'eType' and parent page number 'pgno'.
  49540. **
  49541. ** If *pRC is initially non-zero (non-SQLITE_OK) then this routine is
  49542. ** a no-op. If an error occurs, the appropriate error code is written
  49543. ** into *pRC.
  49544. */
  49545. static void ptrmapPut(BtShared *pBt, Pgno key, u8 eType, Pgno parent, int *pRC){
  49546. DbPage *pDbPage; /* The pointer map page */
  49547. u8 *pPtrmap; /* The pointer map data */
  49548. Pgno iPtrmap; /* The pointer map page number */
  49549. int offset; /* Offset in pointer map page */
  49550. int rc; /* Return code from subfunctions */
  49551. if( *pRC ) return;
  49552. assert( sqlite3_mutex_held(pBt->mutex) );
  49553. /* The master-journal page number must never be used as a pointer map page */
  49554. assert( 0==PTRMAP_ISPAGE(pBt, PENDING_BYTE_PAGE(pBt)) );
  49555. assert( pBt->autoVacuum );
  49556. if( key==0 ){
  49557. *pRC = SQLITE_CORRUPT_BKPT;
  49558. return;
  49559. }
  49560. iPtrmap = PTRMAP_PAGENO(pBt, key);
  49561. rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
  49562. if( rc!=SQLITE_OK ){
  49563. *pRC = rc;
  49564. return;
  49565. }
  49566. offset = PTRMAP_PTROFFSET(iPtrmap, key);
  49567. if( offset<0 ){
  49568. *pRC = SQLITE_CORRUPT_BKPT;
  49569. goto ptrmap_exit;
  49570. }
  49571. assert( offset <= (int)pBt->usableSize-5 );
  49572. pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
  49573. if( eType!=pPtrmap[offset] || get4byte(&pPtrmap[offset+1])!=parent ){
  49574. TRACE(("PTRMAP_UPDATE: %d->(%d,%d)\n", key, eType, parent));
  49575. *pRC= rc = sqlite3PagerWrite(pDbPage);
  49576. if( rc==SQLITE_OK ){
  49577. pPtrmap[offset] = eType;
  49578. put4byte(&pPtrmap[offset+1], parent);
  49579. }
  49580. }
  49581. ptrmap_exit:
  49582. sqlite3PagerUnref(pDbPage);
  49583. }
  49584. /*
  49585. ** Read an entry from the pointer map.
  49586. **
  49587. ** This routine retrieves the pointer map entry for page 'key', writing
  49588. ** the type and parent page number to *pEType and *pPgno respectively.
  49589. ** An error code is returned if something goes wrong, otherwise SQLITE_OK.
  49590. */
  49591. static int ptrmapGet(BtShared *pBt, Pgno key, u8 *pEType, Pgno *pPgno){
  49592. DbPage *pDbPage; /* The pointer map page */
  49593. int iPtrmap; /* Pointer map page index */
  49594. u8 *pPtrmap; /* Pointer map page data */
  49595. int offset; /* Offset of entry in pointer map */
  49596. int rc;
  49597. assert( sqlite3_mutex_held(pBt->mutex) );
  49598. iPtrmap = PTRMAP_PAGENO(pBt, key);
  49599. rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
  49600. if( rc!=0 ){
  49601. return rc;
  49602. }
  49603. pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
  49604. offset = PTRMAP_PTROFFSET(iPtrmap, key);
  49605. if( offset<0 ){
  49606. sqlite3PagerUnref(pDbPage);
  49607. return SQLITE_CORRUPT_BKPT;
  49608. }
  49609. assert( offset <= (int)pBt->usableSize-5 );
  49610. assert( pEType!=0 );
  49611. *pEType = pPtrmap[offset];
  49612. if( pPgno ) *pPgno = get4byte(&pPtrmap[offset+1]);
  49613. sqlite3PagerUnref(pDbPage);
  49614. if( *pEType<1 || *pEType>5 ) return SQLITE_CORRUPT_BKPT;
  49615. return SQLITE_OK;
  49616. }
  49617. #else /* if defined SQLITE_OMIT_AUTOVACUUM */
  49618. #define ptrmapPut(w,x,y,z,rc)
  49619. #define ptrmapGet(w,x,y,z) SQLITE_OK
  49620. #define ptrmapPutOvflPtr(x, y, rc)
  49621. #endif
  49622. /*
  49623. ** Given a btree page and a cell index (0 means the first cell on
  49624. ** the page, 1 means the second cell, and so forth) return a pointer
  49625. ** to the cell content.
  49626. **
  49627. ** This routine works only for pages that do not contain overflow cells.
  49628. */
  49629. #define findCell(P,I) \
  49630. ((P)->aData + ((P)->maskPage & get2byte(&(P)->aCellIdx[2*(I)])))
  49631. #define findCellv2(D,M,O,I) (D+(M&get2byte(D+(O+2*(I)))))
  49632. /*
  49633. ** This a more complex version of findCell() that works for
  49634. ** pages that do contain overflow cells.
  49635. */
  49636. static u8 *findOverflowCell(MemPage *pPage, int iCell){
  49637. int i;
  49638. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  49639. for(i=pPage->nOverflow-1; i>=0; i--){
  49640. int k;
  49641. k = pPage->aiOvfl[i];
  49642. if( k<=iCell ){
  49643. if( k==iCell ){
  49644. return pPage->apOvfl[i];
  49645. }
  49646. iCell--;
  49647. }
  49648. }
  49649. return findCell(pPage, iCell);
  49650. }
  49651. /*
  49652. ** Parse a cell content block and fill in the CellInfo structure. There
  49653. ** are two versions of this function. btreeParseCell() takes a
  49654. ** cell index as the second argument and btreeParseCellPtr()
  49655. ** takes a pointer to the body of the cell as its second argument.
  49656. */
  49657. static void btreeParseCellPtr(
  49658. MemPage *pPage, /* Page containing the cell */
  49659. u8 *pCell, /* Pointer to the cell text. */
  49660. CellInfo *pInfo /* Fill in this structure */
  49661. ){
  49662. u8 *pIter; /* For scanning through pCell */
  49663. u32 nPayload; /* Number of bytes of cell payload */
  49664. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  49665. assert( pPage->leaf==0 || pPage->leaf==1 );
  49666. if( pPage->intKeyLeaf ){
  49667. assert( pPage->childPtrSize==0 );
  49668. pIter = pCell + getVarint32(pCell, nPayload);
  49669. pIter += getVarint(pIter, (u64*)&pInfo->nKey);
  49670. }else if( pPage->noPayload ){
  49671. assert( pPage->childPtrSize==4 );
  49672. pInfo->nSize = 4 + getVarint(&pCell[4], (u64*)&pInfo->nKey);
  49673. pInfo->nPayload = 0;
  49674. pInfo->nLocal = 0;
  49675. pInfo->iOverflow = 0;
  49676. pInfo->pPayload = 0;
  49677. return;
  49678. }else{
  49679. pIter = pCell + pPage->childPtrSize;
  49680. pIter += getVarint32(pIter, nPayload);
  49681. pInfo->nKey = nPayload;
  49682. }
  49683. pInfo->nPayload = nPayload;
  49684. pInfo->pPayload = pIter;
  49685. testcase( nPayload==pPage->maxLocal );
  49686. testcase( nPayload==pPage->maxLocal+1 );
  49687. if( nPayload<=pPage->maxLocal ){
  49688. /* This is the (easy) common case where the entire payload fits
  49689. ** on the local page. No overflow is required.
  49690. */
  49691. pInfo->nSize = nPayload + (u16)(pIter - pCell);
  49692. if( pInfo->nSize<4 ) pInfo->nSize = 4;
  49693. pInfo->nLocal = (u16)nPayload;
  49694. pInfo->iOverflow = 0;
  49695. }else{
  49696. /* If the payload will not fit completely on the local page, we have
  49697. ** to decide how much to store locally and how much to spill onto
  49698. ** overflow pages. The strategy is to minimize the amount of unused
  49699. ** space on overflow pages while keeping the amount of local storage
  49700. ** in between minLocal and maxLocal.
  49701. **
  49702. ** Warning: changing the way overflow payload is distributed in any
  49703. ** way will result in an incompatible file format.
  49704. */
  49705. int minLocal; /* Minimum amount of payload held locally */
  49706. int maxLocal; /* Maximum amount of payload held locally */
  49707. int surplus; /* Overflow payload available for local storage */
  49708. minLocal = pPage->minLocal;
  49709. maxLocal = pPage->maxLocal;
  49710. surplus = minLocal + (nPayload - minLocal)%(pPage->pBt->usableSize - 4);
  49711. testcase( surplus==maxLocal );
  49712. testcase( surplus==maxLocal+1 );
  49713. if( surplus <= maxLocal ){
  49714. pInfo->nLocal = (u16)surplus;
  49715. }else{
  49716. pInfo->nLocal = (u16)minLocal;
  49717. }
  49718. pInfo->iOverflow = (u16)(&pInfo->pPayload[pInfo->nLocal] - pCell);
  49719. pInfo->nSize = pInfo->iOverflow + 4;
  49720. }
  49721. }
  49722. static void btreeParseCell(
  49723. MemPage *pPage, /* Page containing the cell */
  49724. int iCell, /* The cell index. First cell is 0 */
  49725. CellInfo *pInfo /* Fill in this structure */
  49726. ){
  49727. btreeParseCellPtr(pPage, findCell(pPage, iCell), pInfo);
  49728. }
  49729. /*
  49730. ** Compute the total number of bytes that a Cell needs in the cell
  49731. ** data area of the btree-page. The return number includes the cell
  49732. ** data header and the local payload, but not any overflow page or
  49733. ** the space used by the cell pointer.
  49734. */
  49735. static u16 cellSizePtr(MemPage *pPage, u8 *pCell){
  49736. u8 *pIter = pCell + pPage->childPtrSize; /* For looping over bytes of pCell */
  49737. u8 *pEnd; /* End mark for a varint */
  49738. u32 nSize; /* Size value to return */
  49739. #ifdef SQLITE_DEBUG
  49740. /* The value returned by this function should always be the same as
  49741. ** the (CellInfo.nSize) value found by doing a full parse of the
  49742. ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
  49743. ** this function verifies that this invariant is not violated. */
  49744. CellInfo debuginfo;
  49745. btreeParseCellPtr(pPage, pCell, &debuginfo);
  49746. #endif
  49747. if( pPage->noPayload ){
  49748. pEnd = &pIter[9];
  49749. while( (*pIter++)&0x80 && pIter<pEnd );
  49750. assert( pPage->childPtrSize==4 );
  49751. return (u16)(pIter - pCell);
  49752. }
  49753. nSize = *pIter;
  49754. if( nSize>=0x80 ){
  49755. pEnd = &pIter[9];
  49756. nSize &= 0x7f;
  49757. do{
  49758. nSize = (nSize<<7) | (*++pIter & 0x7f);
  49759. }while( *(pIter)>=0x80 && pIter<pEnd );
  49760. }
  49761. pIter++;
  49762. if( pPage->intKey ){
  49763. /* pIter now points at the 64-bit integer key value, a variable length
  49764. ** integer. The following block moves pIter to point at the first byte
  49765. ** past the end of the key value. */
  49766. pEnd = &pIter[9];
  49767. while( (*pIter++)&0x80 && pIter<pEnd );
  49768. }
  49769. testcase( nSize==pPage->maxLocal );
  49770. testcase( nSize==pPage->maxLocal+1 );
  49771. if( nSize<=pPage->maxLocal ){
  49772. nSize += (u32)(pIter - pCell);
  49773. if( nSize<4 ) nSize = 4;
  49774. }else{
  49775. int minLocal = pPage->minLocal;
  49776. nSize = minLocal + (nSize - minLocal) % (pPage->pBt->usableSize - 4);
  49777. testcase( nSize==pPage->maxLocal );
  49778. testcase( nSize==pPage->maxLocal+1 );
  49779. if( nSize>pPage->maxLocal ){
  49780. nSize = minLocal;
  49781. }
  49782. nSize += 4 + (u16)(pIter - pCell);
  49783. }
  49784. assert( nSize==debuginfo.nSize || CORRUPT_DB );
  49785. return (u16)nSize;
  49786. }
  49787. #ifdef SQLITE_DEBUG
  49788. /* This variation on cellSizePtr() is used inside of assert() statements
  49789. ** only. */
  49790. static u16 cellSize(MemPage *pPage, int iCell){
  49791. return cellSizePtr(pPage, findCell(pPage, iCell));
  49792. }
  49793. #endif
  49794. #ifndef SQLITE_OMIT_AUTOVACUUM
  49795. /*
  49796. ** If the cell pCell, part of page pPage contains a pointer
  49797. ** to an overflow page, insert an entry into the pointer-map
  49798. ** for the overflow page.
  49799. */
  49800. static void ptrmapPutOvflPtr(MemPage *pPage, u8 *pCell, int *pRC){
  49801. CellInfo info;
  49802. if( *pRC ) return;
  49803. assert( pCell!=0 );
  49804. btreeParseCellPtr(pPage, pCell, &info);
  49805. if( info.iOverflow ){
  49806. Pgno ovfl = get4byte(&pCell[info.iOverflow]);
  49807. ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno, pRC);
  49808. }
  49809. }
  49810. #endif
  49811. /*
  49812. ** Defragment the page given. All Cells are moved to the
  49813. ** end of the page and all free space is collected into one
  49814. ** big FreeBlk that occurs in between the header and cell
  49815. ** pointer array and the cell content area.
  49816. */
  49817. static int defragmentPage(MemPage *pPage){
  49818. int i; /* Loop counter */
  49819. int pc; /* Address of the i-th cell */
  49820. int hdr; /* Offset to the page header */
  49821. int size; /* Size of a cell */
  49822. int usableSize; /* Number of usable bytes on a page */
  49823. int cellOffset; /* Offset to the cell pointer array */
  49824. int cbrk; /* Offset to the cell content area */
  49825. int nCell; /* Number of cells on the page */
  49826. unsigned char *data; /* The page data */
  49827. unsigned char *temp; /* Temp area for cell content */
  49828. unsigned char *src; /* Source of content */
  49829. int iCellFirst; /* First allowable cell index */
  49830. int iCellLast; /* Last possible cell index */
  49831. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  49832. assert( pPage->pBt!=0 );
  49833. assert( pPage->pBt->usableSize <= SQLITE_MAX_PAGE_SIZE );
  49834. assert( pPage->nOverflow==0 );
  49835. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  49836. temp = 0;
  49837. src = data = pPage->aData;
  49838. hdr = pPage->hdrOffset;
  49839. cellOffset = pPage->cellOffset;
  49840. nCell = pPage->nCell;
  49841. assert( nCell==get2byte(&data[hdr+3]) );
  49842. usableSize = pPage->pBt->usableSize;
  49843. cbrk = usableSize;
  49844. iCellFirst = cellOffset + 2*nCell;
  49845. iCellLast = usableSize - 4;
  49846. for(i=0; i<nCell; i++){
  49847. u8 *pAddr; /* The i-th cell pointer */
  49848. pAddr = &data[cellOffset + i*2];
  49849. pc = get2byte(pAddr);
  49850. testcase( pc==iCellFirst );
  49851. testcase( pc==iCellLast );
  49852. #if !defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
  49853. /* These conditions have already been verified in btreeInitPage()
  49854. ** if SQLITE_ENABLE_OVERSIZE_CELL_CHECK is defined
  49855. */
  49856. if( pc<iCellFirst || pc>iCellLast ){
  49857. return SQLITE_CORRUPT_BKPT;
  49858. }
  49859. #endif
  49860. assert( pc>=iCellFirst && pc<=iCellLast );
  49861. size = cellSizePtr(pPage, &src[pc]);
  49862. cbrk -= size;
  49863. #if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
  49864. if( cbrk<iCellFirst ){
  49865. return SQLITE_CORRUPT_BKPT;
  49866. }
  49867. #else
  49868. if( cbrk<iCellFirst || pc+size>usableSize ){
  49869. return SQLITE_CORRUPT_BKPT;
  49870. }
  49871. #endif
  49872. assert( cbrk+size<=usableSize && cbrk>=iCellFirst );
  49873. testcase( cbrk+size==usableSize );
  49874. testcase( pc+size==usableSize );
  49875. put2byte(pAddr, cbrk);
  49876. if( temp==0 ){
  49877. int x;
  49878. if( cbrk==pc ) continue;
  49879. temp = sqlite3PagerTempSpace(pPage->pBt->pPager);
  49880. x = get2byte(&data[hdr+5]);
  49881. memcpy(&temp[x], &data[x], (cbrk+size) - x);
  49882. src = temp;
  49883. }
  49884. memcpy(&data[cbrk], &src[pc], size);
  49885. }
  49886. assert( cbrk>=iCellFirst );
  49887. put2byte(&data[hdr+5], cbrk);
  49888. data[hdr+1] = 0;
  49889. data[hdr+2] = 0;
  49890. data[hdr+7] = 0;
  49891. memset(&data[iCellFirst], 0, cbrk-iCellFirst);
  49892. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  49893. if( cbrk-iCellFirst!=pPage->nFree ){
  49894. return SQLITE_CORRUPT_BKPT;
  49895. }
  49896. return SQLITE_OK;
  49897. }
  49898. /*
  49899. ** Search the free-list on page pPg for space to store a cell nByte bytes in
  49900. ** size. If one can be found, return a pointer to the space and remove it
  49901. ** from the free-list.
  49902. **
  49903. ** If no suitable space can be found on the free-list, return NULL.
  49904. **
  49905. ** This function may detect corruption within pPg. If it does and argument
  49906. ** pRc is non-NULL, then *pRc is set to SQLITE_CORRUPT and NULL is returned.
  49907. ** Or, if corruption is detected and pRc is NULL, NULL is returned and the
  49908. ** corruption goes unreported.
  49909. **
  49910. ** If a slot of at least nByte bytes is found but cannot be used because
  49911. ** there are already at least 60 fragmented bytes on the page, return NULL.
  49912. ** In this case, if pbDefrag parameter is not NULL, set *pbDefrag to true.
  49913. */
  49914. static u8 *pageFindSlot(MemPage *pPg, int nByte, int *pRc, int *pbDefrag){
  49915. const int hdr = pPg->hdrOffset;
  49916. u8 * const aData = pPg->aData;
  49917. int iAddr;
  49918. int pc;
  49919. int usableSize = pPg->pBt->usableSize;
  49920. for(iAddr=hdr+1; (pc = get2byte(&aData[iAddr]))>0; iAddr=pc){
  49921. int size; /* Size of the free slot */
  49922. if( pc>usableSize-4 || pc<iAddr+4 ){
  49923. if( pRc ) *pRc = SQLITE_CORRUPT_BKPT;
  49924. return 0;
  49925. }
  49926. size = get2byte(&aData[pc+2]);
  49927. if( size>=nByte ){
  49928. int x = size - nByte;
  49929. testcase( x==4 );
  49930. testcase( x==3 );
  49931. if( x<4 ){
  49932. if( aData[hdr+7]>=60 ){
  49933. if( pbDefrag ) *pbDefrag = 1;
  49934. return 0;
  49935. }
  49936. /* Remove the slot from the free-list. Update the number of
  49937. ** fragmented bytes within the page. */
  49938. memcpy(&aData[iAddr], &aData[pc], 2);
  49939. aData[hdr+7] += (u8)x;
  49940. }else if( size+pc > usableSize ){
  49941. if( pRc ) *pRc = SQLITE_CORRUPT_BKPT;
  49942. return 0;
  49943. }else{
  49944. /* The slot remains on the free-list. Reduce its size to account
  49945. ** for the portion used by the new allocation. */
  49946. put2byte(&aData[pc+2], x);
  49947. }
  49948. return &aData[pc + x];
  49949. }
  49950. }
  49951. return 0;
  49952. }
  49953. /*
  49954. ** Allocate nByte bytes of space from within the B-Tree page passed
  49955. ** as the first argument. Write into *pIdx the index into pPage->aData[]
  49956. ** of the first byte of allocated space. Return either SQLITE_OK or
  49957. ** an error code (usually SQLITE_CORRUPT).
  49958. **
  49959. ** The caller guarantees that there is sufficient space to make the
  49960. ** allocation. This routine might need to defragment in order to bring
  49961. ** all the space together, however. This routine will avoid using
  49962. ** the first two bytes past the cell pointer area since presumably this
  49963. ** allocation is being made in order to insert a new cell, so we will
  49964. ** also end up needing a new cell pointer.
  49965. */
  49966. static int allocateSpace(MemPage *pPage, int nByte, int *pIdx){
  49967. const int hdr = pPage->hdrOffset; /* Local cache of pPage->hdrOffset */
  49968. u8 * const data = pPage->aData; /* Local cache of pPage->aData */
  49969. int top; /* First byte of cell content area */
  49970. int gap; /* First byte of gap between cell pointers and cell content */
  49971. int rc; /* Integer return code */
  49972. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  49973. assert( pPage->pBt );
  49974. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  49975. assert( nByte>=0 ); /* Minimum cell size is 4 */
  49976. assert( pPage->nFree>=nByte );
  49977. assert( pPage->nOverflow==0 );
  49978. assert( nByte < (int)(pPage->pBt->usableSize-8) );
  49979. assert( pPage->cellOffset == hdr + 12 - 4*pPage->leaf );
  49980. gap = pPage->cellOffset + 2*pPage->nCell;
  49981. assert( gap<=65536 );
  49982. top = get2byte(&data[hdr+5]);
  49983. if( gap>top ){
  49984. if( top==0 ){
  49985. top = 65536;
  49986. }else{
  49987. return SQLITE_CORRUPT_BKPT;
  49988. }
  49989. }
  49990. /* If there is enough space between gap and top for one more cell pointer
  49991. ** array entry offset, and if the freelist is not empty, then search the
  49992. ** freelist looking for a free slot big enough to satisfy the request.
  49993. */
  49994. testcase( gap+2==top );
  49995. testcase( gap+1==top );
  49996. testcase( gap==top );
  49997. if( gap+2<=top && (data[hdr+1] || data[hdr+2]) ){
  49998. int rc = SQLITE_OK;
  49999. int bDefrag = 0;
  50000. u8 *pSpace = pageFindSlot(pPage, nByte, &rc, &bDefrag);
  50001. if( rc ) return rc;
  50002. if( bDefrag ) goto defragment_page;
  50003. if( pSpace ){
  50004. *pIdx = pSpace - data;
  50005. return SQLITE_OK;
  50006. }
  50007. }
  50008. /* The request could not be fulfilled using a freelist slot. Check
  50009. ** to see if defragmentation is necessary.
  50010. */
  50011. testcase( gap+2+nByte==top );
  50012. if( gap+2+nByte>top ){
  50013. defragment_page:
  50014. testcase( pPage->nCell==0 );
  50015. rc = defragmentPage(pPage);
  50016. if( rc ) return rc;
  50017. top = get2byteNotZero(&data[hdr+5]);
  50018. assert( gap+nByte<=top );
  50019. }
  50020. /* Allocate memory from the gap in between the cell pointer array
  50021. ** and the cell content area. The btreeInitPage() call has already
  50022. ** validated the freelist. Given that the freelist is valid, there
  50023. ** is no way that the allocation can extend off the end of the page.
  50024. ** The assert() below verifies the previous sentence.
  50025. */
  50026. top -= nByte;
  50027. put2byte(&data[hdr+5], top);
  50028. assert( top+nByte <= (int)pPage->pBt->usableSize );
  50029. *pIdx = top;
  50030. return SQLITE_OK;
  50031. }
  50032. /*
  50033. ** Return a section of the pPage->aData to the freelist.
  50034. ** The first byte of the new free block is pPage->aData[iStart]
  50035. ** and the size of the block is iSize bytes.
  50036. **
  50037. ** Adjacent freeblocks are coalesced.
  50038. **
  50039. ** Note that even though the freeblock list was checked by btreeInitPage(),
  50040. ** that routine will not detect overlap between cells or freeblocks. Nor
  50041. ** does it detect cells or freeblocks that encrouch into the reserved bytes
  50042. ** at the end of the page. So do additional corruption checks inside this
  50043. ** routine and return SQLITE_CORRUPT if any problems are found.
  50044. */
  50045. static int freeSpace(MemPage *pPage, u16 iStart, u16 iSize){
  50046. u16 iPtr; /* Address of ptr to next freeblock */
  50047. u16 iFreeBlk; /* Address of the next freeblock */
  50048. u8 hdr; /* Page header size. 0 or 100 */
  50049. u8 nFrag = 0; /* Reduction in fragmentation */
  50050. u16 iOrigSize = iSize; /* Original value of iSize */
  50051. u32 iLast = pPage->pBt->usableSize-4; /* Largest possible freeblock offset */
  50052. u32 iEnd = iStart + iSize; /* First byte past the iStart buffer */
  50053. unsigned char *data = pPage->aData; /* Page content */
  50054. assert( pPage->pBt!=0 );
  50055. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  50056. assert( iStart>=pPage->hdrOffset+6+pPage->childPtrSize );
  50057. assert( CORRUPT_DB || iEnd <= pPage->pBt->usableSize );
  50058. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  50059. assert( iSize>=4 ); /* Minimum cell size is 4 */
  50060. assert( iStart<=iLast );
  50061. /* Overwrite deleted information with zeros when the secure_delete
  50062. ** option is enabled */
  50063. if( pPage->pBt->btsFlags & BTS_SECURE_DELETE ){
  50064. memset(&data[iStart], 0, iSize);
  50065. }
  50066. /* The list of freeblocks must be in ascending order. Find the
  50067. ** spot on the list where iStart should be inserted.
  50068. */
  50069. hdr = pPage->hdrOffset;
  50070. iPtr = hdr + 1;
  50071. if( data[iPtr+1]==0 && data[iPtr]==0 ){
  50072. iFreeBlk = 0; /* Shortcut for the case when the freelist is empty */
  50073. }else{
  50074. while( (iFreeBlk = get2byte(&data[iPtr]))>0 && iFreeBlk<iStart ){
  50075. if( iFreeBlk<iPtr+4 ) return SQLITE_CORRUPT_BKPT;
  50076. iPtr = iFreeBlk;
  50077. }
  50078. if( iFreeBlk>iLast ) return SQLITE_CORRUPT_BKPT;
  50079. assert( iFreeBlk>iPtr || iFreeBlk==0 );
  50080. /* At this point:
  50081. ** iFreeBlk: First freeblock after iStart, or zero if none
  50082. ** iPtr: The address of a pointer iFreeBlk
  50083. **
  50084. ** Check to see if iFreeBlk should be coalesced onto the end of iStart.
  50085. */
  50086. if( iFreeBlk && iEnd+3>=iFreeBlk ){
  50087. nFrag = iFreeBlk - iEnd;
  50088. if( iEnd>iFreeBlk ) return SQLITE_CORRUPT_BKPT;
  50089. iEnd = iFreeBlk + get2byte(&data[iFreeBlk+2]);
  50090. iSize = iEnd - iStart;
  50091. iFreeBlk = get2byte(&data[iFreeBlk]);
  50092. }
  50093. /* If iPtr is another freeblock (that is, if iPtr is not the freelist
  50094. ** pointer in the page header) then check to see if iStart should be
  50095. ** coalesced onto the end of iPtr.
  50096. */
  50097. if( iPtr>hdr+1 ){
  50098. int iPtrEnd = iPtr + get2byte(&data[iPtr+2]);
  50099. if( iPtrEnd+3>=iStart ){
  50100. if( iPtrEnd>iStart ) return SQLITE_CORRUPT_BKPT;
  50101. nFrag += iStart - iPtrEnd;
  50102. iSize = iEnd - iPtr;
  50103. iStart = iPtr;
  50104. }
  50105. }
  50106. if( nFrag>data[hdr+7] ) return SQLITE_CORRUPT_BKPT;
  50107. data[hdr+7] -= nFrag;
  50108. }
  50109. if( iStart==get2byte(&data[hdr+5]) ){
  50110. /* The new freeblock is at the beginning of the cell content area,
  50111. ** so just extend the cell content area rather than create another
  50112. ** freelist entry */
  50113. if( iPtr!=hdr+1 ) return SQLITE_CORRUPT_BKPT;
  50114. put2byte(&data[hdr+1], iFreeBlk);
  50115. put2byte(&data[hdr+5], iEnd);
  50116. }else{
  50117. /* Insert the new freeblock into the freelist */
  50118. put2byte(&data[iPtr], iStart);
  50119. put2byte(&data[iStart], iFreeBlk);
  50120. put2byte(&data[iStart+2], iSize);
  50121. }
  50122. pPage->nFree += iOrigSize;
  50123. return SQLITE_OK;
  50124. }
  50125. /*
  50126. ** Decode the flags byte (the first byte of the header) for a page
  50127. ** and initialize fields of the MemPage structure accordingly.
  50128. **
  50129. ** Only the following combinations are supported. Anything different
  50130. ** indicates a corrupt database files:
  50131. **
  50132. ** PTF_ZERODATA
  50133. ** PTF_ZERODATA | PTF_LEAF
  50134. ** PTF_LEAFDATA | PTF_INTKEY
  50135. ** PTF_LEAFDATA | PTF_INTKEY | PTF_LEAF
  50136. */
  50137. static int decodeFlags(MemPage *pPage, int flagByte){
  50138. BtShared *pBt; /* A copy of pPage->pBt */
  50139. assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) );
  50140. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  50141. pPage->leaf = (u8)(flagByte>>3); assert( PTF_LEAF == 1<<3 );
  50142. flagByte &= ~PTF_LEAF;
  50143. pPage->childPtrSize = 4-4*pPage->leaf;
  50144. pBt = pPage->pBt;
  50145. if( flagByte==(PTF_LEAFDATA | PTF_INTKEY) ){
  50146. pPage->intKey = 1;
  50147. pPage->intKeyLeaf = pPage->leaf;
  50148. pPage->noPayload = !pPage->leaf;
  50149. pPage->maxLocal = pBt->maxLeaf;
  50150. pPage->minLocal = pBt->minLeaf;
  50151. }else if( flagByte==PTF_ZERODATA ){
  50152. pPage->intKey = 0;
  50153. pPage->intKeyLeaf = 0;
  50154. pPage->noPayload = 0;
  50155. pPage->maxLocal = pBt->maxLocal;
  50156. pPage->minLocal = pBt->minLocal;
  50157. }else{
  50158. return SQLITE_CORRUPT_BKPT;
  50159. }
  50160. pPage->max1bytePayload = pBt->max1bytePayload;
  50161. return SQLITE_OK;
  50162. }
  50163. /*
  50164. ** Initialize the auxiliary information for a disk block.
  50165. **
  50166. ** Return SQLITE_OK on success. If we see that the page does
  50167. ** not contain a well-formed database page, then return
  50168. ** SQLITE_CORRUPT. Note that a return of SQLITE_OK does not
  50169. ** guarantee that the page is well-formed. It only shows that
  50170. ** we failed to detect any corruption.
  50171. */
  50172. static int btreeInitPage(MemPage *pPage){
  50173. assert( pPage->pBt!=0 );
  50174. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  50175. assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
  50176. assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) );
  50177. assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) );
  50178. if( !pPage->isInit ){
  50179. u16 pc; /* Address of a freeblock within pPage->aData[] */
  50180. u8 hdr; /* Offset to beginning of page header */
  50181. u8 *data; /* Equal to pPage->aData */
  50182. BtShared *pBt; /* The main btree structure */
  50183. int usableSize; /* Amount of usable space on each page */
  50184. u16 cellOffset; /* Offset from start of page to first cell pointer */
  50185. int nFree; /* Number of unused bytes on the page */
  50186. int top; /* First byte of the cell content area */
  50187. int iCellFirst; /* First allowable cell or freeblock offset */
  50188. int iCellLast; /* Last possible cell or freeblock offset */
  50189. pBt = pPage->pBt;
  50190. hdr = pPage->hdrOffset;
  50191. data = pPage->aData;
  50192. if( decodeFlags(pPage, data[hdr]) ) return SQLITE_CORRUPT_BKPT;
  50193. assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
  50194. pPage->maskPage = (u16)(pBt->pageSize - 1);
  50195. pPage->nOverflow = 0;
  50196. usableSize = pBt->usableSize;
  50197. pPage->cellOffset = cellOffset = hdr + 12 - 4*pPage->leaf;
  50198. pPage->aDataEnd = &data[usableSize];
  50199. pPage->aCellIdx = &data[cellOffset];
  50200. top = get2byteNotZero(&data[hdr+5]);
  50201. pPage->nCell = get2byte(&data[hdr+3]);
  50202. if( pPage->nCell>MX_CELL(pBt) ){
  50203. /* To many cells for a single page. The page must be corrupt */
  50204. return SQLITE_CORRUPT_BKPT;
  50205. }
  50206. testcase( pPage->nCell==MX_CELL(pBt) );
  50207. /* A malformed database page might cause us to read past the end
  50208. ** of page when parsing a cell.
  50209. **
  50210. ** The following block of code checks early to see if a cell extends
  50211. ** past the end of a page boundary and causes SQLITE_CORRUPT to be
  50212. ** returned if it does.
  50213. */
  50214. iCellFirst = cellOffset + 2*pPage->nCell;
  50215. iCellLast = usableSize - 4;
  50216. #if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
  50217. {
  50218. int i; /* Index into the cell pointer array */
  50219. int sz; /* Size of a cell */
  50220. if( !pPage->leaf ) iCellLast--;
  50221. for(i=0; i<pPage->nCell; i++){
  50222. pc = get2byte(&data[cellOffset+i*2]);
  50223. testcase( pc==iCellFirst );
  50224. testcase( pc==iCellLast );
  50225. if( pc<iCellFirst || pc>iCellLast ){
  50226. return SQLITE_CORRUPT_BKPT;
  50227. }
  50228. sz = cellSizePtr(pPage, &data[pc]);
  50229. testcase( pc+sz==usableSize );
  50230. if( pc+sz>usableSize ){
  50231. return SQLITE_CORRUPT_BKPT;
  50232. }
  50233. }
  50234. if( !pPage->leaf ) iCellLast++;
  50235. }
  50236. #endif
  50237. /* Compute the total free space on the page */
  50238. pc = get2byte(&data[hdr+1]);
  50239. nFree = data[hdr+7] + top;
  50240. while( pc>0 ){
  50241. u16 next, size;
  50242. if( pc<iCellFirst || pc>iCellLast ){
  50243. /* Start of free block is off the page */
  50244. return SQLITE_CORRUPT_BKPT;
  50245. }
  50246. next = get2byte(&data[pc]);
  50247. size = get2byte(&data[pc+2]);
  50248. if( (next>0 && next<=pc+size+3) || pc+size>usableSize ){
  50249. /* Free blocks must be in ascending order. And the last byte of
  50250. ** the free-block must lie on the database page. */
  50251. return SQLITE_CORRUPT_BKPT;
  50252. }
  50253. nFree = nFree + size;
  50254. pc = next;
  50255. }
  50256. /* At this point, nFree contains the sum of the offset to the start
  50257. ** of the cell-content area plus the number of free bytes within
  50258. ** the cell-content area. If this is greater than the usable-size
  50259. ** of the page, then the page must be corrupted. This check also
  50260. ** serves to verify that the offset to the start of the cell-content
  50261. ** area, according to the page header, lies within the page.
  50262. */
  50263. if( nFree>usableSize ){
  50264. return SQLITE_CORRUPT_BKPT;
  50265. }
  50266. pPage->nFree = (u16)(nFree - iCellFirst);
  50267. pPage->isInit = 1;
  50268. }
  50269. return SQLITE_OK;
  50270. }
  50271. /*
  50272. ** Set up a raw page so that it looks like a database page holding
  50273. ** no entries.
  50274. */
  50275. static void zeroPage(MemPage *pPage, int flags){
  50276. unsigned char *data = pPage->aData;
  50277. BtShared *pBt = pPage->pBt;
  50278. u8 hdr = pPage->hdrOffset;
  50279. u16 first;
  50280. assert( sqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno );
  50281. assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
  50282. assert( sqlite3PagerGetData(pPage->pDbPage) == data );
  50283. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  50284. assert( sqlite3_mutex_held(pBt->mutex) );
  50285. if( pBt->btsFlags & BTS_SECURE_DELETE ){
  50286. memset(&data[hdr], 0, pBt->usableSize - hdr);
  50287. }
  50288. data[hdr] = (char)flags;
  50289. first = hdr + ((flags&PTF_LEAF)==0 ? 12 : 8);
  50290. memset(&data[hdr+1], 0, 4);
  50291. data[hdr+7] = 0;
  50292. put2byte(&data[hdr+5], pBt->usableSize);
  50293. pPage->nFree = (u16)(pBt->usableSize - first);
  50294. decodeFlags(pPage, flags);
  50295. pPage->cellOffset = first;
  50296. pPage->aDataEnd = &data[pBt->usableSize];
  50297. pPage->aCellIdx = &data[first];
  50298. pPage->nOverflow = 0;
  50299. assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
  50300. pPage->maskPage = (u16)(pBt->pageSize - 1);
  50301. pPage->nCell = 0;
  50302. pPage->isInit = 1;
  50303. }
  50304. /*
  50305. ** Convert a DbPage obtained from the pager into a MemPage used by
  50306. ** the btree layer.
  50307. */
  50308. static MemPage *btreePageFromDbPage(DbPage *pDbPage, Pgno pgno, BtShared *pBt){
  50309. MemPage *pPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
  50310. pPage->aData = sqlite3PagerGetData(pDbPage);
  50311. pPage->pDbPage = pDbPage;
  50312. pPage->pBt = pBt;
  50313. pPage->pgno = pgno;
  50314. pPage->hdrOffset = pPage->pgno==1 ? 100 : 0;
  50315. return pPage;
  50316. }
  50317. /*
  50318. ** Get a page from the pager. Initialize the MemPage.pBt and
  50319. ** MemPage.aData elements if needed.
  50320. **
  50321. ** If the noContent flag is set, it means that we do not care about
  50322. ** the content of the page at this time. So do not go to the disk
  50323. ** to fetch the content. Just fill in the content with zeros for now.
  50324. ** If in the future we call sqlite3PagerWrite() on this page, that
  50325. ** means we have started to be concerned about content and the disk
  50326. ** read should occur at that point.
  50327. */
  50328. static int btreeGetPage(
  50329. BtShared *pBt, /* The btree */
  50330. Pgno pgno, /* Number of the page to fetch */
  50331. MemPage **ppPage, /* Return the page in this parameter */
  50332. int flags /* PAGER_GET_NOCONTENT or PAGER_GET_READONLY */
  50333. ){
  50334. int rc;
  50335. DbPage *pDbPage;
  50336. assert( flags==0 || flags==PAGER_GET_NOCONTENT || flags==PAGER_GET_READONLY );
  50337. assert( sqlite3_mutex_held(pBt->mutex) );
  50338. rc = sqlite3PagerAcquire(pBt->pPager, pgno, (DbPage**)&pDbPage, flags);
  50339. if( rc ) return rc;
  50340. *ppPage = btreePageFromDbPage(pDbPage, pgno, pBt);
  50341. return SQLITE_OK;
  50342. }
  50343. /*
  50344. ** Retrieve a page from the pager cache. If the requested page is not
  50345. ** already in the pager cache return NULL. Initialize the MemPage.pBt and
  50346. ** MemPage.aData elements if needed.
  50347. */
  50348. static MemPage *btreePageLookup(BtShared *pBt, Pgno pgno){
  50349. DbPage *pDbPage;
  50350. assert( sqlite3_mutex_held(pBt->mutex) );
  50351. pDbPage = sqlite3PagerLookup(pBt->pPager, pgno);
  50352. if( pDbPage ){
  50353. return btreePageFromDbPage(pDbPage, pgno, pBt);
  50354. }
  50355. return 0;
  50356. }
  50357. /*
  50358. ** Return the size of the database file in pages. If there is any kind of
  50359. ** error, return ((unsigned int)-1).
  50360. */
  50361. static Pgno btreePagecount(BtShared *pBt){
  50362. return pBt->nPage;
  50363. }
  50364. SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree *p){
  50365. assert( sqlite3BtreeHoldsMutex(p) );
  50366. assert( ((p->pBt->nPage)&0x8000000)==0 );
  50367. return btreePagecount(p->pBt);
  50368. }
  50369. /*
  50370. ** Get a page from the pager and initialize it. This routine is just a
  50371. ** convenience wrapper around separate calls to btreeGetPage() and
  50372. ** btreeInitPage().
  50373. **
  50374. ** If an error occurs, then the value *ppPage is set to is undefined. It
  50375. ** may remain unchanged, or it may be set to an invalid value.
  50376. */
  50377. static int getAndInitPage(
  50378. BtShared *pBt, /* The database file */
  50379. Pgno pgno, /* Number of the page to get */
  50380. MemPage **ppPage, /* Write the page pointer here */
  50381. int bReadonly /* PAGER_GET_READONLY or 0 */
  50382. ){
  50383. int rc;
  50384. assert( sqlite3_mutex_held(pBt->mutex) );
  50385. assert( bReadonly==PAGER_GET_READONLY || bReadonly==0 );
  50386. if( pgno>btreePagecount(pBt) ){
  50387. rc = SQLITE_CORRUPT_BKPT;
  50388. }else{
  50389. rc = btreeGetPage(pBt, pgno, ppPage, bReadonly);
  50390. if( rc==SQLITE_OK && (*ppPage)->isInit==0 ){
  50391. rc = btreeInitPage(*ppPage);
  50392. if( rc!=SQLITE_OK ){
  50393. releasePage(*ppPage);
  50394. }
  50395. }
  50396. }
  50397. testcase( pgno==0 );
  50398. assert( pgno!=0 || rc==SQLITE_CORRUPT );
  50399. return rc;
  50400. }
  50401. /*
  50402. ** Release a MemPage. This should be called once for each prior
  50403. ** call to btreeGetPage.
  50404. */
  50405. static void releasePage(MemPage *pPage){
  50406. if( pPage ){
  50407. assert( pPage->aData );
  50408. assert( pPage->pBt );
  50409. assert( pPage->pDbPage!=0 );
  50410. assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
  50411. assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
  50412. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  50413. sqlite3PagerUnrefNotNull(pPage->pDbPage);
  50414. }
  50415. }
  50416. /*
  50417. ** During a rollback, when the pager reloads information into the cache
  50418. ** so that the cache is restored to its original state at the start of
  50419. ** the transaction, for each page restored this routine is called.
  50420. **
  50421. ** This routine needs to reset the extra data section at the end of the
  50422. ** page to agree with the restored data.
  50423. */
  50424. static void pageReinit(DbPage *pData){
  50425. MemPage *pPage;
  50426. pPage = (MemPage *)sqlite3PagerGetExtra(pData);
  50427. assert( sqlite3PagerPageRefcount(pData)>0 );
  50428. if( pPage->isInit ){
  50429. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  50430. pPage->isInit = 0;
  50431. if( sqlite3PagerPageRefcount(pData)>1 ){
  50432. /* pPage might not be a btree page; it might be an overflow page
  50433. ** or ptrmap page or a free page. In those cases, the following
  50434. ** call to btreeInitPage() will likely return SQLITE_CORRUPT.
  50435. ** But no harm is done by this. And it is very important that
  50436. ** btreeInitPage() be called on every btree page so we make
  50437. ** the call for every page that comes in for re-initing. */
  50438. btreeInitPage(pPage);
  50439. }
  50440. }
  50441. }
  50442. /*
  50443. ** Invoke the busy handler for a btree.
  50444. */
  50445. static int btreeInvokeBusyHandler(void *pArg){
  50446. BtShared *pBt = (BtShared*)pArg;
  50447. assert( pBt->db );
  50448. assert( sqlite3_mutex_held(pBt->db->mutex) );
  50449. return sqlite3InvokeBusyHandler(&pBt->db->busyHandler);
  50450. }
  50451. /*
  50452. ** Open a database file.
  50453. **
  50454. ** zFilename is the name of the database file. If zFilename is NULL
  50455. ** then an ephemeral database is created. The ephemeral database might
  50456. ** be exclusively in memory, or it might use a disk-based memory cache.
  50457. ** Either way, the ephemeral database will be automatically deleted
  50458. ** when sqlite3BtreeClose() is called.
  50459. **
  50460. ** If zFilename is ":memory:" then an in-memory database is created
  50461. ** that is automatically destroyed when it is closed.
  50462. **
  50463. ** The "flags" parameter is a bitmask that might contain bits like
  50464. ** BTREE_OMIT_JOURNAL and/or BTREE_MEMORY.
  50465. **
  50466. ** If the database is already opened in the same database connection
  50467. ** and we are in shared cache mode, then the open will fail with an
  50468. ** SQLITE_CONSTRAINT error. We cannot allow two or more BtShared
  50469. ** objects in the same database connection since doing so will lead
  50470. ** to problems with locking.
  50471. */
  50472. SQLITE_PRIVATE int sqlite3BtreeOpen(
  50473. sqlite3_vfs *pVfs, /* VFS to use for this b-tree */
  50474. const char *zFilename, /* Name of the file containing the BTree database */
  50475. sqlite3 *db, /* Associated database handle */
  50476. Btree **ppBtree, /* Pointer to new Btree object written here */
  50477. int flags, /* Options */
  50478. int vfsFlags /* Flags passed through to sqlite3_vfs.xOpen() */
  50479. ){
  50480. BtShared *pBt = 0; /* Shared part of btree structure */
  50481. Btree *p; /* Handle to return */
  50482. sqlite3_mutex *mutexOpen = 0; /* Prevents a race condition. Ticket #3537 */
  50483. int rc = SQLITE_OK; /* Result code from this function */
  50484. u8 nReserve; /* Byte of unused space on each page */
  50485. unsigned char zDbHeader[100]; /* Database header content */
  50486. /* True if opening an ephemeral, temporary database */
  50487. const int isTempDb = zFilename==0 || zFilename[0]==0;
  50488. /* Set the variable isMemdb to true for an in-memory database, or
  50489. ** false for a file-based database.
  50490. */
  50491. #ifdef SQLITE_OMIT_MEMORYDB
  50492. const int isMemdb = 0;
  50493. #else
  50494. const int isMemdb = (zFilename && strcmp(zFilename, ":memory:")==0)
  50495. || (isTempDb && sqlite3TempInMemory(db))
  50496. || (vfsFlags & SQLITE_OPEN_MEMORY)!=0;
  50497. #endif
  50498. assert( db!=0 );
  50499. assert( pVfs!=0 );
  50500. assert( sqlite3_mutex_held(db->mutex) );
  50501. assert( (flags&0xff)==flags ); /* flags fit in 8 bits */
  50502. /* Only a BTREE_SINGLE database can be BTREE_UNORDERED */
  50503. assert( (flags & BTREE_UNORDERED)==0 || (flags & BTREE_SINGLE)!=0 );
  50504. /* A BTREE_SINGLE database is always a temporary and/or ephemeral */
  50505. assert( (flags & BTREE_SINGLE)==0 || isTempDb );
  50506. if( isMemdb ){
  50507. flags |= BTREE_MEMORY;
  50508. }
  50509. if( (vfsFlags & SQLITE_OPEN_MAIN_DB)!=0 && (isMemdb || isTempDb) ){
  50510. vfsFlags = (vfsFlags & ~SQLITE_OPEN_MAIN_DB) | SQLITE_OPEN_TEMP_DB;
  50511. }
  50512. p = sqlite3MallocZero(sizeof(Btree));
  50513. if( !p ){
  50514. return SQLITE_NOMEM;
  50515. }
  50516. p->inTrans = TRANS_NONE;
  50517. p->db = db;
  50518. #ifndef SQLITE_OMIT_SHARED_CACHE
  50519. p->lock.pBtree = p;
  50520. p->lock.iTable = 1;
  50521. #endif
  50522. #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
  50523. /*
  50524. ** If this Btree is a candidate for shared cache, try to find an
  50525. ** existing BtShared object that we can share with
  50526. */
  50527. if( isTempDb==0 && (isMemdb==0 || (vfsFlags&SQLITE_OPEN_URI)!=0) ){
  50528. if( vfsFlags & SQLITE_OPEN_SHAREDCACHE ){
  50529. int nFullPathname = pVfs->mxPathname+1;
  50530. char *zFullPathname = sqlite3Malloc(nFullPathname);
  50531. MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
  50532. p->sharable = 1;
  50533. if( !zFullPathname ){
  50534. sqlite3_free(p);
  50535. return SQLITE_NOMEM;
  50536. }
  50537. if( isMemdb ){
  50538. memcpy(zFullPathname, zFilename, sqlite3Strlen30(zFilename)+1);
  50539. }else{
  50540. rc = sqlite3OsFullPathname(pVfs, zFilename,
  50541. nFullPathname, zFullPathname);
  50542. if( rc ){
  50543. sqlite3_free(zFullPathname);
  50544. sqlite3_free(p);
  50545. return rc;
  50546. }
  50547. }
  50548. #if SQLITE_THREADSAFE
  50549. mutexOpen = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_OPEN);
  50550. sqlite3_mutex_enter(mutexOpen);
  50551. mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  50552. sqlite3_mutex_enter(mutexShared);
  50553. #endif
  50554. for(pBt=GLOBAL(BtShared*,sqlite3SharedCacheList); pBt; pBt=pBt->pNext){
  50555. assert( pBt->nRef>0 );
  50556. if( 0==strcmp(zFullPathname, sqlite3PagerFilename(pBt->pPager, 0))
  50557. && sqlite3PagerVfs(pBt->pPager)==pVfs ){
  50558. int iDb;
  50559. for(iDb=db->nDb-1; iDb>=0; iDb--){
  50560. Btree *pExisting = db->aDb[iDb].pBt;
  50561. if( pExisting && pExisting->pBt==pBt ){
  50562. sqlite3_mutex_leave(mutexShared);
  50563. sqlite3_mutex_leave(mutexOpen);
  50564. sqlite3_free(zFullPathname);
  50565. sqlite3_free(p);
  50566. return SQLITE_CONSTRAINT;
  50567. }
  50568. }
  50569. p->pBt = pBt;
  50570. pBt->nRef++;
  50571. break;
  50572. }
  50573. }
  50574. sqlite3_mutex_leave(mutexShared);
  50575. sqlite3_free(zFullPathname);
  50576. }
  50577. #ifdef SQLITE_DEBUG
  50578. else{
  50579. /* In debug mode, we mark all persistent databases as sharable
  50580. ** even when they are not. This exercises the locking code and
  50581. ** gives more opportunity for asserts(sqlite3_mutex_held())
  50582. ** statements to find locking problems.
  50583. */
  50584. p->sharable = 1;
  50585. }
  50586. #endif
  50587. }
  50588. #endif
  50589. if( pBt==0 ){
  50590. /*
  50591. ** The following asserts make sure that structures used by the btree are
  50592. ** the right size. This is to guard against size changes that result
  50593. ** when compiling on a different architecture.
  50594. */
  50595. assert( sizeof(i64)==8 || sizeof(i64)==4 );
  50596. assert( sizeof(u64)==8 || sizeof(u64)==4 );
  50597. assert( sizeof(u32)==4 );
  50598. assert( sizeof(u16)==2 );
  50599. assert( sizeof(Pgno)==4 );
  50600. pBt = sqlite3MallocZero( sizeof(*pBt) );
  50601. if( pBt==0 ){
  50602. rc = SQLITE_NOMEM;
  50603. goto btree_open_out;
  50604. }
  50605. rc = sqlite3PagerOpen(pVfs, &pBt->pPager, zFilename,
  50606. EXTRA_SIZE, flags, vfsFlags, pageReinit);
  50607. if( rc==SQLITE_OK ){
  50608. sqlite3PagerSetMmapLimit(pBt->pPager, db->szMmap);
  50609. rc = sqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader);
  50610. }
  50611. if( rc!=SQLITE_OK ){
  50612. goto btree_open_out;
  50613. }
  50614. pBt->openFlags = (u8)flags;
  50615. pBt->db = db;
  50616. sqlite3PagerSetBusyhandler(pBt->pPager, btreeInvokeBusyHandler, pBt);
  50617. p->pBt = pBt;
  50618. pBt->pCursor = 0;
  50619. pBt->pPage1 = 0;
  50620. if( sqlite3PagerIsreadonly(pBt->pPager) ) pBt->btsFlags |= BTS_READ_ONLY;
  50621. #ifdef SQLITE_SECURE_DELETE
  50622. pBt->btsFlags |= BTS_SECURE_DELETE;
  50623. #endif
  50624. pBt->pageSize = (zDbHeader[16]<<8) | (zDbHeader[17]<<16);
  50625. if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE
  50626. || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){
  50627. pBt->pageSize = 0;
  50628. #ifndef SQLITE_OMIT_AUTOVACUUM
  50629. /* If the magic name ":memory:" will create an in-memory database, then
  50630. ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if
  50631. ** SQLITE_DEFAULT_AUTOVACUUM is true. On the other hand, if
  50632. ** SQLITE_OMIT_MEMORYDB has been defined, then ":memory:" is just a
  50633. ** regular file-name. In this case the auto-vacuum applies as per normal.
  50634. */
  50635. if( zFilename && !isMemdb ){
  50636. pBt->autoVacuum = (SQLITE_DEFAULT_AUTOVACUUM ? 1 : 0);
  50637. pBt->incrVacuum = (SQLITE_DEFAULT_AUTOVACUUM==2 ? 1 : 0);
  50638. }
  50639. #endif
  50640. nReserve = 0;
  50641. }else{
  50642. nReserve = zDbHeader[20];
  50643. pBt->btsFlags |= BTS_PAGESIZE_FIXED;
  50644. #ifndef SQLITE_OMIT_AUTOVACUUM
  50645. pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0);
  50646. pBt->incrVacuum = (get4byte(&zDbHeader[36 + 7*4])?1:0);
  50647. #endif
  50648. }
  50649. rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
  50650. if( rc ) goto btree_open_out;
  50651. pBt->usableSize = pBt->pageSize - nReserve;
  50652. assert( (pBt->pageSize & 7)==0 ); /* 8-byte alignment of pageSize */
  50653. #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
  50654. /* Add the new BtShared object to the linked list sharable BtShareds.
  50655. */
  50656. if( p->sharable ){
  50657. MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
  50658. pBt->nRef = 1;
  50659. MUTEX_LOGIC( mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);)
  50660. if( SQLITE_THREADSAFE && sqlite3GlobalConfig.bCoreMutex ){
  50661. pBt->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_FAST);
  50662. if( pBt->mutex==0 ){
  50663. rc = SQLITE_NOMEM;
  50664. db->mallocFailed = 0;
  50665. goto btree_open_out;
  50666. }
  50667. }
  50668. sqlite3_mutex_enter(mutexShared);
  50669. pBt->pNext = GLOBAL(BtShared*,sqlite3SharedCacheList);
  50670. GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt;
  50671. sqlite3_mutex_leave(mutexShared);
  50672. }
  50673. #endif
  50674. }
  50675. #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
  50676. /* If the new Btree uses a sharable pBtShared, then link the new
  50677. ** Btree into the list of all sharable Btrees for the same connection.
  50678. ** The list is kept in ascending order by pBt address.
  50679. */
  50680. if( p->sharable ){
  50681. int i;
  50682. Btree *pSib;
  50683. for(i=0; i<db->nDb; i++){
  50684. if( (pSib = db->aDb[i].pBt)!=0 && pSib->sharable ){
  50685. while( pSib->pPrev ){ pSib = pSib->pPrev; }
  50686. if( p->pBt<pSib->pBt ){
  50687. p->pNext = pSib;
  50688. p->pPrev = 0;
  50689. pSib->pPrev = p;
  50690. }else{
  50691. while( pSib->pNext && pSib->pNext->pBt<p->pBt ){
  50692. pSib = pSib->pNext;
  50693. }
  50694. p->pNext = pSib->pNext;
  50695. p->pPrev = pSib;
  50696. if( p->pNext ){
  50697. p->pNext->pPrev = p;
  50698. }
  50699. pSib->pNext = p;
  50700. }
  50701. break;
  50702. }
  50703. }
  50704. }
  50705. #endif
  50706. *ppBtree = p;
  50707. btree_open_out:
  50708. if( rc!=SQLITE_OK ){
  50709. if( pBt && pBt->pPager ){
  50710. sqlite3PagerClose(pBt->pPager);
  50711. }
  50712. sqlite3_free(pBt);
  50713. sqlite3_free(p);
  50714. *ppBtree = 0;
  50715. }else{
  50716. /* If the B-Tree was successfully opened, set the pager-cache size to the
  50717. ** default value. Except, when opening on an existing shared pager-cache,
  50718. ** do not change the pager-cache size.
  50719. */
  50720. if( sqlite3BtreeSchema(p, 0, 0)==0 ){
  50721. sqlite3PagerSetCachesize(p->pBt->pPager, SQLITE_DEFAULT_CACHE_SIZE);
  50722. }
  50723. }
  50724. if( mutexOpen ){
  50725. assert( sqlite3_mutex_held(mutexOpen) );
  50726. sqlite3_mutex_leave(mutexOpen);
  50727. }
  50728. return rc;
  50729. }
  50730. /*
  50731. ** Decrement the BtShared.nRef counter. When it reaches zero,
  50732. ** remove the BtShared structure from the sharing list. Return
  50733. ** true if the BtShared.nRef counter reaches zero and return
  50734. ** false if it is still positive.
  50735. */
  50736. static int removeFromSharingList(BtShared *pBt){
  50737. #ifndef SQLITE_OMIT_SHARED_CACHE
  50738. MUTEX_LOGIC( sqlite3_mutex *pMaster; )
  50739. BtShared *pList;
  50740. int removed = 0;
  50741. assert( sqlite3_mutex_notheld(pBt->mutex) );
  50742. MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
  50743. sqlite3_mutex_enter(pMaster);
  50744. pBt->nRef--;
  50745. if( pBt->nRef<=0 ){
  50746. if( GLOBAL(BtShared*,sqlite3SharedCacheList)==pBt ){
  50747. GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt->pNext;
  50748. }else{
  50749. pList = GLOBAL(BtShared*,sqlite3SharedCacheList);
  50750. while( ALWAYS(pList) && pList->pNext!=pBt ){
  50751. pList=pList->pNext;
  50752. }
  50753. if( ALWAYS(pList) ){
  50754. pList->pNext = pBt->pNext;
  50755. }
  50756. }
  50757. if( SQLITE_THREADSAFE ){
  50758. sqlite3_mutex_free(pBt->mutex);
  50759. }
  50760. removed = 1;
  50761. }
  50762. sqlite3_mutex_leave(pMaster);
  50763. return removed;
  50764. #else
  50765. return 1;
  50766. #endif
  50767. }
  50768. /*
  50769. ** Make sure pBt->pTmpSpace points to an allocation of
  50770. ** MX_CELL_SIZE(pBt) bytes with a 4-byte prefix for a left-child
  50771. ** pointer.
  50772. */
  50773. static void allocateTempSpace(BtShared *pBt){
  50774. if( !pBt->pTmpSpace ){
  50775. pBt->pTmpSpace = sqlite3PageMalloc( pBt->pageSize );
  50776. /* One of the uses of pBt->pTmpSpace is to format cells before
  50777. ** inserting them into a leaf page (function fillInCell()). If
  50778. ** a cell is less than 4 bytes in size, it is rounded up to 4 bytes
  50779. ** by the various routines that manipulate binary cells. Which
  50780. ** can mean that fillInCell() only initializes the first 2 or 3
  50781. ** bytes of pTmpSpace, but that the first 4 bytes are copied from
  50782. ** it into a database page. This is not actually a problem, but it
  50783. ** does cause a valgrind error when the 1 or 2 bytes of unitialized
  50784. ** data is passed to system call write(). So to avoid this error,
  50785. ** zero the first 4 bytes of temp space here.
  50786. **
  50787. ** Also: Provide four bytes of initialized space before the
  50788. ** beginning of pTmpSpace as an area available to prepend the
  50789. ** left-child pointer to the beginning of a cell.
  50790. */
  50791. if( pBt->pTmpSpace ){
  50792. memset(pBt->pTmpSpace, 0, 8);
  50793. pBt->pTmpSpace += 4;
  50794. }
  50795. }
  50796. }
  50797. /*
  50798. ** Free the pBt->pTmpSpace allocation
  50799. */
  50800. static void freeTempSpace(BtShared *pBt){
  50801. if( pBt->pTmpSpace ){
  50802. pBt->pTmpSpace -= 4;
  50803. sqlite3PageFree(pBt->pTmpSpace);
  50804. pBt->pTmpSpace = 0;
  50805. }
  50806. }
  50807. /*
  50808. ** Close an open database and invalidate all cursors.
  50809. */
  50810. SQLITE_PRIVATE int sqlite3BtreeClose(Btree *p){
  50811. BtShared *pBt = p->pBt;
  50812. BtCursor *pCur;
  50813. /* Close all cursors opened via this handle. */
  50814. assert( sqlite3_mutex_held(p->db->mutex) );
  50815. sqlite3BtreeEnter(p);
  50816. pCur = pBt->pCursor;
  50817. while( pCur ){
  50818. BtCursor *pTmp = pCur;
  50819. pCur = pCur->pNext;
  50820. if( pTmp->pBtree==p ){
  50821. sqlite3BtreeCloseCursor(pTmp);
  50822. }
  50823. }
  50824. /* Rollback any active transaction and free the handle structure.
  50825. ** The call to sqlite3BtreeRollback() drops any table-locks held by
  50826. ** this handle.
  50827. */
  50828. sqlite3BtreeRollback(p, SQLITE_OK);
  50829. sqlite3BtreeLeave(p);
  50830. /* If there are still other outstanding references to the shared-btree
  50831. ** structure, return now. The remainder of this procedure cleans
  50832. ** up the shared-btree.
  50833. */
  50834. assert( p->wantToLock==0 && p->locked==0 );
  50835. if( !p->sharable || removeFromSharingList(pBt) ){
  50836. /* The pBt is no longer on the sharing list, so we can access
  50837. ** it without having to hold the mutex.
  50838. **
  50839. ** Clean out and delete the BtShared object.
  50840. */
  50841. assert( !pBt->pCursor );
  50842. sqlite3PagerClose(pBt->pPager);
  50843. if( pBt->xFreeSchema && pBt->pSchema ){
  50844. pBt->xFreeSchema(pBt->pSchema);
  50845. }
  50846. sqlite3DbFree(0, pBt->pSchema);
  50847. freeTempSpace(pBt);
  50848. sqlite3_free(pBt);
  50849. }
  50850. #ifndef SQLITE_OMIT_SHARED_CACHE
  50851. assert( p->wantToLock==0 );
  50852. assert( p->locked==0 );
  50853. if( p->pPrev ) p->pPrev->pNext = p->pNext;
  50854. if( p->pNext ) p->pNext->pPrev = p->pPrev;
  50855. #endif
  50856. sqlite3_free(p);
  50857. return SQLITE_OK;
  50858. }
  50859. /*
  50860. ** Change the limit on the number of pages allowed in the cache.
  50861. **
  50862. ** The maximum number of cache pages is set to the absolute
  50863. ** value of mxPage. If mxPage is negative, the pager will
  50864. ** operate asynchronously - it will not stop to do fsync()s
  50865. ** to insure data is written to the disk surface before
  50866. ** continuing. Transactions still work if synchronous is off,
  50867. ** and the database cannot be corrupted if this program
  50868. ** crashes. But if the operating system crashes or there is
  50869. ** an abrupt power failure when synchronous is off, the database
  50870. ** could be left in an inconsistent and unrecoverable state.
  50871. ** Synchronous is on by default so database corruption is not
  50872. ** normally a worry.
  50873. */
  50874. SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){
  50875. BtShared *pBt = p->pBt;
  50876. assert( sqlite3_mutex_held(p->db->mutex) );
  50877. sqlite3BtreeEnter(p);
  50878. sqlite3PagerSetCachesize(pBt->pPager, mxPage);
  50879. sqlite3BtreeLeave(p);
  50880. return SQLITE_OK;
  50881. }
  50882. #if SQLITE_MAX_MMAP_SIZE>0
  50883. /*
  50884. ** Change the limit on the amount of the database file that may be
  50885. ** memory mapped.
  50886. */
  50887. SQLITE_PRIVATE int sqlite3BtreeSetMmapLimit(Btree *p, sqlite3_int64 szMmap){
  50888. BtShared *pBt = p->pBt;
  50889. assert( sqlite3_mutex_held(p->db->mutex) );
  50890. sqlite3BtreeEnter(p);
  50891. sqlite3PagerSetMmapLimit(pBt->pPager, szMmap);
  50892. sqlite3BtreeLeave(p);
  50893. return SQLITE_OK;
  50894. }
  50895. #endif /* SQLITE_MAX_MMAP_SIZE>0 */
  50896. /*
  50897. ** Change the way data is synced to disk in order to increase or decrease
  50898. ** how well the database resists damage due to OS crashes and power
  50899. ** failures. Level 1 is the same as asynchronous (no syncs() occur and
  50900. ** there is a high probability of damage) Level 2 is the default. There
  50901. ** is a very low but non-zero probability of damage. Level 3 reduces the
  50902. ** probability of damage to near zero but with a write performance reduction.
  50903. */
  50904. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  50905. SQLITE_PRIVATE int sqlite3BtreeSetPagerFlags(
  50906. Btree *p, /* The btree to set the safety level on */
  50907. unsigned pgFlags /* Various PAGER_* flags */
  50908. ){
  50909. BtShared *pBt = p->pBt;
  50910. assert( sqlite3_mutex_held(p->db->mutex) );
  50911. sqlite3BtreeEnter(p);
  50912. sqlite3PagerSetFlags(pBt->pPager, pgFlags);
  50913. sqlite3BtreeLeave(p);
  50914. return SQLITE_OK;
  50915. }
  50916. #endif
  50917. /*
  50918. ** Return TRUE if the given btree is set to safety level 1. In other
  50919. ** words, return TRUE if no sync() occurs on the disk files.
  50920. */
  50921. SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree *p){
  50922. BtShared *pBt = p->pBt;
  50923. int rc;
  50924. assert( sqlite3_mutex_held(p->db->mutex) );
  50925. sqlite3BtreeEnter(p);
  50926. assert( pBt && pBt->pPager );
  50927. rc = sqlite3PagerNosync(pBt->pPager);
  50928. sqlite3BtreeLeave(p);
  50929. return rc;
  50930. }
  50931. /*
  50932. ** Change the default pages size and the number of reserved bytes per page.
  50933. ** Or, if the page size has already been fixed, return SQLITE_READONLY
  50934. ** without changing anything.
  50935. **
  50936. ** The page size must be a power of 2 between 512 and 65536. If the page
  50937. ** size supplied does not meet this constraint then the page size is not
  50938. ** changed.
  50939. **
  50940. ** Page sizes are constrained to be a power of two so that the region
  50941. ** of the database file used for locking (beginning at PENDING_BYTE,
  50942. ** the first byte past the 1GB boundary, 0x40000000) needs to occur
  50943. ** at the beginning of a page.
  50944. **
  50945. ** If parameter nReserve is less than zero, then the number of reserved
  50946. ** bytes per page is left unchanged.
  50947. **
  50948. ** If the iFix!=0 then the BTS_PAGESIZE_FIXED flag is set so that the page size
  50949. ** and autovacuum mode can no longer be changed.
  50950. */
  50951. SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve, int iFix){
  50952. int rc = SQLITE_OK;
  50953. BtShared *pBt = p->pBt;
  50954. assert( nReserve>=-1 && nReserve<=255 );
  50955. sqlite3BtreeEnter(p);
  50956. if( pBt->btsFlags & BTS_PAGESIZE_FIXED ){
  50957. sqlite3BtreeLeave(p);
  50958. return SQLITE_READONLY;
  50959. }
  50960. if( nReserve<0 ){
  50961. nReserve = pBt->pageSize - pBt->usableSize;
  50962. }
  50963. assert( nReserve>=0 && nReserve<=255 );
  50964. if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE &&
  50965. ((pageSize-1)&pageSize)==0 ){
  50966. assert( (pageSize & 7)==0 );
  50967. assert( !pBt->pPage1 && !pBt->pCursor );
  50968. pBt->pageSize = (u32)pageSize;
  50969. freeTempSpace(pBt);
  50970. }
  50971. rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
  50972. pBt->usableSize = pBt->pageSize - (u16)nReserve;
  50973. if( iFix ) pBt->btsFlags |= BTS_PAGESIZE_FIXED;
  50974. sqlite3BtreeLeave(p);
  50975. return rc;
  50976. }
  50977. /*
  50978. ** Return the currently defined page size
  50979. */
  50980. SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree *p){
  50981. return p->pBt->pageSize;
  50982. }
  50983. #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_DEBUG)
  50984. /*
  50985. ** This function is similar to sqlite3BtreeGetReserve(), except that it
  50986. ** may only be called if it is guaranteed that the b-tree mutex is already
  50987. ** held.
  50988. **
  50989. ** This is useful in one special case in the backup API code where it is
  50990. ** known that the shared b-tree mutex is held, but the mutex on the
  50991. ** database handle that owns *p is not. In this case if sqlite3BtreeEnter()
  50992. ** were to be called, it might collide with some other operation on the
  50993. ** database handle that owns *p, causing undefined behavior.
  50994. */
  50995. SQLITE_PRIVATE int sqlite3BtreeGetReserveNoMutex(Btree *p){
  50996. assert( sqlite3_mutex_held(p->pBt->mutex) );
  50997. return p->pBt->pageSize - p->pBt->usableSize;
  50998. }
  50999. #endif /* SQLITE_HAS_CODEC || SQLITE_DEBUG */
  51000. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM)
  51001. /*
  51002. ** Return the number of bytes of space at the end of every page that
  51003. ** are intentually left unused. This is the "reserved" space that is
  51004. ** sometimes used by extensions.
  51005. */
  51006. SQLITE_PRIVATE int sqlite3BtreeGetReserve(Btree *p){
  51007. int n;
  51008. sqlite3BtreeEnter(p);
  51009. n = p->pBt->pageSize - p->pBt->usableSize;
  51010. sqlite3BtreeLeave(p);
  51011. return n;
  51012. }
  51013. /*
  51014. ** Set the maximum page count for a database if mxPage is positive.
  51015. ** No changes are made if mxPage is 0 or negative.
  51016. ** Regardless of the value of mxPage, return the maximum page count.
  51017. */
  51018. SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree *p, int mxPage){
  51019. int n;
  51020. sqlite3BtreeEnter(p);
  51021. n = sqlite3PagerMaxPageCount(p->pBt->pPager, mxPage);
  51022. sqlite3BtreeLeave(p);
  51023. return n;
  51024. }
  51025. /*
  51026. ** Set the BTS_SECURE_DELETE flag if newFlag is 0 or 1. If newFlag is -1,
  51027. ** then make no changes. Always return the value of the BTS_SECURE_DELETE
  51028. ** setting after the change.
  51029. */
  51030. SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree *p, int newFlag){
  51031. int b;
  51032. if( p==0 ) return 0;
  51033. sqlite3BtreeEnter(p);
  51034. if( newFlag>=0 ){
  51035. p->pBt->btsFlags &= ~BTS_SECURE_DELETE;
  51036. if( newFlag ) p->pBt->btsFlags |= BTS_SECURE_DELETE;
  51037. }
  51038. b = (p->pBt->btsFlags & BTS_SECURE_DELETE)!=0;
  51039. sqlite3BtreeLeave(p);
  51040. return b;
  51041. }
  51042. #endif /* !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM) */
  51043. /*
  51044. ** Change the 'auto-vacuum' property of the database. If the 'autoVacuum'
  51045. ** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it
  51046. ** is disabled. The default value for the auto-vacuum property is
  51047. ** determined by the SQLITE_DEFAULT_AUTOVACUUM macro.
  51048. */
  51049. SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){
  51050. #ifdef SQLITE_OMIT_AUTOVACUUM
  51051. return SQLITE_READONLY;
  51052. #else
  51053. BtShared *pBt = p->pBt;
  51054. int rc = SQLITE_OK;
  51055. u8 av = (u8)autoVacuum;
  51056. sqlite3BtreeEnter(p);
  51057. if( (pBt->btsFlags & BTS_PAGESIZE_FIXED)!=0 && (av ?1:0)!=pBt->autoVacuum ){
  51058. rc = SQLITE_READONLY;
  51059. }else{
  51060. pBt->autoVacuum = av ?1:0;
  51061. pBt->incrVacuum = av==2 ?1:0;
  51062. }
  51063. sqlite3BtreeLeave(p);
  51064. return rc;
  51065. #endif
  51066. }
  51067. /*
  51068. ** Return the value of the 'auto-vacuum' property. If auto-vacuum is
  51069. ** enabled 1 is returned. Otherwise 0.
  51070. */
  51071. SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *p){
  51072. #ifdef SQLITE_OMIT_AUTOVACUUM
  51073. return BTREE_AUTOVACUUM_NONE;
  51074. #else
  51075. int rc;
  51076. sqlite3BtreeEnter(p);
  51077. rc = (
  51078. (!p->pBt->autoVacuum)?BTREE_AUTOVACUUM_NONE:
  51079. (!p->pBt->incrVacuum)?BTREE_AUTOVACUUM_FULL:
  51080. BTREE_AUTOVACUUM_INCR
  51081. );
  51082. sqlite3BtreeLeave(p);
  51083. return rc;
  51084. #endif
  51085. }
  51086. /*
  51087. ** Get a reference to pPage1 of the database file. This will
  51088. ** also acquire a readlock on that file.
  51089. **
  51090. ** SQLITE_OK is returned on success. If the file is not a
  51091. ** well-formed database file, then SQLITE_CORRUPT is returned.
  51092. ** SQLITE_BUSY is returned if the database is locked. SQLITE_NOMEM
  51093. ** is returned if we run out of memory.
  51094. */
  51095. static int lockBtree(BtShared *pBt){
  51096. int rc; /* Result code from subfunctions */
  51097. MemPage *pPage1; /* Page 1 of the database file */
  51098. int nPage; /* Number of pages in the database */
  51099. int nPageFile = 0; /* Number of pages in the database file */
  51100. int nPageHeader; /* Number of pages in the database according to hdr */
  51101. assert( sqlite3_mutex_held(pBt->mutex) );
  51102. assert( pBt->pPage1==0 );
  51103. rc = sqlite3PagerSharedLock(pBt->pPager);
  51104. if( rc!=SQLITE_OK ) return rc;
  51105. rc = btreeGetPage(pBt, 1, &pPage1, 0);
  51106. if( rc!=SQLITE_OK ) return rc;
  51107. /* Do some checking to help insure the file we opened really is
  51108. ** a valid database file.
  51109. */
  51110. nPage = nPageHeader = get4byte(28+(u8*)pPage1->aData);
  51111. sqlite3PagerPagecount(pBt->pPager, &nPageFile);
  51112. if( nPage==0 || memcmp(24+(u8*)pPage1->aData, 92+(u8*)pPage1->aData,4)!=0 ){
  51113. nPage = nPageFile;
  51114. }
  51115. if( nPage>0 ){
  51116. u32 pageSize;
  51117. u32 usableSize;
  51118. u8 *page1 = pPage1->aData;
  51119. rc = SQLITE_NOTADB;
  51120. if( memcmp(page1, zMagicHeader, 16)!=0 ){
  51121. goto page1_init_failed;
  51122. }
  51123. #ifdef SQLITE_OMIT_WAL
  51124. if( page1[18]>1 ){
  51125. pBt->btsFlags |= BTS_READ_ONLY;
  51126. }
  51127. if( page1[19]>1 ){
  51128. goto page1_init_failed;
  51129. }
  51130. #else
  51131. if( page1[18]>2 ){
  51132. pBt->btsFlags |= BTS_READ_ONLY;
  51133. }
  51134. if( page1[19]>2 ){
  51135. goto page1_init_failed;
  51136. }
  51137. /* If the write version is set to 2, this database should be accessed
  51138. ** in WAL mode. If the log is not already open, open it now. Then
  51139. ** return SQLITE_OK and return without populating BtShared.pPage1.
  51140. ** The caller detects this and calls this function again. This is
  51141. ** required as the version of page 1 currently in the page1 buffer
  51142. ** may not be the latest version - there may be a newer one in the log
  51143. ** file.
  51144. */
  51145. if( page1[19]==2 && (pBt->btsFlags & BTS_NO_WAL)==0 ){
  51146. int isOpen = 0;
  51147. rc = sqlite3PagerOpenWal(pBt->pPager, &isOpen);
  51148. if( rc!=SQLITE_OK ){
  51149. goto page1_init_failed;
  51150. }else if( isOpen==0 ){
  51151. releasePage(pPage1);
  51152. return SQLITE_OK;
  51153. }
  51154. rc = SQLITE_NOTADB;
  51155. }
  51156. #endif
  51157. /* The maximum embedded fraction must be exactly 25%. And the minimum
  51158. ** embedded fraction must be 12.5% for both leaf-data and non-leaf-data.
  51159. ** The original design allowed these amounts to vary, but as of
  51160. ** version 3.6.0, we require them to be fixed.
  51161. */
  51162. if( memcmp(&page1[21], "\100\040\040",3)!=0 ){
  51163. goto page1_init_failed;
  51164. }
  51165. pageSize = (page1[16]<<8) | (page1[17]<<16);
  51166. if( ((pageSize-1)&pageSize)!=0
  51167. || pageSize>SQLITE_MAX_PAGE_SIZE
  51168. || pageSize<=256
  51169. ){
  51170. goto page1_init_failed;
  51171. }
  51172. assert( (pageSize & 7)==0 );
  51173. usableSize = pageSize - page1[20];
  51174. if( (u32)pageSize!=pBt->pageSize ){
  51175. /* After reading the first page of the database assuming a page size
  51176. ** of BtShared.pageSize, we have discovered that the page-size is
  51177. ** actually pageSize. Unlock the database, leave pBt->pPage1 at
  51178. ** zero and return SQLITE_OK. The caller will call this function
  51179. ** again with the correct page-size.
  51180. */
  51181. releasePage(pPage1);
  51182. pBt->usableSize = usableSize;
  51183. pBt->pageSize = pageSize;
  51184. freeTempSpace(pBt);
  51185. rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize,
  51186. pageSize-usableSize);
  51187. return rc;
  51188. }
  51189. if( (pBt->db->flags & SQLITE_RecoveryMode)==0 && nPage>nPageFile ){
  51190. rc = SQLITE_CORRUPT_BKPT;
  51191. goto page1_init_failed;
  51192. }
  51193. if( usableSize<480 ){
  51194. goto page1_init_failed;
  51195. }
  51196. pBt->pageSize = pageSize;
  51197. pBt->usableSize = usableSize;
  51198. #ifndef SQLITE_OMIT_AUTOVACUUM
  51199. pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0);
  51200. pBt->incrVacuum = (get4byte(&page1[36 + 7*4])?1:0);
  51201. #endif
  51202. }
  51203. /* maxLocal is the maximum amount of payload to store locally for
  51204. ** a cell. Make sure it is small enough so that at least minFanout
  51205. ** cells can will fit on one page. We assume a 10-byte page header.
  51206. ** Besides the payload, the cell must store:
  51207. ** 2-byte pointer to the cell
  51208. ** 4-byte child pointer
  51209. ** 9-byte nKey value
  51210. ** 4-byte nData value
  51211. ** 4-byte overflow page pointer
  51212. ** So a cell consists of a 2-byte pointer, a header which is as much as
  51213. ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow
  51214. ** page pointer.
  51215. */
  51216. pBt->maxLocal = (u16)((pBt->usableSize-12)*64/255 - 23);
  51217. pBt->minLocal = (u16)((pBt->usableSize-12)*32/255 - 23);
  51218. pBt->maxLeaf = (u16)(pBt->usableSize - 35);
  51219. pBt->minLeaf = (u16)((pBt->usableSize-12)*32/255 - 23);
  51220. if( pBt->maxLocal>127 ){
  51221. pBt->max1bytePayload = 127;
  51222. }else{
  51223. pBt->max1bytePayload = (u8)pBt->maxLocal;
  51224. }
  51225. assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) );
  51226. pBt->pPage1 = pPage1;
  51227. pBt->nPage = nPage;
  51228. return SQLITE_OK;
  51229. page1_init_failed:
  51230. releasePage(pPage1);
  51231. pBt->pPage1 = 0;
  51232. return rc;
  51233. }
  51234. #ifndef NDEBUG
  51235. /*
  51236. ** Return the number of cursors open on pBt. This is for use
  51237. ** in assert() expressions, so it is only compiled if NDEBUG is not
  51238. ** defined.
  51239. **
  51240. ** Only write cursors are counted if wrOnly is true. If wrOnly is
  51241. ** false then all cursors are counted.
  51242. **
  51243. ** For the purposes of this routine, a cursor is any cursor that
  51244. ** is capable of reading or writing to the database. Cursors that
  51245. ** have been tripped into the CURSOR_FAULT state are not counted.
  51246. */
  51247. static int countValidCursors(BtShared *pBt, int wrOnly){
  51248. BtCursor *pCur;
  51249. int r = 0;
  51250. for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
  51251. if( (wrOnly==0 || (pCur->curFlags & BTCF_WriteFlag)!=0)
  51252. && pCur->eState!=CURSOR_FAULT ) r++;
  51253. }
  51254. return r;
  51255. }
  51256. #endif
  51257. /*
  51258. ** If there are no outstanding cursors and we are not in the middle
  51259. ** of a transaction but there is a read lock on the database, then
  51260. ** this routine unrefs the first page of the database file which
  51261. ** has the effect of releasing the read lock.
  51262. **
  51263. ** If there is a transaction in progress, this routine is a no-op.
  51264. */
  51265. static void unlockBtreeIfUnused(BtShared *pBt){
  51266. assert( sqlite3_mutex_held(pBt->mutex) );
  51267. assert( countValidCursors(pBt,0)==0 || pBt->inTransaction>TRANS_NONE );
  51268. if( pBt->inTransaction==TRANS_NONE && pBt->pPage1!=0 ){
  51269. MemPage *pPage1 = pBt->pPage1;
  51270. assert( pPage1->aData );
  51271. assert( sqlite3PagerRefcount(pBt->pPager)==1 );
  51272. pBt->pPage1 = 0;
  51273. releasePage(pPage1);
  51274. }
  51275. }
  51276. /*
  51277. ** If pBt points to an empty file then convert that empty file
  51278. ** into a new empty database by initializing the first page of
  51279. ** the database.
  51280. */
  51281. static int newDatabase(BtShared *pBt){
  51282. MemPage *pP1;
  51283. unsigned char *data;
  51284. int rc;
  51285. assert( sqlite3_mutex_held(pBt->mutex) );
  51286. if( pBt->nPage>0 ){
  51287. return SQLITE_OK;
  51288. }
  51289. pP1 = pBt->pPage1;
  51290. assert( pP1!=0 );
  51291. data = pP1->aData;
  51292. rc = sqlite3PagerWrite(pP1->pDbPage);
  51293. if( rc ) return rc;
  51294. memcpy(data, zMagicHeader, sizeof(zMagicHeader));
  51295. assert( sizeof(zMagicHeader)==16 );
  51296. data[16] = (u8)((pBt->pageSize>>8)&0xff);
  51297. data[17] = (u8)((pBt->pageSize>>16)&0xff);
  51298. data[18] = 1;
  51299. data[19] = 1;
  51300. assert( pBt->usableSize<=pBt->pageSize && pBt->usableSize+255>=pBt->pageSize);
  51301. data[20] = (u8)(pBt->pageSize - pBt->usableSize);
  51302. data[21] = 64;
  51303. data[22] = 32;
  51304. data[23] = 32;
  51305. memset(&data[24], 0, 100-24);
  51306. zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA );
  51307. pBt->btsFlags |= BTS_PAGESIZE_FIXED;
  51308. #ifndef SQLITE_OMIT_AUTOVACUUM
  51309. assert( pBt->autoVacuum==1 || pBt->autoVacuum==0 );
  51310. assert( pBt->incrVacuum==1 || pBt->incrVacuum==0 );
  51311. put4byte(&data[36 + 4*4], pBt->autoVacuum);
  51312. put4byte(&data[36 + 7*4], pBt->incrVacuum);
  51313. #endif
  51314. pBt->nPage = 1;
  51315. data[31] = 1;
  51316. return SQLITE_OK;
  51317. }
  51318. /*
  51319. ** Initialize the first page of the database file (creating a database
  51320. ** consisting of a single page and no schema objects). Return SQLITE_OK
  51321. ** if successful, or an SQLite error code otherwise.
  51322. */
  51323. SQLITE_PRIVATE int sqlite3BtreeNewDb(Btree *p){
  51324. int rc;
  51325. sqlite3BtreeEnter(p);
  51326. p->pBt->nPage = 0;
  51327. rc = newDatabase(p->pBt);
  51328. sqlite3BtreeLeave(p);
  51329. return rc;
  51330. }
  51331. /*
  51332. ** Attempt to start a new transaction. A write-transaction
  51333. ** is started if the second argument is nonzero, otherwise a read-
  51334. ** transaction. If the second argument is 2 or more and exclusive
  51335. ** transaction is started, meaning that no other process is allowed
  51336. ** to access the database. A preexisting transaction may not be
  51337. ** upgraded to exclusive by calling this routine a second time - the
  51338. ** exclusivity flag only works for a new transaction.
  51339. **
  51340. ** A write-transaction must be started before attempting any
  51341. ** changes to the database. None of the following routines
  51342. ** will work unless a transaction is started first:
  51343. **
  51344. ** sqlite3BtreeCreateTable()
  51345. ** sqlite3BtreeCreateIndex()
  51346. ** sqlite3BtreeClearTable()
  51347. ** sqlite3BtreeDropTable()
  51348. ** sqlite3BtreeInsert()
  51349. ** sqlite3BtreeDelete()
  51350. ** sqlite3BtreeUpdateMeta()
  51351. **
  51352. ** If an initial attempt to acquire the lock fails because of lock contention
  51353. ** and the database was previously unlocked, then invoke the busy handler
  51354. ** if there is one. But if there was previously a read-lock, do not
  51355. ** invoke the busy handler - just return SQLITE_BUSY. SQLITE_BUSY is
  51356. ** returned when there is already a read-lock in order to avoid a deadlock.
  51357. **
  51358. ** Suppose there are two processes A and B. A has a read lock and B has
  51359. ** a reserved lock. B tries to promote to exclusive but is blocked because
  51360. ** of A's read lock. A tries to promote to reserved but is blocked by B.
  51361. ** One or the other of the two processes must give way or there can be
  51362. ** no progress. By returning SQLITE_BUSY and not invoking the busy callback
  51363. ** when A already has a read lock, we encourage A to give up and let B
  51364. ** proceed.
  51365. */
  51366. SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree *p, int wrflag){
  51367. sqlite3 *pBlock = 0;
  51368. BtShared *pBt = p->pBt;
  51369. int rc = SQLITE_OK;
  51370. sqlite3BtreeEnter(p);
  51371. btreeIntegrity(p);
  51372. /* If the btree is already in a write-transaction, or it
  51373. ** is already in a read-transaction and a read-transaction
  51374. ** is requested, this is a no-op.
  51375. */
  51376. if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){
  51377. goto trans_begun;
  51378. }
  51379. assert( pBt->inTransaction==TRANS_WRITE || IfNotOmitAV(pBt->bDoTruncate)==0 );
  51380. /* Write transactions are not possible on a read-only database */
  51381. if( (pBt->btsFlags & BTS_READ_ONLY)!=0 && wrflag ){
  51382. rc = SQLITE_READONLY;
  51383. goto trans_begun;
  51384. }
  51385. #ifndef SQLITE_OMIT_SHARED_CACHE
  51386. /* If another database handle has already opened a write transaction
  51387. ** on this shared-btree structure and a second write transaction is
  51388. ** requested, return SQLITE_LOCKED.
  51389. */
  51390. if( (wrflag && pBt->inTransaction==TRANS_WRITE)
  51391. || (pBt->btsFlags & BTS_PENDING)!=0
  51392. ){
  51393. pBlock = pBt->pWriter->db;
  51394. }else if( wrflag>1 ){
  51395. BtLock *pIter;
  51396. for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
  51397. if( pIter->pBtree!=p ){
  51398. pBlock = pIter->pBtree->db;
  51399. break;
  51400. }
  51401. }
  51402. }
  51403. if( pBlock ){
  51404. sqlite3ConnectionBlocked(p->db, pBlock);
  51405. rc = SQLITE_LOCKED_SHAREDCACHE;
  51406. goto trans_begun;
  51407. }
  51408. #endif
  51409. /* Any read-only or read-write transaction implies a read-lock on
  51410. ** page 1. So if some other shared-cache client already has a write-lock
  51411. ** on page 1, the transaction cannot be opened. */
  51412. rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
  51413. if( SQLITE_OK!=rc ) goto trans_begun;
  51414. pBt->btsFlags &= ~BTS_INITIALLY_EMPTY;
  51415. if( pBt->nPage==0 ) pBt->btsFlags |= BTS_INITIALLY_EMPTY;
  51416. do {
  51417. /* Call lockBtree() until either pBt->pPage1 is populated or
  51418. ** lockBtree() returns something other than SQLITE_OK. lockBtree()
  51419. ** may return SQLITE_OK but leave pBt->pPage1 set to 0 if after
  51420. ** reading page 1 it discovers that the page-size of the database
  51421. ** file is not pBt->pageSize. In this case lockBtree() will update
  51422. ** pBt->pageSize to the page-size of the file on disk.
  51423. */
  51424. while( pBt->pPage1==0 && SQLITE_OK==(rc = lockBtree(pBt)) );
  51425. if( rc==SQLITE_OK && wrflag ){
  51426. if( (pBt->btsFlags & BTS_READ_ONLY)!=0 ){
  51427. rc = SQLITE_READONLY;
  51428. }else{
  51429. rc = sqlite3PagerBegin(pBt->pPager,wrflag>1,sqlite3TempInMemory(p->db));
  51430. if( rc==SQLITE_OK ){
  51431. rc = newDatabase(pBt);
  51432. }
  51433. }
  51434. }
  51435. if( rc!=SQLITE_OK ){
  51436. unlockBtreeIfUnused(pBt);
  51437. }
  51438. }while( (rc&0xFF)==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE &&
  51439. btreeInvokeBusyHandler(pBt) );
  51440. if( rc==SQLITE_OK ){
  51441. if( p->inTrans==TRANS_NONE ){
  51442. pBt->nTransaction++;
  51443. #ifndef SQLITE_OMIT_SHARED_CACHE
  51444. if( p->sharable ){
  51445. assert( p->lock.pBtree==p && p->lock.iTable==1 );
  51446. p->lock.eLock = READ_LOCK;
  51447. p->lock.pNext = pBt->pLock;
  51448. pBt->pLock = &p->lock;
  51449. }
  51450. #endif
  51451. }
  51452. p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ);
  51453. if( p->inTrans>pBt->inTransaction ){
  51454. pBt->inTransaction = p->inTrans;
  51455. }
  51456. if( wrflag ){
  51457. MemPage *pPage1 = pBt->pPage1;
  51458. #ifndef SQLITE_OMIT_SHARED_CACHE
  51459. assert( !pBt->pWriter );
  51460. pBt->pWriter = p;
  51461. pBt->btsFlags &= ~BTS_EXCLUSIVE;
  51462. if( wrflag>1 ) pBt->btsFlags |= BTS_EXCLUSIVE;
  51463. #endif
  51464. /* If the db-size header field is incorrect (as it may be if an old
  51465. ** client has been writing the database file), update it now. Doing
  51466. ** this sooner rather than later means the database size can safely
  51467. ** re-read the database size from page 1 if a savepoint or transaction
  51468. ** rollback occurs within the transaction.
  51469. */
  51470. if( pBt->nPage!=get4byte(&pPage1->aData[28]) ){
  51471. rc = sqlite3PagerWrite(pPage1->pDbPage);
  51472. if( rc==SQLITE_OK ){
  51473. put4byte(&pPage1->aData[28], pBt->nPage);
  51474. }
  51475. }
  51476. }
  51477. }
  51478. trans_begun:
  51479. if( rc==SQLITE_OK && wrflag ){
  51480. /* This call makes sure that the pager has the correct number of
  51481. ** open savepoints. If the second parameter is greater than 0 and
  51482. ** the sub-journal is not already open, then it will be opened here.
  51483. */
  51484. rc = sqlite3PagerOpenSavepoint(pBt->pPager, p->db->nSavepoint);
  51485. }
  51486. btreeIntegrity(p);
  51487. sqlite3BtreeLeave(p);
  51488. return rc;
  51489. }
  51490. #ifndef SQLITE_OMIT_AUTOVACUUM
  51491. /*
  51492. ** Set the pointer-map entries for all children of page pPage. Also, if
  51493. ** pPage contains cells that point to overflow pages, set the pointer
  51494. ** map entries for the overflow pages as well.
  51495. */
  51496. static int setChildPtrmaps(MemPage *pPage){
  51497. int i; /* Counter variable */
  51498. int nCell; /* Number of cells in page pPage */
  51499. int rc; /* Return code */
  51500. BtShared *pBt = pPage->pBt;
  51501. u8 isInitOrig = pPage->isInit;
  51502. Pgno pgno = pPage->pgno;
  51503. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  51504. rc = btreeInitPage(pPage);
  51505. if( rc!=SQLITE_OK ){
  51506. goto set_child_ptrmaps_out;
  51507. }
  51508. nCell = pPage->nCell;
  51509. for(i=0; i<nCell; i++){
  51510. u8 *pCell = findCell(pPage, i);
  51511. ptrmapPutOvflPtr(pPage, pCell, &rc);
  51512. if( !pPage->leaf ){
  51513. Pgno childPgno = get4byte(pCell);
  51514. ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
  51515. }
  51516. }
  51517. if( !pPage->leaf ){
  51518. Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
  51519. ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
  51520. }
  51521. set_child_ptrmaps_out:
  51522. pPage->isInit = isInitOrig;
  51523. return rc;
  51524. }
  51525. /*
  51526. ** Somewhere on pPage is a pointer to page iFrom. Modify this pointer so
  51527. ** that it points to iTo. Parameter eType describes the type of pointer to
  51528. ** be modified, as follows:
  51529. **
  51530. ** PTRMAP_BTREE: pPage is a btree-page. The pointer points at a child
  51531. ** page of pPage.
  51532. **
  51533. ** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow
  51534. ** page pointed to by one of the cells on pPage.
  51535. **
  51536. ** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next
  51537. ** overflow page in the list.
  51538. */
  51539. static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){
  51540. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  51541. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  51542. if( eType==PTRMAP_OVERFLOW2 ){
  51543. /* The pointer is always the first 4 bytes of the page in this case. */
  51544. if( get4byte(pPage->aData)!=iFrom ){
  51545. return SQLITE_CORRUPT_BKPT;
  51546. }
  51547. put4byte(pPage->aData, iTo);
  51548. }else{
  51549. u8 isInitOrig = pPage->isInit;
  51550. int i;
  51551. int nCell;
  51552. btreeInitPage(pPage);
  51553. nCell = pPage->nCell;
  51554. for(i=0; i<nCell; i++){
  51555. u8 *pCell = findCell(pPage, i);
  51556. if( eType==PTRMAP_OVERFLOW1 ){
  51557. CellInfo info;
  51558. btreeParseCellPtr(pPage, pCell, &info);
  51559. if( info.iOverflow
  51560. && pCell+info.iOverflow+3<=pPage->aData+pPage->maskPage
  51561. && iFrom==get4byte(&pCell[info.iOverflow])
  51562. ){
  51563. put4byte(&pCell[info.iOverflow], iTo);
  51564. break;
  51565. }
  51566. }else{
  51567. if( get4byte(pCell)==iFrom ){
  51568. put4byte(pCell, iTo);
  51569. break;
  51570. }
  51571. }
  51572. }
  51573. if( i==nCell ){
  51574. if( eType!=PTRMAP_BTREE ||
  51575. get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){
  51576. return SQLITE_CORRUPT_BKPT;
  51577. }
  51578. put4byte(&pPage->aData[pPage->hdrOffset+8], iTo);
  51579. }
  51580. pPage->isInit = isInitOrig;
  51581. }
  51582. return SQLITE_OK;
  51583. }
  51584. /*
  51585. ** Move the open database page pDbPage to location iFreePage in the
  51586. ** database. The pDbPage reference remains valid.
  51587. **
  51588. ** The isCommit flag indicates that there is no need to remember that
  51589. ** the journal needs to be sync()ed before database page pDbPage->pgno
  51590. ** can be written to. The caller has already promised not to write to that
  51591. ** page.
  51592. */
  51593. static int relocatePage(
  51594. BtShared *pBt, /* Btree */
  51595. MemPage *pDbPage, /* Open page to move */
  51596. u8 eType, /* Pointer map 'type' entry for pDbPage */
  51597. Pgno iPtrPage, /* Pointer map 'page-no' entry for pDbPage */
  51598. Pgno iFreePage, /* The location to move pDbPage to */
  51599. int isCommit /* isCommit flag passed to sqlite3PagerMovepage */
  51600. ){
  51601. MemPage *pPtrPage; /* The page that contains a pointer to pDbPage */
  51602. Pgno iDbPage = pDbPage->pgno;
  51603. Pager *pPager = pBt->pPager;
  51604. int rc;
  51605. assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 ||
  51606. eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE );
  51607. assert( sqlite3_mutex_held(pBt->mutex) );
  51608. assert( pDbPage->pBt==pBt );
  51609. /* Move page iDbPage from its current location to page number iFreePage */
  51610. TRACE(("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n",
  51611. iDbPage, iFreePage, iPtrPage, eType));
  51612. rc = sqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage, isCommit);
  51613. if( rc!=SQLITE_OK ){
  51614. return rc;
  51615. }
  51616. pDbPage->pgno = iFreePage;
  51617. /* If pDbPage was a btree-page, then it may have child pages and/or cells
  51618. ** that point to overflow pages. The pointer map entries for all these
  51619. ** pages need to be changed.
  51620. **
  51621. ** If pDbPage is an overflow page, then the first 4 bytes may store a
  51622. ** pointer to a subsequent overflow page. If this is the case, then
  51623. ** the pointer map needs to be updated for the subsequent overflow page.
  51624. */
  51625. if( eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ){
  51626. rc = setChildPtrmaps(pDbPage);
  51627. if( rc!=SQLITE_OK ){
  51628. return rc;
  51629. }
  51630. }else{
  51631. Pgno nextOvfl = get4byte(pDbPage->aData);
  51632. if( nextOvfl!=0 ){
  51633. ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage, &rc);
  51634. if( rc!=SQLITE_OK ){
  51635. return rc;
  51636. }
  51637. }
  51638. }
  51639. /* Fix the database pointer on page iPtrPage that pointed at iDbPage so
  51640. ** that it points at iFreePage. Also fix the pointer map entry for
  51641. ** iPtrPage.
  51642. */
  51643. if( eType!=PTRMAP_ROOTPAGE ){
  51644. rc = btreeGetPage(pBt, iPtrPage, &pPtrPage, 0);
  51645. if( rc!=SQLITE_OK ){
  51646. return rc;
  51647. }
  51648. rc = sqlite3PagerWrite(pPtrPage->pDbPage);
  51649. if( rc!=SQLITE_OK ){
  51650. releasePage(pPtrPage);
  51651. return rc;
  51652. }
  51653. rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType);
  51654. releasePage(pPtrPage);
  51655. if( rc==SQLITE_OK ){
  51656. ptrmapPut(pBt, iFreePage, eType, iPtrPage, &rc);
  51657. }
  51658. }
  51659. return rc;
  51660. }
  51661. /* Forward declaration required by incrVacuumStep(). */
  51662. static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8);
  51663. /*
  51664. ** Perform a single step of an incremental-vacuum. If successful, return
  51665. ** SQLITE_OK. If there is no work to do (and therefore no point in
  51666. ** calling this function again), return SQLITE_DONE. Or, if an error
  51667. ** occurs, return some other error code.
  51668. **
  51669. ** More specifically, this function attempts to re-organize the database so
  51670. ** that the last page of the file currently in use is no longer in use.
  51671. **
  51672. ** Parameter nFin is the number of pages that this database would contain
  51673. ** were this function called until it returns SQLITE_DONE.
  51674. **
  51675. ** If the bCommit parameter is non-zero, this function assumes that the
  51676. ** caller will keep calling incrVacuumStep() until it returns SQLITE_DONE
  51677. ** or an error. bCommit is passed true for an auto-vacuum-on-commit
  51678. ** operation, or false for an incremental vacuum.
  51679. */
  51680. static int incrVacuumStep(BtShared *pBt, Pgno nFin, Pgno iLastPg, int bCommit){
  51681. Pgno nFreeList; /* Number of pages still on the free-list */
  51682. int rc;
  51683. assert( sqlite3_mutex_held(pBt->mutex) );
  51684. assert( iLastPg>nFin );
  51685. if( !PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg!=PENDING_BYTE_PAGE(pBt) ){
  51686. u8 eType;
  51687. Pgno iPtrPage;
  51688. nFreeList = get4byte(&pBt->pPage1->aData[36]);
  51689. if( nFreeList==0 ){
  51690. return SQLITE_DONE;
  51691. }
  51692. rc = ptrmapGet(pBt, iLastPg, &eType, &iPtrPage);
  51693. if( rc!=SQLITE_OK ){
  51694. return rc;
  51695. }
  51696. if( eType==PTRMAP_ROOTPAGE ){
  51697. return SQLITE_CORRUPT_BKPT;
  51698. }
  51699. if( eType==PTRMAP_FREEPAGE ){
  51700. if( bCommit==0 ){
  51701. /* Remove the page from the files free-list. This is not required
  51702. ** if bCommit is non-zero. In that case, the free-list will be
  51703. ** truncated to zero after this function returns, so it doesn't
  51704. ** matter if it still contains some garbage entries.
  51705. */
  51706. Pgno iFreePg;
  51707. MemPage *pFreePg;
  51708. rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iLastPg, BTALLOC_EXACT);
  51709. if( rc!=SQLITE_OK ){
  51710. return rc;
  51711. }
  51712. assert( iFreePg==iLastPg );
  51713. releasePage(pFreePg);
  51714. }
  51715. } else {
  51716. Pgno iFreePg; /* Index of free page to move pLastPg to */
  51717. MemPage *pLastPg;
  51718. u8 eMode = BTALLOC_ANY; /* Mode parameter for allocateBtreePage() */
  51719. Pgno iNear = 0; /* nearby parameter for allocateBtreePage() */
  51720. rc = btreeGetPage(pBt, iLastPg, &pLastPg, 0);
  51721. if( rc!=SQLITE_OK ){
  51722. return rc;
  51723. }
  51724. /* If bCommit is zero, this loop runs exactly once and page pLastPg
  51725. ** is swapped with the first free page pulled off the free list.
  51726. **
  51727. ** On the other hand, if bCommit is greater than zero, then keep
  51728. ** looping until a free-page located within the first nFin pages
  51729. ** of the file is found.
  51730. */
  51731. if( bCommit==0 ){
  51732. eMode = BTALLOC_LE;
  51733. iNear = nFin;
  51734. }
  51735. do {
  51736. MemPage *pFreePg;
  51737. rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iNear, eMode);
  51738. if( rc!=SQLITE_OK ){
  51739. releasePage(pLastPg);
  51740. return rc;
  51741. }
  51742. releasePage(pFreePg);
  51743. }while( bCommit && iFreePg>nFin );
  51744. assert( iFreePg<iLastPg );
  51745. rc = relocatePage(pBt, pLastPg, eType, iPtrPage, iFreePg, bCommit);
  51746. releasePage(pLastPg);
  51747. if( rc!=SQLITE_OK ){
  51748. return rc;
  51749. }
  51750. }
  51751. }
  51752. if( bCommit==0 ){
  51753. do {
  51754. iLastPg--;
  51755. }while( iLastPg==PENDING_BYTE_PAGE(pBt) || PTRMAP_ISPAGE(pBt, iLastPg) );
  51756. pBt->bDoTruncate = 1;
  51757. pBt->nPage = iLastPg;
  51758. }
  51759. return SQLITE_OK;
  51760. }
  51761. /*
  51762. ** The database opened by the first argument is an auto-vacuum database
  51763. ** nOrig pages in size containing nFree free pages. Return the expected
  51764. ** size of the database in pages following an auto-vacuum operation.
  51765. */
  51766. static Pgno finalDbSize(BtShared *pBt, Pgno nOrig, Pgno nFree){
  51767. int nEntry; /* Number of entries on one ptrmap page */
  51768. Pgno nPtrmap; /* Number of PtrMap pages to be freed */
  51769. Pgno nFin; /* Return value */
  51770. nEntry = pBt->usableSize/5;
  51771. nPtrmap = (nFree-nOrig+PTRMAP_PAGENO(pBt, nOrig)+nEntry)/nEntry;
  51772. nFin = nOrig - nFree - nPtrmap;
  51773. if( nOrig>PENDING_BYTE_PAGE(pBt) && nFin<PENDING_BYTE_PAGE(pBt) ){
  51774. nFin--;
  51775. }
  51776. while( PTRMAP_ISPAGE(pBt, nFin) || nFin==PENDING_BYTE_PAGE(pBt) ){
  51777. nFin--;
  51778. }
  51779. return nFin;
  51780. }
  51781. /*
  51782. ** A write-transaction must be opened before calling this function.
  51783. ** It performs a single unit of work towards an incremental vacuum.
  51784. **
  51785. ** If the incremental vacuum is finished after this function has run,
  51786. ** SQLITE_DONE is returned. If it is not finished, but no error occurred,
  51787. ** SQLITE_OK is returned. Otherwise an SQLite error code.
  51788. */
  51789. SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *p){
  51790. int rc;
  51791. BtShared *pBt = p->pBt;
  51792. sqlite3BtreeEnter(p);
  51793. assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE );
  51794. if( !pBt->autoVacuum ){
  51795. rc = SQLITE_DONE;
  51796. }else{
  51797. Pgno nOrig = btreePagecount(pBt);
  51798. Pgno nFree = get4byte(&pBt->pPage1->aData[36]);
  51799. Pgno nFin = finalDbSize(pBt, nOrig, nFree);
  51800. if( nOrig<nFin ){
  51801. rc = SQLITE_CORRUPT_BKPT;
  51802. }else if( nFree>0 ){
  51803. rc = saveAllCursors(pBt, 0, 0);
  51804. if( rc==SQLITE_OK ){
  51805. invalidateAllOverflowCache(pBt);
  51806. rc = incrVacuumStep(pBt, nFin, nOrig, 0);
  51807. }
  51808. if( rc==SQLITE_OK ){
  51809. rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
  51810. put4byte(&pBt->pPage1->aData[28], pBt->nPage);
  51811. }
  51812. }else{
  51813. rc = SQLITE_DONE;
  51814. }
  51815. }
  51816. sqlite3BtreeLeave(p);
  51817. return rc;
  51818. }
  51819. /*
  51820. ** This routine is called prior to sqlite3PagerCommit when a transaction
  51821. ** is committed for an auto-vacuum database.
  51822. **
  51823. ** If SQLITE_OK is returned, then *pnTrunc is set to the number of pages
  51824. ** the database file should be truncated to during the commit process.
  51825. ** i.e. the database has been reorganized so that only the first *pnTrunc
  51826. ** pages are in use.
  51827. */
  51828. static int autoVacuumCommit(BtShared *pBt){
  51829. int rc = SQLITE_OK;
  51830. Pager *pPager = pBt->pPager;
  51831. VVA_ONLY( int nRef = sqlite3PagerRefcount(pPager) );
  51832. assert( sqlite3_mutex_held(pBt->mutex) );
  51833. invalidateAllOverflowCache(pBt);
  51834. assert(pBt->autoVacuum);
  51835. if( !pBt->incrVacuum ){
  51836. Pgno nFin; /* Number of pages in database after autovacuuming */
  51837. Pgno nFree; /* Number of pages on the freelist initially */
  51838. Pgno iFree; /* The next page to be freed */
  51839. Pgno nOrig; /* Database size before freeing */
  51840. nOrig = btreePagecount(pBt);
  51841. if( PTRMAP_ISPAGE(pBt, nOrig) || nOrig==PENDING_BYTE_PAGE(pBt) ){
  51842. /* It is not possible to create a database for which the final page
  51843. ** is either a pointer-map page or the pending-byte page. If one
  51844. ** is encountered, this indicates corruption.
  51845. */
  51846. return SQLITE_CORRUPT_BKPT;
  51847. }
  51848. nFree = get4byte(&pBt->pPage1->aData[36]);
  51849. nFin = finalDbSize(pBt, nOrig, nFree);
  51850. if( nFin>nOrig ) return SQLITE_CORRUPT_BKPT;
  51851. if( nFin<nOrig ){
  51852. rc = saveAllCursors(pBt, 0, 0);
  51853. }
  51854. for(iFree=nOrig; iFree>nFin && rc==SQLITE_OK; iFree--){
  51855. rc = incrVacuumStep(pBt, nFin, iFree, 1);
  51856. }
  51857. if( (rc==SQLITE_DONE || rc==SQLITE_OK) && nFree>0 ){
  51858. rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
  51859. put4byte(&pBt->pPage1->aData[32], 0);
  51860. put4byte(&pBt->pPage1->aData[36], 0);
  51861. put4byte(&pBt->pPage1->aData[28], nFin);
  51862. pBt->bDoTruncate = 1;
  51863. pBt->nPage = nFin;
  51864. }
  51865. if( rc!=SQLITE_OK ){
  51866. sqlite3PagerRollback(pPager);
  51867. }
  51868. }
  51869. assert( nRef>=sqlite3PagerRefcount(pPager) );
  51870. return rc;
  51871. }
  51872. #else /* ifndef SQLITE_OMIT_AUTOVACUUM */
  51873. # define setChildPtrmaps(x) SQLITE_OK
  51874. #endif
  51875. /*
  51876. ** This routine does the first phase of a two-phase commit. This routine
  51877. ** causes a rollback journal to be created (if it does not already exist)
  51878. ** and populated with enough information so that if a power loss occurs
  51879. ** the database can be restored to its original state by playing back
  51880. ** the journal. Then the contents of the journal are flushed out to
  51881. ** the disk. After the journal is safely on oxide, the changes to the
  51882. ** database are written into the database file and flushed to oxide.
  51883. ** At the end of this call, the rollback journal still exists on the
  51884. ** disk and we are still holding all locks, so the transaction has not
  51885. ** committed. See sqlite3BtreeCommitPhaseTwo() for the second phase of the
  51886. ** commit process.
  51887. **
  51888. ** This call is a no-op if no write-transaction is currently active on pBt.
  51889. **
  51890. ** Otherwise, sync the database file for the btree pBt. zMaster points to
  51891. ** the name of a master journal file that should be written into the
  51892. ** individual journal file, or is NULL, indicating no master journal file
  51893. ** (single database transaction).
  51894. **
  51895. ** When this is called, the master journal should already have been
  51896. ** created, populated with this journal pointer and synced to disk.
  51897. **
  51898. ** Once this is routine has returned, the only thing required to commit
  51899. ** the write-transaction for this database file is to delete the journal.
  51900. */
  51901. SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zMaster){
  51902. int rc = SQLITE_OK;
  51903. if( p->inTrans==TRANS_WRITE ){
  51904. BtShared *pBt = p->pBt;
  51905. sqlite3BtreeEnter(p);
  51906. #ifndef SQLITE_OMIT_AUTOVACUUM
  51907. if( pBt->autoVacuum ){
  51908. rc = autoVacuumCommit(pBt);
  51909. if( rc!=SQLITE_OK ){
  51910. sqlite3BtreeLeave(p);
  51911. return rc;
  51912. }
  51913. }
  51914. if( pBt->bDoTruncate ){
  51915. sqlite3PagerTruncateImage(pBt->pPager, pBt->nPage);
  51916. }
  51917. #endif
  51918. rc = sqlite3PagerCommitPhaseOne(pBt->pPager, zMaster, 0);
  51919. sqlite3BtreeLeave(p);
  51920. }
  51921. return rc;
  51922. }
  51923. /*
  51924. ** This function is called from both BtreeCommitPhaseTwo() and BtreeRollback()
  51925. ** at the conclusion of a transaction.
  51926. */
  51927. static void btreeEndTransaction(Btree *p){
  51928. BtShared *pBt = p->pBt;
  51929. sqlite3 *db = p->db;
  51930. assert( sqlite3BtreeHoldsMutex(p) );
  51931. #ifndef SQLITE_OMIT_AUTOVACUUM
  51932. pBt->bDoTruncate = 0;
  51933. #endif
  51934. if( p->inTrans>TRANS_NONE && db->nVdbeRead>1 ){
  51935. /* If there are other active statements that belong to this database
  51936. ** handle, downgrade to a read-only transaction. The other statements
  51937. ** may still be reading from the database. */
  51938. downgradeAllSharedCacheTableLocks(p);
  51939. p->inTrans = TRANS_READ;
  51940. }else{
  51941. /* If the handle had any kind of transaction open, decrement the
  51942. ** transaction count of the shared btree. If the transaction count
  51943. ** reaches 0, set the shared state to TRANS_NONE. The unlockBtreeIfUnused()
  51944. ** call below will unlock the pager. */
  51945. if( p->inTrans!=TRANS_NONE ){
  51946. clearAllSharedCacheTableLocks(p);
  51947. pBt->nTransaction--;
  51948. if( 0==pBt->nTransaction ){
  51949. pBt->inTransaction = TRANS_NONE;
  51950. }
  51951. }
  51952. /* Set the current transaction state to TRANS_NONE and unlock the
  51953. ** pager if this call closed the only read or write transaction. */
  51954. p->inTrans = TRANS_NONE;
  51955. unlockBtreeIfUnused(pBt);
  51956. }
  51957. btreeIntegrity(p);
  51958. }
  51959. /*
  51960. ** Commit the transaction currently in progress.
  51961. **
  51962. ** This routine implements the second phase of a 2-phase commit. The
  51963. ** sqlite3BtreeCommitPhaseOne() routine does the first phase and should
  51964. ** be invoked prior to calling this routine. The sqlite3BtreeCommitPhaseOne()
  51965. ** routine did all the work of writing information out to disk and flushing the
  51966. ** contents so that they are written onto the disk platter. All this
  51967. ** routine has to do is delete or truncate or zero the header in the
  51968. ** the rollback journal (which causes the transaction to commit) and
  51969. ** drop locks.
  51970. **
  51971. ** Normally, if an error occurs while the pager layer is attempting to
  51972. ** finalize the underlying journal file, this function returns an error and
  51973. ** the upper layer will attempt a rollback. However, if the second argument
  51974. ** is non-zero then this b-tree transaction is part of a multi-file
  51975. ** transaction. In this case, the transaction has already been committed
  51976. ** (by deleting a master journal file) and the caller will ignore this
  51977. ** functions return code. So, even if an error occurs in the pager layer,
  51978. ** reset the b-tree objects internal state to indicate that the write
  51979. ** transaction has been closed. This is quite safe, as the pager will have
  51980. ** transitioned to the error state.
  51981. **
  51982. ** This will release the write lock on the database file. If there
  51983. ** are no active cursors, it also releases the read lock.
  51984. */
  51985. SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree *p, int bCleanup){
  51986. if( p->inTrans==TRANS_NONE ) return SQLITE_OK;
  51987. sqlite3BtreeEnter(p);
  51988. btreeIntegrity(p);
  51989. /* If the handle has a write-transaction open, commit the shared-btrees
  51990. ** transaction and set the shared state to TRANS_READ.
  51991. */
  51992. if( p->inTrans==TRANS_WRITE ){
  51993. int rc;
  51994. BtShared *pBt = p->pBt;
  51995. assert( pBt->inTransaction==TRANS_WRITE );
  51996. assert( pBt->nTransaction>0 );
  51997. rc = sqlite3PagerCommitPhaseTwo(pBt->pPager);
  51998. if( rc!=SQLITE_OK && bCleanup==0 ){
  51999. sqlite3BtreeLeave(p);
  52000. return rc;
  52001. }
  52002. pBt->inTransaction = TRANS_READ;
  52003. btreeClearHasContent(pBt);
  52004. }
  52005. btreeEndTransaction(p);
  52006. sqlite3BtreeLeave(p);
  52007. return SQLITE_OK;
  52008. }
  52009. /*
  52010. ** Do both phases of a commit.
  52011. */
  52012. SQLITE_PRIVATE int sqlite3BtreeCommit(Btree *p){
  52013. int rc;
  52014. sqlite3BtreeEnter(p);
  52015. rc = sqlite3BtreeCommitPhaseOne(p, 0);
  52016. if( rc==SQLITE_OK ){
  52017. rc = sqlite3BtreeCommitPhaseTwo(p, 0);
  52018. }
  52019. sqlite3BtreeLeave(p);
  52020. return rc;
  52021. }
  52022. /*
  52023. ** This routine sets the state to CURSOR_FAULT and the error
  52024. ** code to errCode for every cursor on BtShared that pBtree
  52025. ** references.
  52026. **
  52027. ** Every cursor is tripped, including cursors that belong
  52028. ** to other database connections that happen to be sharing
  52029. ** the cache with pBtree.
  52030. **
  52031. ** This routine gets called when a rollback occurs.
  52032. ** All cursors using the same cache must be tripped
  52033. ** to prevent them from trying to use the btree after
  52034. ** the rollback. The rollback may have deleted tables
  52035. ** or moved root pages, so it is not sufficient to
  52036. ** save the state of the cursor. The cursor must be
  52037. ** invalidated.
  52038. */
  52039. SQLITE_PRIVATE void sqlite3BtreeTripAllCursors(Btree *pBtree, int errCode){
  52040. BtCursor *p;
  52041. if( pBtree==0 ) return;
  52042. sqlite3BtreeEnter(pBtree);
  52043. for(p=pBtree->pBt->pCursor; p; p=p->pNext){
  52044. int i;
  52045. sqlite3BtreeClearCursor(p);
  52046. p->eState = CURSOR_FAULT;
  52047. p->skipNext = errCode;
  52048. for(i=0; i<=p->iPage; i++){
  52049. releasePage(p->apPage[i]);
  52050. p->apPage[i] = 0;
  52051. }
  52052. }
  52053. sqlite3BtreeLeave(pBtree);
  52054. }
  52055. /*
  52056. ** Rollback the transaction in progress. All cursors will be
  52057. ** invalided by this operation. Any attempt to use a cursor
  52058. ** that was open at the beginning of this operation will result
  52059. ** in an error.
  52060. **
  52061. ** This will release the write lock on the database file. If there
  52062. ** are no active cursors, it also releases the read lock.
  52063. */
  52064. SQLITE_PRIVATE int sqlite3BtreeRollback(Btree *p, int tripCode){
  52065. int rc;
  52066. BtShared *pBt = p->pBt;
  52067. MemPage *pPage1;
  52068. sqlite3BtreeEnter(p);
  52069. if( tripCode==SQLITE_OK ){
  52070. rc = tripCode = saveAllCursors(pBt, 0, 0);
  52071. }else{
  52072. rc = SQLITE_OK;
  52073. }
  52074. if( tripCode ){
  52075. sqlite3BtreeTripAllCursors(p, tripCode);
  52076. }
  52077. btreeIntegrity(p);
  52078. if( p->inTrans==TRANS_WRITE ){
  52079. int rc2;
  52080. assert( TRANS_WRITE==pBt->inTransaction );
  52081. rc2 = sqlite3PagerRollback(pBt->pPager);
  52082. if( rc2!=SQLITE_OK ){
  52083. rc = rc2;
  52084. }
  52085. /* The rollback may have destroyed the pPage1->aData value. So
  52086. ** call btreeGetPage() on page 1 again to make
  52087. ** sure pPage1->aData is set correctly. */
  52088. if( btreeGetPage(pBt, 1, &pPage1, 0)==SQLITE_OK ){
  52089. int nPage = get4byte(28+(u8*)pPage1->aData);
  52090. testcase( nPage==0 );
  52091. if( nPage==0 ) sqlite3PagerPagecount(pBt->pPager, &nPage);
  52092. testcase( pBt->nPage!=nPage );
  52093. pBt->nPage = nPage;
  52094. releasePage(pPage1);
  52095. }
  52096. assert( countValidCursors(pBt, 1)==0 );
  52097. pBt->inTransaction = TRANS_READ;
  52098. btreeClearHasContent(pBt);
  52099. }
  52100. btreeEndTransaction(p);
  52101. sqlite3BtreeLeave(p);
  52102. return rc;
  52103. }
  52104. /*
  52105. ** Start a statement subtransaction. The subtransaction can be rolled
  52106. ** back independently of the main transaction. You must start a transaction
  52107. ** before starting a subtransaction. The subtransaction is ended automatically
  52108. ** if the main transaction commits or rolls back.
  52109. **
  52110. ** Statement subtransactions are used around individual SQL statements
  52111. ** that are contained within a BEGIN...COMMIT block. If a constraint
  52112. ** error occurs within the statement, the effect of that one statement
  52113. ** can be rolled back without having to rollback the entire transaction.
  52114. **
  52115. ** A statement sub-transaction is implemented as an anonymous savepoint. The
  52116. ** value passed as the second parameter is the total number of savepoints,
  52117. ** including the new anonymous savepoint, open on the B-Tree. i.e. if there
  52118. ** are no active savepoints and no other statement-transactions open,
  52119. ** iStatement is 1. This anonymous savepoint can be released or rolled back
  52120. ** using the sqlite3BtreeSavepoint() function.
  52121. */
  52122. SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree *p, int iStatement){
  52123. int rc;
  52124. BtShared *pBt = p->pBt;
  52125. sqlite3BtreeEnter(p);
  52126. assert( p->inTrans==TRANS_WRITE );
  52127. assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
  52128. assert( iStatement>0 );
  52129. assert( iStatement>p->db->nSavepoint );
  52130. assert( pBt->inTransaction==TRANS_WRITE );
  52131. /* At the pager level, a statement transaction is a savepoint with
  52132. ** an index greater than all savepoints created explicitly using
  52133. ** SQL statements. It is illegal to open, release or rollback any
  52134. ** such savepoints while the statement transaction savepoint is active.
  52135. */
  52136. rc = sqlite3PagerOpenSavepoint(pBt->pPager, iStatement);
  52137. sqlite3BtreeLeave(p);
  52138. return rc;
  52139. }
  52140. /*
  52141. ** The second argument to this function, op, is always SAVEPOINT_ROLLBACK
  52142. ** or SAVEPOINT_RELEASE. This function either releases or rolls back the
  52143. ** savepoint identified by parameter iSavepoint, depending on the value
  52144. ** of op.
  52145. **
  52146. ** Normally, iSavepoint is greater than or equal to zero. However, if op is
  52147. ** SAVEPOINT_ROLLBACK, then iSavepoint may also be -1. In this case the
  52148. ** contents of the entire transaction are rolled back. This is different
  52149. ** from a normal transaction rollback, as no locks are released and the
  52150. ** transaction remains open.
  52151. */
  52152. SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *p, int op, int iSavepoint){
  52153. int rc = SQLITE_OK;
  52154. if( p && p->inTrans==TRANS_WRITE ){
  52155. BtShared *pBt = p->pBt;
  52156. assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
  52157. assert( iSavepoint>=0 || (iSavepoint==-1 && op==SAVEPOINT_ROLLBACK) );
  52158. sqlite3BtreeEnter(p);
  52159. rc = sqlite3PagerSavepoint(pBt->pPager, op, iSavepoint);
  52160. if( rc==SQLITE_OK ){
  52161. if( iSavepoint<0 && (pBt->btsFlags & BTS_INITIALLY_EMPTY)!=0 ){
  52162. pBt->nPage = 0;
  52163. }
  52164. rc = newDatabase(pBt);
  52165. pBt->nPage = get4byte(28 + pBt->pPage1->aData);
  52166. /* The database size was written into the offset 28 of the header
  52167. ** when the transaction started, so we know that the value at offset
  52168. ** 28 is nonzero. */
  52169. assert( pBt->nPage>0 );
  52170. }
  52171. sqlite3BtreeLeave(p);
  52172. }
  52173. return rc;
  52174. }
  52175. /*
  52176. ** Create a new cursor for the BTree whose root is on the page
  52177. ** iTable. If a read-only cursor is requested, it is assumed that
  52178. ** the caller already has at least a read-only transaction open
  52179. ** on the database already. If a write-cursor is requested, then
  52180. ** the caller is assumed to have an open write transaction.
  52181. **
  52182. ** If wrFlag==0, then the cursor can only be used for reading.
  52183. ** If wrFlag==1, then the cursor can be used for reading or for
  52184. ** writing if other conditions for writing are also met. These
  52185. ** are the conditions that must be met in order for writing to
  52186. ** be allowed:
  52187. **
  52188. ** 1: The cursor must have been opened with wrFlag==1
  52189. **
  52190. ** 2: Other database connections that share the same pager cache
  52191. ** but which are not in the READ_UNCOMMITTED state may not have
  52192. ** cursors open with wrFlag==0 on the same table. Otherwise
  52193. ** the changes made by this write cursor would be visible to
  52194. ** the read cursors in the other database connection.
  52195. **
  52196. ** 3: The database must be writable (not on read-only media)
  52197. **
  52198. ** 4: There must be an active transaction.
  52199. **
  52200. ** No checking is done to make sure that page iTable really is the
  52201. ** root page of a b-tree. If it is not, then the cursor acquired
  52202. ** will not work correctly.
  52203. **
  52204. ** It is assumed that the sqlite3BtreeCursorZero() has been called
  52205. ** on pCur to initialize the memory space prior to invoking this routine.
  52206. */
  52207. static int btreeCursor(
  52208. Btree *p, /* The btree */
  52209. int iTable, /* Root page of table to open */
  52210. int wrFlag, /* 1 to write. 0 read-only */
  52211. struct KeyInfo *pKeyInfo, /* First arg to comparison function */
  52212. BtCursor *pCur /* Space for new cursor */
  52213. ){
  52214. BtShared *pBt = p->pBt; /* Shared b-tree handle */
  52215. assert( sqlite3BtreeHoldsMutex(p) );
  52216. assert( wrFlag==0 || wrFlag==1 );
  52217. /* The following assert statements verify that if this is a sharable
  52218. ** b-tree database, the connection is holding the required table locks,
  52219. ** and that no other connection has any open cursor that conflicts with
  52220. ** this lock. */
  52221. assert( hasSharedCacheTableLock(p, iTable, pKeyInfo!=0, wrFlag+1) );
  52222. assert( wrFlag==0 || !hasReadConflicts(p, iTable) );
  52223. /* Assert that the caller has opened the required transaction. */
  52224. assert( p->inTrans>TRANS_NONE );
  52225. assert( wrFlag==0 || p->inTrans==TRANS_WRITE );
  52226. assert( pBt->pPage1 && pBt->pPage1->aData );
  52227. if( NEVER(wrFlag && (pBt->btsFlags & BTS_READ_ONLY)!=0) ){
  52228. return SQLITE_READONLY;
  52229. }
  52230. if( wrFlag ){
  52231. allocateTempSpace(pBt);
  52232. if( pBt->pTmpSpace==0 ) return SQLITE_NOMEM;
  52233. }
  52234. if( iTable==1 && btreePagecount(pBt)==0 ){
  52235. assert( wrFlag==0 );
  52236. iTable = 0;
  52237. }
  52238. /* Now that no other errors can occur, finish filling in the BtCursor
  52239. ** variables and link the cursor into the BtShared list. */
  52240. pCur->pgnoRoot = (Pgno)iTable;
  52241. pCur->iPage = -1;
  52242. pCur->pKeyInfo = pKeyInfo;
  52243. pCur->pBtree = p;
  52244. pCur->pBt = pBt;
  52245. assert( wrFlag==0 || wrFlag==BTCF_WriteFlag );
  52246. pCur->curFlags = wrFlag;
  52247. pCur->pNext = pBt->pCursor;
  52248. if( pCur->pNext ){
  52249. pCur->pNext->pPrev = pCur;
  52250. }
  52251. pBt->pCursor = pCur;
  52252. pCur->eState = CURSOR_INVALID;
  52253. return SQLITE_OK;
  52254. }
  52255. SQLITE_PRIVATE int sqlite3BtreeCursor(
  52256. Btree *p, /* The btree */
  52257. int iTable, /* Root page of table to open */
  52258. int wrFlag, /* 1 to write. 0 read-only */
  52259. struct KeyInfo *pKeyInfo, /* First arg to xCompare() */
  52260. BtCursor *pCur /* Write new cursor here */
  52261. ){
  52262. int rc;
  52263. sqlite3BtreeEnter(p);
  52264. rc = btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur);
  52265. sqlite3BtreeLeave(p);
  52266. return rc;
  52267. }
  52268. /*
  52269. ** Return the size of a BtCursor object in bytes.
  52270. **
  52271. ** This interfaces is needed so that users of cursors can preallocate
  52272. ** sufficient storage to hold a cursor. The BtCursor object is opaque
  52273. ** to users so they cannot do the sizeof() themselves - they must call
  52274. ** this routine.
  52275. */
  52276. SQLITE_PRIVATE int sqlite3BtreeCursorSize(void){
  52277. return ROUND8(sizeof(BtCursor));
  52278. }
  52279. /*
  52280. ** Initialize memory that will be converted into a BtCursor object.
  52281. **
  52282. ** The simple approach here would be to memset() the entire object
  52283. ** to zero. But it turns out that the apPage[] and aiIdx[] arrays
  52284. ** do not need to be zeroed and they are large, so we can save a lot
  52285. ** of run-time by skipping the initialization of those elements.
  52286. */
  52287. SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor *p){
  52288. memset(p, 0, offsetof(BtCursor, iPage));
  52289. }
  52290. /*
  52291. ** Close a cursor. The read lock on the database file is released
  52292. ** when the last cursor is closed.
  52293. */
  52294. SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor *pCur){
  52295. Btree *pBtree = pCur->pBtree;
  52296. if( pBtree ){
  52297. int i;
  52298. BtShared *pBt = pCur->pBt;
  52299. sqlite3BtreeEnter(pBtree);
  52300. sqlite3BtreeClearCursor(pCur);
  52301. if( pCur->pPrev ){
  52302. pCur->pPrev->pNext = pCur->pNext;
  52303. }else{
  52304. pBt->pCursor = pCur->pNext;
  52305. }
  52306. if( pCur->pNext ){
  52307. pCur->pNext->pPrev = pCur->pPrev;
  52308. }
  52309. for(i=0; i<=pCur->iPage; i++){
  52310. releasePage(pCur->apPage[i]);
  52311. }
  52312. unlockBtreeIfUnused(pBt);
  52313. sqlite3DbFree(pBtree->db, pCur->aOverflow);
  52314. /* sqlite3_free(pCur); */
  52315. sqlite3BtreeLeave(pBtree);
  52316. }
  52317. return SQLITE_OK;
  52318. }
  52319. /*
  52320. ** Make sure the BtCursor* given in the argument has a valid
  52321. ** BtCursor.info structure. If it is not already valid, call
  52322. ** btreeParseCell() to fill it in.
  52323. **
  52324. ** BtCursor.info is a cache of the information in the current cell.
  52325. ** Using this cache reduces the number of calls to btreeParseCell().
  52326. **
  52327. ** 2007-06-25: There is a bug in some versions of MSVC that cause the
  52328. ** compiler to crash when getCellInfo() is implemented as a macro.
  52329. ** But there is a measureable speed advantage to using the macro on gcc
  52330. ** (when less compiler optimizations like -Os or -O0 are used and the
  52331. ** compiler is not doing aggressive inlining.) So we use a real function
  52332. ** for MSVC and a macro for everything else. Ticket #2457.
  52333. */
  52334. #ifndef NDEBUG
  52335. static void assertCellInfo(BtCursor *pCur){
  52336. CellInfo info;
  52337. int iPage = pCur->iPage;
  52338. memset(&info, 0, sizeof(info));
  52339. btreeParseCell(pCur->apPage[iPage], pCur->aiIdx[iPage], &info);
  52340. assert( CORRUPT_DB || memcmp(&info, &pCur->info, sizeof(info))==0 );
  52341. }
  52342. #else
  52343. #define assertCellInfo(x)
  52344. #endif
  52345. #ifdef _MSC_VER
  52346. /* Use a real function in MSVC to work around bugs in that compiler. */
  52347. static void getCellInfo(BtCursor *pCur){
  52348. if( pCur->info.nSize==0 ){
  52349. int iPage = pCur->iPage;
  52350. btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info);
  52351. pCur->curFlags |= BTCF_ValidNKey;
  52352. }else{
  52353. assertCellInfo(pCur);
  52354. }
  52355. }
  52356. #else /* if not _MSC_VER */
  52357. /* Use a macro in all other compilers so that the function is inlined */
  52358. #define getCellInfo(pCur) \
  52359. if( pCur->info.nSize==0 ){ \
  52360. int iPage = pCur->iPage; \
  52361. btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info); \
  52362. pCur->curFlags |= BTCF_ValidNKey; \
  52363. }else{ \
  52364. assertCellInfo(pCur); \
  52365. }
  52366. #endif /* _MSC_VER */
  52367. #ifndef NDEBUG /* The next routine used only within assert() statements */
  52368. /*
  52369. ** Return true if the given BtCursor is valid. A valid cursor is one
  52370. ** that is currently pointing to a row in a (non-empty) table.
  52371. ** This is a verification routine is used only within assert() statements.
  52372. */
  52373. SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor *pCur){
  52374. return pCur && pCur->eState==CURSOR_VALID;
  52375. }
  52376. #endif /* NDEBUG */
  52377. /*
  52378. ** Set *pSize to the size of the buffer needed to hold the value of
  52379. ** the key for the current entry. If the cursor is not pointing
  52380. ** to a valid entry, *pSize is set to 0.
  52381. **
  52382. ** For a table with the INTKEY flag set, this routine returns the key
  52383. ** itself, not the number of bytes in the key.
  52384. **
  52385. ** The caller must position the cursor prior to invoking this routine.
  52386. **
  52387. ** This routine cannot fail. It always returns SQLITE_OK.
  52388. */
  52389. SQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor *pCur, i64 *pSize){
  52390. assert( cursorHoldsMutex(pCur) );
  52391. assert( pCur->eState==CURSOR_INVALID || pCur->eState==CURSOR_VALID );
  52392. if( pCur->eState!=CURSOR_VALID ){
  52393. *pSize = 0;
  52394. }else{
  52395. getCellInfo(pCur);
  52396. *pSize = pCur->info.nKey;
  52397. }
  52398. return SQLITE_OK;
  52399. }
  52400. /*
  52401. ** Set *pSize to the number of bytes of data in the entry the
  52402. ** cursor currently points to.
  52403. **
  52404. ** The caller must guarantee that the cursor is pointing to a non-NULL
  52405. ** valid entry. In other words, the calling procedure must guarantee
  52406. ** that the cursor has Cursor.eState==CURSOR_VALID.
  52407. **
  52408. ** Failure is not possible. This function always returns SQLITE_OK.
  52409. ** It might just as well be a procedure (returning void) but we continue
  52410. ** to return an integer result code for historical reasons.
  52411. */
  52412. SQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor *pCur, u32 *pSize){
  52413. assert( cursorHoldsMutex(pCur) );
  52414. assert( pCur->eState==CURSOR_VALID );
  52415. assert( pCur->apPage[pCur->iPage]->intKeyLeaf==1 );
  52416. getCellInfo(pCur);
  52417. *pSize = pCur->info.nPayload;
  52418. return SQLITE_OK;
  52419. }
  52420. /*
  52421. ** Given the page number of an overflow page in the database (parameter
  52422. ** ovfl), this function finds the page number of the next page in the
  52423. ** linked list of overflow pages. If possible, it uses the auto-vacuum
  52424. ** pointer-map data instead of reading the content of page ovfl to do so.
  52425. **
  52426. ** If an error occurs an SQLite error code is returned. Otherwise:
  52427. **
  52428. ** The page number of the next overflow page in the linked list is
  52429. ** written to *pPgnoNext. If page ovfl is the last page in its linked
  52430. ** list, *pPgnoNext is set to zero.
  52431. **
  52432. ** If ppPage is not NULL, and a reference to the MemPage object corresponding
  52433. ** to page number pOvfl was obtained, then *ppPage is set to point to that
  52434. ** reference. It is the responsibility of the caller to call releasePage()
  52435. ** on *ppPage to free the reference. In no reference was obtained (because
  52436. ** the pointer-map was used to obtain the value for *pPgnoNext), then
  52437. ** *ppPage is set to zero.
  52438. */
  52439. static int getOverflowPage(
  52440. BtShared *pBt, /* The database file */
  52441. Pgno ovfl, /* Current overflow page number */
  52442. MemPage **ppPage, /* OUT: MemPage handle (may be NULL) */
  52443. Pgno *pPgnoNext /* OUT: Next overflow page number */
  52444. ){
  52445. Pgno next = 0;
  52446. MemPage *pPage = 0;
  52447. int rc = SQLITE_OK;
  52448. assert( sqlite3_mutex_held(pBt->mutex) );
  52449. assert(pPgnoNext);
  52450. #ifndef SQLITE_OMIT_AUTOVACUUM
  52451. /* Try to find the next page in the overflow list using the
  52452. ** autovacuum pointer-map pages. Guess that the next page in
  52453. ** the overflow list is page number (ovfl+1). If that guess turns
  52454. ** out to be wrong, fall back to loading the data of page
  52455. ** number ovfl to determine the next page number.
  52456. */
  52457. if( pBt->autoVacuum ){
  52458. Pgno pgno;
  52459. Pgno iGuess = ovfl+1;
  52460. u8 eType;
  52461. while( PTRMAP_ISPAGE(pBt, iGuess) || iGuess==PENDING_BYTE_PAGE(pBt) ){
  52462. iGuess++;
  52463. }
  52464. if( iGuess<=btreePagecount(pBt) ){
  52465. rc = ptrmapGet(pBt, iGuess, &eType, &pgno);
  52466. if( rc==SQLITE_OK && eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){
  52467. next = iGuess;
  52468. rc = SQLITE_DONE;
  52469. }
  52470. }
  52471. }
  52472. #endif
  52473. assert( next==0 || rc==SQLITE_DONE );
  52474. if( rc==SQLITE_OK ){
  52475. rc = btreeGetPage(pBt, ovfl, &pPage, (ppPage==0) ? PAGER_GET_READONLY : 0);
  52476. assert( rc==SQLITE_OK || pPage==0 );
  52477. if( rc==SQLITE_OK ){
  52478. next = get4byte(pPage->aData);
  52479. }
  52480. }
  52481. *pPgnoNext = next;
  52482. if( ppPage ){
  52483. *ppPage = pPage;
  52484. }else{
  52485. releasePage(pPage);
  52486. }
  52487. return (rc==SQLITE_DONE ? SQLITE_OK : rc);
  52488. }
  52489. /*
  52490. ** Copy data from a buffer to a page, or from a page to a buffer.
  52491. **
  52492. ** pPayload is a pointer to data stored on database page pDbPage.
  52493. ** If argument eOp is false, then nByte bytes of data are copied
  52494. ** from pPayload to the buffer pointed at by pBuf. If eOp is true,
  52495. ** then sqlite3PagerWrite() is called on pDbPage and nByte bytes
  52496. ** of data are copied from the buffer pBuf to pPayload.
  52497. **
  52498. ** SQLITE_OK is returned on success, otherwise an error code.
  52499. */
  52500. static int copyPayload(
  52501. void *pPayload, /* Pointer to page data */
  52502. void *pBuf, /* Pointer to buffer */
  52503. int nByte, /* Number of bytes to copy */
  52504. int eOp, /* 0 -> copy from page, 1 -> copy to page */
  52505. DbPage *pDbPage /* Page containing pPayload */
  52506. ){
  52507. if( eOp ){
  52508. /* Copy data from buffer to page (a write operation) */
  52509. int rc = sqlite3PagerWrite(pDbPage);
  52510. if( rc!=SQLITE_OK ){
  52511. return rc;
  52512. }
  52513. memcpy(pPayload, pBuf, nByte);
  52514. }else{
  52515. /* Copy data from page to buffer (a read operation) */
  52516. memcpy(pBuf, pPayload, nByte);
  52517. }
  52518. return SQLITE_OK;
  52519. }
  52520. /*
  52521. ** This function is used to read or overwrite payload information
  52522. ** for the entry that the pCur cursor is pointing to. The eOp
  52523. ** argument is interpreted as follows:
  52524. **
  52525. ** 0: The operation is a read. Populate the overflow cache.
  52526. ** 1: The operation is a write. Populate the overflow cache.
  52527. ** 2: The operation is a read. Do not populate the overflow cache.
  52528. **
  52529. ** A total of "amt" bytes are read or written beginning at "offset".
  52530. ** Data is read to or from the buffer pBuf.
  52531. **
  52532. ** The content being read or written might appear on the main page
  52533. ** or be scattered out on multiple overflow pages.
  52534. **
  52535. ** If the current cursor entry uses one or more overflow pages and the
  52536. ** eOp argument is not 2, this function may allocate space for and lazily
  52537. ** populates the overflow page-list cache array (BtCursor.aOverflow).
  52538. ** Subsequent calls use this cache to make seeking to the supplied offset
  52539. ** more efficient.
  52540. **
  52541. ** Once an overflow page-list cache has been allocated, it may be
  52542. ** invalidated if some other cursor writes to the same table, or if
  52543. ** the cursor is moved to a different row. Additionally, in auto-vacuum
  52544. ** mode, the following events may invalidate an overflow page-list cache.
  52545. **
  52546. ** * An incremental vacuum,
  52547. ** * A commit in auto_vacuum="full" mode,
  52548. ** * Creating a table (may require moving an overflow page).
  52549. */
  52550. static int accessPayload(
  52551. BtCursor *pCur, /* Cursor pointing to entry to read from */
  52552. u32 offset, /* Begin reading this far into payload */
  52553. u32 amt, /* Read this many bytes */
  52554. unsigned char *pBuf, /* Write the bytes into this buffer */
  52555. int eOp /* zero to read. non-zero to write. */
  52556. ){
  52557. unsigned char *aPayload;
  52558. int rc = SQLITE_OK;
  52559. int iIdx = 0;
  52560. MemPage *pPage = pCur->apPage[pCur->iPage]; /* Btree page of current entry */
  52561. BtShared *pBt = pCur->pBt; /* Btree this cursor belongs to */
  52562. #ifdef SQLITE_DIRECT_OVERFLOW_READ
  52563. unsigned char * const pBufStart = pBuf;
  52564. int bEnd; /* True if reading to end of data */
  52565. #endif
  52566. assert( pPage );
  52567. assert( pCur->eState==CURSOR_VALID );
  52568. assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
  52569. assert( cursorHoldsMutex(pCur) );
  52570. assert( eOp!=2 || offset==0 ); /* Always start from beginning for eOp==2 */
  52571. getCellInfo(pCur);
  52572. aPayload = pCur->info.pPayload;
  52573. #ifdef SQLITE_DIRECT_OVERFLOW_READ
  52574. bEnd = offset+amt==pCur->info.nPayload;
  52575. #endif
  52576. assert( offset+amt <= pCur->info.nPayload );
  52577. if( &aPayload[pCur->info.nLocal] > &pPage->aData[pBt->usableSize] ){
  52578. /* Trying to read or write past the end of the data is an error */
  52579. return SQLITE_CORRUPT_BKPT;
  52580. }
  52581. /* Check if data must be read/written to/from the btree page itself. */
  52582. if( offset<pCur->info.nLocal ){
  52583. int a = amt;
  52584. if( a+offset>pCur->info.nLocal ){
  52585. a = pCur->info.nLocal - offset;
  52586. }
  52587. rc = copyPayload(&aPayload[offset], pBuf, a, (eOp & 0x01), pPage->pDbPage);
  52588. offset = 0;
  52589. pBuf += a;
  52590. amt -= a;
  52591. }else{
  52592. offset -= pCur->info.nLocal;
  52593. }
  52594. if( rc==SQLITE_OK && amt>0 ){
  52595. const u32 ovflSize = pBt->usableSize - 4; /* Bytes content per ovfl page */
  52596. Pgno nextPage;
  52597. nextPage = get4byte(&aPayload[pCur->info.nLocal]);
  52598. /* If the BtCursor.aOverflow[] has not been allocated, allocate it now.
  52599. ** Except, do not allocate aOverflow[] for eOp==2.
  52600. **
  52601. ** The aOverflow[] array is sized at one entry for each overflow page
  52602. ** in the overflow chain. The page number of the first overflow page is
  52603. ** stored in aOverflow[0], etc. A value of 0 in the aOverflow[] array
  52604. ** means "not yet known" (the cache is lazily populated).
  52605. */
  52606. if( eOp!=2 && (pCur->curFlags & BTCF_ValidOvfl)==0 ){
  52607. int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize;
  52608. if( nOvfl>pCur->nOvflAlloc ){
  52609. Pgno *aNew = (Pgno*)sqlite3DbRealloc(
  52610. pCur->pBtree->db, pCur->aOverflow, nOvfl*2*sizeof(Pgno)
  52611. );
  52612. if( aNew==0 ){
  52613. rc = SQLITE_NOMEM;
  52614. }else{
  52615. pCur->nOvflAlloc = nOvfl*2;
  52616. pCur->aOverflow = aNew;
  52617. }
  52618. }
  52619. if( rc==SQLITE_OK ){
  52620. memset(pCur->aOverflow, 0, nOvfl*sizeof(Pgno));
  52621. pCur->curFlags |= BTCF_ValidOvfl;
  52622. }
  52623. }
  52624. /* If the overflow page-list cache has been allocated and the
  52625. ** entry for the first required overflow page is valid, skip
  52626. ** directly to it.
  52627. */
  52628. if( (pCur->curFlags & BTCF_ValidOvfl)!=0
  52629. && pCur->aOverflow[offset/ovflSize]
  52630. ){
  52631. iIdx = (offset/ovflSize);
  52632. nextPage = pCur->aOverflow[iIdx];
  52633. offset = (offset%ovflSize);
  52634. }
  52635. for( ; rc==SQLITE_OK && amt>0 && nextPage; iIdx++){
  52636. /* If required, populate the overflow page-list cache. */
  52637. if( (pCur->curFlags & BTCF_ValidOvfl)!=0 ){
  52638. assert(!pCur->aOverflow[iIdx] || pCur->aOverflow[iIdx]==nextPage);
  52639. pCur->aOverflow[iIdx] = nextPage;
  52640. }
  52641. if( offset>=ovflSize ){
  52642. /* The only reason to read this page is to obtain the page
  52643. ** number for the next page in the overflow chain. The page
  52644. ** data is not required. So first try to lookup the overflow
  52645. ** page-list cache, if any, then fall back to the getOverflowPage()
  52646. ** function.
  52647. **
  52648. ** Note that the aOverflow[] array must be allocated because eOp!=2
  52649. ** here. If eOp==2, then offset==0 and this branch is never taken.
  52650. */
  52651. assert( eOp!=2 );
  52652. assert( pCur->curFlags & BTCF_ValidOvfl );
  52653. if( pCur->aOverflow[iIdx+1] ){
  52654. nextPage = pCur->aOverflow[iIdx+1];
  52655. }else{
  52656. rc = getOverflowPage(pBt, nextPage, 0, &nextPage);
  52657. }
  52658. offset -= ovflSize;
  52659. }else{
  52660. /* Need to read this page properly. It contains some of the
  52661. ** range of data that is being read (eOp==0) or written (eOp!=0).
  52662. */
  52663. #ifdef SQLITE_DIRECT_OVERFLOW_READ
  52664. sqlite3_file *fd;
  52665. #endif
  52666. int a = amt;
  52667. if( a + offset > ovflSize ){
  52668. a = ovflSize - offset;
  52669. }
  52670. #ifdef SQLITE_DIRECT_OVERFLOW_READ
  52671. /* If all the following are true:
  52672. **
  52673. ** 1) this is a read operation, and
  52674. ** 2) data is required from the start of this overflow page, and
  52675. ** 3) the database is file-backed, and
  52676. ** 4) there is no open write-transaction, and
  52677. ** 5) the database is not a WAL database,
  52678. ** 6) all data from the page is being read.
  52679. ** 7) at least 4 bytes have already been read into the output buffer
  52680. **
  52681. ** then data can be read directly from the database file into the
  52682. ** output buffer, bypassing the page-cache altogether. This speeds
  52683. ** up loading large records that span many overflow pages.
  52684. */
  52685. if( (eOp&0x01)==0 /* (1) */
  52686. && offset==0 /* (2) */
  52687. && (bEnd || a==ovflSize) /* (6) */
  52688. && pBt->inTransaction==TRANS_READ /* (4) */
  52689. && (fd = sqlite3PagerFile(pBt->pPager))->pMethods /* (3) */
  52690. && pBt->pPage1->aData[19]==0x01 /* (5) */
  52691. && &pBuf[-4]>=pBufStart /* (7) */
  52692. ){
  52693. u8 aSave[4];
  52694. u8 *aWrite = &pBuf[-4];
  52695. assert( aWrite>=pBufStart ); /* hence (7) */
  52696. memcpy(aSave, aWrite, 4);
  52697. rc = sqlite3OsRead(fd, aWrite, a+4, (i64)pBt->pageSize*(nextPage-1));
  52698. nextPage = get4byte(aWrite);
  52699. memcpy(aWrite, aSave, 4);
  52700. }else
  52701. #endif
  52702. {
  52703. DbPage *pDbPage;
  52704. rc = sqlite3PagerAcquire(pBt->pPager, nextPage, &pDbPage,
  52705. ((eOp&0x01)==0 ? PAGER_GET_READONLY : 0)
  52706. );
  52707. if( rc==SQLITE_OK ){
  52708. aPayload = sqlite3PagerGetData(pDbPage);
  52709. nextPage = get4byte(aPayload);
  52710. rc = copyPayload(&aPayload[offset+4], pBuf, a, (eOp&0x01), pDbPage);
  52711. sqlite3PagerUnref(pDbPage);
  52712. offset = 0;
  52713. }
  52714. }
  52715. amt -= a;
  52716. pBuf += a;
  52717. }
  52718. }
  52719. }
  52720. if( rc==SQLITE_OK && amt>0 ){
  52721. return SQLITE_CORRUPT_BKPT;
  52722. }
  52723. return rc;
  52724. }
  52725. /*
  52726. ** Read part of the key associated with cursor pCur. Exactly
  52727. ** "amt" bytes will be transferred into pBuf[]. The transfer
  52728. ** begins at "offset".
  52729. **
  52730. ** The caller must ensure that pCur is pointing to a valid row
  52731. ** in the table.
  52732. **
  52733. ** Return SQLITE_OK on success or an error code if anything goes
  52734. ** wrong. An error is returned if "offset+amt" is larger than
  52735. ** the available payload.
  52736. */
  52737. SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
  52738. assert( cursorHoldsMutex(pCur) );
  52739. assert( pCur->eState==CURSOR_VALID );
  52740. assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
  52741. assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
  52742. return accessPayload(pCur, offset, amt, (unsigned char*)pBuf, 0);
  52743. }
  52744. /*
  52745. ** Read part of the data associated with cursor pCur. Exactly
  52746. ** "amt" bytes will be transfered into pBuf[]. The transfer
  52747. ** begins at "offset".
  52748. **
  52749. ** Return SQLITE_OK on success or an error code if anything goes
  52750. ** wrong. An error is returned if "offset+amt" is larger than
  52751. ** the available payload.
  52752. */
  52753. SQLITE_PRIVATE int sqlite3BtreeData(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
  52754. int rc;
  52755. #ifndef SQLITE_OMIT_INCRBLOB
  52756. if ( pCur->eState==CURSOR_INVALID ){
  52757. return SQLITE_ABORT;
  52758. }
  52759. #endif
  52760. assert( cursorHoldsMutex(pCur) );
  52761. rc = restoreCursorPosition(pCur);
  52762. if( rc==SQLITE_OK ){
  52763. assert( pCur->eState==CURSOR_VALID );
  52764. assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
  52765. assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
  52766. rc = accessPayload(pCur, offset, amt, pBuf, 0);
  52767. }
  52768. return rc;
  52769. }
  52770. /*
  52771. ** Return a pointer to payload information from the entry that the
  52772. ** pCur cursor is pointing to. The pointer is to the beginning of
  52773. ** the key if index btrees (pPage->intKey==0) and is the data for
  52774. ** table btrees (pPage->intKey==1). The number of bytes of available
  52775. ** key/data is written into *pAmt. If *pAmt==0, then the value
  52776. ** returned will not be a valid pointer.
  52777. **
  52778. ** This routine is an optimization. It is common for the entire key
  52779. ** and data to fit on the local page and for there to be no overflow
  52780. ** pages. When that is so, this routine can be used to access the
  52781. ** key and data without making a copy. If the key and/or data spills
  52782. ** onto overflow pages, then accessPayload() must be used to reassemble
  52783. ** the key/data and copy it into a preallocated buffer.
  52784. **
  52785. ** The pointer returned by this routine looks directly into the cached
  52786. ** page of the database. The data might change or move the next time
  52787. ** any btree routine is called.
  52788. */
  52789. static const void *fetchPayload(
  52790. BtCursor *pCur, /* Cursor pointing to entry to read from */
  52791. u32 *pAmt /* Write the number of available bytes here */
  52792. ){
  52793. assert( pCur!=0 && pCur->iPage>=0 && pCur->apPage[pCur->iPage]);
  52794. assert( pCur->eState==CURSOR_VALID );
  52795. assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
  52796. assert( cursorHoldsMutex(pCur) );
  52797. assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
  52798. assert( pCur->info.nSize>0 );
  52799. *pAmt = pCur->info.nLocal;
  52800. return (void*)pCur->info.pPayload;
  52801. }
  52802. /*
  52803. ** For the entry that cursor pCur is point to, return as
  52804. ** many bytes of the key or data as are available on the local
  52805. ** b-tree page. Write the number of available bytes into *pAmt.
  52806. **
  52807. ** The pointer returned is ephemeral. The key/data may move
  52808. ** or be destroyed on the next call to any Btree routine,
  52809. ** including calls from other threads against the same cache.
  52810. ** Hence, a mutex on the BtShared should be held prior to calling
  52811. ** this routine.
  52812. **
  52813. ** These routines is used to get quick access to key and data
  52814. ** in the common case where no overflow pages are used.
  52815. */
  52816. SQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor *pCur, u32 *pAmt){
  52817. return fetchPayload(pCur, pAmt);
  52818. }
  52819. SQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor *pCur, u32 *pAmt){
  52820. return fetchPayload(pCur, pAmt);
  52821. }
  52822. /*
  52823. ** Move the cursor down to a new child page. The newPgno argument is the
  52824. ** page number of the child page to move to.
  52825. **
  52826. ** This function returns SQLITE_CORRUPT if the page-header flags field of
  52827. ** the new child page does not match the flags field of the parent (i.e.
  52828. ** if an intkey page appears to be the parent of a non-intkey page, or
  52829. ** vice-versa).
  52830. */
  52831. static int moveToChild(BtCursor *pCur, u32 newPgno){
  52832. int rc;
  52833. int i = pCur->iPage;
  52834. MemPage *pNewPage;
  52835. BtShared *pBt = pCur->pBt;
  52836. assert( cursorHoldsMutex(pCur) );
  52837. assert( pCur->eState==CURSOR_VALID );
  52838. assert( pCur->iPage<BTCURSOR_MAX_DEPTH );
  52839. assert( pCur->iPage>=0 );
  52840. if( pCur->iPage>=(BTCURSOR_MAX_DEPTH-1) ){
  52841. return SQLITE_CORRUPT_BKPT;
  52842. }
  52843. rc = getAndInitPage(pBt, newPgno, &pNewPage,
  52844. (pCur->curFlags & BTCF_WriteFlag)==0 ? PAGER_GET_READONLY : 0);
  52845. if( rc ) return rc;
  52846. pCur->apPage[i+1] = pNewPage;
  52847. pCur->aiIdx[i+1] = 0;
  52848. pCur->iPage++;
  52849. pCur->info.nSize = 0;
  52850. pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
  52851. if( pNewPage->nCell<1 || pNewPage->intKey!=pCur->apPage[i]->intKey ){
  52852. return SQLITE_CORRUPT_BKPT;
  52853. }
  52854. return SQLITE_OK;
  52855. }
  52856. #if 0
  52857. /*
  52858. ** Page pParent is an internal (non-leaf) tree page. This function
  52859. ** asserts that page number iChild is the left-child if the iIdx'th
  52860. ** cell in page pParent. Or, if iIdx is equal to the total number of
  52861. ** cells in pParent, that page number iChild is the right-child of
  52862. ** the page.
  52863. */
  52864. static void assertParentIndex(MemPage *pParent, int iIdx, Pgno iChild){
  52865. assert( iIdx<=pParent->nCell );
  52866. if( iIdx==pParent->nCell ){
  52867. assert( get4byte(&pParent->aData[pParent->hdrOffset+8])==iChild );
  52868. }else{
  52869. assert( get4byte(findCell(pParent, iIdx))==iChild );
  52870. }
  52871. }
  52872. #else
  52873. # define assertParentIndex(x,y,z)
  52874. #endif
  52875. /*
  52876. ** Move the cursor up to the parent page.
  52877. **
  52878. ** pCur->idx is set to the cell index that contains the pointer
  52879. ** to the page we are coming from. If we are coming from the
  52880. ** right-most child page then pCur->idx is set to one more than
  52881. ** the largest cell index.
  52882. */
  52883. static void moveToParent(BtCursor *pCur){
  52884. assert( cursorHoldsMutex(pCur) );
  52885. assert( pCur->eState==CURSOR_VALID );
  52886. assert( pCur->iPage>0 );
  52887. assert( pCur->apPage[pCur->iPage] );
  52888. /* UPDATE: It is actually possible for the condition tested by the assert
  52889. ** below to be untrue if the database file is corrupt. This can occur if
  52890. ** one cursor has modified page pParent while a reference to it is held
  52891. ** by a second cursor. Which can only happen if a single page is linked
  52892. ** into more than one b-tree structure in a corrupt database. */
  52893. #if 0
  52894. assertParentIndex(
  52895. pCur->apPage[pCur->iPage-1],
  52896. pCur->aiIdx[pCur->iPage-1],
  52897. pCur->apPage[pCur->iPage]->pgno
  52898. );
  52899. #endif
  52900. testcase( pCur->aiIdx[pCur->iPage-1] > pCur->apPage[pCur->iPage-1]->nCell );
  52901. releasePage(pCur->apPage[pCur->iPage]);
  52902. pCur->iPage--;
  52903. pCur->info.nSize = 0;
  52904. pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
  52905. }
  52906. /*
  52907. ** Move the cursor to point to the root page of its b-tree structure.
  52908. **
  52909. ** If the table has a virtual root page, then the cursor is moved to point
  52910. ** to the virtual root page instead of the actual root page. A table has a
  52911. ** virtual root page when the actual root page contains no cells and a
  52912. ** single child page. This can only happen with the table rooted at page 1.
  52913. **
  52914. ** If the b-tree structure is empty, the cursor state is set to
  52915. ** CURSOR_INVALID. Otherwise, the cursor is set to point to the first
  52916. ** cell located on the root (or virtual root) page and the cursor state
  52917. ** is set to CURSOR_VALID.
  52918. **
  52919. ** If this function returns successfully, it may be assumed that the
  52920. ** page-header flags indicate that the [virtual] root-page is the expected
  52921. ** kind of b-tree page (i.e. if when opening the cursor the caller did not
  52922. ** specify a KeyInfo structure the flags byte is set to 0x05 or 0x0D,
  52923. ** indicating a table b-tree, or if the caller did specify a KeyInfo
  52924. ** structure the flags byte is set to 0x02 or 0x0A, indicating an index
  52925. ** b-tree).
  52926. */
  52927. static int moveToRoot(BtCursor *pCur){
  52928. MemPage *pRoot;
  52929. int rc = SQLITE_OK;
  52930. assert( cursorHoldsMutex(pCur) );
  52931. assert( CURSOR_INVALID < CURSOR_REQUIRESEEK );
  52932. assert( CURSOR_VALID < CURSOR_REQUIRESEEK );
  52933. assert( CURSOR_FAULT > CURSOR_REQUIRESEEK );
  52934. if( pCur->eState>=CURSOR_REQUIRESEEK ){
  52935. if( pCur->eState==CURSOR_FAULT ){
  52936. assert( pCur->skipNext!=SQLITE_OK );
  52937. return pCur->skipNext;
  52938. }
  52939. sqlite3BtreeClearCursor(pCur);
  52940. }
  52941. if( pCur->iPage>=0 ){
  52942. while( pCur->iPage ) releasePage(pCur->apPage[pCur->iPage--]);
  52943. }else if( pCur->pgnoRoot==0 ){
  52944. pCur->eState = CURSOR_INVALID;
  52945. return SQLITE_OK;
  52946. }else{
  52947. rc = getAndInitPage(pCur->pBtree->pBt, pCur->pgnoRoot, &pCur->apPage[0],
  52948. (pCur->curFlags & BTCF_WriteFlag)==0 ? PAGER_GET_READONLY : 0);
  52949. if( rc!=SQLITE_OK ){
  52950. pCur->eState = CURSOR_INVALID;
  52951. return rc;
  52952. }
  52953. pCur->iPage = 0;
  52954. }
  52955. pRoot = pCur->apPage[0];
  52956. assert( pRoot->pgno==pCur->pgnoRoot );
  52957. /* If pCur->pKeyInfo is not NULL, then the caller that opened this cursor
  52958. ** expected to open it on an index b-tree. Otherwise, if pKeyInfo is
  52959. ** NULL, the caller expects a table b-tree. If this is not the case,
  52960. ** return an SQLITE_CORRUPT error.
  52961. **
  52962. ** Earlier versions of SQLite assumed that this test could not fail
  52963. ** if the root page was already loaded when this function was called (i.e.
  52964. ** if pCur->iPage>=0). But this is not so if the database is corrupted
  52965. ** in such a way that page pRoot is linked into a second b-tree table
  52966. ** (or the freelist). */
  52967. assert( pRoot->intKey==1 || pRoot->intKey==0 );
  52968. if( pRoot->isInit==0 || (pCur->pKeyInfo==0)!=pRoot->intKey ){
  52969. return SQLITE_CORRUPT_BKPT;
  52970. }
  52971. pCur->aiIdx[0] = 0;
  52972. pCur->info.nSize = 0;
  52973. pCur->curFlags &= ~(BTCF_AtLast|BTCF_ValidNKey|BTCF_ValidOvfl);
  52974. if( pRoot->nCell>0 ){
  52975. pCur->eState = CURSOR_VALID;
  52976. }else if( !pRoot->leaf ){
  52977. Pgno subpage;
  52978. if( pRoot->pgno!=1 ) return SQLITE_CORRUPT_BKPT;
  52979. subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]);
  52980. pCur->eState = CURSOR_VALID;
  52981. rc = moveToChild(pCur, subpage);
  52982. }else{
  52983. pCur->eState = CURSOR_INVALID;
  52984. }
  52985. return rc;
  52986. }
  52987. /*
  52988. ** Move the cursor down to the left-most leaf entry beneath the
  52989. ** entry to which it is currently pointing.
  52990. **
  52991. ** The left-most leaf is the one with the smallest key - the first
  52992. ** in ascending order.
  52993. */
  52994. static int moveToLeftmost(BtCursor *pCur){
  52995. Pgno pgno;
  52996. int rc = SQLITE_OK;
  52997. MemPage *pPage;
  52998. assert( cursorHoldsMutex(pCur) );
  52999. assert( pCur->eState==CURSOR_VALID );
  53000. while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
  53001. assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
  53002. pgno = get4byte(findCell(pPage, pCur->aiIdx[pCur->iPage]));
  53003. rc = moveToChild(pCur, pgno);
  53004. }
  53005. return rc;
  53006. }
  53007. /*
  53008. ** Move the cursor down to the right-most leaf entry beneath the
  53009. ** page to which it is currently pointing. Notice the difference
  53010. ** between moveToLeftmost() and moveToRightmost(). moveToLeftmost()
  53011. ** finds the left-most entry beneath the *entry* whereas moveToRightmost()
  53012. ** finds the right-most entry beneath the *page*.
  53013. **
  53014. ** The right-most entry is the one with the largest key - the last
  53015. ** key in ascending order.
  53016. */
  53017. static int moveToRightmost(BtCursor *pCur){
  53018. Pgno pgno;
  53019. int rc = SQLITE_OK;
  53020. MemPage *pPage = 0;
  53021. assert( cursorHoldsMutex(pCur) );
  53022. assert( pCur->eState==CURSOR_VALID );
  53023. while( !(pPage = pCur->apPage[pCur->iPage])->leaf ){
  53024. pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
  53025. pCur->aiIdx[pCur->iPage] = pPage->nCell;
  53026. rc = moveToChild(pCur, pgno);
  53027. if( rc ) return rc;
  53028. }
  53029. pCur->aiIdx[pCur->iPage] = pPage->nCell-1;
  53030. assert( pCur->info.nSize==0 );
  53031. assert( (pCur->curFlags & BTCF_ValidNKey)==0 );
  53032. return SQLITE_OK;
  53033. }
  53034. /* Move the cursor to the first entry in the table. Return SQLITE_OK
  53035. ** on success. Set *pRes to 0 if the cursor actually points to something
  53036. ** or set *pRes to 1 if the table is empty.
  53037. */
  53038. SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){
  53039. int rc;
  53040. assert( cursorHoldsMutex(pCur) );
  53041. assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
  53042. rc = moveToRoot(pCur);
  53043. if( rc==SQLITE_OK ){
  53044. if( pCur->eState==CURSOR_INVALID ){
  53045. assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
  53046. *pRes = 1;
  53047. }else{
  53048. assert( pCur->apPage[pCur->iPage]->nCell>0 );
  53049. *pRes = 0;
  53050. rc = moveToLeftmost(pCur);
  53051. }
  53052. }
  53053. return rc;
  53054. }
  53055. /* Move the cursor to the last entry in the table. Return SQLITE_OK
  53056. ** on success. Set *pRes to 0 if the cursor actually points to something
  53057. ** or set *pRes to 1 if the table is empty.
  53058. */
  53059. SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
  53060. int rc;
  53061. assert( cursorHoldsMutex(pCur) );
  53062. assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
  53063. /* If the cursor already points to the last entry, this is a no-op. */
  53064. if( CURSOR_VALID==pCur->eState && (pCur->curFlags & BTCF_AtLast)!=0 ){
  53065. #ifdef SQLITE_DEBUG
  53066. /* This block serves to assert() that the cursor really does point
  53067. ** to the last entry in the b-tree. */
  53068. int ii;
  53069. for(ii=0; ii<pCur->iPage; ii++){
  53070. assert( pCur->aiIdx[ii]==pCur->apPage[ii]->nCell );
  53071. }
  53072. assert( pCur->aiIdx[pCur->iPage]==pCur->apPage[pCur->iPage]->nCell-1 );
  53073. assert( pCur->apPage[pCur->iPage]->leaf );
  53074. #endif
  53075. return SQLITE_OK;
  53076. }
  53077. rc = moveToRoot(pCur);
  53078. if( rc==SQLITE_OK ){
  53079. if( CURSOR_INVALID==pCur->eState ){
  53080. assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
  53081. *pRes = 1;
  53082. }else{
  53083. assert( pCur->eState==CURSOR_VALID );
  53084. *pRes = 0;
  53085. rc = moveToRightmost(pCur);
  53086. if( rc==SQLITE_OK ){
  53087. pCur->curFlags |= BTCF_AtLast;
  53088. }else{
  53089. pCur->curFlags &= ~BTCF_AtLast;
  53090. }
  53091. }
  53092. }
  53093. return rc;
  53094. }
  53095. /* Move the cursor so that it points to an entry near the key
  53096. ** specified by pIdxKey or intKey. Return a success code.
  53097. **
  53098. ** For INTKEY tables, the intKey parameter is used. pIdxKey
  53099. ** must be NULL. For index tables, pIdxKey is used and intKey
  53100. ** is ignored.
  53101. **
  53102. ** If an exact match is not found, then the cursor is always
  53103. ** left pointing at a leaf page which would hold the entry if it
  53104. ** were present. The cursor might point to an entry that comes
  53105. ** before or after the key.
  53106. **
  53107. ** An integer is written into *pRes which is the result of
  53108. ** comparing the key with the entry to which the cursor is
  53109. ** pointing. The meaning of the integer written into
  53110. ** *pRes is as follows:
  53111. **
  53112. ** *pRes<0 The cursor is left pointing at an entry that
  53113. ** is smaller than intKey/pIdxKey or if the table is empty
  53114. ** and the cursor is therefore left point to nothing.
  53115. **
  53116. ** *pRes==0 The cursor is left pointing at an entry that
  53117. ** exactly matches intKey/pIdxKey.
  53118. **
  53119. ** *pRes>0 The cursor is left pointing at an entry that
  53120. ** is larger than intKey/pIdxKey.
  53121. **
  53122. */
  53123. SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
  53124. BtCursor *pCur, /* The cursor to be moved */
  53125. UnpackedRecord *pIdxKey, /* Unpacked index key */
  53126. i64 intKey, /* The table key */
  53127. int biasRight, /* If true, bias the search to the high end */
  53128. int *pRes /* Write search results here */
  53129. ){
  53130. int rc;
  53131. RecordCompare xRecordCompare;
  53132. assert( cursorHoldsMutex(pCur) );
  53133. assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
  53134. assert( pRes );
  53135. assert( (pIdxKey==0)==(pCur->pKeyInfo==0) );
  53136. /* If the cursor is already positioned at the point we are trying
  53137. ** to move to, then just return without doing any work */
  53138. if( pCur->eState==CURSOR_VALID && (pCur->curFlags & BTCF_ValidNKey)!=0
  53139. && pCur->apPage[0]->intKey
  53140. ){
  53141. if( pCur->info.nKey==intKey ){
  53142. *pRes = 0;
  53143. return SQLITE_OK;
  53144. }
  53145. if( (pCur->curFlags & BTCF_AtLast)!=0 && pCur->info.nKey<intKey ){
  53146. *pRes = -1;
  53147. return SQLITE_OK;
  53148. }
  53149. }
  53150. if( pIdxKey ){
  53151. xRecordCompare = sqlite3VdbeFindCompare(pIdxKey);
  53152. pIdxKey->errCode = 0;
  53153. assert( pIdxKey->default_rc==1
  53154. || pIdxKey->default_rc==0
  53155. || pIdxKey->default_rc==-1
  53156. );
  53157. }else{
  53158. xRecordCompare = 0; /* All keys are integers */
  53159. }
  53160. rc = moveToRoot(pCur);
  53161. if( rc ){
  53162. return rc;
  53163. }
  53164. assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage] );
  53165. assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->isInit );
  53166. assert( pCur->eState==CURSOR_INVALID || pCur->apPage[pCur->iPage]->nCell>0 );
  53167. if( pCur->eState==CURSOR_INVALID ){
  53168. *pRes = -1;
  53169. assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
  53170. return SQLITE_OK;
  53171. }
  53172. assert( pCur->apPage[0]->intKey || pIdxKey );
  53173. for(;;){
  53174. int lwr, upr, idx, c;
  53175. Pgno chldPg;
  53176. MemPage *pPage = pCur->apPage[pCur->iPage];
  53177. u8 *pCell; /* Pointer to current cell in pPage */
  53178. /* pPage->nCell must be greater than zero. If this is the root-page
  53179. ** the cursor would have been INVALID above and this for(;;) loop
  53180. ** not run. If this is not the root-page, then the moveToChild() routine
  53181. ** would have already detected db corruption. Similarly, pPage must
  53182. ** be the right kind (index or table) of b-tree page. Otherwise
  53183. ** a moveToChild() or moveToRoot() call would have detected corruption. */
  53184. assert( pPage->nCell>0 );
  53185. assert( pPage->intKey==(pIdxKey==0) );
  53186. lwr = 0;
  53187. upr = pPage->nCell-1;
  53188. assert( biasRight==0 || biasRight==1 );
  53189. idx = upr>>(1-biasRight); /* idx = biasRight ? upr : (lwr+upr)/2; */
  53190. pCur->aiIdx[pCur->iPage] = (u16)idx;
  53191. if( xRecordCompare==0 ){
  53192. for(;;){
  53193. i64 nCellKey;
  53194. pCell = findCell(pPage, idx) + pPage->childPtrSize;
  53195. if( pPage->intKeyLeaf ){
  53196. while( 0x80 <= *(pCell++) ){
  53197. if( pCell>=pPage->aDataEnd ) return SQLITE_CORRUPT_BKPT;
  53198. }
  53199. }
  53200. getVarint(pCell, (u64*)&nCellKey);
  53201. if( nCellKey<intKey ){
  53202. lwr = idx+1;
  53203. if( lwr>upr ){ c = -1; break; }
  53204. }else if( nCellKey>intKey ){
  53205. upr = idx-1;
  53206. if( lwr>upr ){ c = +1; break; }
  53207. }else{
  53208. assert( nCellKey==intKey );
  53209. pCur->curFlags |= BTCF_ValidNKey;
  53210. pCur->info.nKey = nCellKey;
  53211. pCur->aiIdx[pCur->iPage] = (u16)idx;
  53212. if( !pPage->leaf ){
  53213. lwr = idx;
  53214. goto moveto_next_layer;
  53215. }else{
  53216. *pRes = 0;
  53217. rc = SQLITE_OK;
  53218. goto moveto_finish;
  53219. }
  53220. }
  53221. assert( lwr+upr>=0 );
  53222. idx = (lwr+upr)>>1; /* idx = (lwr+upr)/2; */
  53223. }
  53224. }else{
  53225. for(;;){
  53226. int nCell;
  53227. pCell = findCell(pPage, idx) + pPage->childPtrSize;
  53228. /* The maximum supported page-size is 65536 bytes. This means that
  53229. ** the maximum number of record bytes stored on an index B-Tree
  53230. ** page is less than 16384 bytes and may be stored as a 2-byte
  53231. ** varint. This information is used to attempt to avoid parsing
  53232. ** the entire cell by checking for the cases where the record is
  53233. ** stored entirely within the b-tree page by inspecting the first
  53234. ** 2 bytes of the cell.
  53235. */
  53236. nCell = pCell[0];
  53237. if( nCell<=pPage->max1bytePayload ){
  53238. /* This branch runs if the record-size field of the cell is a
  53239. ** single byte varint and the record fits entirely on the main
  53240. ** b-tree page. */
  53241. testcase( pCell+nCell+1==pPage->aDataEnd );
  53242. c = xRecordCompare(nCell, (void*)&pCell[1], pIdxKey);
  53243. }else if( !(pCell[1] & 0x80)
  53244. && (nCell = ((nCell&0x7f)<<7) + pCell[1])<=pPage->maxLocal
  53245. ){
  53246. /* The record-size field is a 2 byte varint and the record
  53247. ** fits entirely on the main b-tree page. */
  53248. testcase( pCell+nCell+2==pPage->aDataEnd );
  53249. c = xRecordCompare(nCell, (void*)&pCell[2], pIdxKey);
  53250. }else{
  53251. /* The record flows over onto one or more overflow pages. In
  53252. ** this case the whole cell needs to be parsed, a buffer allocated
  53253. ** and accessPayload() used to retrieve the record into the
  53254. ** buffer before VdbeRecordCompare() can be called. */
  53255. void *pCellKey;
  53256. u8 * const pCellBody = pCell - pPage->childPtrSize;
  53257. btreeParseCellPtr(pPage, pCellBody, &pCur->info);
  53258. nCell = (int)pCur->info.nKey;
  53259. pCellKey = sqlite3Malloc( nCell );
  53260. if( pCellKey==0 ){
  53261. rc = SQLITE_NOMEM;
  53262. goto moveto_finish;
  53263. }
  53264. pCur->aiIdx[pCur->iPage] = (u16)idx;
  53265. rc = accessPayload(pCur, 0, nCell, (unsigned char*)pCellKey, 2);
  53266. if( rc ){
  53267. sqlite3_free(pCellKey);
  53268. goto moveto_finish;
  53269. }
  53270. c = xRecordCompare(nCell, pCellKey, pIdxKey);
  53271. sqlite3_free(pCellKey);
  53272. }
  53273. assert(
  53274. (pIdxKey->errCode!=SQLITE_CORRUPT || c==0)
  53275. && (pIdxKey->errCode!=SQLITE_NOMEM || pCur->pBtree->db->mallocFailed)
  53276. );
  53277. if( c<0 ){
  53278. lwr = idx+1;
  53279. }else if( c>0 ){
  53280. upr = idx-1;
  53281. }else{
  53282. assert( c==0 );
  53283. *pRes = 0;
  53284. rc = SQLITE_OK;
  53285. pCur->aiIdx[pCur->iPage] = (u16)idx;
  53286. if( pIdxKey->errCode ) rc = SQLITE_CORRUPT;
  53287. goto moveto_finish;
  53288. }
  53289. if( lwr>upr ) break;
  53290. assert( lwr+upr>=0 );
  53291. idx = (lwr+upr)>>1; /* idx = (lwr+upr)/2 */
  53292. }
  53293. }
  53294. assert( lwr==upr+1 || (pPage->intKey && !pPage->leaf) );
  53295. assert( pPage->isInit );
  53296. if( pPage->leaf ){
  53297. assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
  53298. pCur->aiIdx[pCur->iPage] = (u16)idx;
  53299. *pRes = c;
  53300. rc = SQLITE_OK;
  53301. goto moveto_finish;
  53302. }
  53303. moveto_next_layer:
  53304. if( lwr>=pPage->nCell ){
  53305. chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
  53306. }else{
  53307. chldPg = get4byte(findCell(pPage, lwr));
  53308. }
  53309. pCur->aiIdx[pCur->iPage] = (u16)lwr;
  53310. rc = moveToChild(pCur, chldPg);
  53311. if( rc ) break;
  53312. }
  53313. moveto_finish:
  53314. pCur->info.nSize = 0;
  53315. pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
  53316. return rc;
  53317. }
  53318. /*
  53319. ** Return TRUE if the cursor is not pointing at an entry of the table.
  53320. **
  53321. ** TRUE will be returned after a call to sqlite3BtreeNext() moves
  53322. ** past the last entry in the table or sqlite3BtreePrev() moves past
  53323. ** the first entry. TRUE is also returned if the table is empty.
  53324. */
  53325. SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor *pCur){
  53326. /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries
  53327. ** have been deleted? This API will need to change to return an error code
  53328. ** as well as the boolean result value.
  53329. */
  53330. return (CURSOR_VALID!=pCur->eState);
  53331. }
  53332. /*
  53333. ** Advance the cursor to the next entry in the database. If
  53334. ** successful then set *pRes=0. If the cursor
  53335. ** was already pointing to the last entry in the database before
  53336. ** this routine was called, then set *pRes=1.
  53337. **
  53338. ** The main entry point is sqlite3BtreeNext(). That routine is optimized
  53339. ** for the common case of merely incrementing the cell counter BtCursor.aiIdx
  53340. ** to the next cell on the current page. The (slower) btreeNext() helper
  53341. ** routine is called when it is necessary to move to a different page or
  53342. ** to restore the cursor.
  53343. **
  53344. ** The calling function will set *pRes to 0 or 1. The initial *pRes value
  53345. ** will be 1 if the cursor being stepped corresponds to an SQL index and
  53346. ** if this routine could have been skipped if that SQL index had been
  53347. ** a unique index. Otherwise the caller will have set *pRes to zero.
  53348. ** Zero is the common case. The btree implementation is free to use the
  53349. ** initial *pRes value as a hint to improve performance, but the current
  53350. ** SQLite btree implementation does not. (Note that the comdb2 btree
  53351. ** implementation does use this hint, however.)
  53352. */
  53353. static SQLITE_NOINLINE int btreeNext(BtCursor *pCur, int *pRes){
  53354. int rc;
  53355. int idx;
  53356. MemPage *pPage;
  53357. assert( cursorHoldsMutex(pCur) );
  53358. assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
  53359. assert( *pRes==0 );
  53360. if( pCur->eState!=CURSOR_VALID ){
  53361. assert( (pCur->curFlags & BTCF_ValidOvfl)==0 );
  53362. rc = restoreCursorPosition(pCur);
  53363. if( rc!=SQLITE_OK ){
  53364. return rc;
  53365. }
  53366. if( CURSOR_INVALID==pCur->eState ){
  53367. *pRes = 1;
  53368. return SQLITE_OK;
  53369. }
  53370. if( pCur->skipNext ){
  53371. assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_SKIPNEXT );
  53372. pCur->eState = CURSOR_VALID;
  53373. if( pCur->skipNext>0 ){
  53374. pCur->skipNext = 0;
  53375. return SQLITE_OK;
  53376. }
  53377. pCur->skipNext = 0;
  53378. }
  53379. }
  53380. pPage = pCur->apPage[pCur->iPage];
  53381. idx = ++pCur->aiIdx[pCur->iPage];
  53382. assert( pPage->isInit );
  53383. /* If the database file is corrupt, it is possible for the value of idx
  53384. ** to be invalid here. This can only occur if a second cursor modifies
  53385. ** the page while cursor pCur is holding a reference to it. Which can
  53386. ** only happen if the database is corrupt in such a way as to link the
  53387. ** page into more than one b-tree structure. */
  53388. testcase( idx>pPage->nCell );
  53389. if( idx>=pPage->nCell ){
  53390. if( !pPage->leaf ){
  53391. rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
  53392. if( rc ) return rc;
  53393. return moveToLeftmost(pCur);
  53394. }
  53395. do{
  53396. if( pCur->iPage==0 ){
  53397. *pRes = 1;
  53398. pCur->eState = CURSOR_INVALID;
  53399. return SQLITE_OK;
  53400. }
  53401. moveToParent(pCur);
  53402. pPage = pCur->apPage[pCur->iPage];
  53403. }while( pCur->aiIdx[pCur->iPage]>=pPage->nCell );
  53404. if( pPage->intKey ){
  53405. return sqlite3BtreeNext(pCur, pRes);
  53406. }else{
  53407. return SQLITE_OK;
  53408. }
  53409. }
  53410. if( pPage->leaf ){
  53411. return SQLITE_OK;
  53412. }else{
  53413. return moveToLeftmost(pCur);
  53414. }
  53415. }
  53416. SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor *pCur, int *pRes){
  53417. MemPage *pPage;
  53418. assert( cursorHoldsMutex(pCur) );
  53419. assert( pRes!=0 );
  53420. assert( *pRes==0 || *pRes==1 );
  53421. assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
  53422. pCur->info.nSize = 0;
  53423. pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
  53424. *pRes = 0;
  53425. if( pCur->eState!=CURSOR_VALID ) return btreeNext(pCur, pRes);
  53426. pPage = pCur->apPage[pCur->iPage];
  53427. if( (++pCur->aiIdx[pCur->iPage])>=pPage->nCell ){
  53428. pCur->aiIdx[pCur->iPage]--;
  53429. return btreeNext(pCur, pRes);
  53430. }
  53431. if( pPage->leaf ){
  53432. return SQLITE_OK;
  53433. }else{
  53434. return moveToLeftmost(pCur);
  53435. }
  53436. }
  53437. /*
  53438. ** Step the cursor to the back to the previous entry in the database. If
  53439. ** successful then set *pRes=0. If the cursor
  53440. ** was already pointing to the first entry in the database before
  53441. ** this routine was called, then set *pRes=1.
  53442. **
  53443. ** The main entry point is sqlite3BtreePrevious(). That routine is optimized
  53444. ** for the common case of merely decrementing the cell counter BtCursor.aiIdx
  53445. ** to the previous cell on the current page. The (slower) btreePrevious()
  53446. ** helper routine is called when it is necessary to move to a different page
  53447. ** or to restore the cursor.
  53448. **
  53449. ** The calling function will set *pRes to 0 or 1. The initial *pRes value
  53450. ** will be 1 if the cursor being stepped corresponds to an SQL index and
  53451. ** if this routine could have been skipped if that SQL index had been
  53452. ** a unique index. Otherwise the caller will have set *pRes to zero.
  53453. ** Zero is the common case. The btree implementation is free to use the
  53454. ** initial *pRes value as a hint to improve performance, but the current
  53455. ** SQLite btree implementation does not. (Note that the comdb2 btree
  53456. ** implementation does use this hint, however.)
  53457. */
  53458. static SQLITE_NOINLINE int btreePrevious(BtCursor *pCur, int *pRes){
  53459. int rc;
  53460. MemPage *pPage;
  53461. assert( cursorHoldsMutex(pCur) );
  53462. assert( pRes!=0 );
  53463. assert( *pRes==0 );
  53464. assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
  53465. assert( (pCur->curFlags & (BTCF_AtLast|BTCF_ValidOvfl|BTCF_ValidNKey))==0 );
  53466. assert( pCur->info.nSize==0 );
  53467. if( pCur->eState!=CURSOR_VALID ){
  53468. rc = restoreCursorPosition(pCur);
  53469. if( rc!=SQLITE_OK ){
  53470. return rc;
  53471. }
  53472. if( CURSOR_INVALID==pCur->eState ){
  53473. *pRes = 1;
  53474. return SQLITE_OK;
  53475. }
  53476. if( pCur->skipNext ){
  53477. assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_SKIPNEXT );
  53478. pCur->eState = CURSOR_VALID;
  53479. if( pCur->skipNext<0 ){
  53480. pCur->skipNext = 0;
  53481. return SQLITE_OK;
  53482. }
  53483. pCur->skipNext = 0;
  53484. }
  53485. }
  53486. pPage = pCur->apPage[pCur->iPage];
  53487. assert( pPage->isInit );
  53488. if( !pPage->leaf ){
  53489. int idx = pCur->aiIdx[pCur->iPage];
  53490. rc = moveToChild(pCur, get4byte(findCell(pPage, idx)));
  53491. if( rc ) return rc;
  53492. rc = moveToRightmost(pCur);
  53493. }else{
  53494. while( pCur->aiIdx[pCur->iPage]==0 ){
  53495. if( pCur->iPage==0 ){
  53496. pCur->eState = CURSOR_INVALID;
  53497. *pRes = 1;
  53498. return SQLITE_OK;
  53499. }
  53500. moveToParent(pCur);
  53501. }
  53502. assert( pCur->info.nSize==0 );
  53503. assert( (pCur->curFlags & (BTCF_ValidNKey|BTCF_ValidOvfl))==0 );
  53504. pCur->aiIdx[pCur->iPage]--;
  53505. pPage = pCur->apPage[pCur->iPage];
  53506. if( pPage->intKey && !pPage->leaf ){
  53507. rc = sqlite3BtreePrevious(pCur, pRes);
  53508. }else{
  53509. rc = SQLITE_OK;
  53510. }
  53511. }
  53512. return rc;
  53513. }
  53514. SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor *pCur, int *pRes){
  53515. assert( cursorHoldsMutex(pCur) );
  53516. assert( pRes!=0 );
  53517. assert( *pRes==0 || *pRes==1 );
  53518. assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
  53519. *pRes = 0;
  53520. pCur->curFlags &= ~(BTCF_AtLast|BTCF_ValidOvfl|BTCF_ValidNKey);
  53521. pCur->info.nSize = 0;
  53522. if( pCur->eState!=CURSOR_VALID
  53523. || pCur->aiIdx[pCur->iPage]==0
  53524. || pCur->apPage[pCur->iPage]->leaf==0
  53525. ){
  53526. return btreePrevious(pCur, pRes);
  53527. }
  53528. pCur->aiIdx[pCur->iPage]--;
  53529. return SQLITE_OK;
  53530. }
  53531. /*
  53532. ** Allocate a new page from the database file.
  53533. **
  53534. ** The new page is marked as dirty. (In other words, sqlite3PagerWrite()
  53535. ** has already been called on the new page.) The new page has also
  53536. ** been referenced and the calling routine is responsible for calling
  53537. ** sqlite3PagerUnref() on the new page when it is done.
  53538. **
  53539. ** SQLITE_OK is returned on success. Any other return value indicates
  53540. ** an error. *ppPage and *pPgno are undefined in the event of an error.
  53541. ** Do not invoke sqlite3PagerUnref() on *ppPage if an error is returned.
  53542. **
  53543. ** If the "nearby" parameter is not 0, then an effort is made to
  53544. ** locate a page close to the page number "nearby". This can be used in an
  53545. ** attempt to keep related pages close to each other in the database file,
  53546. ** which in turn can make database access faster.
  53547. **
  53548. ** If the eMode parameter is BTALLOC_EXACT and the nearby page exists
  53549. ** anywhere on the free-list, then it is guaranteed to be returned. If
  53550. ** eMode is BTALLOC_LT then the page returned will be less than or equal
  53551. ** to nearby if any such page exists. If eMode is BTALLOC_ANY then there
  53552. ** are no restrictions on which page is returned.
  53553. */
  53554. static int allocateBtreePage(
  53555. BtShared *pBt, /* The btree */
  53556. MemPage **ppPage, /* Store pointer to the allocated page here */
  53557. Pgno *pPgno, /* Store the page number here */
  53558. Pgno nearby, /* Search for a page near this one */
  53559. u8 eMode /* BTALLOC_EXACT, BTALLOC_LT, or BTALLOC_ANY */
  53560. ){
  53561. MemPage *pPage1;
  53562. int rc;
  53563. u32 n; /* Number of pages on the freelist */
  53564. u32 k; /* Number of leaves on the trunk of the freelist */
  53565. MemPage *pTrunk = 0;
  53566. MemPage *pPrevTrunk = 0;
  53567. Pgno mxPage; /* Total size of the database file */
  53568. assert( sqlite3_mutex_held(pBt->mutex) );
  53569. assert( eMode==BTALLOC_ANY || (nearby>0 && IfNotOmitAV(pBt->autoVacuum)) );
  53570. pPage1 = pBt->pPage1;
  53571. mxPage = btreePagecount(pBt);
  53572. n = get4byte(&pPage1->aData[36]);
  53573. testcase( n==mxPage-1 );
  53574. if( n>=mxPage ){
  53575. return SQLITE_CORRUPT_BKPT;
  53576. }
  53577. if( n>0 ){
  53578. /* There are pages on the freelist. Reuse one of those pages. */
  53579. Pgno iTrunk;
  53580. u8 searchList = 0; /* If the free-list must be searched for 'nearby' */
  53581. /* If eMode==BTALLOC_EXACT and a query of the pointer-map
  53582. ** shows that the page 'nearby' is somewhere on the free-list, then
  53583. ** the entire-list will be searched for that page.
  53584. */
  53585. #ifndef SQLITE_OMIT_AUTOVACUUM
  53586. if( eMode==BTALLOC_EXACT ){
  53587. if( nearby<=mxPage ){
  53588. u8 eType;
  53589. assert( nearby>0 );
  53590. assert( pBt->autoVacuum );
  53591. rc = ptrmapGet(pBt, nearby, &eType, 0);
  53592. if( rc ) return rc;
  53593. if( eType==PTRMAP_FREEPAGE ){
  53594. searchList = 1;
  53595. }
  53596. }
  53597. }else if( eMode==BTALLOC_LE ){
  53598. searchList = 1;
  53599. }
  53600. #endif
  53601. /* Decrement the free-list count by 1. Set iTrunk to the index of the
  53602. ** first free-list trunk page. iPrevTrunk is initially 1.
  53603. */
  53604. rc = sqlite3PagerWrite(pPage1->pDbPage);
  53605. if( rc ) return rc;
  53606. put4byte(&pPage1->aData[36], n-1);
  53607. /* The code within this loop is run only once if the 'searchList' variable
  53608. ** is not true. Otherwise, it runs once for each trunk-page on the
  53609. ** free-list until the page 'nearby' is located (eMode==BTALLOC_EXACT)
  53610. ** or until a page less than 'nearby' is located (eMode==BTALLOC_LT)
  53611. */
  53612. do {
  53613. pPrevTrunk = pTrunk;
  53614. if( pPrevTrunk ){
  53615. iTrunk = get4byte(&pPrevTrunk->aData[0]);
  53616. }else{
  53617. iTrunk = get4byte(&pPage1->aData[32]);
  53618. }
  53619. testcase( iTrunk==mxPage );
  53620. if( iTrunk>mxPage ){
  53621. rc = SQLITE_CORRUPT_BKPT;
  53622. }else{
  53623. rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
  53624. }
  53625. if( rc ){
  53626. pTrunk = 0;
  53627. goto end_allocate_page;
  53628. }
  53629. assert( pTrunk!=0 );
  53630. assert( pTrunk->aData!=0 );
  53631. k = get4byte(&pTrunk->aData[4]); /* # of leaves on this trunk page */
  53632. if( k==0 && !searchList ){
  53633. /* The trunk has no leaves and the list is not being searched.
  53634. ** So extract the trunk page itself and use it as the newly
  53635. ** allocated page */
  53636. assert( pPrevTrunk==0 );
  53637. rc = sqlite3PagerWrite(pTrunk->pDbPage);
  53638. if( rc ){
  53639. goto end_allocate_page;
  53640. }
  53641. *pPgno = iTrunk;
  53642. memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
  53643. *ppPage = pTrunk;
  53644. pTrunk = 0;
  53645. TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
  53646. }else if( k>(u32)(pBt->usableSize/4 - 2) ){
  53647. /* Value of k is out of range. Database corruption */
  53648. rc = SQLITE_CORRUPT_BKPT;
  53649. goto end_allocate_page;
  53650. #ifndef SQLITE_OMIT_AUTOVACUUM
  53651. }else if( searchList
  53652. && (nearby==iTrunk || (iTrunk<nearby && eMode==BTALLOC_LE))
  53653. ){
  53654. /* The list is being searched and this trunk page is the page
  53655. ** to allocate, regardless of whether it has leaves.
  53656. */
  53657. *pPgno = iTrunk;
  53658. *ppPage = pTrunk;
  53659. searchList = 0;
  53660. rc = sqlite3PagerWrite(pTrunk->pDbPage);
  53661. if( rc ){
  53662. goto end_allocate_page;
  53663. }
  53664. if( k==0 ){
  53665. if( !pPrevTrunk ){
  53666. memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
  53667. }else{
  53668. rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
  53669. if( rc!=SQLITE_OK ){
  53670. goto end_allocate_page;
  53671. }
  53672. memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4);
  53673. }
  53674. }else{
  53675. /* The trunk page is required by the caller but it contains
  53676. ** pointers to free-list leaves. The first leaf becomes a trunk
  53677. ** page in this case.
  53678. */
  53679. MemPage *pNewTrunk;
  53680. Pgno iNewTrunk = get4byte(&pTrunk->aData[8]);
  53681. if( iNewTrunk>mxPage ){
  53682. rc = SQLITE_CORRUPT_BKPT;
  53683. goto end_allocate_page;
  53684. }
  53685. testcase( iNewTrunk==mxPage );
  53686. rc = btreeGetPage(pBt, iNewTrunk, &pNewTrunk, 0);
  53687. if( rc!=SQLITE_OK ){
  53688. goto end_allocate_page;
  53689. }
  53690. rc = sqlite3PagerWrite(pNewTrunk->pDbPage);
  53691. if( rc!=SQLITE_OK ){
  53692. releasePage(pNewTrunk);
  53693. goto end_allocate_page;
  53694. }
  53695. memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4);
  53696. put4byte(&pNewTrunk->aData[4], k-1);
  53697. memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4);
  53698. releasePage(pNewTrunk);
  53699. if( !pPrevTrunk ){
  53700. assert( sqlite3PagerIswriteable(pPage1->pDbPage) );
  53701. put4byte(&pPage1->aData[32], iNewTrunk);
  53702. }else{
  53703. rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
  53704. if( rc ){
  53705. goto end_allocate_page;
  53706. }
  53707. put4byte(&pPrevTrunk->aData[0], iNewTrunk);
  53708. }
  53709. }
  53710. pTrunk = 0;
  53711. TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
  53712. #endif
  53713. }else if( k>0 ){
  53714. /* Extract a leaf from the trunk */
  53715. u32 closest;
  53716. Pgno iPage;
  53717. unsigned char *aData = pTrunk->aData;
  53718. if( nearby>0 ){
  53719. u32 i;
  53720. closest = 0;
  53721. if( eMode==BTALLOC_LE ){
  53722. for(i=0; i<k; i++){
  53723. iPage = get4byte(&aData[8+i*4]);
  53724. if( iPage<=nearby ){
  53725. closest = i;
  53726. break;
  53727. }
  53728. }
  53729. }else{
  53730. int dist;
  53731. dist = sqlite3AbsInt32(get4byte(&aData[8]) - nearby);
  53732. for(i=1; i<k; i++){
  53733. int d2 = sqlite3AbsInt32(get4byte(&aData[8+i*4]) - nearby);
  53734. if( d2<dist ){
  53735. closest = i;
  53736. dist = d2;
  53737. }
  53738. }
  53739. }
  53740. }else{
  53741. closest = 0;
  53742. }
  53743. iPage = get4byte(&aData[8+closest*4]);
  53744. testcase( iPage==mxPage );
  53745. if( iPage>mxPage ){
  53746. rc = SQLITE_CORRUPT_BKPT;
  53747. goto end_allocate_page;
  53748. }
  53749. testcase( iPage==mxPage );
  53750. if( !searchList
  53751. || (iPage==nearby || (iPage<nearby && eMode==BTALLOC_LE))
  53752. ){
  53753. int noContent;
  53754. *pPgno = iPage;
  53755. TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d"
  53756. ": %d more free pages\n",
  53757. *pPgno, closest+1, k, pTrunk->pgno, n-1));
  53758. rc = sqlite3PagerWrite(pTrunk->pDbPage);
  53759. if( rc ) goto end_allocate_page;
  53760. if( closest<k-1 ){
  53761. memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
  53762. }
  53763. put4byte(&aData[4], k-1);
  53764. noContent = !btreeGetHasContent(pBt, *pPgno)? PAGER_GET_NOCONTENT : 0;
  53765. rc = btreeGetPage(pBt, *pPgno, ppPage, noContent);
  53766. if( rc==SQLITE_OK ){
  53767. rc = sqlite3PagerWrite((*ppPage)->pDbPage);
  53768. if( rc!=SQLITE_OK ){
  53769. releasePage(*ppPage);
  53770. }
  53771. }
  53772. searchList = 0;
  53773. }
  53774. }
  53775. releasePage(pPrevTrunk);
  53776. pPrevTrunk = 0;
  53777. }while( searchList );
  53778. }else{
  53779. /* There are no pages on the freelist, so append a new page to the
  53780. ** database image.
  53781. **
  53782. ** Normally, new pages allocated by this block can be requested from the
  53783. ** pager layer with the 'no-content' flag set. This prevents the pager
  53784. ** from trying to read the pages content from disk. However, if the
  53785. ** current transaction has already run one or more incremental-vacuum
  53786. ** steps, then the page we are about to allocate may contain content
  53787. ** that is required in the event of a rollback. In this case, do
  53788. ** not set the no-content flag. This causes the pager to load and journal
  53789. ** the current page content before overwriting it.
  53790. **
  53791. ** Note that the pager will not actually attempt to load or journal
  53792. ** content for any page that really does lie past the end of the database
  53793. ** file on disk. So the effects of disabling the no-content optimization
  53794. ** here are confined to those pages that lie between the end of the
  53795. ** database image and the end of the database file.
  53796. */
  53797. int bNoContent = (0==IfNotOmitAV(pBt->bDoTruncate))? PAGER_GET_NOCONTENT:0;
  53798. rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
  53799. if( rc ) return rc;
  53800. pBt->nPage++;
  53801. if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ) pBt->nPage++;
  53802. #ifndef SQLITE_OMIT_AUTOVACUUM
  53803. if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, pBt->nPage) ){
  53804. /* If *pPgno refers to a pointer-map page, allocate two new pages
  53805. ** at the end of the file instead of one. The first allocated page
  53806. ** becomes a new pointer-map page, the second is used by the caller.
  53807. */
  53808. MemPage *pPg = 0;
  53809. TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", pBt->nPage));
  53810. assert( pBt->nPage!=PENDING_BYTE_PAGE(pBt) );
  53811. rc = btreeGetPage(pBt, pBt->nPage, &pPg, bNoContent);
  53812. if( rc==SQLITE_OK ){
  53813. rc = sqlite3PagerWrite(pPg->pDbPage);
  53814. releasePage(pPg);
  53815. }
  53816. if( rc ) return rc;
  53817. pBt->nPage++;
  53818. if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ){ pBt->nPage++; }
  53819. }
  53820. #endif
  53821. put4byte(28 + (u8*)pBt->pPage1->aData, pBt->nPage);
  53822. *pPgno = pBt->nPage;
  53823. assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
  53824. rc = btreeGetPage(pBt, *pPgno, ppPage, bNoContent);
  53825. if( rc ) return rc;
  53826. rc = sqlite3PagerWrite((*ppPage)->pDbPage);
  53827. if( rc!=SQLITE_OK ){
  53828. releasePage(*ppPage);
  53829. }
  53830. TRACE(("ALLOCATE: %d from end of file\n", *pPgno));
  53831. }
  53832. assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
  53833. end_allocate_page:
  53834. releasePage(pTrunk);
  53835. releasePage(pPrevTrunk);
  53836. if( rc==SQLITE_OK ){
  53837. if( sqlite3PagerPageRefcount((*ppPage)->pDbPage)>1 ){
  53838. releasePage(*ppPage);
  53839. *ppPage = 0;
  53840. return SQLITE_CORRUPT_BKPT;
  53841. }
  53842. (*ppPage)->isInit = 0;
  53843. }else{
  53844. *ppPage = 0;
  53845. }
  53846. assert( rc!=SQLITE_OK || sqlite3PagerIswriteable((*ppPage)->pDbPage) );
  53847. return rc;
  53848. }
  53849. /*
  53850. ** This function is used to add page iPage to the database file free-list.
  53851. ** It is assumed that the page is not already a part of the free-list.
  53852. **
  53853. ** The value passed as the second argument to this function is optional.
  53854. ** If the caller happens to have a pointer to the MemPage object
  53855. ** corresponding to page iPage handy, it may pass it as the second value.
  53856. ** Otherwise, it may pass NULL.
  53857. **
  53858. ** If a pointer to a MemPage object is passed as the second argument,
  53859. ** its reference count is not altered by this function.
  53860. */
  53861. static int freePage2(BtShared *pBt, MemPage *pMemPage, Pgno iPage){
  53862. MemPage *pTrunk = 0; /* Free-list trunk page */
  53863. Pgno iTrunk = 0; /* Page number of free-list trunk page */
  53864. MemPage *pPage1 = pBt->pPage1; /* Local reference to page 1 */
  53865. MemPage *pPage; /* Page being freed. May be NULL. */
  53866. int rc; /* Return Code */
  53867. int nFree; /* Initial number of pages on free-list */
  53868. assert( sqlite3_mutex_held(pBt->mutex) );
  53869. assert( iPage>1 );
  53870. assert( !pMemPage || pMemPage->pgno==iPage );
  53871. if( pMemPage ){
  53872. pPage = pMemPage;
  53873. sqlite3PagerRef(pPage->pDbPage);
  53874. }else{
  53875. pPage = btreePageLookup(pBt, iPage);
  53876. }
  53877. /* Increment the free page count on pPage1 */
  53878. rc = sqlite3PagerWrite(pPage1->pDbPage);
  53879. if( rc ) goto freepage_out;
  53880. nFree = get4byte(&pPage1->aData[36]);
  53881. put4byte(&pPage1->aData[36], nFree+1);
  53882. if( pBt->btsFlags & BTS_SECURE_DELETE ){
  53883. /* If the secure_delete option is enabled, then
  53884. ** always fully overwrite deleted information with zeros.
  53885. */
  53886. if( (!pPage && ((rc = btreeGetPage(pBt, iPage, &pPage, 0))!=0) )
  53887. || ((rc = sqlite3PagerWrite(pPage->pDbPage))!=0)
  53888. ){
  53889. goto freepage_out;
  53890. }
  53891. memset(pPage->aData, 0, pPage->pBt->pageSize);
  53892. }
  53893. /* If the database supports auto-vacuum, write an entry in the pointer-map
  53894. ** to indicate that the page is free.
  53895. */
  53896. if( ISAUTOVACUUM ){
  53897. ptrmapPut(pBt, iPage, PTRMAP_FREEPAGE, 0, &rc);
  53898. if( rc ) goto freepage_out;
  53899. }
  53900. /* Now manipulate the actual database free-list structure. There are two
  53901. ** possibilities. If the free-list is currently empty, or if the first
  53902. ** trunk page in the free-list is full, then this page will become a
  53903. ** new free-list trunk page. Otherwise, it will become a leaf of the
  53904. ** first trunk page in the current free-list. This block tests if it
  53905. ** is possible to add the page as a new free-list leaf.
  53906. */
  53907. if( nFree!=0 ){
  53908. u32 nLeaf; /* Initial number of leaf cells on trunk page */
  53909. iTrunk = get4byte(&pPage1->aData[32]);
  53910. rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
  53911. if( rc!=SQLITE_OK ){
  53912. goto freepage_out;
  53913. }
  53914. nLeaf = get4byte(&pTrunk->aData[4]);
  53915. assert( pBt->usableSize>32 );
  53916. if( nLeaf > (u32)pBt->usableSize/4 - 2 ){
  53917. rc = SQLITE_CORRUPT_BKPT;
  53918. goto freepage_out;
  53919. }
  53920. if( nLeaf < (u32)pBt->usableSize/4 - 8 ){
  53921. /* In this case there is room on the trunk page to insert the page
  53922. ** being freed as a new leaf.
  53923. **
  53924. ** Note that the trunk page is not really full until it contains
  53925. ** usableSize/4 - 2 entries, not usableSize/4 - 8 entries as we have
  53926. ** coded. But due to a coding error in versions of SQLite prior to
  53927. ** 3.6.0, databases with freelist trunk pages holding more than
  53928. ** usableSize/4 - 8 entries will be reported as corrupt. In order
  53929. ** to maintain backwards compatibility with older versions of SQLite,
  53930. ** we will continue to restrict the number of entries to usableSize/4 - 8
  53931. ** for now. At some point in the future (once everyone has upgraded
  53932. ** to 3.6.0 or later) we should consider fixing the conditional above
  53933. ** to read "usableSize/4-2" instead of "usableSize/4-8".
  53934. */
  53935. rc = sqlite3PagerWrite(pTrunk->pDbPage);
  53936. if( rc==SQLITE_OK ){
  53937. put4byte(&pTrunk->aData[4], nLeaf+1);
  53938. put4byte(&pTrunk->aData[8+nLeaf*4], iPage);
  53939. if( pPage && (pBt->btsFlags & BTS_SECURE_DELETE)==0 ){
  53940. sqlite3PagerDontWrite(pPage->pDbPage);
  53941. }
  53942. rc = btreeSetHasContent(pBt, iPage);
  53943. }
  53944. TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno));
  53945. goto freepage_out;
  53946. }
  53947. }
  53948. /* If control flows to this point, then it was not possible to add the
  53949. ** the page being freed as a leaf page of the first trunk in the free-list.
  53950. ** Possibly because the free-list is empty, or possibly because the
  53951. ** first trunk in the free-list is full. Either way, the page being freed
  53952. ** will become the new first trunk page in the free-list.
  53953. */
  53954. if( pPage==0 && SQLITE_OK!=(rc = btreeGetPage(pBt, iPage, &pPage, 0)) ){
  53955. goto freepage_out;
  53956. }
  53957. rc = sqlite3PagerWrite(pPage->pDbPage);
  53958. if( rc!=SQLITE_OK ){
  53959. goto freepage_out;
  53960. }
  53961. put4byte(pPage->aData, iTrunk);
  53962. put4byte(&pPage->aData[4], 0);
  53963. put4byte(&pPage1->aData[32], iPage);
  53964. TRACE(("FREE-PAGE: %d new trunk page replacing %d\n", pPage->pgno, iTrunk));
  53965. freepage_out:
  53966. if( pPage ){
  53967. pPage->isInit = 0;
  53968. }
  53969. releasePage(pPage);
  53970. releasePage(pTrunk);
  53971. return rc;
  53972. }
  53973. static void freePage(MemPage *pPage, int *pRC){
  53974. if( (*pRC)==SQLITE_OK ){
  53975. *pRC = freePage2(pPage->pBt, pPage, pPage->pgno);
  53976. }
  53977. }
  53978. /*
  53979. ** Free any overflow pages associated with the given Cell. Write the
  53980. ** local Cell size (the number of bytes on the original page, omitting
  53981. ** overflow) into *pnSize.
  53982. */
  53983. static int clearCell(
  53984. MemPage *pPage, /* The page that contains the Cell */
  53985. unsigned char *pCell, /* First byte of the Cell */
  53986. u16 *pnSize /* Write the size of the Cell here */
  53987. ){
  53988. BtShared *pBt = pPage->pBt;
  53989. CellInfo info;
  53990. Pgno ovflPgno;
  53991. int rc;
  53992. int nOvfl;
  53993. u32 ovflPageSize;
  53994. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  53995. btreeParseCellPtr(pPage, pCell, &info);
  53996. *pnSize = info.nSize;
  53997. if( info.iOverflow==0 ){
  53998. return SQLITE_OK; /* No overflow pages. Return without doing anything */
  53999. }
  54000. if( pCell+info.iOverflow+3 > pPage->aData+pPage->maskPage ){
  54001. return SQLITE_CORRUPT_BKPT; /* Cell extends past end of page */
  54002. }
  54003. ovflPgno = get4byte(&pCell[info.iOverflow]);
  54004. assert( pBt->usableSize > 4 );
  54005. ovflPageSize = pBt->usableSize - 4;
  54006. nOvfl = (info.nPayload - info.nLocal + ovflPageSize - 1)/ovflPageSize;
  54007. assert( ovflPgno==0 || nOvfl>0 );
  54008. while( nOvfl-- ){
  54009. Pgno iNext = 0;
  54010. MemPage *pOvfl = 0;
  54011. if( ovflPgno<2 || ovflPgno>btreePagecount(pBt) ){
  54012. /* 0 is not a legal page number and page 1 cannot be an
  54013. ** overflow page. Therefore if ovflPgno<2 or past the end of the
  54014. ** file the database must be corrupt. */
  54015. return SQLITE_CORRUPT_BKPT;
  54016. }
  54017. if( nOvfl ){
  54018. rc = getOverflowPage(pBt, ovflPgno, &pOvfl, &iNext);
  54019. if( rc ) return rc;
  54020. }
  54021. if( ( pOvfl || ((pOvfl = btreePageLookup(pBt, ovflPgno))!=0) )
  54022. && sqlite3PagerPageRefcount(pOvfl->pDbPage)!=1
  54023. ){
  54024. /* There is no reason any cursor should have an outstanding reference
  54025. ** to an overflow page belonging to a cell that is being deleted/updated.
  54026. ** So if there exists more than one reference to this page, then it
  54027. ** must not really be an overflow page and the database must be corrupt.
  54028. ** It is helpful to detect this before calling freePage2(), as
  54029. ** freePage2() may zero the page contents if secure-delete mode is
  54030. ** enabled. If this 'overflow' page happens to be a page that the
  54031. ** caller is iterating through or using in some other way, this
  54032. ** can be problematic.
  54033. */
  54034. rc = SQLITE_CORRUPT_BKPT;
  54035. }else{
  54036. rc = freePage2(pBt, pOvfl, ovflPgno);
  54037. }
  54038. if( pOvfl ){
  54039. sqlite3PagerUnref(pOvfl->pDbPage);
  54040. }
  54041. if( rc ) return rc;
  54042. ovflPgno = iNext;
  54043. }
  54044. return SQLITE_OK;
  54045. }
  54046. /*
  54047. ** Create the byte sequence used to represent a cell on page pPage
  54048. ** and write that byte sequence into pCell[]. Overflow pages are
  54049. ** allocated and filled in as necessary. The calling procedure
  54050. ** is responsible for making sure sufficient space has been allocated
  54051. ** for pCell[].
  54052. **
  54053. ** Note that pCell does not necessary need to point to the pPage->aData
  54054. ** area. pCell might point to some temporary storage. The cell will
  54055. ** be constructed in this temporary area then copied into pPage->aData
  54056. ** later.
  54057. */
  54058. static int fillInCell(
  54059. MemPage *pPage, /* The page that contains the cell */
  54060. unsigned char *pCell, /* Complete text of the cell */
  54061. const void *pKey, i64 nKey, /* The key */
  54062. const void *pData,int nData, /* The data */
  54063. int nZero, /* Extra zero bytes to append to pData */
  54064. int *pnSize /* Write cell size here */
  54065. ){
  54066. int nPayload;
  54067. const u8 *pSrc;
  54068. int nSrc, n, rc;
  54069. int spaceLeft;
  54070. MemPage *pOvfl = 0;
  54071. MemPage *pToRelease = 0;
  54072. unsigned char *pPrior;
  54073. unsigned char *pPayload;
  54074. BtShared *pBt = pPage->pBt;
  54075. Pgno pgnoOvfl = 0;
  54076. int nHeader;
  54077. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  54078. /* pPage is not necessarily writeable since pCell might be auxiliary
  54079. ** buffer space that is separate from the pPage buffer area */
  54080. assert( pCell<pPage->aData || pCell>=&pPage->aData[pBt->pageSize]
  54081. || sqlite3PagerIswriteable(pPage->pDbPage) );
  54082. /* Fill in the header. */
  54083. nHeader = pPage->childPtrSize;
  54084. nPayload = nData + nZero;
  54085. if( pPage->intKeyLeaf ){
  54086. nHeader += putVarint32(&pCell[nHeader], nPayload);
  54087. }else{
  54088. assert( nData==0 );
  54089. assert( nZero==0 );
  54090. }
  54091. nHeader += putVarint(&pCell[nHeader], *(u64*)&nKey);
  54092. /* Fill in the payload size */
  54093. if( pPage->intKey ){
  54094. pSrc = pData;
  54095. nSrc = nData;
  54096. nData = 0;
  54097. }else{
  54098. if( NEVER(nKey>0x7fffffff || pKey==0) ){
  54099. return SQLITE_CORRUPT_BKPT;
  54100. }
  54101. nPayload = (int)nKey;
  54102. pSrc = pKey;
  54103. nSrc = (int)nKey;
  54104. }
  54105. if( nPayload<=pPage->maxLocal ){
  54106. n = nHeader + nPayload;
  54107. testcase( n==3 );
  54108. testcase( n==4 );
  54109. if( n<4 ) n = 4;
  54110. *pnSize = n;
  54111. spaceLeft = nPayload;
  54112. pPrior = pCell;
  54113. }else{
  54114. int mn = pPage->minLocal;
  54115. n = mn + (nPayload - mn) % (pPage->pBt->usableSize - 4);
  54116. testcase( n==pPage->maxLocal );
  54117. testcase( n==pPage->maxLocal+1 );
  54118. if( n > pPage->maxLocal ) n = mn;
  54119. spaceLeft = n;
  54120. *pnSize = n + nHeader + 4;
  54121. pPrior = &pCell[nHeader+n];
  54122. }
  54123. pPayload = &pCell[nHeader];
  54124. /* At this point variables should be set as follows:
  54125. **
  54126. ** nPayload Total payload size in bytes
  54127. ** pPayload Begin writing payload here
  54128. ** spaceLeft Space available at pPayload. If nPayload>spaceLeft,
  54129. ** that means content must spill into overflow pages.
  54130. ** *pnSize Size of the local cell (not counting overflow pages)
  54131. ** pPrior Where to write the pgno of the first overflow page
  54132. **
  54133. ** Use a call to btreeParseCellPtr() to verify that the values above
  54134. ** were computed correctly.
  54135. */
  54136. #if SQLITE_DEBUG
  54137. {
  54138. CellInfo info;
  54139. btreeParseCellPtr(pPage, pCell, &info);
  54140. assert( nHeader=(int)(info.pPayload - pCell) );
  54141. assert( info.nKey==nKey );
  54142. assert( *pnSize == info.nSize );
  54143. assert( spaceLeft == info.nLocal );
  54144. assert( pPrior == &pCell[info.iOverflow] );
  54145. }
  54146. #endif
  54147. /* Write the payload into the local Cell and any extra into overflow pages */
  54148. while( nPayload>0 ){
  54149. if( spaceLeft==0 ){
  54150. #ifndef SQLITE_OMIT_AUTOVACUUM
  54151. Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */
  54152. if( pBt->autoVacuum ){
  54153. do{
  54154. pgnoOvfl++;
  54155. } while(
  54156. PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl==PENDING_BYTE_PAGE(pBt)
  54157. );
  54158. }
  54159. #endif
  54160. rc = allocateBtreePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, 0);
  54161. #ifndef SQLITE_OMIT_AUTOVACUUM
  54162. /* If the database supports auto-vacuum, and the second or subsequent
  54163. ** overflow page is being allocated, add an entry to the pointer-map
  54164. ** for that page now.
  54165. **
  54166. ** If this is the first overflow page, then write a partial entry
  54167. ** to the pointer-map. If we write nothing to this pointer-map slot,
  54168. ** then the optimistic overflow chain processing in clearCell()
  54169. ** may misinterpret the uninitialized values and delete the
  54170. ** wrong pages from the database.
  54171. */
  54172. if( pBt->autoVacuum && rc==SQLITE_OK ){
  54173. u8 eType = (pgnoPtrmap?PTRMAP_OVERFLOW2:PTRMAP_OVERFLOW1);
  54174. ptrmapPut(pBt, pgnoOvfl, eType, pgnoPtrmap, &rc);
  54175. if( rc ){
  54176. releasePage(pOvfl);
  54177. }
  54178. }
  54179. #endif
  54180. if( rc ){
  54181. releasePage(pToRelease);
  54182. return rc;
  54183. }
  54184. /* If pToRelease is not zero than pPrior points into the data area
  54185. ** of pToRelease. Make sure pToRelease is still writeable. */
  54186. assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
  54187. /* If pPrior is part of the data area of pPage, then make sure pPage
  54188. ** is still writeable */
  54189. assert( pPrior<pPage->aData || pPrior>=&pPage->aData[pBt->pageSize]
  54190. || sqlite3PagerIswriteable(pPage->pDbPage) );
  54191. put4byte(pPrior, pgnoOvfl);
  54192. releasePage(pToRelease);
  54193. pToRelease = pOvfl;
  54194. pPrior = pOvfl->aData;
  54195. put4byte(pPrior, 0);
  54196. pPayload = &pOvfl->aData[4];
  54197. spaceLeft = pBt->usableSize - 4;
  54198. }
  54199. n = nPayload;
  54200. if( n>spaceLeft ) n = spaceLeft;
  54201. /* If pToRelease is not zero than pPayload points into the data area
  54202. ** of pToRelease. Make sure pToRelease is still writeable. */
  54203. assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
  54204. /* If pPayload is part of the data area of pPage, then make sure pPage
  54205. ** is still writeable */
  54206. assert( pPayload<pPage->aData || pPayload>=&pPage->aData[pBt->pageSize]
  54207. || sqlite3PagerIswriteable(pPage->pDbPage) );
  54208. if( nSrc>0 ){
  54209. if( n>nSrc ) n = nSrc;
  54210. assert( pSrc );
  54211. memcpy(pPayload, pSrc, n);
  54212. }else{
  54213. memset(pPayload, 0, n);
  54214. }
  54215. nPayload -= n;
  54216. pPayload += n;
  54217. pSrc += n;
  54218. nSrc -= n;
  54219. spaceLeft -= n;
  54220. if( nSrc==0 ){
  54221. nSrc = nData;
  54222. pSrc = pData;
  54223. }
  54224. }
  54225. releasePage(pToRelease);
  54226. return SQLITE_OK;
  54227. }
  54228. /*
  54229. ** Remove the i-th cell from pPage. This routine effects pPage only.
  54230. ** The cell content is not freed or deallocated. It is assumed that
  54231. ** the cell content has been copied someplace else. This routine just
  54232. ** removes the reference to the cell from pPage.
  54233. **
  54234. ** "sz" must be the number of bytes in the cell.
  54235. */
  54236. static void dropCell(MemPage *pPage, int idx, int sz, int *pRC){
  54237. u32 pc; /* Offset to cell content of cell being deleted */
  54238. u8 *data; /* pPage->aData */
  54239. u8 *ptr; /* Used to move bytes around within data[] */
  54240. int rc; /* The return code */
  54241. int hdr; /* Beginning of the header. 0 most pages. 100 page 1 */
  54242. if( *pRC ) return;
  54243. assert( idx>=0 && idx<pPage->nCell );
  54244. assert( sz==cellSize(pPage, idx) );
  54245. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  54246. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  54247. data = pPage->aData;
  54248. ptr = &pPage->aCellIdx[2*idx];
  54249. pc = get2byte(ptr);
  54250. hdr = pPage->hdrOffset;
  54251. testcase( pc==get2byte(&data[hdr+5]) );
  54252. testcase( pc+sz==pPage->pBt->usableSize );
  54253. if( pc < (u32)get2byte(&data[hdr+5]) || pc+sz > pPage->pBt->usableSize ){
  54254. *pRC = SQLITE_CORRUPT_BKPT;
  54255. return;
  54256. }
  54257. rc = freeSpace(pPage, pc, sz);
  54258. if( rc ){
  54259. *pRC = rc;
  54260. return;
  54261. }
  54262. pPage->nCell--;
  54263. memmove(ptr, ptr+2, 2*(pPage->nCell - idx));
  54264. put2byte(&data[hdr+3], pPage->nCell);
  54265. pPage->nFree += 2;
  54266. }
  54267. /*
  54268. ** Insert a new cell on pPage at cell index "i". pCell points to the
  54269. ** content of the cell.
  54270. **
  54271. ** If the cell content will fit on the page, then put it there. If it
  54272. ** will not fit, then make a copy of the cell content into pTemp if
  54273. ** pTemp is not null. Regardless of pTemp, allocate a new entry
  54274. ** in pPage->apOvfl[] and make it point to the cell content (either
  54275. ** in pTemp or the original pCell) and also record its index.
  54276. ** Allocating a new entry in pPage->aCell[] implies that
  54277. ** pPage->nOverflow is incremented.
  54278. */
  54279. static void insertCell(
  54280. MemPage *pPage, /* Page into which we are copying */
  54281. int i, /* New cell becomes the i-th cell of the page */
  54282. u8 *pCell, /* Content of the new cell */
  54283. int sz, /* Bytes of content in pCell */
  54284. u8 *pTemp, /* Temp storage space for pCell, if needed */
  54285. Pgno iChild, /* If non-zero, replace first 4 bytes with this value */
  54286. int *pRC /* Read and write return code from here */
  54287. ){
  54288. int idx = 0; /* Where to write new cell content in data[] */
  54289. int j; /* Loop counter */
  54290. int end; /* First byte past the last cell pointer in data[] */
  54291. int ins; /* Index in data[] where new cell pointer is inserted */
  54292. int cellOffset; /* Address of first cell pointer in data[] */
  54293. u8 *data; /* The content of the whole page */
  54294. if( *pRC ) return;
  54295. assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
  54296. assert( MX_CELL(pPage->pBt)<=10921 );
  54297. assert( pPage->nCell<=MX_CELL(pPage->pBt) || CORRUPT_DB );
  54298. assert( pPage->nOverflow<=ArraySize(pPage->apOvfl) );
  54299. assert( ArraySize(pPage->apOvfl)==ArraySize(pPage->aiOvfl) );
  54300. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  54301. /* The cell should normally be sized correctly. However, when moving a
  54302. ** malformed cell from a leaf page to an interior page, if the cell size
  54303. ** wanted to be less than 4 but got rounded up to 4 on the leaf, then size
  54304. ** might be less than 8 (leaf-size + pointer) on the interior node. Hence
  54305. ** the term after the || in the following assert(). */
  54306. assert( sz==cellSizePtr(pPage, pCell) || (sz==8 && iChild>0) );
  54307. if( pPage->nOverflow || sz+2>pPage->nFree ){
  54308. if( pTemp ){
  54309. memcpy(pTemp, pCell, sz);
  54310. pCell = pTemp;
  54311. }
  54312. if( iChild ){
  54313. put4byte(pCell, iChild);
  54314. }
  54315. j = pPage->nOverflow++;
  54316. assert( j<(int)(sizeof(pPage->apOvfl)/sizeof(pPage->apOvfl[0])) );
  54317. pPage->apOvfl[j] = pCell;
  54318. pPage->aiOvfl[j] = (u16)i;
  54319. }else{
  54320. int rc = sqlite3PagerWrite(pPage->pDbPage);
  54321. if( rc!=SQLITE_OK ){
  54322. *pRC = rc;
  54323. return;
  54324. }
  54325. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  54326. data = pPage->aData;
  54327. cellOffset = pPage->cellOffset;
  54328. end = cellOffset + 2*pPage->nCell;
  54329. ins = cellOffset + 2*i;
  54330. rc = allocateSpace(pPage, sz, &idx);
  54331. if( rc ){ *pRC = rc; return; }
  54332. /* The allocateSpace() routine guarantees the following two properties
  54333. ** if it returns success */
  54334. assert( idx >= end+2 );
  54335. assert( idx+sz <= (int)pPage->pBt->usableSize );
  54336. pPage->nCell++;
  54337. pPage->nFree -= (u16)(2 + sz);
  54338. memcpy(&data[idx], pCell, sz);
  54339. if( iChild ){
  54340. put4byte(&data[idx], iChild);
  54341. }
  54342. memmove(&data[ins+2], &data[ins], end-ins);
  54343. put2byte(&data[ins], idx);
  54344. put2byte(&data[pPage->hdrOffset+3], pPage->nCell);
  54345. #ifndef SQLITE_OMIT_AUTOVACUUM
  54346. if( pPage->pBt->autoVacuum ){
  54347. /* The cell may contain a pointer to an overflow page. If so, write
  54348. ** the entry for the overflow page into the pointer map.
  54349. */
  54350. ptrmapPutOvflPtr(pPage, pCell, pRC);
  54351. }
  54352. #endif
  54353. }
  54354. }
  54355. /*
  54356. ** Array apCell[] contains pointers to nCell b-tree page cells. The
  54357. ** szCell[] array contains the size in bytes of each cell. This function
  54358. ** replaces the current contents of page pPg with the contents of the cell
  54359. ** array.
  54360. **
  54361. ** Some of the cells in apCell[] may currently be stored in pPg. This
  54362. ** function works around problems caused by this by making a copy of any
  54363. ** such cells before overwriting the page data.
  54364. **
  54365. ** The MemPage.nFree field is invalidated by this function. It is the
  54366. ** responsibility of the caller to set it correctly.
  54367. */
  54368. static void rebuildPage(
  54369. MemPage *pPg, /* Edit this page */
  54370. int nCell, /* Final number of cells on page */
  54371. u8 **apCell, /* Array of cells */
  54372. u16 *szCell /* Array of cell sizes */
  54373. ){
  54374. const int hdr = pPg->hdrOffset; /* Offset of header on pPg */
  54375. u8 * const aData = pPg->aData; /* Pointer to data for pPg */
  54376. const int usableSize = pPg->pBt->usableSize;
  54377. u8 * const pEnd = &aData[usableSize];
  54378. int i;
  54379. u8 *pCellptr = pPg->aCellIdx;
  54380. u8 *pTmp = sqlite3PagerTempSpace(pPg->pBt->pPager);
  54381. u8 *pData;
  54382. i = get2byte(&aData[hdr+5]);
  54383. memcpy(&pTmp[i], &aData[i], usableSize - i);
  54384. pData = pEnd;
  54385. for(i=0; i<nCell; i++){
  54386. u8 *pCell = apCell[i];
  54387. if( pCell>aData && pCell<pEnd ){
  54388. pCell = &pTmp[pCell - aData];
  54389. }
  54390. pData -= szCell[i];
  54391. memcpy(pData, pCell, szCell[i]);
  54392. put2byte(pCellptr, (pData - aData));
  54393. pCellptr += 2;
  54394. assert( szCell[i]==cellSizePtr(pPg, pCell) );
  54395. }
  54396. /* The pPg->nFree field is now set incorrectly. The caller will fix it. */
  54397. pPg->nCell = nCell;
  54398. pPg->nOverflow = 0;
  54399. put2byte(&aData[hdr+1], 0);
  54400. put2byte(&aData[hdr+3], pPg->nCell);
  54401. put2byte(&aData[hdr+5], pData - aData);
  54402. aData[hdr+7] = 0x00;
  54403. }
  54404. /*
  54405. ** Array apCell[] contains nCell pointers to b-tree cells. Array szCell
  54406. ** contains the size in bytes of each such cell. This function attempts to
  54407. ** add the cells stored in the array to page pPg. If it cannot (because
  54408. ** the page needs to be defragmented before the cells will fit), non-zero
  54409. ** is returned. Otherwise, if the cells are added successfully, zero is
  54410. ** returned.
  54411. **
  54412. ** Argument pCellptr points to the first entry in the cell-pointer array
  54413. ** (part of page pPg) to populate. After cell apCell[0] is written to the
  54414. ** page body, a 16-bit offset is written to pCellptr. And so on, for each
  54415. ** cell in the array. It is the responsibility of the caller to ensure
  54416. ** that it is safe to overwrite this part of the cell-pointer array.
  54417. **
  54418. ** When this function is called, *ppData points to the start of the
  54419. ** content area on page pPg. If the size of the content area is extended,
  54420. ** *ppData is updated to point to the new start of the content area
  54421. ** before returning.
  54422. **
  54423. ** Finally, argument pBegin points to the byte immediately following the
  54424. ** end of the space required by this page for the cell-pointer area (for
  54425. ** all cells - not just those inserted by the current call). If the content
  54426. ** area must be extended to before this point in order to accomodate all
  54427. ** cells in apCell[], then the cells do not fit and non-zero is returned.
  54428. */
  54429. static int pageInsertArray(
  54430. MemPage *pPg, /* Page to add cells to */
  54431. u8 *pBegin, /* End of cell-pointer array */
  54432. u8 **ppData, /* IN/OUT: Page content -area pointer */
  54433. u8 *pCellptr, /* Pointer to cell-pointer area */
  54434. int nCell, /* Number of cells to add to pPg */
  54435. u8 **apCell, /* Array of cells */
  54436. u16 *szCell /* Array of cell sizes */
  54437. ){
  54438. int i;
  54439. u8 *aData = pPg->aData;
  54440. u8 *pData = *ppData;
  54441. const int bFreelist = aData[1] || aData[2];
  54442. assert( CORRUPT_DB || pPg->hdrOffset==0 ); /* Never called on page 1 */
  54443. for(i=0; i<nCell; i++){
  54444. int sz = szCell[i];
  54445. u8 *pSlot;
  54446. if( bFreelist==0 || (pSlot = pageFindSlot(pPg, sz, 0, 0))==0 ){
  54447. pData -= sz;
  54448. if( pData<pBegin ) return 1;
  54449. pSlot = pData;
  54450. }
  54451. memcpy(pSlot, apCell[i], sz);
  54452. put2byte(pCellptr, (pSlot - aData));
  54453. pCellptr += 2;
  54454. }
  54455. *ppData = pData;
  54456. return 0;
  54457. }
  54458. /*
  54459. ** Array apCell[] contains nCell pointers to b-tree cells. Array szCell
  54460. ** contains the size in bytes of each such cell. This function adds the
  54461. ** space associated with each cell in the array that is currently stored
  54462. ** within the body of pPg to the pPg free-list. The cell-pointers and other
  54463. ** fields of the page are not updated.
  54464. **
  54465. ** This function returns the total number of cells added to the free-list.
  54466. */
  54467. static int pageFreeArray(
  54468. MemPage *pPg, /* Page to edit */
  54469. int nCell, /* Cells to delete */
  54470. u8 **apCell, /* Array of cells */
  54471. u16 *szCell /* Array of cell sizes */
  54472. ){
  54473. u8 * const aData = pPg->aData;
  54474. u8 * const pEnd = &aData[pPg->pBt->usableSize];
  54475. u8 * const pStart = &aData[pPg->hdrOffset + 8 + pPg->childPtrSize];
  54476. int nRet = 0;
  54477. int i;
  54478. u8 *pFree = 0;
  54479. int szFree = 0;
  54480. for(i=0; i<nCell; i++){
  54481. u8 *pCell = apCell[i];
  54482. if( pCell>=pStart && pCell<pEnd ){
  54483. int sz = szCell[i];
  54484. if( pFree!=(pCell + sz) ){
  54485. if( pFree ) freeSpace(pPg, pFree - aData, szFree);
  54486. pFree = pCell;
  54487. szFree = sz;
  54488. if( pFree+sz>pEnd ) return 0;
  54489. }else{
  54490. pFree = pCell;
  54491. szFree += sz;
  54492. }
  54493. nRet++;
  54494. }
  54495. }
  54496. if( pFree ) freeSpace(pPg, pFree - aData, szFree);
  54497. return nRet;
  54498. }
  54499. /*
  54500. ** The pPg->nFree field is invalid when this function returns. It is the
  54501. ** responsibility of the caller to set it correctly.
  54502. */
  54503. static void editPage(
  54504. MemPage *pPg, /* Edit this page */
  54505. int iOld, /* Index of first cell currently on page */
  54506. int iNew, /* Index of new first cell on page */
  54507. int nNew, /* Final number of cells on page */
  54508. u8 **apCell, /* Array of cells */
  54509. u16 *szCell /* Array of cell sizes */
  54510. ){
  54511. u8 * const aData = pPg->aData;
  54512. const int hdr = pPg->hdrOffset;
  54513. u8 *pBegin = &pPg->aCellIdx[nNew * 2];
  54514. int nCell = pPg->nCell; /* Cells stored on pPg */
  54515. u8 *pData;
  54516. u8 *pCellptr;
  54517. int i;
  54518. int iOldEnd = iOld + pPg->nCell + pPg->nOverflow;
  54519. int iNewEnd = iNew + nNew;
  54520. #ifdef SQLITE_DEBUG
  54521. u8 *pTmp = sqlite3PagerTempSpace(pPg->pBt->pPager);
  54522. memcpy(pTmp, aData, pPg->pBt->usableSize);
  54523. #endif
  54524. /* Remove cells from the start and end of the page */
  54525. if( iOld<iNew ){
  54526. int nShift = pageFreeArray(
  54527. pPg, iNew-iOld, &apCell[iOld], &szCell[iOld]
  54528. );
  54529. memmove(pPg->aCellIdx, &pPg->aCellIdx[nShift*2], nCell*2);
  54530. nCell -= nShift;
  54531. }
  54532. if( iNewEnd < iOldEnd ){
  54533. nCell -= pageFreeArray(
  54534. pPg, iOldEnd-iNewEnd, &apCell[iNewEnd], &szCell[iNewEnd]
  54535. );
  54536. }
  54537. pData = &aData[get2byte(&aData[hdr+5])];
  54538. if( pData<pBegin ) goto editpage_fail;
  54539. /* Add cells to the start of the page */
  54540. if( iNew<iOld ){
  54541. int nAdd = iOld-iNew;
  54542. pCellptr = pPg->aCellIdx;
  54543. memmove(&pCellptr[nAdd*2], pCellptr, nCell*2);
  54544. if( pageInsertArray(
  54545. pPg, pBegin, &pData, pCellptr,
  54546. nAdd, &apCell[iNew], &szCell[iNew]
  54547. ) ) goto editpage_fail;
  54548. nCell += nAdd;
  54549. }
  54550. /* Add any overflow cells */
  54551. for(i=0; i<pPg->nOverflow; i++){
  54552. int iCell = (iOld + pPg->aiOvfl[i]) - iNew;
  54553. if( iCell>=0 && iCell<nNew ){
  54554. u8 *pCellptr = &pPg->aCellIdx[iCell * 2];
  54555. memmove(&pCellptr[2], pCellptr, (nCell - iCell) * 2);
  54556. nCell++;
  54557. if( pageInsertArray(
  54558. pPg, pBegin, &pData, pCellptr,
  54559. 1, &apCell[iCell + iNew], &szCell[iCell + iNew]
  54560. ) ) goto editpage_fail;
  54561. }
  54562. }
  54563. /* Append cells to the end of the page */
  54564. pCellptr = &pPg->aCellIdx[nCell*2];
  54565. if( pageInsertArray(
  54566. pPg, pBegin, &pData, pCellptr,
  54567. nNew-nCell, &apCell[iNew+nCell], &szCell[iNew+nCell]
  54568. ) ) goto editpage_fail;
  54569. pPg->nCell = nNew;
  54570. pPg->nOverflow = 0;
  54571. put2byte(&aData[hdr+3], pPg->nCell);
  54572. put2byte(&aData[hdr+5], pData - aData);
  54573. #ifdef SQLITE_DEBUG
  54574. for(i=0; i<nNew && !CORRUPT_DB; i++){
  54575. u8 *pCell = apCell[i+iNew];
  54576. int iOff = get2byte(&pPg->aCellIdx[i*2]);
  54577. if( pCell>=aData && pCell<&aData[pPg->pBt->usableSize] ){
  54578. pCell = &pTmp[pCell - aData];
  54579. }
  54580. assert( 0==memcmp(pCell, &aData[iOff], szCell[i+iNew]) );
  54581. }
  54582. #endif
  54583. return;
  54584. editpage_fail:
  54585. /* Unable to edit this page. Rebuild it from scratch instead. */
  54586. rebuildPage(pPg, nNew, &apCell[iNew], &szCell[iNew]);
  54587. }
  54588. /*
  54589. ** The following parameters determine how many adjacent pages get involved
  54590. ** in a balancing operation. NN is the number of neighbors on either side
  54591. ** of the page that participate in the balancing operation. NB is the
  54592. ** total number of pages that participate, including the target page and
  54593. ** NN neighbors on either side.
  54594. **
  54595. ** The minimum value of NN is 1 (of course). Increasing NN above 1
  54596. ** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
  54597. ** in exchange for a larger degradation in INSERT and UPDATE performance.
  54598. ** The value of NN appears to give the best results overall.
  54599. */
  54600. #define NN 1 /* Number of neighbors on either side of pPage */
  54601. #define NB (NN*2+1) /* Total pages involved in the balance */
  54602. #ifndef SQLITE_OMIT_QUICKBALANCE
  54603. /*
  54604. ** This version of balance() handles the common special case where
  54605. ** a new entry is being inserted on the extreme right-end of the
  54606. ** tree, in other words, when the new entry will become the largest
  54607. ** entry in the tree.
  54608. **
  54609. ** Instead of trying to balance the 3 right-most leaf pages, just add
  54610. ** a new page to the right-hand side and put the one new entry in
  54611. ** that page. This leaves the right side of the tree somewhat
  54612. ** unbalanced. But odds are that we will be inserting new entries
  54613. ** at the end soon afterwards so the nearly empty page will quickly
  54614. ** fill up. On average.
  54615. **
  54616. ** pPage is the leaf page which is the right-most page in the tree.
  54617. ** pParent is its parent. pPage must have a single overflow entry
  54618. ** which is also the right-most entry on the page.
  54619. **
  54620. ** The pSpace buffer is used to store a temporary copy of the divider
  54621. ** cell that will be inserted into pParent. Such a cell consists of a 4
  54622. ** byte page number followed by a variable length integer. In other
  54623. ** words, at most 13 bytes. Hence the pSpace buffer must be at
  54624. ** least 13 bytes in size.
  54625. */
  54626. static int balance_quick(MemPage *pParent, MemPage *pPage, u8 *pSpace){
  54627. BtShared *const pBt = pPage->pBt; /* B-Tree Database */
  54628. MemPage *pNew; /* Newly allocated page */
  54629. int rc; /* Return Code */
  54630. Pgno pgnoNew; /* Page number of pNew */
  54631. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  54632. assert( sqlite3PagerIswriteable(pParent->pDbPage) );
  54633. assert( pPage->nOverflow==1 );
  54634. /* This error condition is now caught prior to reaching this function */
  54635. if( pPage->nCell==0 ) return SQLITE_CORRUPT_BKPT;
  54636. /* Allocate a new page. This page will become the right-sibling of
  54637. ** pPage. Make the parent page writable, so that the new divider cell
  54638. ** may be inserted. If both these operations are successful, proceed.
  54639. */
  54640. rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);
  54641. if( rc==SQLITE_OK ){
  54642. u8 *pOut = &pSpace[4];
  54643. u8 *pCell = pPage->apOvfl[0];
  54644. u16 szCell = cellSizePtr(pPage, pCell);
  54645. u8 *pStop;
  54646. assert( sqlite3PagerIswriteable(pNew->pDbPage) );
  54647. assert( pPage->aData[0]==(PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF) );
  54648. zeroPage(pNew, PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF);
  54649. rebuildPage(pNew, 1, &pCell, &szCell);
  54650. pNew->nFree = pBt->usableSize - pNew->cellOffset - 2 - szCell;
  54651. /* If this is an auto-vacuum database, update the pointer map
  54652. ** with entries for the new page, and any pointer from the
  54653. ** cell on the page to an overflow page. If either of these
  54654. ** operations fails, the return code is set, but the contents
  54655. ** of the parent page are still manipulated by thh code below.
  54656. ** That is Ok, at this point the parent page is guaranteed to
  54657. ** be marked as dirty. Returning an error code will cause a
  54658. ** rollback, undoing any changes made to the parent page.
  54659. */
  54660. if( ISAUTOVACUUM ){
  54661. ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno, &rc);
  54662. if( szCell>pNew->minLocal ){
  54663. ptrmapPutOvflPtr(pNew, pCell, &rc);
  54664. }
  54665. }
  54666. /* Create a divider cell to insert into pParent. The divider cell
  54667. ** consists of a 4-byte page number (the page number of pPage) and
  54668. ** a variable length key value (which must be the same value as the
  54669. ** largest key on pPage).
  54670. **
  54671. ** To find the largest key value on pPage, first find the right-most
  54672. ** cell on pPage. The first two fields of this cell are the
  54673. ** record-length (a variable length integer at most 32-bits in size)
  54674. ** and the key value (a variable length integer, may have any value).
  54675. ** The first of the while(...) loops below skips over the record-length
  54676. ** field. The second while(...) loop copies the key value from the
  54677. ** cell on pPage into the pSpace buffer.
  54678. */
  54679. pCell = findCell(pPage, pPage->nCell-1);
  54680. pStop = &pCell[9];
  54681. while( (*(pCell++)&0x80) && pCell<pStop );
  54682. pStop = &pCell[9];
  54683. while( ((*(pOut++) = *(pCell++))&0x80) && pCell<pStop );
  54684. /* Insert the new divider cell into pParent. */
  54685. insertCell(pParent, pParent->nCell, pSpace, (int)(pOut-pSpace),
  54686. 0, pPage->pgno, &rc);
  54687. /* Set the right-child pointer of pParent to point to the new page. */
  54688. put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew);
  54689. /* Release the reference to the new page. */
  54690. releasePage(pNew);
  54691. }
  54692. return rc;
  54693. }
  54694. #endif /* SQLITE_OMIT_QUICKBALANCE */
  54695. #if 0
  54696. /*
  54697. ** This function does not contribute anything to the operation of SQLite.
  54698. ** it is sometimes activated temporarily while debugging code responsible
  54699. ** for setting pointer-map entries.
  54700. */
  54701. static int ptrmapCheckPages(MemPage **apPage, int nPage){
  54702. int i, j;
  54703. for(i=0; i<nPage; i++){
  54704. Pgno n;
  54705. u8 e;
  54706. MemPage *pPage = apPage[i];
  54707. BtShared *pBt = pPage->pBt;
  54708. assert( pPage->isInit );
  54709. for(j=0; j<pPage->nCell; j++){
  54710. CellInfo info;
  54711. u8 *z;
  54712. z = findCell(pPage, j);
  54713. btreeParseCellPtr(pPage, z, &info);
  54714. if( info.iOverflow ){
  54715. Pgno ovfl = get4byte(&z[info.iOverflow]);
  54716. ptrmapGet(pBt, ovfl, &e, &n);
  54717. assert( n==pPage->pgno && e==PTRMAP_OVERFLOW1 );
  54718. }
  54719. if( !pPage->leaf ){
  54720. Pgno child = get4byte(z);
  54721. ptrmapGet(pBt, child, &e, &n);
  54722. assert( n==pPage->pgno && e==PTRMAP_BTREE );
  54723. }
  54724. }
  54725. if( !pPage->leaf ){
  54726. Pgno child = get4byte(&pPage->aData[pPage->hdrOffset+8]);
  54727. ptrmapGet(pBt, child, &e, &n);
  54728. assert( n==pPage->pgno && e==PTRMAP_BTREE );
  54729. }
  54730. }
  54731. return 1;
  54732. }
  54733. #endif
  54734. /*
  54735. ** This function is used to copy the contents of the b-tree node stored
  54736. ** on page pFrom to page pTo. If page pFrom was not a leaf page, then
  54737. ** the pointer-map entries for each child page are updated so that the
  54738. ** parent page stored in the pointer map is page pTo. If pFrom contained
  54739. ** any cells with overflow page pointers, then the corresponding pointer
  54740. ** map entries are also updated so that the parent page is page pTo.
  54741. **
  54742. ** If pFrom is currently carrying any overflow cells (entries in the
  54743. ** MemPage.apOvfl[] array), they are not copied to pTo.
  54744. **
  54745. ** Before returning, page pTo is reinitialized using btreeInitPage().
  54746. **
  54747. ** The performance of this function is not critical. It is only used by
  54748. ** the balance_shallower() and balance_deeper() procedures, neither of
  54749. ** which are called often under normal circumstances.
  54750. */
  54751. static void copyNodeContent(MemPage *pFrom, MemPage *pTo, int *pRC){
  54752. if( (*pRC)==SQLITE_OK ){
  54753. BtShared * const pBt = pFrom->pBt;
  54754. u8 * const aFrom = pFrom->aData;
  54755. u8 * const aTo = pTo->aData;
  54756. int const iFromHdr = pFrom->hdrOffset;
  54757. int const iToHdr = ((pTo->pgno==1) ? 100 : 0);
  54758. int rc;
  54759. int iData;
  54760. assert( pFrom->isInit );
  54761. assert( pFrom->nFree>=iToHdr );
  54762. assert( get2byte(&aFrom[iFromHdr+5]) <= (int)pBt->usableSize );
  54763. /* Copy the b-tree node content from page pFrom to page pTo. */
  54764. iData = get2byte(&aFrom[iFromHdr+5]);
  54765. memcpy(&aTo[iData], &aFrom[iData], pBt->usableSize-iData);
  54766. memcpy(&aTo[iToHdr], &aFrom[iFromHdr], pFrom->cellOffset + 2*pFrom->nCell);
  54767. /* Reinitialize page pTo so that the contents of the MemPage structure
  54768. ** match the new data. The initialization of pTo can actually fail under
  54769. ** fairly obscure circumstances, even though it is a copy of initialized
  54770. ** page pFrom.
  54771. */
  54772. pTo->isInit = 0;
  54773. rc = btreeInitPage(pTo);
  54774. if( rc!=SQLITE_OK ){
  54775. *pRC = rc;
  54776. return;
  54777. }
  54778. /* If this is an auto-vacuum database, update the pointer-map entries
  54779. ** for any b-tree or overflow pages that pTo now contains the pointers to.
  54780. */
  54781. if( ISAUTOVACUUM ){
  54782. *pRC = setChildPtrmaps(pTo);
  54783. }
  54784. }
  54785. }
  54786. /*
  54787. ** This routine redistributes cells on the iParentIdx'th child of pParent
  54788. ** (hereafter "the page") and up to 2 siblings so that all pages have about the
  54789. ** same amount of free space. Usually a single sibling on either side of the
  54790. ** page are used in the balancing, though both siblings might come from one
  54791. ** side if the page is the first or last child of its parent. If the page
  54792. ** has fewer than 2 siblings (something which can only happen if the page
  54793. ** is a root page or a child of a root page) then all available siblings
  54794. ** participate in the balancing.
  54795. **
  54796. ** The number of siblings of the page might be increased or decreased by
  54797. ** one or two in an effort to keep pages nearly full but not over full.
  54798. **
  54799. ** Note that when this routine is called, some of the cells on the page
  54800. ** might not actually be stored in MemPage.aData[]. This can happen
  54801. ** if the page is overfull. This routine ensures that all cells allocated
  54802. ** to the page and its siblings fit into MemPage.aData[] before returning.
  54803. **
  54804. ** In the course of balancing the page and its siblings, cells may be
  54805. ** inserted into or removed from the parent page (pParent). Doing so
  54806. ** may cause the parent page to become overfull or underfull. If this
  54807. ** happens, it is the responsibility of the caller to invoke the correct
  54808. ** balancing routine to fix this problem (see the balance() routine).
  54809. **
  54810. ** If this routine fails for any reason, it might leave the database
  54811. ** in a corrupted state. So if this routine fails, the database should
  54812. ** be rolled back.
  54813. **
  54814. ** The third argument to this function, aOvflSpace, is a pointer to a
  54815. ** buffer big enough to hold one page. If while inserting cells into the parent
  54816. ** page (pParent) the parent page becomes overfull, this buffer is
  54817. ** used to store the parent's overflow cells. Because this function inserts
  54818. ** a maximum of four divider cells into the parent page, and the maximum
  54819. ** size of a cell stored within an internal node is always less than 1/4
  54820. ** of the page-size, the aOvflSpace[] buffer is guaranteed to be large
  54821. ** enough for all overflow cells.
  54822. **
  54823. ** If aOvflSpace is set to a null pointer, this function returns
  54824. ** SQLITE_NOMEM.
  54825. */
  54826. #if defined(_MSC_VER) && _MSC_VER >= 1700 && defined(_M_ARM)
  54827. #pragma optimize("", off)
  54828. #endif
  54829. static int balance_nonroot(
  54830. MemPage *pParent, /* Parent page of siblings being balanced */
  54831. int iParentIdx, /* Index of "the page" in pParent */
  54832. u8 *aOvflSpace, /* page-size bytes of space for parent ovfl */
  54833. int isRoot, /* True if pParent is a root-page */
  54834. int bBulk /* True if this call is part of a bulk load */
  54835. ){
  54836. BtShared *pBt; /* The whole database */
  54837. int nCell = 0; /* Number of cells in apCell[] */
  54838. int nMaxCells = 0; /* Allocated size of apCell, szCell, aFrom. */
  54839. int nNew = 0; /* Number of pages in apNew[] */
  54840. int nOld; /* Number of pages in apOld[] */
  54841. int i, j, k; /* Loop counters */
  54842. int nxDiv; /* Next divider slot in pParent->aCell[] */
  54843. int rc = SQLITE_OK; /* The return code */
  54844. u16 leafCorrection; /* 4 if pPage is a leaf. 0 if not */
  54845. int leafData; /* True if pPage is a leaf of a LEAFDATA tree */
  54846. int usableSpace; /* Bytes in pPage beyond the header */
  54847. int pageFlags; /* Value of pPage->aData[0] */
  54848. int subtotal; /* Subtotal of bytes in cells on one page */
  54849. int iSpace1 = 0; /* First unused byte of aSpace1[] */
  54850. int iOvflSpace = 0; /* First unused byte of aOvflSpace[] */
  54851. int szScratch; /* Size of scratch memory requested */
  54852. MemPage *apOld[NB]; /* pPage and up to two siblings */
  54853. MemPage *apNew[NB+2]; /* pPage and up to NB siblings after balancing */
  54854. u8 *pRight; /* Location in parent of right-sibling pointer */
  54855. u8 *apDiv[NB-1]; /* Divider cells in pParent */
  54856. int cntNew[NB+2]; /* Index in aCell[] of cell after i-th page */
  54857. int cntOld[NB+2]; /* Old index in aCell[] after i-th page */
  54858. int szNew[NB+2]; /* Combined size of cells place on i-th page */
  54859. u8 **apCell = 0; /* All cells begin balanced */
  54860. u16 *szCell; /* Local size of all cells in apCell[] */
  54861. u8 *aSpace1; /* Space for copies of dividers cells */
  54862. Pgno pgno; /* Temp var to store a page number in */
  54863. u8 abDone[NB+2]; /* True after i'th new page is populated */
  54864. Pgno aPgno[NB+2]; /* Page numbers of new pages before shuffling */
  54865. u16 aPgFlags[NB+2]; /* flags field of new pages before shuffling */
  54866. memset(abDone, 0, sizeof(abDone));
  54867. pBt = pParent->pBt;
  54868. assert( sqlite3_mutex_held(pBt->mutex) );
  54869. assert( sqlite3PagerIswriteable(pParent->pDbPage) );
  54870. #if 0
  54871. TRACE(("BALANCE: begin page %d child of %d\n", pPage->pgno, pParent->pgno));
  54872. #endif
  54873. /* At this point pParent may have at most one overflow cell. And if
  54874. ** this overflow cell is present, it must be the cell with
  54875. ** index iParentIdx. This scenario comes about when this function
  54876. ** is called (indirectly) from sqlite3BtreeDelete().
  54877. */
  54878. assert( pParent->nOverflow==0 || pParent->nOverflow==1 );
  54879. assert( pParent->nOverflow==0 || pParent->aiOvfl[0]==iParentIdx );
  54880. if( !aOvflSpace ){
  54881. return SQLITE_NOMEM;
  54882. }
  54883. /* Find the sibling pages to balance. Also locate the cells in pParent
  54884. ** that divide the siblings. An attempt is made to find NN siblings on
  54885. ** either side of pPage. More siblings are taken from one side, however,
  54886. ** if there are fewer than NN siblings on the other side. If pParent
  54887. ** has NB or fewer children then all children of pParent are taken.
  54888. **
  54889. ** This loop also drops the divider cells from the parent page. This
  54890. ** way, the remainder of the function does not have to deal with any
  54891. ** overflow cells in the parent page, since if any existed they will
  54892. ** have already been removed.
  54893. */
  54894. i = pParent->nOverflow + pParent->nCell;
  54895. if( i<2 ){
  54896. nxDiv = 0;
  54897. }else{
  54898. assert( bBulk==0 || bBulk==1 );
  54899. if( iParentIdx==0 ){
  54900. nxDiv = 0;
  54901. }else if( iParentIdx==i ){
  54902. nxDiv = i-2+bBulk;
  54903. }else{
  54904. assert( bBulk==0 );
  54905. nxDiv = iParentIdx-1;
  54906. }
  54907. i = 2-bBulk;
  54908. }
  54909. nOld = i+1;
  54910. if( (i+nxDiv-pParent->nOverflow)==pParent->nCell ){
  54911. pRight = &pParent->aData[pParent->hdrOffset+8];
  54912. }else{
  54913. pRight = findCell(pParent, i+nxDiv-pParent->nOverflow);
  54914. }
  54915. pgno = get4byte(pRight);
  54916. while( 1 ){
  54917. rc = getAndInitPage(pBt, pgno, &apOld[i], 0);
  54918. if( rc ){
  54919. memset(apOld, 0, (i+1)*sizeof(MemPage*));
  54920. goto balance_cleanup;
  54921. }
  54922. nMaxCells += 1+apOld[i]->nCell+apOld[i]->nOverflow;
  54923. if( (i--)==0 ) break;
  54924. if( i+nxDiv==pParent->aiOvfl[0] && pParent->nOverflow ){
  54925. apDiv[i] = pParent->apOvfl[0];
  54926. pgno = get4byte(apDiv[i]);
  54927. szNew[i] = cellSizePtr(pParent, apDiv[i]);
  54928. pParent->nOverflow = 0;
  54929. }else{
  54930. apDiv[i] = findCell(pParent, i+nxDiv-pParent->nOverflow);
  54931. pgno = get4byte(apDiv[i]);
  54932. szNew[i] = cellSizePtr(pParent, apDiv[i]);
  54933. /* Drop the cell from the parent page. apDiv[i] still points to
  54934. ** the cell within the parent, even though it has been dropped.
  54935. ** This is safe because dropping a cell only overwrites the first
  54936. ** four bytes of it, and this function does not need the first
  54937. ** four bytes of the divider cell. So the pointer is safe to use
  54938. ** later on.
  54939. **
  54940. ** But not if we are in secure-delete mode. In secure-delete mode,
  54941. ** the dropCell() routine will overwrite the entire cell with zeroes.
  54942. ** In this case, temporarily copy the cell into the aOvflSpace[]
  54943. ** buffer. It will be copied out again as soon as the aSpace[] buffer
  54944. ** is allocated. */
  54945. if( pBt->btsFlags & BTS_SECURE_DELETE ){
  54946. int iOff;
  54947. iOff = SQLITE_PTR_TO_INT(apDiv[i]) - SQLITE_PTR_TO_INT(pParent->aData);
  54948. if( (iOff+szNew[i])>(int)pBt->usableSize ){
  54949. rc = SQLITE_CORRUPT_BKPT;
  54950. memset(apOld, 0, (i+1)*sizeof(MemPage*));
  54951. goto balance_cleanup;
  54952. }else{
  54953. memcpy(&aOvflSpace[iOff], apDiv[i], szNew[i]);
  54954. apDiv[i] = &aOvflSpace[apDiv[i]-pParent->aData];
  54955. }
  54956. }
  54957. dropCell(pParent, i+nxDiv-pParent->nOverflow, szNew[i], &rc);
  54958. }
  54959. }
  54960. /* Make nMaxCells a multiple of 4 in order to preserve 8-byte
  54961. ** alignment */
  54962. nMaxCells = (nMaxCells + 3)&~3;
  54963. /*
  54964. ** Allocate space for memory structures
  54965. */
  54966. szScratch =
  54967. nMaxCells*sizeof(u8*) /* apCell */
  54968. + nMaxCells*sizeof(u16) /* szCell */
  54969. + pBt->pageSize; /* aSpace1 */
  54970. assert( szScratch<=16896 || szScratch<=6*pBt->pageSize );
  54971. apCell = sqlite3ScratchMalloc( szScratch );
  54972. if( apCell==0 ){
  54973. rc = SQLITE_NOMEM;
  54974. goto balance_cleanup;
  54975. }
  54976. szCell = (u16*)&apCell[nMaxCells];
  54977. aSpace1 = (u8*)&szCell[nMaxCells];
  54978. assert( EIGHT_BYTE_ALIGNMENT(aSpace1) );
  54979. /*
  54980. ** Load pointers to all cells on sibling pages and the divider cells
  54981. ** into the local apCell[] array. Make copies of the divider cells
  54982. ** into space obtained from aSpace1[]. The divider cells have already
  54983. ** been removed from pParent.
  54984. **
  54985. ** If the siblings are on leaf pages, then the child pointers of the
  54986. ** divider cells are stripped from the cells before they are copied
  54987. ** into aSpace1[]. In this way, all cells in apCell[] are without
  54988. ** child pointers. If siblings are not leaves, then all cell in
  54989. ** apCell[] include child pointers. Either way, all cells in apCell[]
  54990. ** are alike.
  54991. **
  54992. ** leafCorrection: 4 if pPage is a leaf. 0 if pPage is not a leaf.
  54993. ** leafData: 1 if pPage holds key+data and pParent holds only keys.
  54994. */
  54995. leafCorrection = apOld[0]->leaf*4;
  54996. leafData = apOld[0]->intKeyLeaf;
  54997. for(i=0; i<nOld; i++){
  54998. int limit;
  54999. MemPage *pOld = apOld[i];
  55000. limit = pOld->nCell+pOld->nOverflow;
  55001. if( pOld->nOverflow>0 ){
  55002. for(j=0; j<limit; j++){
  55003. assert( nCell<nMaxCells );
  55004. apCell[nCell] = findOverflowCell(pOld, j);
  55005. szCell[nCell] = cellSizePtr(pOld, apCell[nCell]);
  55006. nCell++;
  55007. }
  55008. }else{
  55009. u8 *aData = pOld->aData;
  55010. u16 maskPage = pOld->maskPage;
  55011. u16 cellOffset = pOld->cellOffset;
  55012. for(j=0; j<limit; j++){
  55013. assert( nCell<nMaxCells );
  55014. apCell[nCell] = findCellv2(aData, maskPage, cellOffset, j);
  55015. szCell[nCell] = cellSizePtr(pOld, apCell[nCell]);
  55016. nCell++;
  55017. }
  55018. }
  55019. cntOld[i] = nCell;
  55020. if( i<nOld-1 && !leafData){
  55021. u16 sz = (u16)szNew[i];
  55022. u8 *pTemp;
  55023. assert( nCell<nMaxCells );
  55024. szCell[nCell] = sz;
  55025. pTemp = &aSpace1[iSpace1];
  55026. iSpace1 += sz;
  55027. assert( sz<=pBt->maxLocal+23 );
  55028. assert( iSpace1 <= (int)pBt->pageSize );
  55029. memcpy(pTemp, apDiv[i], sz);
  55030. apCell[nCell] = pTemp+leafCorrection;
  55031. assert( leafCorrection==0 || leafCorrection==4 );
  55032. szCell[nCell] = szCell[nCell] - leafCorrection;
  55033. if( !pOld->leaf ){
  55034. assert( leafCorrection==0 );
  55035. assert( pOld->hdrOffset==0 );
  55036. /* The right pointer of the child page pOld becomes the left
  55037. ** pointer of the divider cell */
  55038. memcpy(apCell[nCell], &pOld->aData[8], 4);
  55039. }else{
  55040. assert( leafCorrection==4 );
  55041. if( szCell[nCell]<4 ){
  55042. /* Do not allow any cells smaller than 4 bytes. */
  55043. szCell[nCell] = 4;
  55044. }
  55045. }
  55046. nCell++;
  55047. }
  55048. }
  55049. /*
  55050. ** Figure out the number of pages needed to hold all nCell cells.
  55051. ** Store this number in "k". Also compute szNew[] which is the total
  55052. ** size of all cells on the i-th page and cntNew[] which is the index
  55053. ** in apCell[] of the cell that divides page i from page i+1.
  55054. ** cntNew[k] should equal nCell.
  55055. **
  55056. ** Values computed by this block:
  55057. **
  55058. ** k: The total number of sibling pages
  55059. ** szNew[i]: Spaced used on the i-th sibling page.
  55060. ** cntNew[i]: Index in apCell[] and szCell[] for the first cell to
  55061. ** the right of the i-th sibling page.
  55062. ** usableSpace: Number of bytes of space available on each sibling.
  55063. **
  55064. */
  55065. usableSpace = pBt->usableSize - 12 + leafCorrection;
  55066. for(subtotal=k=i=0; i<nCell; i++){
  55067. assert( i<nMaxCells );
  55068. subtotal += szCell[i] + 2;
  55069. if( subtotal > usableSpace ){
  55070. szNew[k] = subtotal - szCell[i] - 2;
  55071. cntNew[k] = i;
  55072. if( leafData ){ i--; }
  55073. subtotal = 0;
  55074. k++;
  55075. if( k>NB+1 ){ rc = SQLITE_CORRUPT_BKPT; goto balance_cleanup; }
  55076. }
  55077. }
  55078. szNew[k] = subtotal;
  55079. cntNew[k] = nCell;
  55080. k++;
  55081. /*
  55082. ** The packing computed by the previous block is biased toward the siblings
  55083. ** on the left side. The left siblings are always nearly full, while the
  55084. ** right-most sibling might be nearly empty. This block of code attempts
  55085. ** to adjust the packing of siblings to get a better balance.
  55086. **
  55087. ** This adjustment is more than an optimization. The packing above might
  55088. ** be so out of balance as to be illegal. For example, the right-most
  55089. ** sibling might be completely empty. This adjustment is not optional.
  55090. */
  55091. for(i=k-1; i>0; i--){
  55092. int szRight = szNew[i]; /* Size of sibling on the right */
  55093. int szLeft = szNew[i-1]; /* Size of sibling on the left */
  55094. int r; /* Index of right-most cell in left sibling */
  55095. int d; /* Index of first cell to the left of right sibling */
  55096. r = cntNew[i-1] - 1;
  55097. d = r + 1 - leafData;
  55098. assert( d<nMaxCells );
  55099. assert( r<nMaxCells );
  55100. while( szRight==0
  55101. || (!bBulk && szRight+szCell[d]+2<=szLeft-(szCell[r]+2))
  55102. ){
  55103. szRight += szCell[d] + 2;
  55104. szLeft -= szCell[r] + 2;
  55105. cntNew[i-1]--;
  55106. r = cntNew[i-1] - 1;
  55107. d = r + 1 - leafData;
  55108. }
  55109. szNew[i] = szRight;
  55110. szNew[i-1] = szLeft;
  55111. }
  55112. /* Either we found one or more cells (cntnew[0])>0) or pPage is
  55113. ** a virtual root page. A virtual root page is when the real root
  55114. ** page is page 1 and we are the only child of that page.
  55115. **
  55116. ** UPDATE: The assert() below is not necessarily true if the database
  55117. ** file is corrupt. The corruption will be detected and reported later
  55118. ** in this procedure so there is no need to act upon it now.
  55119. */
  55120. #if 0
  55121. assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) );
  55122. #endif
  55123. TRACE(("BALANCE: old: %d(nc=%d) %d(nc=%d) %d(nc=%d)\n",
  55124. apOld[0]->pgno, apOld[0]->nCell,
  55125. nOld>=2 ? apOld[1]->pgno : 0, nOld>=2 ? apOld[1]->nCell : 0,
  55126. nOld>=3 ? apOld[2]->pgno : 0, nOld>=3 ? apOld[2]->nCell : 0
  55127. ));
  55128. /*
  55129. ** Allocate k new pages. Reuse old pages where possible.
  55130. */
  55131. if( apOld[0]->pgno<=1 ){
  55132. rc = SQLITE_CORRUPT_BKPT;
  55133. goto balance_cleanup;
  55134. }
  55135. pageFlags = apOld[0]->aData[0];
  55136. for(i=0; i<k; i++){
  55137. MemPage *pNew;
  55138. if( i<nOld ){
  55139. pNew = apNew[i] = apOld[i];
  55140. apOld[i] = 0;
  55141. rc = sqlite3PagerWrite(pNew->pDbPage);
  55142. nNew++;
  55143. if( rc ) goto balance_cleanup;
  55144. }else{
  55145. assert( i>0 );
  55146. rc = allocateBtreePage(pBt, &pNew, &pgno, (bBulk ? 1 : pgno), 0);
  55147. if( rc ) goto balance_cleanup;
  55148. zeroPage(pNew, pageFlags);
  55149. apNew[i] = pNew;
  55150. nNew++;
  55151. cntOld[i] = nCell;
  55152. /* Set the pointer-map entry for the new sibling page. */
  55153. if( ISAUTOVACUUM ){
  55154. ptrmapPut(pBt, pNew->pgno, PTRMAP_BTREE, pParent->pgno, &rc);
  55155. if( rc!=SQLITE_OK ){
  55156. goto balance_cleanup;
  55157. }
  55158. }
  55159. }
  55160. }
  55161. /*
  55162. ** Reassign page numbers so that the new pages are in ascending order.
  55163. ** This helps to keep entries in the disk file in order so that a scan
  55164. ** of the table is closer to a linear scan through the file. That in turn
  55165. ** helps the operating system to deliver pages from the disk more rapidly.
  55166. **
  55167. ** An O(n^2) insertion sort algorithm is used, but since n is never more
  55168. ** than (NB+2) (a small constant), that should not be a problem.
  55169. **
  55170. ** When NB==3, this one optimization makes the database about 25% faster
  55171. ** for large insertions and deletions.
  55172. */
  55173. for(i=0; i<nNew; i++){
  55174. aPgno[i] = apNew[i]->pgno;
  55175. aPgFlags[i] = apNew[i]->pDbPage->flags;
  55176. for(j=0; j<i; j++){
  55177. if( aPgno[j]==aPgno[i] ){
  55178. /* This branch is taken if the set of sibling pages somehow contains
  55179. ** duplicate entries. This can happen if the database is corrupt.
  55180. ** It would be simpler to detect this as part of the loop below, but
  55181. ** in order to avoid populating the pager cache with two separate
  55182. ** objects associated with the same page number. */
  55183. assert( CORRUPT_DB );
  55184. rc = SQLITE_CORRUPT_BKPT;
  55185. goto balance_cleanup;
  55186. }
  55187. }
  55188. }
  55189. for(i=0; i<nNew; i++){
  55190. int iBest = 0; /* aPgno[] index of page number to use */
  55191. Pgno pgno; /* Page number to use */
  55192. for(j=1; j<nNew; j++){
  55193. if( aPgno[j]<aPgno[iBest] ) iBest = j;
  55194. }
  55195. pgno = aPgno[iBest];
  55196. aPgno[iBest] = 0xffffffff;
  55197. if( iBest!=i ){
  55198. if( iBest>i ){
  55199. sqlite3PagerRekey(apNew[iBest]->pDbPage, pBt->nPage+iBest+1, 0);
  55200. }
  55201. sqlite3PagerRekey(apNew[i]->pDbPage, pgno, aPgFlags[iBest]);
  55202. apNew[i]->pgno = pgno;
  55203. }
  55204. }
  55205. TRACE(("BALANCE: new: %d(%d nc=%d) %d(%d nc=%d) %d(%d nc=%d) "
  55206. "%d(%d nc=%d) %d(%d nc=%d)\n",
  55207. apNew[0]->pgno, szNew[0], cntNew[0],
  55208. nNew>=2 ? apNew[1]->pgno : 0, nNew>=2 ? szNew[1] : 0,
  55209. nNew>=2 ? cntNew[1] - cntNew[0] - !leafData : 0,
  55210. nNew>=3 ? apNew[2]->pgno : 0, nNew>=3 ? szNew[2] : 0,
  55211. nNew>=3 ? cntNew[2] - cntNew[1] - !leafData : 0,
  55212. nNew>=4 ? apNew[3]->pgno : 0, nNew>=4 ? szNew[3] : 0,
  55213. nNew>=4 ? cntNew[3] - cntNew[2] - !leafData : 0,
  55214. nNew>=5 ? apNew[4]->pgno : 0, nNew>=5 ? szNew[4] : 0,
  55215. nNew>=5 ? cntNew[4] - cntNew[3] - !leafData : 0
  55216. ));
  55217. assert( sqlite3PagerIswriteable(pParent->pDbPage) );
  55218. put4byte(pRight, apNew[nNew-1]->pgno);
  55219. /* If the sibling pages are not leaves, ensure that the right-child pointer
  55220. ** of the right-most new sibling page is set to the value that was
  55221. ** originally in the same field of the right-most old sibling page. */
  55222. if( (pageFlags & PTF_LEAF)==0 && nOld!=nNew ){
  55223. MemPage *pOld = (nNew>nOld ? apNew : apOld)[nOld-1];
  55224. memcpy(&apNew[nNew-1]->aData[8], &pOld->aData[8], 4);
  55225. }
  55226. /* Make any required updates to pointer map entries associated with
  55227. ** cells stored on sibling pages following the balance operation. Pointer
  55228. ** map entries associated with divider cells are set by the insertCell()
  55229. ** routine. The associated pointer map entries are:
  55230. **
  55231. ** a) if the cell contains a reference to an overflow chain, the
  55232. ** entry associated with the first page in the overflow chain, and
  55233. **
  55234. ** b) if the sibling pages are not leaves, the child page associated
  55235. ** with the cell.
  55236. **
  55237. ** If the sibling pages are not leaves, then the pointer map entry
  55238. ** associated with the right-child of each sibling may also need to be
  55239. ** updated. This happens below, after the sibling pages have been
  55240. ** populated, not here.
  55241. */
  55242. if( ISAUTOVACUUM ){
  55243. MemPage *pNew = apNew[0];
  55244. u8 *aOld = pNew->aData;
  55245. int cntOldNext = pNew->nCell + pNew->nOverflow;
  55246. int usableSize = pBt->usableSize;
  55247. int iNew = 0;
  55248. int iOld = 0;
  55249. for(i=0; i<nCell; i++){
  55250. u8 *pCell = apCell[i];
  55251. if( i==cntOldNext ){
  55252. MemPage *pOld = (++iOld)<nNew ? apNew[iOld] : apOld[iOld];
  55253. cntOldNext += pOld->nCell + pOld->nOverflow + !leafData;
  55254. aOld = pOld->aData;
  55255. }
  55256. if( i==cntNew[iNew] ){
  55257. pNew = apNew[++iNew];
  55258. if( !leafData ) continue;
  55259. }
  55260. /* Cell pCell is destined for new sibling page pNew. Originally, it
  55261. ** was either part of sibling page iOld (possibly an overflow page),
  55262. ** or else the divider cell to the left of sibling page iOld. So,
  55263. ** if sibling page iOld had the same page number as pNew, and if
  55264. ** pCell really was a part of sibling page iOld (not a divider or
  55265. ** overflow cell), we can skip updating the pointer map entries. */
  55266. if( pNew->pgno!=aPgno[iOld] || pCell<aOld || pCell>=&aOld[usableSize] ){
  55267. if( !leafCorrection ){
  55268. ptrmapPut(pBt, get4byte(pCell), PTRMAP_BTREE, pNew->pgno, &rc);
  55269. }
  55270. if( szCell[i]>pNew->minLocal ){
  55271. ptrmapPutOvflPtr(pNew, pCell, &rc);
  55272. }
  55273. }
  55274. }
  55275. }
  55276. /* Insert new divider cells into pParent. */
  55277. for(i=0; i<nNew-1; i++){
  55278. u8 *pCell;
  55279. u8 *pTemp;
  55280. int sz;
  55281. MemPage *pNew = apNew[i];
  55282. j = cntNew[i];
  55283. assert( j<nMaxCells );
  55284. pCell = apCell[j];
  55285. sz = szCell[j] + leafCorrection;
  55286. pTemp = &aOvflSpace[iOvflSpace];
  55287. if( !pNew->leaf ){
  55288. memcpy(&pNew->aData[8], pCell, 4);
  55289. }else if( leafData ){
  55290. /* If the tree is a leaf-data tree, and the siblings are leaves,
  55291. ** then there is no divider cell in apCell[]. Instead, the divider
  55292. ** cell consists of the integer key for the right-most cell of
  55293. ** the sibling-page assembled above only.
  55294. */
  55295. CellInfo info;
  55296. j--;
  55297. btreeParseCellPtr(pNew, apCell[j], &info);
  55298. pCell = pTemp;
  55299. sz = 4 + putVarint(&pCell[4], info.nKey);
  55300. pTemp = 0;
  55301. }else{
  55302. pCell -= 4;
  55303. /* Obscure case for non-leaf-data trees: If the cell at pCell was
  55304. ** previously stored on a leaf node, and its reported size was 4
  55305. ** bytes, then it may actually be smaller than this
  55306. ** (see btreeParseCellPtr(), 4 bytes is the minimum size of
  55307. ** any cell). But it is important to pass the correct size to
  55308. ** insertCell(), so reparse the cell now.
  55309. **
  55310. ** Note that this can never happen in an SQLite data file, as all
  55311. ** cells are at least 4 bytes. It only happens in b-trees used
  55312. ** to evaluate "IN (SELECT ...)" and similar clauses.
  55313. */
  55314. if( szCell[j]==4 ){
  55315. assert(leafCorrection==4);
  55316. sz = cellSizePtr(pParent, pCell);
  55317. }
  55318. }
  55319. iOvflSpace += sz;
  55320. assert( sz<=pBt->maxLocal+23 );
  55321. assert( iOvflSpace <= (int)pBt->pageSize );
  55322. insertCell(pParent, nxDiv+i, pCell, sz, pTemp, pNew->pgno, &rc);
  55323. if( rc!=SQLITE_OK ) goto balance_cleanup;
  55324. assert( sqlite3PagerIswriteable(pParent->pDbPage) );
  55325. }
  55326. /* Now update the actual sibling pages. The order in which they are updated
  55327. ** is important, as this code needs to avoid disrupting any page from which
  55328. ** cells may still to be read. In practice, this means:
  55329. **
  55330. ** 1) If cells are to be removed from the start of the page and shifted
  55331. ** to the left-hand sibling, it is not safe to update the page until
  55332. ** the left-hand sibling (apNew[i-1]) has already been updated.
  55333. **
  55334. ** 2) If cells are to be removed from the end of the page and shifted
  55335. ** to the right-hand sibling, it is not safe to update the page until
  55336. ** the right-hand sibling (apNew[i+1]) has already been updated.
  55337. **
  55338. ** If neither of the above apply, the page is safe to update.
  55339. */
  55340. for(i=0; i<nNew*2; i++){
  55341. int iPg = (i>=nNew ? i-nNew : nNew-1-i);
  55342. if( abDone[iPg]==0
  55343. && (iPg==0 || cntOld[iPg-1]>=cntNew[iPg-1] || abDone[iPg-1])
  55344. && (cntNew[iPg]>=cntOld[iPg] || abDone[iPg+1])
  55345. ){
  55346. int iNew;
  55347. int iOld;
  55348. int nNewCell;
  55349. if( iPg==0 ){
  55350. iNew = iOld = 0;
  55351. nNewCell = cntNew[0];
  55352. }else{
  55353. iOld = iPg<nOld ? (cntOld[iPg-1] + !leafData) : nCell;
  55354. iNew = cntNew[iPg-1] + !leafData;
  55355. nNewCell = cntNew[iPg] - iNew;
  55356. }
  55357. editPage(apNew[iPg], iOld, iNew, nNewCell, apCell, szCell);
  55358. abDone[iPg] = 1;
  55359. apNew[iPg]->nFree = usableSpace-szNew[iPg];
  55360. assert( apNew[iPg]->nOverflow==0 );
  55361. assert( apNew[iPg]->nCell==nNewCell );
  55362. }
  55363. }
  55364. assert( memcmp(abDone, "\01\01\01\01\01", nNew)==0 );
  55365. assert( nOld>0 );
  55366. assert( nNew>0 );
  55367. if( isRoot && pParent->nCell==0 && pParent->hdrOffset<=apNew[0]->nFree ){
  55368. /* The root page of the b-tree now contains no cells. The only sibling
  55369. ** page is the right-child of the parent. Copy the contents of the
  55370. ** child page into the parent, decreasing the overall height of the
  55371. ** b-tree structure by one. This is described as the "balance-shallower"
  55372. ** sub-algorithm in some documentation.
  55373. **
  55374. ** If this is an auto-vacuum database, the call to copyNodeContent()
  55375. ** sets all pointer-map entries corresponding to database image pages
  55376. ** for which the pointer is stored within the content being copied.
  55377. **
  55378. ** The second assert below verifies that the child page is defragmented
  55379. ** (it must be, as it was just reconstructed using assemblePage()). This
  55380. ** is important if the parent page happens to be page 1 of the database
  55381. ** image. */
  55382. assert( nNew==1 );
  55383. rc = defragmentPage(apNew[0]);
  55384. if( rc==SQLITE_OK ){
  55385. assert( apNew[0]->nFree ==
  55386. (get2byte(&apNew[0]->aData[5])-apNew[0]->cellOffset-apNew[0]->nCell*2)
  55387. );
  55388. copyNodeContent(apNew[0], pParent, &rc);
  55389. freePage(apNew[0], &rc);
  55390. }
  55391. }else if( ISAUTOVACUUM && !leafCorrection ){
  55392. /* Fix the pointer map entries associated with the right-child of each
  55393. ** sibling page. All other pointer map entries have already been taken
  55394. ** care of. */
  55395. for(i=0; i<nNew; i++){
  55396. u32 key = get4byte(&apNew[i]->aData[8]);
  55397. ptrmapPut(pBt, key, PTRMAP_BTREE, apNew[i]->pgno, &rc);
  55398. }
  55399. }
  55400. assert( pParent->isInit );
  55401. TRACE(("BALANCE: finished: old=%d new=%d cells=%d\n",
  55402. nOld, nNew, nCell));
  55403. /* Free any old pages that were not reused as new pages.
  55404. */
  55405. for(i=nNew; i<nOld; i++){
  55406. freePage(apOld[i], &rc);
  55407. }
  55408. #if 0
  55409. if( ISAUTOVACUUM && rc==SQLITE_OK && apNew[0]->isInit ){
  55410. /* The ptrmapCheckPages() contains assert() statements that verify that
  55411. ** all pointer map pages are set correctly. This is helpful while
  55412. ** debugging. This is usually disabled because a corrupt database may
  55413. ** cause an assert() statement to fail. */
  55414. ptrmapCheckPages(apNew, nNew);
  55415. ptrmapCheckPages(&pParent, 1);
  55416. }
  55417. #endif
  55418. /*
  55419. ** Cleanup before returning.
  55420. */
  55421. balance_cleanup:
  55422. sqlite3ScratchFree(apCell);
  55423. for(i=0; i<nOld; i++){
  55424. releasePage(apOld[i]);
  55425. }
  55426. for(i=0; i<nNew; i++){
  55427. releasePage(apNew[i]);
  55428. }
  55429. return rc;
  55430. }
  55431. #if defined(_MSC_VER) && _MSC_VER >= 1700 && defined(_M_ARM)
  55432. #pragma optimize("", on)
  55433. #endif
  55434. /*
  55435. ** This function is called when the root page of a b-tree structure is
  55436. ** overfull (has one or more overflow pages).
  55437. **
  55438. ** A new child page is allocated and the contents of the current root
  55439. ** page, including overflow cells, are copied into the child. The root
  55440. ** page is then overwritten to make it an empty page with the right-child
  55441. ** pointer pointing to the new page.
  55442. **
  55443. ** Before returning, all pointer-map entries corresponding to pages
  55444. ** that the new child-page now contains pointers to are updated. The
  55445. ** entry corresponding to the new right-child pointer of the root
  55446. ** page is also updated.
  55447. **
  55448. ** If successful, *ppChild is set to contain a reference to the child
  55449. ** page and SQLITE_OK is returned. In this case the caller is required
  55450. ** to call releasePage() on *ppChild exactly once. If an error occurs,
  55451. ** an error code is returned and *ppChild is set to 0.
  55452. */
  55453. static int balance_deeper(MemPage *pRoot, MemPage **ppChild){
  55454. int rc; /* Return value from subprocedures */
  55455. MemPage *pChild = 0; /* Pointer to a new child page */
  55456. Pgno pgnoChild = 0; /* Page number of the new child page */
  55457. BtShared *pBt = pRoot->pBt; /* The BTree */
  55458. assert( pRoot->nOverflow>0 );
  55459. assert( sqlite3_mutex_held(pBt->mutex) );
  55460. /* Make pRoot, the root page of the b-tree, writable. Allocate a new
  55461. ** page that will become the new right-child of pPage. Copy the contents
  55462. ** of the node stored on pRoot into the new child page.
  55463. */
  55464. rc = sqlite3PagerWrite(pRoot->pDbPage);
  55465. if( rc==SQLITE_OK ){
  55466. rc = allocateBtreePage(pBt,&pChild,&pgnoChild,pRoot->pgno,0);
  55467. copyNodeContent(pRoot, pChild, &rc);
  55468. if( ISAUTOVACUUM ){
  55469. ptrmapPut(pBt, pgnoChild, PTRMAP_BTREE, pRoot->pgno, &rc);
  55470. }
  55471. }
  55472. if( rc ){
  55473. *ppChild = 0;
  55474. releasePage(pChild);
  55475. return rc;
  55476. }
  55477. assert( sqlite3PagerIswriteable(pChild->pDbPage) );
  55478. assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
  55479. assert( pChild->nCell==pRoot->nCell );
  55480. TRACE(("BALANCE: copy root %d into %d\n", pRoot->pgno, pChild->pgno));
  55481. /* Copy the overflow cells from pRoot to pChild */
  55482. memcpy(pChild->aiOvfl, pRoot->aiOvfl,
  55483. pRoot->nOverflow*sizeof(pRoot->aiOvfl[0]));
  55484. memcpy(pChild->apOvfl, pRoot->apOvfl,
  55485. pRoot->nOverflow*sizeof(pRoot->apOvfl[0]));
  55486. pChild->nOverflow = pRoot->nOverflow;
  55487. /* Zero the contents of pRoot. Then install pChild as the right-child. */
  55488. zeroPage(pRoot, pChild->aData[0] & ~PTF_LEAF);
  55489. put4byte(&pRoot->aData[pRoot->hdrOffset+8], pgnoChild);
  55490. *ppChild = pChild;
  55491. return SQLITE_OK;
  55492. }
  55493. /*
  55494. ** The page that pCur currently points to has just been modified in
  55495. ** some way. This function figures out if this modification means the
  55496. ** tree needs to be balanced, and if so calls the appropriate balancing
  55497. ** routine. Balancing routines are:
  55498. **
  55499. ** balance_quick()
  55500. ** balance_deeper()
  55501. ** balance_nonroot()
  55502. */
  55503. static int balance(BtCursor *pCur){
  55504. int rc = SQLITE_OK;
  55505. const int nMin = pCur->pBt->usableSize * 2 / 3;
  55506. u8 aBalanceQuickSpace[13];
  55507. u8 *pFree = 0;
  55508. TESTONLY( int balance_quick_called = 0 );
  55509. TESTONLY( int balance_deeper_called = 0 );
  55510. do {
  55511. int iPage = pCur->iPage;
  55512. MemPage *pPage = pCur->apPage[iPage];
  55513. if( iPage==0 ){
  55514. if( pPage->nOverflow ){
  55515. /* The root page of the b-tree is overfull. In this case call the
  55516. ** balance_deeper() function to create a new child for the root-page
  55517. ** and copy the current contents of the root-page to it. The
  55518. ** next iteration of the do-loop will balance the child page.
  55519. */
  55520. assert( (balance_deeper_called++)==0 );
  55521. rc = balance_deeper(pPage, &pCur->apPage[1]);
  55522. if( rc==SQLITE_OK ){
  55523. pCur->iPage = 1;
  55524. pCur->aiIdx[0] = 0;
  55525. pCur->aiIdx[1] = 0;
  55526. assert( pCur->apPage[1]->nOverflow );
  55527. }
  55528. }else{
  55529. break;
  55530. }
  55531. }else if( pPage->nOverflow==0 && pPage->nFree<=nMin ){
  55532. break;
  55533. }else{
  55534. MemPage * const pParent = pCur->apPage[iPage-1];
  55535. int const iIdx = pCur->aiIdx[iPage-1];
  55536. rc = sqlite3PagerWrite(pParent->pDbPage);
  55537. if( rc==SQLITE_OK ){
  55538. #ifndef SQLITE_OMIT_QUICKBALANCE
  55539. if( pPage->intKeyLeaf
  55540. && pPage->nOverflow==1
  55541. && pPage->aiOvfl[0]==pPage->nCell
  55542. && pParent->pgno!=1
  55543. && pParent->nCell==iIdx
  55544. ){
  55545. /* Call balance_quick() to create a new sibling of pPage on which
  55546. ** to store the overflow cell. balance_quick() inserts a new cell
  55547. ** into pParent, which may cause pParent overflow. If this
  55548. ** happens, the next iteration of the do-loop will balance pParent
  55549. ** use either balance_nonroot() or balance_deeper(). Until this
  55550. ** happens, the overflow cell is stored in the aBalanceQuickSpace[]
  55551. ** buffer.
  55552. **
  55553. ** The purpose of the following assert() is to check that only a
  55554. ** single call to balance_quick() is made for each call to this
  55555. ** function. If this were not verified, a subtle bug involving reuse
  55556. ** of the aBalanceQuickSpace[] might sneak in.
  55557. */
  55558. assert( (balance_quick_called++)==0 );
  55559. rc = balance_quick(pParent, pPage, aBalanceQuickSpace);
  55560. }else
  55561. #endif
  55562. {
  55563. /* In this case, call balance_nonroot() to redistribute cells
  55564. ** between pPage and up to 2 of its sibling pages. This involves
  55565. ** modifying the contents of pParent, which may cause pParent to
  55566. ** become overfull or underfull. The next iteration of the do-loop
  55567. ** will balance the parent page to correct this.
  55568. **
  55569. ** If the parent page becomes overfull, the overflow cell or cells
  55570. ** are stored in the pSpace buffer allocated immediately below.
  55571. ** A subsequent iteration of the do-loop will deal with this by
  55572. ** calling balance_nonroot() (balance_deeper() may be called first,
  55573. ** but it doesn't deal with overflow cells - just moves them to a
  55574. ** different page). Once this subsequent call to balance_nonroot()
  55575. ** has completed, it is safe to release the pSpace buffer used by
  55576. ** the previous call, as the overflow cell data will have been
  55577. ** copied either into the body of a database page or into the new
  55578. ** pSpace buffer passed to the latter call to balance_nonroot().
  55579. */
  55580. u8 *pSpace = sqlite3PageMalloc(pCur->pBt->pageSize);
  55581. rc = balance_nonroot(pParent, iIdx, pSpace, iPage==1, pCur->hints);
  55582. if( pFree ){
  55583. /* If pFree is not NULL, it points to the pSpace buffer used
  55584. ** by a previous call to balance_nonroot(). Its contents are
  55585. ** now stored either on real database pages or within the
  55586. ** new pSpace buffer, so it may be safely freed here. */
  55587. sqlite3PageFree(pFree);
  55588. }
  55589. /* The pSpace buffer will be freed after the next call to
  55590. ** balance_nonroot(), or just before this function returns, whichever
  55591. ** comes first. */
  55592. pFree = pSpace;
  55593. }
  55594. }
  55595. pPage->nOverflow = 0;
  55596. /* The next iteration of the do-loop balances the parent page. */
  55597. releasePage(pPage);
  55598. pCur->iPage--;
  55599. }
  55600. }while( rc==SQLITE_OK );
  55601. if( pFree ){
  55602. sqlite3PageFree(pFree);
  55603. }
  55604. return rc;
  55605. }
  55606. /*
  55607. ** Insert a new record into the BTree. The key is given by (pKey,nKey)
  55608. ** and the data is given by (pData,nData). The cursor is used only to
  55609. ** define what table the record should be inserted into. The cursor
  55610. ** is left pointing at a random location.
  55611. **
  55612. ** For an INTKEY table, only the nKey value of the key is used. pKey is
  55613. ** ignored. For a ZERODATA table, the pData and nData are both ignored.
  55614. **
  55615. ** If the seekResult parameter is non-zero, then a successful call to
  55616. ** MovetoUnpacked() to seek cursor pCur to (pKey, nKey) has already
  55617. ** been performed. seekResult is the search result returned (a negative
  55618. ** number if pCur points at an entry that is smaller than (pKey, nKey), or
  55619. ** a positive value if pCur points at an entry that is larger than
  55620. ** (pKey, nKey)).
  55621. **
  55622. ** If the seekResult parameter is non-zero, then the caller guarantees that
  55623. ** cursor pCur is pointing at the existing copy of a row that is to be
  55624. ** overwritten. If the seekResult parameter is 0, then cursor pCur may
  55625. ** point to any entry or to no entry at all and so this function has to seek
  55626. ** the cursor before the new key can be inserted.
  55627. */
  55628. SQLITE_PRIVATE int sqlite3BtreeInsert(
  55629. BtCursor *pCur, /* Insert data into the table of this cursor */
  55630. const void *pKey, i64 nKey, /* The key of the new record */
  55631. const void *pData, int nData, /* The data of the new record */
  55632. int nZero, /* Number of extra 0 bytes to append to data */
  55633. int appendBias, /* True if this is likely an append */
  55634. int seekResult /* Result of prior MovetoUnpacked() call */
  55635. ){
  55636. int rc;
  55637. int loc = seekResult; /* -1: before desired location +1: after */
  55638. int szNew = 0;
  55639. int idx;
  55640. MemPage *pPage;
  55641. Btree *p = pCur->pBtree;
  55642. BtShared *pBt = p->pBt;
  55643. unsigned char *oldCell;
  55644. unsigned char *newCell = 0;
  55645. if( pCur->eState==CURSOR_FAULT ){
  55646. assert( pCur->skipNext!=SQLITE_OK );
  55647. return pCur->skipNext;
  55648. }
  55649. assert( cursorHoldsMutex(pCur) );
  55650. assert( (pCur->curFlags & BTCF_WriteFlag)!=0
  55651. && pBt->inTransaction==TRANS_WRITE
  55652. && (pBt->btsFlags & BTS_READ_ONLY)==0 );
  55653. assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
  55654. /* Assert that the caller has been consistent. If this cursor was opened
  55655. ** expecting an index b-tree, then the caller should be inserting blob
  55656. ** keys with no associated data. If the cursor was opened expecting an
  55657. ** intkey table, the caller should be inserting integer keys with a
  55658. ** blob of associated data. */
  55659. assert( (pKey==0)==(pCur->pKeyInfo==0) );
  55660. /* Save the positions of any other cursors open on this table.
  55661. **
  55662. ** In some cases, the call to btreeMoveto() below is a no-op. For
  55663. ** example, when inserting data into a table with auto-generated integer
  55664. ** keys, the VDBE layer invokes sqlite3BtreeLast() to figure out the
  55665. ** integer key to use. It then calls this function to actually insert the
  55666. ** data into the intkey B-Tree. In this case btreeMoveto() recognizes
  55667. ** that the cursor is already where it needs to be and returns without
  55668. ** doing any work. To avoid thwarting these optimizations, it is important
  55669. ** not to clear the cursor here.
  55670. */
  55671. rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
  55672. if( rc ) return rc;
  55673. if( pCur->pKeyInfo==0 ){
  55674. /* If this is an insert into a table b-tree, invalidate any incrblob
  55675. ** cursors open on the row being replaced */
  55676. invalidateIncrblobCursors(p, nKey, 0);
  55677. /* If the cursor is currently on the last row and we are appending a
  55678. ** new row onto the end, set the "loc" to avoid an unnecessary btreeMoveto()
  55679. ** call */
  55680. if( (pCur->curFlags&BTCF_ValidNKey)!=0 && nKey>0
  55681. && pCur->info.nKey==nKey-1 ){
  55682. loc = -1;
  55683. }
  55684. }
  55685. if( !loc ){
  55686. rc = btreeMoveto(pCur, pKey, nKey, appendBias, &loc);
  55687. if( rc ) return rc;
  55688. }
  55689. assert( pCur->eState==CURSOR_VALID || (pCur->eState==CURSOR_INVALID && loc) );
  55690. pPage = pCur->apPage[pCur->iPage];
  55691. assert( pPage->intKey || nKey>=0 );
  55692. assert( pPage->leaf || !pPage->intKey );
  55693. TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n",
  55694. pCur->pgnoRoot, nKey, nData, pPage->pgno,
  55695. loc==0 ? "overwrite" : "new entry"));
  55696. assert( pPage->isInit );
  55697. newCell = pBt->pTmpSpace;
  55698. assert( newCell!=0 );
  55699. rc = fillInCell(pPage, newCell, pKey, nKey, pData, nData, nZero, &szNew);
  55700. if( rc ) goto end_insert;
  55701. assert( szNew==cellSizePtr(pPage, newCell) );
  55702. assert( szNew <= MX_CELL_SIZE(pBt) );
  55703. idx = pCur->aiIdx[pCur->iPage];
  55704. if( loc==0 ){
  55705. u16 szOld;
  55706. assert( idx<pPage->nCell );
  55707. rc = sqlite3PagerWrite(pPage->pDbPage);
  55708. if( rc ){
  55709. goto end_insert;
  55710. }
  55711. oldCell = findCell(pPage, idx);
  55712. if( !pPage->leaf ){
  55713. memcpy(newCell, oldCell, 4);
  55714. }
  55715. rc = clearCell(pPage, oldCell, &szOld);
  55716. dropCell(pPage, idx, szOld, &rc);
  55717. if( rc ) goto end_insert;
  55718. }else if( loc<0 && pPage->nCell>0 ){
  55719. assert( pPage->leaf );
  55720. idx = ++pCur->aiIdx[pCur->iPage];
  55721. }else{
  55722. assert( pPage->leaf );
  55723. }
  55724. insertCell(pPage, idx, newCell, szNew, 0, 0, &rc);
  55725. assert( rc!=SQLITE_OK || pPage->nCell>0 || pPage->nOverflow>0 );
  55726. /* If no error has occurred and pPage has an overflow cell, call balance()
  55727. ** to redistribute the cells within the tree. Since balance() may move
  55728. ** the cursor, zero the BtCursor.info.nSize and BTCF_ValidNKey
  55729. ** variables.
  55730. **
  55731. ** Previous versions of SQLite called moveToRoot() to move the cursor
  55732. ** back to the root page as balance() used to invalidate the contents
  55733. ** of BtCursor.apPage[] and BtCursor.aiIdx[]. Instead of doing that,
  55734. ** set the cursor state to "invalid". This makes common insert operations
  55735. ** slightly faster.
  55736. **
  55737. ** There is a subtle but important optimization here too. When inserting
  55738. ** multiple records into an intkey b-tree using a single cursor (as can
  55739. ** happen while processing an "INSERT INTO ... SELECT" statement), it
  55740. ** is advantageous to leave the cursor pointing to the last entry in
  55741. ** the b-tree if possible. If the cursor is left pointing to the last
  55742. ** entry in the table, and the next row inserted has an integer key
  55743. ** larger than the largest existing key, it is possible to insert the
  55744. ** row without seeking the cursor. This can be a big performance boost.
  55745. */
  55746. pCur->info.nSize = 0;
  55747. if( rc==SQLITE_OK && pPage->nOverflow ){
  55748. pCur->curFlags &= ~(BTCF_ValidNKey);
  55749. rc = balance(pCur);
  55750. /* Must make sure nOverflow is reset to zero even if the balance()
  55751. ** fails. Internal data structure corruption will result otherwise.
  55752. ** Also, set the cursor state to invalid. This stops saveCursorPosition()
  55753. ** from trying to save the current position of the cursor. */
  55754. pCur->apPage[pCur->iPage]->nOverflow = 0;
  55755. pCur->eState = CURSOR_INVALID;
  55756. }
  55757. assert( pCur->apPage[pCur->iPage]->nOverflow==0 );
  55758. end_insert:
  55759. return rc;
  55760. }
  55761. /*
  55762. ** Delete the entry that the cursor is pointing to. The cursor
  55763. ** is left pointing at an arbitrary location.
  55764. */
  55765. SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor *pCur){
  55766. Btree *p = pCur->pBtree;
  55767. BtShared *pBt = p->pBt;
  55768. int rc; /* Return code */
  55769. MemPage *pPage; /* Page to delete cell from */
  55770. unsigned char *pCell; /* Pointer to cell to delete */
  55771. int iCellIdx; /* Index of cell to delete */
  55772. int iCellDepth; /* Depth of node containing pCell */
  55773. u16 szCell; /* Size of the cell being deleted */
  55774. assert( cursorHoldsMutex(pCur) );
  55775. assert( pBt->inTransaction==TRANS_WRITE );
  55776. assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
  55777. assert( pCur->curFlags & BTCF_WriteFlag );
  55778. assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
  55779. assert( !hasReadConflicts(p, pCur->pgnoRoot) );
  55780. if( NEVER(pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell)
  55781. || NEVER(pCur->eState!=CURSOR_VALID)
  55782. ){
  55783. return SQLITE_ERROR; /* Something has gone awry. */
  55784. }
  55785. iCellDepth = pCur->iPage;
  55786. iCellIdx = pCur->aiIdx[iCellDepth];
  55787. pPage = pCur->apPage[iCellDepth];
  55788. pCell = findCell(pPage, iCellIdx);
  55789. /* If the page containing the entry to delete is not a leaf page, move
  55790. ** the cursor to the largest entry in the tree that is smaller than
  55791. ** the entry being deleted. This cell will replace the cell being deleted
  55792. ** from the internal node. The 'previous' entry is used for this instead
  55793. ** of the 'next' entry, as the previous entry is always a part of the
  55794. ** sub-tree headed by the child page of the cell being deleted. This makes
  55795. ** balancing the tree following the delete operation easier. */
  55796. if( !pPage->leaf ){
  55797. int notUsed = 0;
  55798. rc = sqlite3BtreePrevious(pCur, &notUsed);
  55799. if( rc ) return rc;
  55800. }
  55801. /* Save the positions of any other cursors open on this table before
  55802. ** making any modifications. Make the page containing the entry to be
  55803. ** deleted writable. Then free any overflow pages associated with the
  55804. ** entry and finally remove the cell itself from within the page.
  55805. */
  55806. rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
  55807. if( rc ) return rc;
  55808. /* If this is a delete operation to remove a row from a table b-tree,
  55809. ** invalidate any incrblob cursors open on the row being deleted. */
  55810. if( pCur->pKeyInfo==0 ){
  55811. invalidateIncrblobCursors(p, pCur->info.nKey, 0);
  55812. }
  55813. rc = sqlite3PagerWrite(pPage->pDbPage);
  55814. if( rc ) return rc;
  55815. rc = clearCell(pPage, pCell, &szCell);
  55816. dropCell(pPage, iCellIdx, szCell, &rc);
  55817. if( rc ) return rc;
  55818. /* If the cell deleted was not located on a leaf page, then the cursor
  55819. ** is currently pointing to the largest entry in the sub-tree headed
  55820. ** by the child-page of the cell that was just deleted from an internal
  55821. ** node. The cell from the leaf node needs to be moved to the internal
  55822. ** node to replace the deleted cell. */
  55823. if( !pPage->leaf ){
  55824. MemPage *pLeaf = pCur->apPage[pCur->iPage];
  55825. int nCell;
  55826. Pgno n = pCur->apPage[iCellDepth+1]->pgno;
  55827. unsigned char *pTmp;
  55828. pCell = findCell(pLeaf, pLeaf->nCell-1);
  55829. nCell = cellSizePtr(pLeaf, pCell);
  55830. assert( MX_CELL_SIZE(pBt) >= nCell );
  55831. pTmp = pBt->pTmpSpace;
  55832. assert( pTmp!=0 );
  55833. rc = sqlite3PagerWrite(pLeaf->pDbPage);
  55834. insertCell(pPage, iCellIdx, pCell-4, nCell+4, pTmp, n, &rc);
  55835. dropCell(pLeaf, pLeaf->nCell-1, nCell, &rc);
  55836. if( rc ) return rc;
  55837. }
  55838. /* Balance the tree. If the entry deleted was located on a leaf page,
  55839. ** then the cursor still points to that page. In this case the first
  55840. ** call to balance() repairs the tree, and the if(...) condition is
  55841. ** never true.
  55842. **
  55843. ** Otherwise, if the entry deleted was on an internal node page, then
  55844. ** pCur is pointing to the leaf page from which a cell was removed to
  55845. ** replace the cell deleted from the internal node. This is slightly
  55846. ** tricky as the leaf node may be underfull, and the internal node may
  55847. ** be either under or overfull. In this case run the balancing algorithm
  55848. ** on the leaf node first. If the balance proceeds far enough up the
  55849. ** tree that we can be sure that any problem in the internal node has
  55850. ** been corrected, so be it. Otherwise, after balancing the leaf node,
  55851. ** walk the cursor up the tree to the internal node and balance it as
  55852. ** well. */
  55853. rc = balance(pCur);
  55854. if( rc==SQLITE_OK && pCur->iPage>iCellDepth ){
  55855. while( pCur->iPage>iCellDepth ){
  55856. releasePage(pCur->apPage[pCur->iPage--]);
  55857. }
  55858. rc = balance(pCur);
  55859. }
  55860. if( rc==SQLITE_OK ){
  55861. moveToRoot(pCur);
  55862. }
  55863. return rc;
  55864. }
  55865. /*
  55866. ** Create a new BTree table. Write into *piTable the page
  55867. ** number for the root page of the new table.
  55868. **
  55869. ** The type of type is determined by the flags parameter. Only the
  55870. ** following values of flags are currently in use. Other values for
  55871. ** flags might not work:
  55872. **
  55873. ** BTREE_INTKEY|BTREE_LEAFDATA Used for SQL tables with rowid keys
  55874. ** BTREE_ZERODATA Used for SQL indices
  55875. */
  55876. static int btreeCreateTable(Btree *p, int *piTable, int createTabFlags){
  55877. BtShared *pBt = p->pBt;
  55878. MemPage *pRoot;
  55879. Pgno pgnoRoot;
  55880. int rc;
  55881. int ptfFlags; /* Page-type flage for the root page of new table */
  55882. assert( sqlite3BtreeHoldsMutex(p) );
  55883. assert( pBt->inTransaction==TRANS_WRITE );
  55884. assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
  55885. #ifdef SQLITE_OMIT_AUTOVACUUM
  55886. rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
  55887. if( rc ){
  55888. return rc;
  55889. }
  55890. #else
  55891. if( pBt->autoVacuum ){
  55892. Pgno pgnoMove; /* Move a page here to make room for the root-page */
  55893. MemPage *pPageMove; /* The page to move to. */
  55894. /* Creating a new table may probably require moving an existing database
  55895. ** to make room for the new tables root page. In case this page turns
  55896. ** out to be an overflow page, delete all overflow page-map caches
  55897. ** held by open cursors.
  55898. */
  55899. invalidateAllOverflowCache(pBt);
  55900. /* Read the value of meta[3] from the database to determine where the
  55901. ** root page of the new table should go. meta[3] is the largest root-page
  55902. ** created so far, so the new root-page is (meta[3]+1).
  55903. */
  55904. sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &pgnoRoot);
  55905. pgnoRoot++;
  55906. /* The new root-page may not be allocated on a pointer-map page, or the
  55907. ** PENDING_BYTE page.
  55908. */
  55909. while( pgnoRoot==PTRMAP_PAGENO(pBt, pgnoRoot) ||
  55910. pgnoRoot==PENDING_BYTE_PAGE(pBt) ){
  55911. pgnoRoot++;
  55912. }
  55913. assert( pgnoRoot>=3 );
  55914. /* Allocate a page. The page that currently resides at pgnoRoot will
  55915. ** be moved to the allocated page (unless the allocated page happens
  55916. ** to reside at pgnoRoot).
  55917. */
  55918. rc = allocateBtreePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, BTALLOC_EXACT);
  55919. if( rc!=SQLITE_OK ){
  55920. return rc;
  55921. }
  55922. if( pgnoMove!=pgnoRoot ){
  55923. /* pgnoRoot is the page that will be used for the root-page of
  55924. ** the new table (assuming an error did not occur). But we were
  55925. ** allocated pgnoMove. If required (i.e. if it was not allocated
  55926. ** by extending the file), the current page at position pgnoMove
  55927. ** is already journaled.
  55928. */
  55929. u8 eType = 0;
  55930. Pgno iPtrPage = 0;
  55931. /* Save the positions of any open cursors. This is required in
  55932. ** case they are holding a reference to an xFetch reference
  55933. ** corresponding to page pgnoRoot. */
  55934. rc = saveAllCursors(pBt, 0, 0);
  55935. releasePage(pPageMove);
  55936. if( rc!=SQLITE_OK ){
  55937. return rc;
  55938. }
  55939. /* Move the page currently at pgnoRoot to pgnoMove. */
  55940. rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
  55941. if( rc!=SQLITE_OK ){
  55942. return rc;
  55943. }
  55944. rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage);
  55945. if( eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){
  55946. rc = SQLITE_CORRUPT_BKPT;
  55947. }
  55948. if( rc!=SQLITE_OK ){
  55949. releasePage(pRoot);
  55950. return rc;
  55951. }
  55952. assert( eType!=PTRMAP_ROOTPAGE );
  55953. assert( eType!=PTRMAP_FREEPAGE );
  55954. rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove, 0);
  55955. releasePage(pRoot);
  55956. /* Obtain the page at pgnoRoot */
  55957. if( rc!=SQLITE_OK ){
  55958. return rc;
  55959. }
  55960. rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
  55961. if( rc!=SQLITE_OK ){
  55962. return rc;
  55963. }
  55964. rc = sqlite3PagerWrite(pRoot->pDbPage);
  55965. if( rc!=SQLITE_OK ){
  55966. releasePage(pRoot);
  55967. return rc;
  55968. }
  55969. }else{
  55970. pRoot = pPageMove;
  55971. }
  55972. /* Update the pointer-map and meta-data with the new root-page number. */
  55973. ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0, &rc);
  55974. if( rc ){
  55975. releasePage(pRoot);
  55976. return rc;
  55977. }
  55978. /* When the new root page was allocated, page 1 was made writable in
  55979. ** order either to increase the database filesize, or to decrement the
  55980. ** freelist count. Hence, the sqlite3BtreeUpdateMeta() call cannot fail.
  55981. */
  55982. assert( sqlite3PagerIswriteable(pBt->pPage1->pDbPage) );
  55983. rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot);
  55984. if( NEVER(rc) ){
  55985. releasePage(pRoot);
  55986. return rc;
  55987. }
  55988. }else{
  55989. rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
  55990. if( rc ) return rc;
  55991. }
  55992. #endif
  55993. assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
  55994. if( createTabFlags & BTREE_INTKEY ){
  55995. ptfFlags = PTF_INTKEY | PTF_LEAFDATA | PTF_LEAF;
  55996. }else{
  55997. ptfFlags = PTF_ZERODATA | PTF_LEAF;
  55998. }
  55999. zeroPage(pRoot, ptfFlags);
  56000. sqlite3PagerUnref(pRoot->pDbPage);
  56001. assert( (pBt->openFlags & BTREE_SINGLE)==0 || pgnoRoot==2 );
  56002. *piTable = (int)pgnoRoot;
  56003. return SQLITE_OK;
  56004. }
  56005. SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree *p, int *piTable, int flags){
  56006. int rc;
  56007. sqlite3BtreeEnter(p);
  56008. rc = btreeCreateTable(p, piTable, flags);
  56009. sqlite3BtreeLeave(p);
  56010. return rc;
  56011. }
  56012. /*
  56013. ** Erase the given database page and all its children. Return
  56014. ** the page to the freelist.
  56015. */
  56016. static int clearDatabasePage(
  56017. BtShared *pBt, /* The BTree that contains the table */
  56018. Pgno pgno, /* Page number to clear */
  56019. int freePageFlag, /* Deallocate page if true */
  56020. int *pnChange /* Add number of Cells freed to this counter */
  56021. ){
  56022. MemPage *pPage;
  56023. int rc;
  56024. unsigned char *pCell;
  56025. int i;
  56026. int hdr;
  56027. u16 szCell;
  56028. assert( sqlite3_mutex_held(pBt->mutex) );
  56029. if( pgno>btreePagecount(pBt) ){
  56030. return SQLITE_CORRUPT_BKPT;
  56031. }
  56032. rc = getAndInitPage(pBt, pgno, &pPage, 0);
  56033. if( rc ) return rc;
  56034. hdr = pPage->hdrOffset;
  56035. for(i=0; i<pPage->nCell; i++){
  56036. pCell = findCell(pPage, i);
  56037. if( !pPage->leaf ){
  56038. rc = clearDatabasePage(pBt, get4byte(pCell), 1, pnChange);
  56039. if( rc ) goto cleardatabasepage_out;
  56040. }
  56041. rc = clearCell(pPage, pCell, &szCell);
  56042. if( rc ) goto cleardatabasepage_out;
  56043. }
  56044. if( !pPage->leaf ){
  56045. rc = clearDatabasePage(pBt, get4byte(&pPage->aData[hdr+8]), 1, pnChange);
  56046. if( rc ) goto cleardatabasepage_out;
  56047. }else if( pnChange ){
  56048. assert( pPage->intKey );
  56049. *pnChange += pPage->nCell;
  56050. }
  56051. if( freePageFlag ){
  56052. freePage(pPage, &rc);
  56053. }else if( (rc = sqlite3PagerWrite(pPage->pDbPage))==0 ){
  56054. zeroPage(pPage, pPage->aData[hdr] | PTF_LEAF);
  56055. }
  56056. cleardatabasepage_out:
  56057. releasePage(pPage);
  56058. return rc;
  56059. }
  56060. /*
  56061. ** Delete all information from a single table in the database. iTable is
  56062. ** the page number of the root of the table. After this routine returns,
  56063. ** the root page is empty, but still exists.
  56064. **
  56065. ** This routine will fail with SQLITE_LOCKED if there are any open
  56066. ** read cursors on the table. Open write cursors are moved to the
  56067. ** root of the table.
  56068. **
  56069. ** If pnChange is not NULL, then table iTable must be an intkey table. The
  56070. ** integer value pointed to by pnChange is incremented by the number of
  56071. ** entries in the table.
  56072. */
  56073. SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree *p, int iTable, int *pnChange){
  56074. int rc;
  56075. BtShared *pBt = p->pBt;
  56076. sqlite3BtreeEnter(p);
  56077. assert( p->inTrans==TRANS_WRITE );
  56078. rc = saveAllCursors(pBt, (Pgno)iTable, 0);
  56079. if( SQLITE_OK==rc ){
  56080. /* Invalidate all incrblob cursors open on table iTable (assuming iTable
  56081. ** is the root of a table b-tree - if it is not, the following call is
  56082. ** a no-op). */
  56083. invalidateIncrblobCursors(p, 0, 1);
  56084. rc = clearDatabasePage(pBt, (Pgno)iTable, 0, pnChange);
  56085. }
  56086. sqlite3BtreeLeave(p);
  56087. return rc;
  56088. }
  56089. /*
  56090. ** Delete all information from the single table that pCur is open on.
  56091. **
  56092. ** This routine only work for pCur on an ephemeral table.
  56093. */
  56094. SQLITE_PRIVATE int sqlite3BtreeClearTableOfCursor(BtCursor *pCur){
  56095. return sqlite3BtreeClearTable(pCur->pBtree, pCur->pgnoRoot, 0);
  56096. }
  56097. /*
  56098. ** Erase all information in a table and add the root of the table to
  56099. ** the freelist. Except, the root of the principle table (the one on
  56100. ** page 1) is never added to the freelist.
  56101. **
  56102. ** This routine will fail with SQLITE_LOCKED if there are any open
  56103. ** cursors on the table.
  56104. **
  56105. ** If AUTOVACUUM is enabled and the page at iTable is not the last
  56106. ** root page in the database file, then the last root page
  56107. ** in the database file is moved into the slot formerly occupied by
  56108. ** iTable and that last slot formerly occupied by the last root page
  56109. ** is added to the freelist instead of iTable. In this say, all
  56110. ** root pages are kept at the beginning of the database file, which
  56111. ** is necessary for AUTOVACUUM to work right. *piMoved is set to the
  56112. ** page number that used to be the last root page in the file before
  56113. ** the move. If no page gets moved, *piMoved is set to 0.
  56114. ** The last root page is recorded in meta[3] and the value of
  56115. ** meta[3] is updated by this procedure.
  56116. */
  56117. static int btreeDropTable(Btree *p, Pgno iTable, int *piMoved){
  56118. int rc;
  56119. MemPage *pPage = 0;
  56120. BtShared *pBt = p->pBt;
  56121. assert( sqlite3BtreeHoldsMutex(p) );
  56122. assert( p->inTrans==TRANS_WRITE );
  56123. /* It is illegal to drop a table if any cursors are open on the
  56124. ** database. This is because in auto-vacuum mode the backend may
  56125. ** need to move another root-page to fill a gap left by the deleted
  56126. ** root page. If an open cursor was using this page a problem would
  56127. ** occur.
  56128. **
  56129. ** This error is caught long before control reaches this point.
  56130. */
  56131. if( NEVER(pBt->pCursor) ){
  56132. sqlite3ConnectionBlocked(p->db, pBt->pCursor->pBtree->db);
  56133. return SQLITE_LOCKED_SHAREDCACHE;
  56134. }
  56135. rc = btreeGetPage(pBt, (Pgno)iTable, &pPage, 0);
  56136. if( rc ) return rc;
  56137. rc = sqlite3BtreeClearTable(p, iTable, 0);
  56138. if( rc ){
  56139. releasePage(pPage);
  56140. return rc;
  56141. }
  56142. *piMoved = 0;
  56143. if( iTable>1 ){
  56144. #ifdef SQLITE_OMIT_AUTOVACUUM
  56145. freePage(pPage, &rc);
  56146. releasePage(pPage);
  56147. #else
  56148. if( pBt->autoVacuum ){
  56149. Pgno maxRootPgno;
  56150. sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &maxRootPgno);
  56151. if( iTable==maxRootPgno ){
  56152. /* If the table being dropped is the table with the largest root-page
  56153. ** number in the database, put the root page on the free list.
  56154. */
  56155. freePage(pPage, &rc);
  56156. releasePage(pPage);
  56157. if( rc!=SQLITE_OK ){
  56158. return rc;
  56159. }
  56160. }else{
  56161. /* The table being dropped does not have the largest root-page
  56162. ** number in the database. So move the page that does into the
  56163. ** gap left by the deleted root-page.
  56164. */
  56165. MemPage *pMove;
  56166. releasePage(pPage);
  56167. rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
  56168. if( rc!=SQLITE_OK ){
  56169. return rc;
  56170. }
  56171. rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable, 0);
  56172. releasePage(pMove);
  56173. if( rc!=SQLITE_OK ){
  56174. return rc;
  56175. }
  56176. pMove = 0;
  56177. rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
  56178. freePage(pMove, &rc);
  56179. releasePage(pMove);
  56180. if( rc!=SQLITE_OK ){
  56181. return rc;
  56182. }
  56183. *piMoved = maxRootPgno;
  56184. }
  56185. /* Set the new 'max-root-page' value in the database header. This
  56186. ** is the old value less one, less one more if that happens to
  56187. ** be a root-page number, less one again if that is the
  56188. ** PENDING_BYTE_PAGE.
  56189. */
  56190. maxRootPgno--;
  56191. while( maxRootPgno==PENDING_BYTE_PAGE(pBt)
  56192. || PTRMAP_ISPAGE(pBt, maxRootPgno) ){
  56193. maxRootPgno--;
  56194. }
  56195. assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) );
  56196. rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno);
  56197. }else{
  56198. freePage(pPage, &rc);
  56199. releasePage(pPage);
  56200. }
  56201. #endif
  56202. }else{
  56203. /* If sqlite3BtreeDropTable was called on page 1.
  56204. ** This really never should happen except in a corrupt
  56205. ** database.
  56206. */
  56207. zeroPage(pPage, PTF_INTKEY|PTF_LEAF );
  56208. releasePage(pPage);
  56209. }
  56210. return rc;
  56211. }
  56212. SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){
  56213. int rc;
  56214. sqlite3BtreeEnter(p);
  56215. rc = btreeDropTable(p, iTable, piMoved);
  56216. sqlite3BtreeLeave(p);
  56217. return rc;
  56218. }
  56219. /*
  56220. ** This function may only be called if the b-tree connection already
  56221. ** has a read or write transaction open on the database.
  56222. **
  56223. ** Read the meta-information out of a database file. Meta[0]
  56224. ** is the number of free pages currently in the database. Meta[1]
  56225. ** through meta[15] are available for use by higher layers. Meta[0]
  56226. ** is read-only, the others are read/write.
  56227. **
  56228. ** The schema layer numbers meta values differently. At the schema
  56229. ** layer (and the SetCookie and ReadCookie opcodes) the number of
  56230. ** free pages is not visible. So Cookie[0] is the same as Meta[1].
  56231. */
  56232. SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){
  56233. BtShared *pBt = p->pBt;
  56234. sqlite3BtreeEnter(p);
  56235. assert( p->inTrans>TRANS_NONE );
  56236. assert( SQLITE_OK==querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK) );
  56237. assert( pBt->pPage1 );
  56238. assert( idx>=0 && idx<=15 );
  56239. *pMeta = get4byte(&pBt->pPage1->aData[36 + idx*4]);
  56240. /* If auto-vacuum is disabled in this build and this is an auto-vacuum
  56241. ** database, mark the database as read-only. */
  56242. #ifdef SQLITE_OMIT_AUTOVACUUM
  56243. if( idx==BTREE_LARGEST_ROOT_PAGE && *pMeta>0 ){
  56244. pBt->btsFlags |= BTS_READ_ONLY;
  56245. }
  56246. #endif
  56247. sqlite3BtreeLeave(p);
  56248. }
  56249. /*
  56250. ** Write meta-information back into the database. Meta[0] is
  56251. ** read-only and may not be written.
  56252. */
  56253. SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){
  56254. BtShared *pBt = p->pBt;
  56255. unsigned char *pP1;
  56256. int rc;
  56257. assert( idx>=1 && idx<=15 );
  56258. sqlite3BtreeEnter(p);
  56259. assert( p->inTrans==TRANS_WRITE );
  56260. assert( pBt->pPage1!=0 );
  56261. pP1 = pBt->pPage1->aData;
  56262. rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
  56263. if( rc==SQLITE_OK ){
  56264. put4byte(&pP1[36 + idx*4], iMeta);
  56265. #ifndef SQLITE_OMIT_AUTOVACUUM
  56266. if( idx==BTREE_INCR_VACUUM ){
  56267. assert( pBt->autoVacuum || iMeta==0 );
  56268. assert( iMeta==0 || iMeta==1 );
  56269. pBt->incrVacuum = (u8)iMeta;
  56270. }
  56271. #endif
  56272. }
  56273. sqlite3BtreeLeave(p);
  56274. return rc;
  56275. }
  56276. #ifndef SQLITE_OMIT_BTREECOUNT
  56277. /*
  56278. ** The first argument, pCur, is a cursor opened on some b-tree. Count the
  56279. ** number of entries in the b-tree and write the result to *pnEntry.
  56280. **
  56281. ** SQLITE_OK is returned if the operation is successfully executed.
  56282. ** Otherwise, if an error is encountered (i.e. an IO error or database
  56283. ** corruption) an SQLite error code is returned.
  56284. */
  56285. SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *pCur, i64 *pnEntry){
  56286. i64 nEntry = 0; /* Value to return in *pnEntry */
  56287. int rc; /* Return code */
  56288. if( pCur->pgnoRoot==0 ){
  56289. *pnEntry = 0;
  56290. return SQLITE_OK;
  56291. }
  56292. rc = moveToRoot(pCur);
  56293. /* Unless an error occurs, the following loop runs one iteration for each
  56294. ** page in the B-Tree structure (not including overflow pages).
  56295. */
  56296. while( rc==SQLITE_OK ){
  56297. int iIdx; /* Index of child node in parent */
  56298. MemPage *pPage; /* Current page of the b-tree */
  56299. /* If this is a leaf page or the tree is not an int-key tree, then
  56300. ** this page contains countable entries. Increment the entry counter
  56301. ** accordingly.
  56302. */
  56303. pPage = pCur->apPage[pCur->iPage];
  56304. if( pPage->leaf || !pPage->intKey ){
  56305. nEntry += pPage->nCell;
  56306. }
  56307. /* pPage is a leaf node. This loop navigates the cursor so that it
  56308. ** points to the first interior cell that it points to the parent of
  56309. ** the next page in the tree that has not yet been visited. The
  56310. ** pCur->aiIdx[pCur->iPage] value is set to the index of the parent cell
  56311. ** of the page, or to the number of cells in the page if the next page
  56312. ** to visit is the right-child of its parent.
  56313. **
  56314. ** If all pages in the tree have been visited, return SQLITE_OK to the
  56315. ** caller.
  56316. */
  56317. if( pPage->leaf ){
  56318. do {
  56319. if( pCur->iPage==0 ){
  56320. /* All pages of the b-tree have been visited. Return successfully. */
  56321. *pnEntry = nEntry;
  56322. return SQLITE_OK;
  56323. }
  56324. moveToParent(pCur);
  56325. }while ( pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell );
  56326. pCur->aiIdx[pCur->iPage]++;
  56327. pPage = pCur->apPage[pCur->iPage];
  56328. }
  56329. /* Descend to the child node of the cell that the cursor currently
  56330. ** points at. This is the right-child if (iIdx==pPage->nCell).
  56331. */
  56332. iIdx = pCur->aiIdx[pCur->iPage];
  56333. if( iIdx==pPage->nCell ){
  56334. rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
  56335. }else{
  56336. rc = moveToChild(pCur, get4byte(findCell(pPage, iIdx)));
  56337. }
  56338. }
  56339. /* An error has occurred. Return an error code. */
  56340. return rc;
  56341. }
  56342. #endif
  56343. /*
  56344. ** Return the pager associated with a BTree. This routine is used for
  56345. ** testing and debugging only.
  56346. */
  56347. SQLITE_PRIVATE Pager *sqlite3BtreePager(Btree *p){
  56348. return p->pBt->pPager;
  56349. }
  56350. #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  56351. /*
  56352. ** Append a message to the error message string.
  56353. */
  56354. static void checkAppendMsg(
  56355. IntegrityCk *pCheck,
  56356. const char *zFormat,
  56357. ...
  56358. ){
  56359. va_list ap;
  56360. char zBuf[200];
  56361. if( !pCheck->mxErr ) return;
  56362. pCheck->mxErr--;
  56363. pCheck->nErr++;
  56364. va_start(ap, zFormat);
  56365. if( pCheck->errMsg.nChar ){
  56366. sqlite3StrAccumAppend(&pCheck->errMsg, "\n", 1);
  56367. }
  56368. if( pCheck->zPfx ){
  56369. sqlite3_snprintf(sizeof(zBuf), zBuf, pCheck->zPfx, pCheck->v1, pCheck->v2);
  56370. sqlite3StrAccumAppendAll(&pCheck->errMsg, zBuf);
  56371. }
  56372. sqlite3VXPrintf(&pCheck->errMsg, 1, zFormat, ap);
  56373. va_end(ap);
  56374. if( pCheck->errMsg.accError==STRACCUM_NOMEM ){
  56375. pCheck->mallocFailed = 1;
  56376. }
  56377. }
  56378. #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  56379. #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  56380. /*
  56381. ** Return non-zero if the bit in the IntegrityCk.aPgRef[] array that
  56382. ** corresponds to page iPg is already set.
  56383. */
  56384. static int getPageReferenced(IntegrityCk *pCheck, Pgno iPg){
  56385. assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
  56386. return (pCheck->aPgRef[iPg/8] & (1 << (iPg & 0x07)));
  56387. }
  56388. /*
  56389. ** Set the bit in the IntegrityCk.aPgRef[] array that corresponds to page iPg.
  56390. */
  56391. static void setPageReferenced(IntegrityCk *pCheck, Pgno iPg){
  56392. assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
  56393. pCheck->aPgRef[iPg/8] |= (1 << (iPg & 0x07));
  56394. }
  56395. /*
  56396. ** Add 1 to the reference count for page iPage. If this is the second
  56397. ** reference to the page, add an error message to pCheck->zErrMsg.
  56398. ** Return 1 if there are 2 or more references to the page and 0 if
  56399. ** if this is the first reference to the page.
  56400. **
  56401. ** Also check that the page number is in bounds.
  56402. */
  56403. static int checkRef(IntegrityCk *pCheck, Pgno iPage){
  56404. if( iPage==0 ) return 1;
  56405. if( iPage>pCheck->nPage ){
  56406. checkAppendMsg(pCheck, "invalid page number %d", iPage);
  56407. return 1;
  56408. }
  56409. if( getPageReferenced(pCheck, iPage) ){
  56410. checkAppendMsg(pCheck, "2nd reference to page %d", iPage);
  56411. return 1;
  56412. }
  56413. setPageReferenced(pCheck, iPage);
  56414. return 0;
  56415. }
  56416. #ifndef SQLITE_OMIT_AUTOVACUUM
  56417. /*
  56418. ** Check that the entry in the pointer-map for page iChild maps to
  56419. ** page iParent, pointer type ptrType. If not, append an error message
  56420. ** to pCheck.
  56421. */
  56422. static void checkPtrmap(
  56423. IntegrityCk *pCheck, /* Integrity check context */
  56424. Pgno iChild, /* Child page number */
  56425. u8 eType, /* Expected pointer map type */
  56426. Pgno iParent /* Expected pointer map parent page number */
  56427. ){
  56428. int rc;
  56429. u8 ePtrmapType;
  56430. Pgno iPtrmapParent;
  56431. rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
  56432. if( rc!=SQLITE_OK ){
  56433. if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ) pCheck->mallocFailed = 1;
  56434. checkAppendMsg(pCheck, "Failed to read ptrmap key=%d", iChild);
  56435. return;
  56436. }
  56437. if( ePtrmapType!=eType || iPtrmapParent!=iParent ){
  56438. checkAppendMsg(pCheck,
  56439. "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)",
  56440. iChild, eType, iParent, ePtrmapType, iPtrmapParent);
  56441. }
  56442. }
  56443. #endif
  56444. /*
  56445. ** Check the integrity of the freelist or of an overflow page list.
  56446. ** Verify that the number of pages on the list is N.
  56447. */
  56448. static void checkList(
  56449. IntegrityCk *pCheck, /* Integrity checking context */
  56450. int isFreeList, /* True for a freelist. False for overflow page list */
  56451. int iPage, /* Page number for first page in the list */
  56452. int N /* Expected number of pages in the list */
  56453. ){
  56454. int i;
  56455. int expected = N;
  56456. int iFirst = iPage;
  56457. while( N-- > 0 && pCheck->mxErr ){
  56458. DbPage *pOvflPage;
  56459. unsigned char *pOvflData;
  56460. if( iPage<1 ){
  56461. checkAppendMsg(pCheck,
  56462. "%d of %d pages missing from overflow list starting at %d",
  56463. N+1, expected, iFirst);
  56464. break;
  56465. }
  56466. if( checkRef(pCheck, iPage) ) break;
  56467. if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage) ){
  56468. checkAppendMsg(pCheck, "failed to get page %d", iPage);
  56469. break;
  56470. }
  56471. pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage);
  56472. if( isFreeList ){
  56473. int n = get4byte(&pOvflData[4]);
  56474. #ifndef SQLITE_OMIT_AUTOVACUUM
  56475. if( pCheck->pBt->autoVacuum ){
  56476. checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0);
  56477. }
  56478. #endif
  56479. if( n>(int)pCheck->pBt->usableSize/4-2 ){
  56480. checkAppendMsg(pCheck,
  56481. "freelist leaf count too big on page %d", iPage);
  56482. N--;
  56483. }else{
  56484. for(i=0; i<n; i++){
  56485. Pgno iFreePage = get4byte(&pOvflData[8+i*4]);
  56486. #ifndef SQLITE_OMIT_AUTOVACUUM
  56487. if( pCheck->pBt->autoVacuum ){
  56488. checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0);
  56489. }
  56490. #endif
  56491. checkRef(pCheck, iFreePage);
  56492. }
  56493. N -= n;
  56494. }
  56495. }
  56496. #ifndef SQLITE_OMIT_AUTOVACUUM
  56497. else{
  56498. /* If this database supports auto-vacuum and iPage is not the last
  56499. ** page in this overflow list, check that the pointer-map entry for
  56500. ** the following page matches iPage.
  56501. */
  56502. if( pCheck->pBt->autoVacuum && N>0 ){
  56503. i = get4byte(pOvflData);
  56504. checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage);
  56505. }
  56506. }
  56507. #endif
  56508. iPage = get4byte(pOvflData);
  56509. sqlite3PagerUnref(pOvflPage);
  56510. }
  56511. }
  56512. #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  56513. #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  56514. /*
  56515. ** Do various sanity checks on a single page of a tree. Return
  56516. ** the tree depth. Root pages return 0. Parents of root pages
  56517. ** return 1, and so forth.
  56518. **
  56519. ** These checks are done:
  56520. **
  56521. ** 1. Make sure that cells and freeblocks do not overlap
  56522. ** but combine to completely cover the page.
  56523. ** NO 2. Make sure cell keys are in order.
  56524. ** NO 3. Make sure no key is less than or equal to zLowerBound.
  56525. ** NO 4. Make sure no key is greater than or equal to zUpperBound.
  56526. ** 5. Check the integrity of overflow pages.
  56527. ** 6. Recursively call checkTreePage on all children.
  56528. ** 7. Verify that the depth of all children is the same.
  56529. ** 8. Make sure this page is at least 33% full or else it is
  56530. ** the root of the tree.
  56531. */
  56532. static int checkTreePage(
  56533. IntegrityCk *pCheck, /* Context for the sanity check */
  56534. int iPage, /* Page number of the page to check */
  56535. i64 *pnParentMinKey,
  56536. i64 *pnParentMaxKey
  56537. ){
  56538. MemPage *pPage;
  56539. int i, rc, depth, d2, pgno, cnt;
  56540. int hdr, cellStart;
  56541. int nCell;
  56542. u8 *data;
  56543. BtShared *pBt;
  56544. int usableSize;
  56545. char *hit = 0;
  56546. i64 nMinKey = 0;
  56547. i64 nMaxKey = 0;
  56548. const char *saved_zPfx = pCheck->zPfx;
  56549. int saved_v1 = pCheck->v1;
  56550. int saved_v2 = pCheck->v2;
  56551. /* Check that the page exists
  56552. */
  56553. pBt = pCheck->pBt;
  56554. usableSize = pBt->usableSize;
  56555. if( iPage==0 ) return 0;
  56556. if( checkRef(pCheck, iPage) ) return 0;
  56557. pCheck->zPfx = "Page %d: ";
  56558. pCheck->v1 = iPage;
  56559. if( (rc = btreeGetPage(pBt, (Pgno)iPage, &pPage, 0))!=0 ){
  56560. checkAppendMsg(pCheck,
  56561. "unable to get the page. error code=%d", rc);
  56562. depth = -1;
  56563. goto end_of_check;
  56564. }
  56565. /* Clear MemPage.isInit to make sure the corruption detection code in
  56566. ** btreeInitPage() is executed. */
  56567. pPage->isInit = 0;
  56568. if( (rc = btreeInitPage(pPage))!=0 ){
  56569. assert( rc==SQLITE_CORRUPT ); /* The only possible error from InitPage */
  56570. checkAppendMsg(pCheck,
  56571. "btreeInitPage() returns error code %d", rc);
  56572. releasePage(pPage);
  56573. depth = -1;
  56574. goto end_of_check;
  56575. }
  56576. /* Check out all the cells.
  56577. */
  56578. depth = 0;
  56579. for(i=0; i<pPage->nCell && pCheck->mxErr; i++){
  56580. u8 *pCell;
  56581. u32 sz;
  56582. CellInfo info;
  56583. /* Check payload overflow pages
  56584. */
  56585. pCheck->zPfx = "On tree page %d cell %d: ";
  56586. pCheck->v1 = iPage;
  56587. pCheck->v2 = i;
  56588. pCell = findCell(pPage,i);
  56589. btreeParseCellPtr(pPage, pCell, &info);
  56590. sz = info.nPayload;
  56591. /* For intKey pages, check that the keys are in order.
  56592. */
  56593. if( pPage->intKey ){
  56594. if( i==0 ){
  56595. nMinKey = nMaxKey = info.nKey;
  56596. }else if( info.nKey <= nMaxKey ){
  56597. checkAppendMsg(pCheck,
  56598. "Rowid %lld out of order (previous was %lld)", info.nKey, nMaxKey);
  56599. }
  56600. nMaxKey = info.nKey;
  56601. }
  56602. if( (sz>info.nLocal)
  56603. && (&pCell[info.iOverflow]<=&pPage->aData[pBt->usableSize])
  56604. ){
  56605. int nPage = (sz - info.nLocal + usableSize - 5)/(usableSize - 4);
  56606. Pgno pgnoOvfl = get4byte(&pCell[info.iOverflow]);
  56607. #ifndef SQLITE_OMIT_AUTOVACUUM
  56608. if( pBt->autoVacuum ){
  56609. checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage);
  56610. }
  56611. #endif
  56612. checkList(pCheck, 0, pgnoOvfl, nPage);
  56613. }
  56614. /* Check sanity of left child page.
  56615. */
  56616. if( !pPage->leaf ){
  56617. pgno = get4byte(pCell);
  56618. #ifndef SQLITE_OMIT_AUTOVACUUM
  56619. if( pBt->autoVacuum ){
  56620. checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage);
  56621. }
  56622. #endif
  56623. d2 = checkTreePage(pCheck, pgno, &nMinKey, i==0?NULL:&nMaxKey);
  56624. if( i>0 && d2!=depth ){
  56625. checkAppendMsg(pCheck, "Child page depth differs");
  56626. }
  56627. depth = d2;
  56628. }
  56629. }
  56630. if( !pPage->leaf ){
  56631. pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
  56632. pCheck->zPfx = "On page %d at right child: ";
  56633. pCheck->v1 = iPage;
  56634. #ifndef SQLITE_OMIT_AUTOVACUUM
  56635. if( pBt->autoVacuum ){
  56636. checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage);
  56637. }
  56638. #endif
  56639. checkTreePage(pCheck, pgno, NULL, !pPage->nCell?NULL:&nMaxKey);
  56640. }
  56641. /* For intKey leaf pages, check that the min/max keys are in order
  56642. ** with any left/parent/right pages.
  56643. */
  56644. pCheck->zPfx = "Page %d: ";
  56645. pCheck->v1 = iPage;
  56646. if( pPage->leaf && pPage->intKey ){
  56647. /* if we are a left child page */
  56648. if( pnParentMinKey ){
  56649. /* if we are the left most child page */
  56650. if( !pnParentMaxKey ){
  56651. if( nMaxKey > *pnParentMinKey ){
  56652. checkAppendMsg(pCheck,
  56653. "Rowid %lld out of order (max larger than parent min of %lld)",
  56654. nMaxKey, *pnParentMinKey);
  56655. }
  56656. }else{
  56657. if( nMinKey <= *pnParentMinKey ){
  56658. checkAppendMsg(pCheck,
  56659. "Rowid %lld out of order (min less than parent min of %lld)",
  56660. nMinKey, *pnParentMinKey);
  56661. }
  56662. if( nMaxKey > *pnParentMaxKey ){
  56663. checkAppendMsg(pCheck,
  56664. "Rowid %lld out of order (max larger than parent max of %lld)",
  56665. nMaxKey, *pnParentMaxKey);
  56666. }
  56667. *pnParentMinKey = nMaxKey;
  56668. }
  56669. /* else if we're a right child page */
  56670. } else if( pnParentMaxKey ){
  56671. if( nMinKey <= *pnParentMaxKey ){
  56672. checkAppendMsg(pCheck,
  56673. "Rowid %lld out of order (min less than parent max of %lld)",
  56674. nMinKey, *pnParentMaxKey);
  56675. }
  56676. }
  56677. }
  56678. /* Check for complete coverage of the page
  56679. */
  56680. data = pPage->aData;
  56681. hdr = pPage->hdrOffset;
  56682. hit = sqlite3PageMalloc( pBt->pageSize );
  56683. pCheck->zPfx = 0;
  56684. if( hit==0 ){
  56685. pCheck->mallocFailed = 1;
  56686. }else{
  56687. int contentOffset = get2byteNotZero(&data[hdr+5]);
  56688. assert( contentOffset<=usableSize ); /* Enforced by btreeInitPage() */
  56689. memset(hit+contentOffset, 0, usableSize-contentOffset);
  56690. memset(hit, 1, contentOffset);
  56691. nCell = get2byte(&data[hdr+3]);
  56692. cellStart = hdr + 12 - 4*pPage->leaf;
  56693. for(i=0; i<nCell; i++){
  56694. int pc = get2byte(&data[cellStart+i*2]);
  56695. u32 size = 65536;
  56696. int j;
  56697. if( pc<=usableSize-4 ){
  56698. size = cellSizePtr(pPage, &data[pc]);
  56699. }
  56700. if( (int)(pc+size-1)>=usableSize ){
  56701. pCheck->zPfx = 0;
  56702. checkAppendMsg(pCheck,
  56703. "Corruption detected in cell %d on page %d",i,iPage);
  56704. }else{
  56705. for(j=pc+size-1; j>=pc; j--) hit[j]++;
  56706. }
  56707. }
  56708. i = get2byte(&data[hdr+1]);
  56709. while( i>0 ){
  56710. int size, j;
  56711. assert( i<=usableSize-4 ); /* Enforced by btreeInitPage() */
  56712. size = get2byte(&data[i+2]);
  56713. assert( i+size<=usableSize ); /* Enforced by btreeInitPage() */
  56714. for(j=i+size-1; j>=i; j--) hit[j]++;
  56715. j = get2byte(&data[i]);
  56716. assert( j==0 || j>i+size ); /* Enforced by btreeInitPage() */
  56717. assert( j<=usableSize-4 ); /* Enforced by btreeInitPage() */
  56718. i = j;
  56719. }
  56720. for(i=cnt=0; i<usableSize; i++){
  56721. if( hit[i]==0 ){
  56722. cnt++;
  56723. }else if( hit[i]>1 ){
  56724. checkAppendMsg(pCheck,
  56725. "Multiple uses for byte %d of page %d", i, iPage);
  56726. break;
  56727. }
  56728. }
  56729. if( cnt!=data[hdr+7] ){
  56730. checkAppendMsg(pCheck,
  56731. "Fragmentation of %d bytes reported as %d on page %d",
  56732. cnt, data[hdr+7], iPage);
  56733. }
  56734. }
  56735. sqlite3PageFree(hit);
  56736. releasePage(pPage);
  56737. end_of_check:
  56738. pCheck->zPfx = saved_zPfx;
  56739. pCheck->v1 = saved_v1;
  56740. pCheck->v2 = saved_v2;
  56741. return depth+1;
  56742. }
  56743. #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  56744. #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  56745. /*
  56746. ** This routine does a complete check of the given BTree file. aRoot[] is
  56747. ** an array of pages numbers were each page number is the root page of
  56748. ** a table. nRoot is the number of entries in aRoot.
  56749. **
  56750. ** A read-only or read-write transaction must be opened before calling
  56751. ** this function.
  56752. **
  56753. ** Write the number of error seen in *pnErr. Except for some memory
  56754. ** allocation errors, an error message held in memory obtained from
  56755. ** malloc is returned if *pnErr is non-zero. If *pnErr==0 then NULL is
  56756. ** returned. If a memory allocation error occurs, NULL is returned.
  56757. */
  56758. SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(
  56759. Btree *p, /* The btree to be checked */
  56760. int *aRoot, /* An array of root pages numbers for individual trees */
  56761. int nRoot, /* Number of entries in aRoot[] */
  56762. int mxErr, /* Stop reporting errors after this many */
  56763. int *pnErr /* Write number of errors seen to this variable */
  56764. ){
  56765. Pgno i;
  56766. int nRef;
  56767. IntegrityCk sCheck;
  56768. BtShared *pBt = p->pBt;
  56769. char zErr[100];
  56770. sqlite3BtreeEnter(p);
  56771. assert( p->inTrans>TRANS_NONE && pBt->inTransaction>TRANS_NONE );
  56772. nRef = sqlite3PagerRefcount(pBt->pPager);
  56773. sCheck.pBt = pBt;
  56774. sCheck.pPager = pBt->pPager;
  56775. sCheck.nPage = btreePagecount(sCheck.pBt);
  56776. sCheck.mxErr = mxErr;
  56777. sCheck.nErr = 0;
  56778. sCheck.mallocFailed = 0;
  56779. sCheck.zPfx = 0;
  56780. sCheck.v1 = 0;
  56781. sCheck.v2 = 0;
  56782. *pnErr = 0;
  56783. if( sCheck.nPage==0 ){
  56784. sqlite3BtreeLeave(p);
  56785. return 0;
  56786. }
  56787. sCheck.aPgRef = sqlite3MallocZero((sCheck.nPage / 8)+ 1);
  56788. if( !sCheck.aPgRef ){
  56789. *pnErr = 1;
  56790. sqlite3BtreeLeave(p);
  56791. return 0;
  56792. }
  56793. i = PENDING_BYTE_PAGE(pBt);
  56794. if( i<=sCheck.nPage ) setPageReferenced(&sCheck, i);
  56795. sqlite3StrAccumInit(&sCheck.errMsg, zErr, sizeof(zErr), SQLITE_MAX_LENGTH);
  56796. sCheck.errMsg.useMalloc = 2;
  56797. /* Check the integrity of the freelist
  56798. */
  56799. sCheck.zPfx = "Main freelist: ";
  56800. checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
  56801. get4byte(&pBt->pPage1->aData[36]));
  56802. sCheck.zPfx = 0;
  56803. /* Check all the tables.
  56804. */
  56805. for(i=0; (int)i<nRoot && sCheck.mxErr; i++){
  56806. if( aRoot[i]==0 ) continue;
  56807. #ifndef SQLITE_OMIT_AUTOVACUUM
  56808. if( pBt->autoVacuum && aRoot[i]>1 ){
  56809. checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0);
  56810. }
  56811. #endif
  56812. sCheck.zPfx = "List of tree roots: ";
  56813. checkTreePage(&sCheck, aRoot[i], NULL, NULL);
  56814. sCheck.zPfx = 0;
  56815. }
  56816. /* Make sure every page in the file is referenced
  56817. */
  56818. for(i=1; i<=sCheck.nPage && sCheck.mxErr; i++){
  56819. #ifdef SQLITE_OMIT_AUTOVACUUM
  56820. if( getPageReferenced(&sCheck, i)==0 ){
  56821. checkAppendMsg(&sCheck, "Page %d is never used", i);
  56822. }
  56823. #else
  56824. /* If the database supports auto-vacuum, make sure no tables contain
  56825. ** references to pointer-map pages.
  56826. */
  56827. if( getPageReferenced(&sCheck, i)==0 &&
  56828. (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){
  56829. checkAppendMsg(&sCheck, "Page %d is never used", i);
  56830. }
  56831. if( getPageReferenced(&sCheck, i)!=0 &&
  56832. (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){
  56833. checkAppendMsg(&sCheck, "Pointer map page %d is referenced", i);
  56834. }
  56835. #endif
  56836. }
  56837. /* Make sure this analysis did not leave any unref() pages.
  56838. ** This is an internal consistency check; an integrity check
  56839. ** of the integrity check.
  56840. */
  56841. if( NEVER(nRef != sqlite3PagerRefcount(pBt->pPager)) ){
  56842. checkAppendMsg(&sCheck,
  56843. "Outstanding page count goes from %d to %d during this analysis",
  56844. nRef, sqlite3PagerRefcount(pBt->pPager)
  56845. );
  56846. }
  56847. /* Clean up and report errors.
  56848. */
  56849. sqlite3BtreeLeave(p);
  56850. sqlite3_free(sCheck.aPgRef);
  56851. if( sCheck.mallocFailed ){
  56852. sqlite3StrAccumReset(&sCheck.errMsg);
  56853. *pnErr = sCheck.nErr+1;
  56854. return 0;
  56855. }
  56856. *pnErr = sCheck.nErr;
  56857. if( sCheck.nErr==0 ) sqlite3StrAccumReset(&sCheck.errMsg);
  56858. return sqlite3StrAccumFinish(&sCheck.errMsg);
  56859. }
  56860. #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  56861. /*
  56862. ** Return the full pathname of the underlying database file. Return
  56863. ** an empty string if the database is in-memory or a TEMP database.
  56864. **
  56865. ** The pager filename is invariant as long as the pager is
  56866. ** open so it is safe to access without the BtShared mutex.
  56867. */
  56868. SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *p){
  56869. assert( p->pBt->pPager!=0 );
  56870. return sqlite3PagerFilename(p->pBt->pPager, 1);
  56871. }
  56872. /*
  56873. ** Return the pathname of the journal file for this database. The return
  56874. ** value of this routine is the same regardless of whether the journal file
  56875. ** has been created or not.
  56876. **
  56877. ** The pager journal filename is invariant as long as the pager is
  56878. ** open so it is safe to access without the BtShared mutex.
  56879. */
  56880. SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *p){
  56881. assert( p->pBt->pPager!=0 );
  56882. return sqlite3PagerJournalname(p->pBt->pPager);
  56883. }
  56884. /*
  56885. ** Return non-zero if a transaction is active.
  56886. */
  56887. SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree *p){
  56888. assert( p==0 || sqlite3_mutex_held(p->db->mutex) );
  56889. return (p && (p->inTrans==TRANS_WRITE));
  56890. }
  56891. #ifndef SQLITE_OMIT_WAL
  56892. /*
  56893. ** Run a checkpoint on the Btree passed as the first argument.
  56894. **
  56895. ** Return SQLITE_LOCKED if this or any other connection has an open
  56896. ** transaction on the shared-cache the argument Btree is connected to.
  56897. **
  56898. ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
  56899. */
  56900. SQLITE_PRIVATE int sqlite3BtreeCheckpoint(Btree *p, int eMode, int *pnLog, int *pnCkpt){
  56901. int rc = SQLITE_OK;
  56902. if( p ){
  56903. BtShared *pBt = p->pBt;
  56904. sqlite3BtreeEnter(p);
  56905. if( pBt->inTransaction!=TRANS_NONE ){
  56906. rc = SQLITE_LOCKED;
  56907. }else{
  56908. rc = sqlite3PagerCheckpoint(pBt->pPager, eMode, pnLog, pnCkpt);
  56909. }
  56910. sqlite3BtreeLeave(p);
  56911. }
  56912. return rc;
  56913. }
  56914. #endif
  56915. /*
  56916. ** Return non-zero if a read (or write) transaction is active.
  56917. */
  56918. SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree *p){
  56919. assert( p );
  56920. assert( sqlite3_mutex_held(p->db->mutex) );
  56921. return p->inTrans!=TRANS_NONE;
  56922. }
  56923. SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree *p){
  56924. assert( p );
  56925. assert( sqlite3_mutex_held(p->db->mutex) );
  56926. return p->nBackup!=0;
  56927. }
  56928. /*
  56929. ** This function returns a pointer to a blob of memory associated with
  56930. ** a single shared-btree. The memory is used by client code for its own
  56931. ** purposes (for example, to store a high-level schema associated with
  56932. ** the shared-btree). The btree layer manages reference counting issues.
  56933. **
  56934. ** The first time this is called on a shared-btree, nBytes bytes of memory
  56935. ** are allocated, zeroed, and returned to the caller. For each subsequent
  56936. ** call the nBytes parameter is ignored and a pointer to the same blob
  56937. ** of memory returned.
  56938. **
  56939. ** If the nBytes parameter is 0 and the blob of memory has not yet been
  56940. ** allocated, a null pointer is returned. If the blob has already been
  56941. ** allocated, it is returned as normal.
  56942. **
  56943. ** Just before the shared-btree is closed, the function passed as the
  56944. ** xFree argument when the memory allocation was made is invoked on the
  56945. ** blob of allocated memory. The xFree function should not call sqlite3_free()
  56946. ** on the memory, the btree layer does that.
  56947. */
  56948. SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){
  56949. BtShared *pBt = p->pBt;
  56950. sqlite3BtreeEnter(p);
  56951. if( !pBt->pSchema && nBytes ){
  56952. pBt->pSchema = sqlite3DbMallocZero(0, nBytes);
  56953. pBt->xFreeSchema = xFree;
  56954. }
  56955. sqlite3BtreeLeave(p);
  56956. return pBt->pSchema;
  56957. }
  56958. /*
  56959. ** Return SQLITE_LOCKED_SHAREDCACHE if another user of the same shared
  56960. ** btree as the argument handle holds an exclusive lock on the
  56961. ** sqlite_master table. Otherwise SQLITE_OK.
  56962. */
  56963. SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *p){
  56964. int rc;
  56965. assert( sqlite3_mutex_held(p->db->mutex) );
  56966. sqlite3BtreeEnter(p);
  56967. rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
  56968. assert( rc==SQLITE_OK || rc==SQLITE_LOCKED_SHAREDCACHE );
  56969. sqlite3BtreeLeave(p);
  56970. return rc;
  56971. }
  56972. #ifndef SQLITE_OMIT_SHARED_CACHE
  56973. /*
  56974. ** Obtain a lock on the table whose root page is iTab. The
  56975. ** lock is a write lock if isWritelock is true or a read lock
  56976. ** if it is false.
  56977. */
  56978. SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){
  56979. int rc = SQLITE_OK;
  56980. assert( p->inTrans!=TRANS_NONE );
  56981. if( p->sharable ){
  56982. u8 lockType = READ_LOCK + isWriteLock;
  56983. assert( READ_LOCK+1==WRITE_LOCK );
  56984. assert( isWriteLock==0 || isWriteLock==1 );
  56985. sqlite3BtreeEnter(p);
  56986. rc = querySharedCacheTableLock(p, iTab, lockType);
  56987. if( rc==SQLITE_OK ){
  56988. rc = setSharedCacheTableLock(p, iTab, lockType);
  56989. }
  56990. sqlite3BtreeLeave(p);
  56991. }
  56992. return rc;
  56993. }
  56994. #endif
  56995. #ifndef SQLITE_OMIT_INCRBLOB
  56996. /*
  56997. ** Argument pCsr must be a cursor opened for writing on an
  56998. ** INTKEY table currently pointing at a valid table entry.
  56999. ** This function modifies the data stored as part of that entry.
  57000. **
  57001. ** Only the data content may only be modified, it is not possible to
  57002. ** change the length of the data stored. If this function is called with
  57003. ** parameters that attempt to write past the end of the existing data,
  57004. ** no modifications are made and SQLITE_CORRUPT is returned.
  57005. */
  57006. SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){
  57007. int rc;
  57008. assert( cursorHoldsMutex(pCsr) );
  57009. assert( sqlite3_mutex_held(pCsr->pBtree->db->mutex) );
  57010. assert( pCsr->curFlags & BTCF_Incrblob );
  57011. rc = restoreCursorPosition(pCsr);
  57012. if( rc!=SQLITE_OK ){
  57013. return rc;
  57014. }
  57015. assert( pCsr->eState!=CURSOR_REQUIRESEEK );
  57016. if( pCsr->eState!=CURSOR_VALID ){
  57017. return SQLITE_ABORT;
  57018. }
  57019. /* Save the positions of all other cursors open on this table. This is
  57020. ** required in case any of them are holding references to an xFetch
  57021. ** version of the b-tree page modified by the accessPayload call below.
  57022. **
  57023. ** Note that pCsr must be open on a INTKEY table and saveCursorPosition()
  57024. ** and hence saveAllCursors() cannot fail on a BTREE_INTKEY table, hence
  57025. ** saveAllCursors can only return SQLITE_OK.
  57026. */
  57027. VVA_ONLY(rc =) saveAllCursors(pCsr->pBt, pCsr->pgnoRoot, pCsr);
  57028. assert( rc==SQLITE_OK );
  57029. /* Check some assumptions:
  57030. ** (a) the cursor is open for writing,
  57031. ** (b) there is a read/write transaction open,
  57032. ** (c) the connection holds a write-lock on the table (if required),
  57033. ** (d) there are no conflicting read-locks, and
  57034. ** (e) the cursor points at a valid row of an intKey table.
  57035. */
  57036. if( (pCsr->curFlags & BTCF_WriteFlag)==0 ){
  57037. return SQLITE_READONLY;
  57038. }
  57039. assert( (pCsr->pBt->btsFlags & BTS_READ_ONLY)==0
  57040. && pCsr->pBt->inTransaction==TRANS_WRITE );
  57041. assert( hasSharedCacheTableLock(pCsr->pBtree, pCsr->pgnoRoot, 0, 2) );
  57042. assert( !hasReadConflicts(pCsr->pBtree, pCsr->pgnoRoot) );
  57043. assert( pCsr->apPage[pCsr->iPage]->intKey );
  57044. return accessPayload(pCsr, offset, amt, (unsigned char *)z, 1);
  57045. }
  57046. /*
  57047. ** Mark this cursor as an incremental blob cursor.
  57048. */
  57049. SQLITE_PRIVATE void sqlite3BtreeIncrblobCursor(BtCursor *pCur){
  57050. pCur->curFlags |= BTCF_Incrblob;
  57051. }
  57052. #endif
  57053. /*
  57054. ** Set both the "read version" (single byte at byte offset 18) and
  57055. ** "write version" (single byte at byte offset 19) fields in the database
  57056. ** header to iVersion.
  57057. */
  57058. SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBtree, int iVersion){
  57059. BtShared *pBt = pBtree->pBt;
  57060. int rc; /* Return code */
  57061. assert( iVersion==1 || iVersion==2 );
  57062. /* If setting the version fields to 1, do not automatically open the
  57063. ** WAL connection, even if the version fields are currently set to 2.
  57064. */
  57065. pBt->btsFlags &= ~BTS_NO_WAL;
  57066. if( iVersion==1 ) pBt->btsFlags |= BTS_NO_WAL;
  57067. rc = sqlite3BtreeBeginTrans(pBtree, 0);
  57068. if( rc==SQLITE_OK ){
  57069. u8 *aData = pBt->pPage1->aData;
  57070. if( aData[18]!=(u8)iVersion || aData[19]!=(u8)iVersion ){
  57071. rc = sqlite3BtreeBeginTrans(pBtree, 2);
  57072. if( rc==SQLITE_OK ){
  57073. rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
  57074. if( rc==SQLITE_OK ){
  57075. aData[18] = (u8)iVersion;
  57076. aData[19] = (u8)iVersion;
  57077. }
  57078. }
  57079. }
  57080. }
  57081. pBt->btsFlags &= ~BTS_NO_WAL;
  57082. return rc;
  57083. }
  57084. /*
  57085. ** set the mask of hint flags for cursor pCsr. Currently the only valid
  57086. ** values are 0 and BTREE_BULKLOAD.
  57087. */
  57088. SQLITE_PRIVATE void sqlite3BtreeCursorHints(BtCursor *pCsr, unsigned int mask){
  57089. assert( mask==BTREE_BULKLOAD || mask==0 );
  57090. pCsr->hints = mask;
  57091. }
  57092. /*
  57093. ** Return true if the given Btree is read-only.
  57094. */
  57095. SQLITE_PRIVATE int sqlite3BtreeIsReadonly(Btree *p){
  57096. return (p->pBt->btsFlags & BTS_READ_ONLY)!=0;
  57097. }
  57098. /************** End of btree.c ***********************************************/
  57099. /************** Begin file backup.c ******************************************/
  57100. /*
  57101. ** 2009 January 28
  57102. **
  57103. ** The author disclaims copyright to this source code. In place of
  57104. ** a legal notice, here is a blessing:
  57105. **
  57106. ** May you do good and not evil.
  57107. ** May you find forgiveness for yourself and forgive others.
  57108. ** May you share freely, never taking more than you give.
  57109. **
  57110. *************************************************************************
  57111. ** This file contains the implementation of the sqlite3_backup_XXX()
  57112. ** API functions and the related features.
  57113. */
  57114. /*
  57115. ** Structure allocated for each backup operation.
  57116. */
  57117. struct sqlite3_backup {
  57118. sqlite3* pDestDb; /* Destination database handle */
  57119. Btree *pDest; /* Destination b-tree file */
  57120. u32 iDestSchema; /* Original schema cookie in destination */
  57121. int bDestLocked; /* True once a write-transaction is open on pDest */
  57122. Pgno iNext; /* Page number of the next source page to copy */
  57123. sqlite3* pSrcDb; /* Source database handle */
  57124. Btree *pSrc; /* Source b-tree file */
  57125. int rc; /* Backup process error code */
  57126. /* These two variables are set by every call to backup_step(). They are
  57127. ** read by calls to backup_remaining() and backup_pagecount().
  57128. */
  57129. Pgno nRemaining; /* Number of pages left to copy */
  57130. Pgno nPagecount; /* Total number of pages to copy */
  57131. int isAttached; /* True once backup has been registered with pager */
  57132. sqlite3_backup *pNext; /* Next backup associated with source pager */
  57133. };
  57134. /*
  57135. ** THREAD SAFETY NOTES:
  57136. **
  57137. ** Once it has been created using backup_init(), a single sqlite3_backup
  57138. ** structure may be accessed via two groups of thread-safe entry points:
  57139. **
  57140. ** * Via the sqlite3_backup_XXX() API function backup_step() and
  57141. ** backup_finish(). Both these functions obtain the source database
  57142. ** handle mutex and the mutex associated with the source BtShared
  57143. ** structure, in that order.
  57144. **
  57145. ** * Via the BackupUpdate() and BackupRestart() functions, which are
  57146. ** invoked by the pager layer to report various state changes in
  57147. ** the page cache associated with the source database. The mutex
  57148. ** associated with the source database BtShared structure will always
  57149. ** be held when either of these functions are invoked.
  57150. **
  57151. ** The other sqlite3_backup_XXX() API functions, backup_remaining() and
  57152. ** backup_pagecount() are not thread-safe functions. If they are called
  57153. ** while some other thread is calling backup_step() or backup_finish(),
  57154. ** the values returned may be invalid. There is no way for a call to
  57155. ** BackupUpdate() or BackupRestart() to interfere with backup_remaining()
  57156. ** or backup_pagecount().
  57157. **
  57158. ** Depending on the SQLite configuration, the database handles and/or
  57159. ** the Btree objects may have their own mutexes that require locking.
  57160. ** Non-sharable Btrees (in-memory databases for example), do not have
  57161. ** associated mutexes.
  57162. */
  57163. /*
  57164. ** Return a pointer corresponding to database zDb (i.e. "main", "temp")
  57165. ** in connection handle pDb. If such a database cannot be found, return
  57166. ** a NULL pointer and write an error message to pErrorDb.
  57167. **
  57168. ** If the "temp" database is requested, it may need to be opened by this
  57169. ** function. If an error occurs while doing so, return 0 and write an
  57170. ** error message to pErrorDb.
  57171. */
  57172. static Btree *findBtree(sqlite3 *pErrorDb, sqlite3 *pDb, const char *zDb){
  57173. int i = sqlite3FindDbName(pDb, zDb);
  57174. if( i==1 ){
  57175. Parse *pParse;
  57176. int rc = 0;
  57177. pParse = sqlite3StackAllocZero(pErrorDb, sizeof(*pParse));
  57178. if( pParse==0 ){
  57179. sqlite3ErrorWithMsg(pErrorDb, SQLITE_NOMEM, "out of memory");
  57180. rc = SQLITE_NOMEM;
  57181. }else{
  57182. pParse->db = pDb;
  57183. if( sqlite3OpenTempDatabase(pParse) ){
  57184. sqlite3ErrorWithMsg(pErrorDb, pParse->rc, "%s", pParse->zErrMsg);
  57185. rc = SQLITE_ERROR;
  57186. }
  57187. sqlite3DbFree(pErrorDb, pParse->zErrMsg);
  57188. sqlite3ParserReset(pParse);
  57189. sqlite3StackFree(pErrorDb, pParse);
  57190. }
  57191. if( rc ){
  57192. return 0;
  57193. }
  57194. }
  57195. if( i<0 ){
  57196. sqlite3ErrorWithMsg(pErrorDb, SQLITE_ERROR, "unknown database %s", zDb);
  57197. return 0;
  57198. }
  57199. return pDb->aDb[i].pBt;
  57200. }
  57201. /*
  57202. ** Attempt to set the page size of the destination to match the page size
  57203. ** of the source.
  57204. */
  57205. static int setDestPgsz(sqlite3_backup *p){
  57206. int rc;
  57207. rc = sqlite3BtreeSetPageSize(p->pDest,sqlite3BtreeGetPageSize(p->pSrc),-1,0);
  57208. return rc;
  57209. }
  57210. /*
  57211. ** Create an sqlite3_backup process to copy the contents of zSrcDb from
  57212. ** connection handle pSrcDb to zDestDb in pDestDb. If successful, return
  57213. ** a pointer to the new sqlite3_backup object.
  57214. **
  57215. ** If an error occurs, NULL is returned and an error code and error message
  57216. ** stored in database handle pDestDb.
  57217. */
  57218. SQLITE_API sqlite3_backup *sqlite3_backup_init(
  57219. sqlite3* pDestDb, /* Database to write to */
  57220. const char *zDestDb, /* Name of database within pDestDb */
  57221. sqlite3* pSrcDb, /* Database connection to read from */
  57222. const char *zSrcDb /* Name of database within pSrcDb */
  57223. ){
  57224. sqlite3_backup *p; /* Value to return */
  57225. #ifdef SQLITE_ENABLE_API_ARMOR
  57226. if( !sqlite3SafetyCheckOk(pSrcDb)||!sqlite3SafetyCheckOk(pDestDb) ){
  57227. (void)SQLITE_MISUSE_BKPT;
  57228. return 0;
  57229. }
  57230. #endif
  57231. /* Lock the source database handle. The destination database
  57232. ** handle is not locked in this routine, but it is locked in
  57233. ** sqlite3_backup_step(). The user is required to ensure that no
  57234. ** other thread accesses the destination handle for the duration
  57235. ** of the backup operation. Any attempt to use the destination
  57236. ** database connection while a backup is in progress may cause
  57237. ** a malfunction or a deadlock.
  57238. */
  57239. sqlite3_mutex_enter(pSrcDb->mutex);
  57240. sqlite3_mutex_enter(pDestDb->mutex);
  57241. if( pSrcDb==pDestDb ){
  57242. sqlite3ErrorWithMsg(
  57243. pDestDb, SQLITE_ERROR, "source and destination must be distinct"
  57244. );
  57245. p = 0;
  57246. }else {
  57247. /* Allocate space for a new sqlite3_backup object...
  57248. ** EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
  57249. ** call to sqlite3_backup_init() and is destroyed by a call to
  57250. ** sqlite3_backup_finish(). */
  57251. p = (sqlite3_backup *)sqlite3MallocZero(sizeof(sqlite3_backup));
  57252. if( !p ){
  57253. sqlite3Error(pDestDb, SQLITE_NOMEM);
  57254. }
  57255. }
  57256. /* If the allocation succeeded, populate the new object. */
  57257. if( p ){
  57258. p->pSrc = findBtree(pDestDb, pSrcDb, zSrcDb);
  57259. p->pDest = findBtree(pDestDb, pDestDb, zDestDb);
  57260. p->pDestDb = pDestDb;
  57261. p->pSrcDb = pSrcDb;
  57262. p->iNext = 1;
  57263. p->isAttached = 0;
  57264. if( 0==p->pSrc || 0==p->pDest || setDestPgsz(p)==SQLITE_NOMEM ){
  57265. /* One (or both) of the named databases did not exist or an OOM
  57266. ** error was hit. The error has already been written into the
  57267. ** pDestDb handle. All that is left to do here is free the
  57268. ** sqlite3_backup structure.
  57269. */
  57270. sqlite3_free(p);
  57271. p = 0;
  57272. }
  57273. }
  57274. if( p ){
  57275. p->pSrc->nBackup++;
  57276. }
  57277. sqlite3_mutex_leave(pDestDb->mutex);
  57278. sqlite3_mutex_leave(pSrcDb->mutex);
  57279. return p;
  57280. }
  57281. /*
  57282. ** Argument rc is an SQLite error code. Return true if this error is
  57283. ** considered fatal if encountered during a backup operation. All errors
  57284. ** are considered fatal except for SQLITE_BUSY and SQLITE_LOCKED.
  57285. */
  57286. static int isFatalError(int rc){
  57287. return (rc!=SQLITE_OK && rc!=SQLITE_BUSY && ALWAYS(rc!=SQLITE_LOCKED));
  57288. }
  57289. /*
  57290. ** Parameter zSrcData points to a buffer containing the data for
  57291. ** page iSrcPg from the source database. Copy this data into the
  57292. ** destination database.
  57293. */
  57294. static int backupOnePage(
  57295. sqlite3_backup *p, /* Backup handle */
  57296. Pgno iSrcPg, /* Source database page to backup */
  57297. const u8 *zSrcData, /* Source database page data */
  57298. int bUpdate /* True for an update, false otherwise */
  57299. ){
  57300. Pager * const pDestPager = sqlite3BtreePager(p->pDest);
  57301. const int nSrcPgsz = sqlite3BtreeGetPageSize(p->pSrc);
  57302. int nDestPgsz = sqlite3BtreeGetPageSize(p->pDest);
  57303. const int nCopy = MIN(nSrcPgsz, nDestPgsz);
  57304. const i64 iEnd = (i64)iSrcPg*(i64)nSrcPgsz;
  57305. #ifdef SQLITE_HAS_CODEC
  57306. /* Use BtreeGetReserveNoMutex() for the source b-tree, as although it is
  57307. ** guaranteed that the shared-mutex is held by this thread, handle
  57308. ** p->pSrc may not actually be the owner. */
  57309. int nSrcReserve = sqlite3BtreeGetReserveNoMutex(p->pSrc);
  57310. int nDestReserve = sqlite3BtreeGetReserve(p->pDest);
  57311. #endif
  57312. int rc = SQLITE_OK;
  57313. i64 iOff;
  57314. assert( sqlite3BtreeGetReserveNoMutex(p->pSrc)>=0 );
  57315. assert( p->bDestLocked );
  57316. assert( !isFatalError(p->rc) );
  57317. assert( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) );
  57318. assert( zSrcData );
  57319. /* Catch the case where the destination is an in-memory database and the
  57320. ** page sizes of the source and destination differ.
  57321. */
  57322. if( nSrcPgsz!=nDestPgsz && sqlite3PagerIsMemdb(pDestPager) ){
  57323. rc = SQLITE_READONLY;
  57324. }
  57325. #ifdef SQLITE_HAS_CODEC
  57326. /* Backup is not possible if the page size of the destination is changing
  57327. ** and a codec is in use.
  57328. */
  57329. if( nSrcPgsz!=nDestPgsz && sqlite3PagerGetCodec(pDestPager)!=0 ){
  57330. rc = SQLITE_READONLY;
  57331. }
  57332. /* Backup is not possible if the number of bytes of reserve space differ
  57333. ** between source and destination. If there is a difference, try to
  57334. ** fix the destination to agree with the source. If that is not possible,
  57335. ** then the backup cannot proceed.
  57336. */
  57337. if( nSrcReserve!=nDestReserve ){
  57338. u32 newPgsz = nSrcPgsz;
  57339. rc = sqlite3PagerSetPagesize(pDestPager, &newPgsz, nSrcReserve);
  57340. if( rc==SQLITE_OK && newPgsz!=nSrcPgsz ) rc = SQLITE_READONLY;
  57341. }
  57342. #endif
  57343. /* This loop runs once for each destination page spanned by the source
  57344. ** page. For each iteration, variable iOff is set to the byte offset
  57345. ** of the destination page.
  57346. */
  57347. for(iOff=iEnd-(i64)nSrcPgsz; rc==SQLITE_OK && iOff<iEnd; iOff+=nDestPgsz){
  57348. DbPage *pDestPg = 0;
  57349. Pgno iDest = (Pgno)(iOff/nDestPgsz)+1;
  57350. if( iDest==PENDING_BYTE_PAGE(p->pDest->pBt) ) continue;
  57351. if( SQLITE_OK==(rc = sqlite3PagerGet(pDestPager, iDest, &pDestPg))
  57352. && SQLITE_OK==(rc = sqlite3PagerWrite(pDestPg))
  57353. ){
  57354. const u8 *zIn = &zSrcData[iOff%nSrcPgsz];
  57355. u8 *zDestData = sqlite3PagerGetData(pDestPg);
  57356. u8 *zOut = &zDestData[iOff%nDestPgsz];
  57357. /* Copy the data from the source page into the destination page.
  57358. ** Then clear the Btree layer MemPage.isInit flag. Both this module
  57359. ** and the pager code use this trick (clearing the first byte
  57360. ** of the page 'extra' space to invalidate the Btree layers
  57361. ** cached parse of the page). MemPage.isInit is marked
  57362. ** "MUST BE FIRST" for this purpose.
  57363. */
  57364. memcpy(zOut, zIn, nCopy);
  57365. ((u8 *)sqlite3PagerGetExtra(pDestPg))[0] = 0;
  57366. if( iOff==0 && bUpdate==0 ){
  57367. sqlite3Put4byte(&zOut[28], sqlite3BtreeLastPage(p->pSrc));
  57368. }
  57369. }
  57370. sqlite3PagerUnref(pDestPg);
  57371. }
  57372. return rc;
  57373. }
  57374. /*
  57375. ** If pFile is currently larger than iSize bytes, then truncate it to
  57376. ** exactly iSize bytes. If pFile is not larger than iSize bytes, then
  57377. ** this function is a no-op.
  57378. **
  57379. ** Return SQLITE_OK if everything is successful, or an SQLite error
  57380. ** code if an error occurs.
  57381. */
  57382. static int backupTruncateFile(sqlite3_file *pFile, i64 iSize){
  57383. i64 iCurrent;
  57384. int rc = sqlite3OsFileSize(pFile, &iCurrent);
  57385. if( rc==SQLITE_OK && iCurrent>iSize ){
  57386. rc = sqlite3OsTruncate(pFile, iSize);
  57387. }
  57388. return rc;
  57389. }
  57390. /*
  57391. ** Register this backup object with the associated source pager for
  57392. ** callbacks when pages are changed or the cache invalidated.
  57393. */
  57394. static void attachBackupObject(sqlite3_backup *p){
  57395. sqlite3_backup **pp;
  57396. assert( sqlite3BtreeHoldsMutex(p->pSrc) );
  57397. pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
  57398. p->pNext = *pp;
  57399. *pp = p;
  57400. p->isAttached = 1;
  57401. }
  57402. /*
  57403. ** Copy nPage pages from the source b-tree to the destination.
  57404. */
  57405. SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage){
  57406. int rc;
  57407. int destMode; /* Destination journal mode */
  57408. int pgszSrc = 0; /* Source page size */
  57409. int pgszDest = 0; /* Destination page size */
  57410. #ifdef SQLITE_ENABLE_API_ARMOR
  57411. if( p==0 ) return SQLITE_MISUSE_BKPT;
  57412. #endif
  57413. sqlite3_mutex_enter(p->pSrcDb->mutex);
  57414. sqlite3BtreeEnter(p->pSrc);
  57415. if( p->pDestDb ){
  57416. sqlite3_mutex_enter(p->pDestDb->mutex);
  57417. }
  57418. rc = p->rc;
  57419. if( !isFatalError(rc) ){
  57420. Pager * const pSrcPager = sqlite3BtreePager(p->pSrc); /* Source pager */
  57421. Pager * const pDestPager = sqlite3BtreePager(p->pDest); /* Dest pager */
  57422. int ii; /* Iterator variable */
  57423. int nSrcPage = -1; /* Size of source db in pages */
  57424. int bCloseTrans = 0; /* True if src db requires unlocking */
  57425. /* If the source pager is currently in a write-transaction, return
  57426. ** SQLITE_BUSY immediately.
  57427. */
  57428. if( p->pDestDb && p->pSrc->pBt->inTransaction==TRANS_WRITE ){
  57429. rc = SQLITE_BUSY;
  57430. }else{
  57431. rc = SQLITE_OK;
  57432. }
  57433. /* Lock the destination database, if it is not locked already. */
  57434. if( SQLITE_OK==rc && p->bDestLocked==0
  57435. && SQLITE_OK==(rc = sqlite3BtreeBeginTrans(p->pDest, 2))
  57436. ){
  57437. p->bDestLocked = 1;
  57438. sqlite3BtreeGetMeta(p->pDest, BTREE_SCHEMA_VERSION, &p->iDestSchema);
  57439. }
  57440. /* If there is no open read-transaction on the source database, open
  57441. ** one now. If a transaction is opened here, then it will be closed
  57442. ** before this function exits.
  57443. */
  57444. if( rc==SQLITE_OK && 0==sqlite3BtreeIsInReadTrans(p->pSrc) ){
  57445. rc = sqlite3BtreeBeginTrans(p->pSrc, 0);
  57446. bCloseTrans = 1;
  57447. }
  57448. /* Do not allow backup if the destination database is in WAL mode
  57449. ** and the page sizes are different between source and destination */
  57450. pgszSrc = sqlite3BtreeGetPageSize(p->pSrc);
  57451. pgszDest = sqlite3BtreeGetPageSize(p->pDest);
  57452. destMode = sqlite3PagerGetJournalMode(sqlite3BtreePager(p->pDest));
  57453. if( SQLITE_OK==rc && destMode==PAGER_JOURNALMODE_WAL && pgszSrc!=pgszDest ){
  57454. rc = SQLITE_READONLY;
  57455. }
  57456. /* Now that there is a read-lock on the source database, query the
  57457. ** source pager for the number of pages in the database.
  57458. */
  57459. nSrcPage = (int)sqlite3BtreeLastPage(p->pSrc);
  57460. assert( nSrcPage>=0 );
  57461. for(ii=0; (nPage<0 || ii<nPage) && p->iNext<=(Pgno)nSrcPage && !rc; ii++){
  57462. const Pgno iSrcPg = p->iNext; /* Source page number */
  57463. if( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) ){
  57464. DbPage *pSrcPg; /* Source page object */
  57465. rc = sqlite3PagerAcquire(pSrcPager, iSrcPg, &pSrcPg,
  57466. PAGER_GET_READONLY);
  57467. if( rc==SQLITE_OK ){
  57468. rc = backupOnePage(p, iSrcPg, sqlite3PagerGetData(pSrcPg), 0);
  57469. sqlite3PagerUnref(pSrcPg);
  57470. }
  57471. }
  57472. p->iNext++;
  57473. }
  57474. if( rc==SQLITE_OK ){
  57475. p->nPagecount = nSrcPage;
  57476. p->nRemaining = nSrcPage+1-p->iNext;
  57477. if( p->iNext>(Pgno)nSrcPage ){
  57478. rc = SQLITE_DONE;
  57479. }else if( !p->isAttached ){
  57480. attachBackupObject(p);
  57481. }
  57482. }
  57483. /* Update the schema version field in the destination database. This
  57484. ** is to make sure that the schema-version really does change in
  57485. ** the case where the source and destination databases have the
  57486. ** same schema version.
  57487. */
  57488. if( rc==SQLITE_DONE ){
  57489. if( nSrcPage==0 ){
  57490. rc = sqlite3BtreeNewDb(p->pDest);
  57491. nSrcPage = 1;
  57492. }
  57493. if( rc==SQLITE_OK || rc==SQLITE_DONE ){
  57494. rc = sqlite3BtreeUpdateMeta(p->pDest,1,p->iDestSchema+1);
  57495. }
  57496. if( rc==SQLITE_OK ){
  57497. if( p->pDestDb ){
  57498. sqlite3ResetAllSchemasOfConnection(p->pDestDb);
  57499. }
  57500. if( destMode==PAGER_JOURNALMODE_WAL ){
  57501. rc = sqlite3BtreeSetVersion(p->pDest, 2);
  57502. }
  57503. }
  57504. if( rc==SQLITE_OK ){
  57505. int nDestTruncate;
  57506. /* Set nDestTruncate to the final number of pages in the destination
  57507. ** database. The complication here is that the destination page
  57508. ** size may be different to the source page size.
  57509. **
  57510. ** If the source page size is smaller than the destination page size,
  57511. ** round up. In this case the call to sqlite3OsTruncate() below will
  57512. ** fix the size of the file. However it is important to call
  57513. ** sqlite3PagerTruncateImage() here so that any pages in the
  57514. ** destination file that lie beyond the nDestTruncate page mark are
  57515. ** journalled by PagerCommitPhaseOne() before they are destroyed
  57516. ** by the file truncation.
  57517. */
  57518. assert( pgszSrc==sqlite3BtreeGetPageSize(p->pSrc) );
  57519. assert( pgszDest==sqlite3BtreeGetPageSize(p->pDest) );
  57520. if( pgszSrc<pgszDest ){
  57521. int ratio = pgszDest/pgszSrc;
  57522. nDestTruncate = (nSrcPage+ratio-1)/ratio;
  57523. if( nDestTruncate==(int)PENDING_BYTE_PAGE(p->pDest->pBt) ){
  57524. nDestTruncate--;
  57525. }
  57526. }else{
  57527. nDestTruncate = nSrcPage * (pgszSrc/pgszDest);
  57528. }
  57529. assert( nDestTruncate>0 );
  57530. if( pgszSrc<pgszDest ){
  57531. /* If the source page-size is smaller than the destination page-size,
  57532. ** two extra things may need to happen:
  57533. **
  57534. ** * The destination may need to be truncated, and
  57535. **
  57536. ** * Data stored on the pages immediately following the
  57537. ** pending-byte page in the source database may need to be
  57538. ** copied into the destination database.
  57539. */
  57540. const i64 iSize = (i64)pgszSrc * (i64)nSrcPage;
  57541. sqlite3_file * const pFile = sqlite3PagerFile(pDestPager);
  57542. Pgno iPg;
  57543. int nDstPage;
  57544. i64 iOff;
  57545. i64 iEnd;
  57546. assert( pFile );
  57547. assert( nDestTruncate==0
  57548. || (i64)nDestTruncate*(i64)pgszDest >= iSize || (
  57549. nDestTruncate==(int)(PENDING_BYTE_PAGE(p->pDest->pBt)-1)
  57550. && iSize>=PENDING_BYTE && iSize<=PENDING_BYTE+pgszDest
  57551. ));
  57552. /* This block ensures that all data required to recreate the original
  57553. ** database has been stored in the journal for pDestPager and the
  57554. ** journal synced to disk. So at this point we may safely modify
  57555. ** the database file in any way, knowing that if a power failure
  57556. ** occurs, the original database will be reconstructed from the
  57557. ** journal file. */
  57558. sqlite3PagerPagecount(pDestPager, &nDstPage);
  57559. for(iPg=nDestTruncate; rc==SQLITE_OK && iPg<=(Pgno)nDstPage; iPg++){
  57560. if( iPg!=PENDING_BYTE_PAGE(p->pDest->pBt) ){
  57561. DbPage *pPg;
  57562. rc = sqlite3PagerGet(pDestPager, iPg, &pPg);
  57563. if( rc==SQLITE_OK ){
  57564. rc = sqlite3PagerWrite(pPg);
  57565. sqlite3PagerUnref(pPg);
  57566. }
  57567. }
  57568. }
  57569. if( rc==SQLITE_OK ){
  57570. rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 1);
  57571. }
  57572. /* Write the extra pages and truncate the database file as required */
  57573. iEnd = MIN(PENDING_BYTE + pgszDest, iSize);
  57574. for(
  57575. iOff=PENDING_BYTE+pgszSrc;
  57576. rc==SQLITE_OK && iOff<iEnd;
  57577. iOff+=pgszSrc
  57578. ){
  57579. PgHdr *pSrcPg = 0;
  57580. const Pgno iSrcPg = (Pgno)((iOff/pgszSrc)+1);
  57581. rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg);
  57582. if( rc==SQLITE_OK ){
  57583. u8 *zData = sqlite3PagerGetData(pSrcPg);
  57584. rc = sqlite3OsWrite(pFile, zData, pgszSrc, iOff);
  57585. }
  57586. sqlite3PagerUnref(pSrcPg);
  57587. }
  57588. if( rc==SQLITE_OK ){
  57589. rc = backupTruncateFile(pFile, iSize);
  57590. }
  57591. /* Sync the database file to disk. */
  57592. if( rc==SQLITE_OK ){
  57593. rc = sqlite3PagerSync(pDestPager, 0);
  57594. }
  57595. }else{
  57596. sqlite3PagerTruncateImage(pDestPager, nDestTruncate);
  57597. rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 0);
  57598. }
  57599. /* Finish committing the transaction to the destination database. */
  57600. if( SQLITE_OK==rc
  57601. && SQLITE_OK==(rc = sqlite3BtreeCommitPhaseTwo(p->pDest, 0))
  57602. ){
  57603. rc = SQLITE_DONE;
  57604. }
  57605. }
  57606. }
  57607. /* If bCloseTrans is true, then this function opened a read transaction
  57608. ** on the source database. Close the read transaction here. There is
  57609. ** no need to check the return values of the btree methods here, as
  57610. ** "committing" a read-only transaction cannot fail.
  57611. */
  57612. if( bCloseTrans ){
  57613. TESTONLY( int rc2 );
  57614. TESTONLY( rc2 = ) sqlite3BtreeCommitPhaseOne(p->pSrc, 0);
  57615. TESTONLY( rc2 |= ) sqlite3BtreeCommitPhaseTwo(p->pSrc, 0);
  57616. assert( rc2==SQLITE_OK );
  57617. }
  57618. if( rc==SQLITE_IOERR_NOMEM ){
  57619. rc = SQLITE_NOMEM;
  57620. }
  57621. p->rc = rc;
  57622. }
  57623. if( p->pDestDb ){
  57624. sqlite3_mutex_leave(p->pDestDb->mutex);
  57625. }
  57626. sqlite3BtreeLeave(p->pSrc);
  57627. sqlite3_mutex_leave(p->pSrcDb->mutex);
  57628. return rc;
  57629. }
  57630. /*
  57631. ** Release all resources associated with an sqlite3_backup* handle.
  57632. */
  57633. SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p){
  57634. sqlite3_backup **pp; /* Ptr to head of pagers backup list */
  57635. sqlite3 *pSrcDb; /* Source database connection */
  57636. int rc; /* Value to return */
  57637. /* Enter the mutexes */
  57638. if( p==0 ) return SQLITE_OK;
  57639. pSrcDb = p->pSrcDb;
  57640. sqlite3_mutex_enter(pSrcDb->mutex);
  57641. sqlite3BtreeEnter(p->pSrc);
  57642. if( p->pDestDb ){
  57643. sqlite3_mutex_enter(p->pDestDb->mutex);
  57644. }
  57645. /* Detach this backup from the source pager. */
  57646. if( p->pDestDb ){
  57647. p->pSrc->nBackup--;
  57648. }
  57649. if( p->isAttached ){
  57650. pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
  57651. while( *pp!=p ){
  57652. pp = &(*pp)->pNext;
  57653. }
  57654. *pp = p->pNext;
  57655. }
  57656. /* If a transaction is still open on the Btree, roll it back. */
  57657. sqlite3BtreeRollback(p->pDest, SQLITE_OK);
  57658. /* Set the error code of the destination database handle. */
  57659. rc = (p->rc==SQLITE_DONE) ? SQLITE_OK : p->rc;
  57660. if( p->pDestDb ){
  57661. sqlite3Error(p->pDestDb, rc);
  57662. /* Exit the mutexes and free the backup context structure. */
  57663. sqlite3LeaveMutexAndCloseZombie(p->pDestDb);
  57664. }
  57665. sqlite3BtreeLeave(p->pSrc);
  57666. if( p->pDestDb ){
  57667. /* EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
  57668. ** call to sqlite3_backup_init() and is destroyed by a call to
  57669. ** sqlite3_backup_finish(). */
  57670. sqlite3_free(p);
  57671. }
  57672. sqlite3LeaveMutexAndCloseZombie(pSrcDb);
  57673. return rc;
  57674. }
  57675. /*
  57676. ** Return the number of pages still to be backed up as of the most recent
  57677. ** call to sqlite3_backup_step().
  57678. */
  57679. SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p){
  57680. #ifdef SQLITE_ENABLE_API_ARMOR
  57681. if( p==0 ){
  57682. (void)SQLITE_MISUSE_BKPT;
  57683. return 0;
  57684. }
  57685. #endif
  57686. return p->nRemaining;
  57687. }
  57688. /*
  57689. ** Return the total number of pages in the source database as of the most
  57690. ** recent call to sqlite3_backup_step().
  57691. */
  57692. SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p){
  57693. #ifdef SQLITE_ENABLE_API_ARMOR
  57694. if( p==0 ){
  57695. (void)SQLITE_MISUSE_BKPT;
  57696. return 0;
  57697. }
  57698. #endif
  57699. return p->nPagecount;
  57700. }
  57701. /*
  57702. ** This function is called after the contents of page iPage of the
  57703. ** source database have been modified. If page iPage has already been
  57704. ** copied into the destination database, then the data written to the
  57705. ** destination is now invalidated. The destination copy of iPage needs
  57706. ** to be updated with the new data before the backup operation is
  57707. ** complete.
  57708. **
  57709. ** It is assumed that the mutex associated with the BtShared object
  57710. ** corresponding to the source database is held when this function is
  57711. ** called.
  57712. */
  57713. SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *pBackup, Pgno iPage, const u8 *aData){
  57714. sqlite3_backup *p; /* Iterator variable */
  57715. for(p=pBackup; p; p=p->pNext){
  57716. assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
  57717. if( !isFatalError(p->rc) && iPage<p->iNext ){
  57718. /* The backup process p has already copied page iPage. But now it
  57719. ** has been modified by a transaction on the source pager. Copy
  57720. ** the new data into the backup.
  57721. */
  57722. int rc;
  57723. assert( p->pDestDb );
  57724. sqlite3_mutex_enter(p->pDestDb->mutex);
  57725. rc = backupOnePage(p, iPage, aData, 1);
  57726. sqlite3_mutex_leave(p->pDestDb->mutex);
  57727. assert( rc!=SQLITE_BUSY && rc!=SQLITE_LOCKED );
  57728. if( rc!=SQLITE_OK ){
  57729. p->rc = rc;
  57730. }
  57731. }
  57732. }
  57733. }
  57734. /*
  57735. ** Restart the backup process. This is called when the pager layer
  57736. ** detects that the database has been modified by an external database
  57737. ** connection. In this case there is no way of knowing which of the
  57738. ** pages that have been copied into the destination database are still
  57739. ** valid and which are not, so the entire process needs to be restarted.
  57740. **
  57741. ** It is assumed that the mutex associated with the BtShared object
  57742. ** corresponding to the source database is held when this function is
  57743. ** called.
  57744. */
  57745. SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *pBackup){
  57746. sqlite3_backup *p; /* Iterator variable */
  57747. for(p=pBackup; p; p=p->pNext){
  57748. assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
  57749. p->iNext = 1;
  57750. }
  57751. }
  57752. #ifndef SQLITE_OMIT_VACUUM
  57753. /*
  57754. ** Copy the complete content of pBtFrom into pBtTo. A transaction
  57755. ** must be active for both files.
  57756. **
  57757. ** The size of file pTo may be reduced by this operation. If anything
  57758. ** goes wrong, the transaction on pTo is rolled back. If successful, the
  57759. ** transaction is committed before returning.
  57760. */
  57761. SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *pTo, Btree *pFrom){
  57762. int rc;
  57763. sqlite3_file *pFd; /* File descriptor for database pTo */
  57764. sqlite3_backup b;
  57765. sqlite3BtreeEnter(pTo);
  57766. sqlite3BtreeEnter(pFrom);
  57767. assert( sqlite3BtreeIsInTrans(pTo) );
  57768. pFd = sqlite3PagerFile(sqlite3BtreePager(pTo));
  57769. if( pFd->pMethods ){
  57770. i64 nByte = sqlite3BtreeGetPageSize(pFrom)*(i64)sqlite3BtreeLastPage(pFrom);
  57771. rc = sqlite3OsFileControl(pFd, SQLITE_FCNTL_OVERWRITE, &nByte);
  57772. if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
  57773. if( rc ) goto copy_finished;
  57774. }
  57775. /* Set up an sqlite3_backup object. sqlite3_backup.pDestDb must be set
  57776. ** to 0. This is used by the implementations of sqlite3_backup_step()
  57777. ** and sqlite3_backup_finish() to detect that they are being called
  57778. ** from this function, not directly by the user.
  57779. */
  57780. memset(&b, 0, sizeof(b));
  57781. b.pSrcDb = pFrom->db;
  57782. b.pSrc = pFrom;
  57783. b.pDest = pTo;
  57784. b.iNext = 1;
  57785. /* 0x7FFFFFFF is the hard limit for the number of pages in a database
  57786. ** file. By passing this as the number of pages to copy to
  57787. ** sqlite3_backup_step(), we can guarantee that the copy finishes
  57788. ** within a single call (unless an error occurs). The assert() statement
  57789. ** checks this assumption - (p->rc) should be set to either SQLITE_DONE
  57790. ** or an error code.
  57791. */
  57792. sqlite3_backup_step(&b, 0x7FFFFFFF);
  57793. assert( b.rc!=SQLITE_OK );
  57794. rc = sqlite3_backup_finish(&b);
  57795. if( rc==SQLITE_OK ){
  57796. pTo->pBt->btsFlags &= ~BTS_PAGESIZE_FIXED;
  57797. }else{
  57798. sqlite3PagerClearCache(sqlite3BtreePager(b.pDest));
  57799. }
  57800. assert( sqlite3BtreeIsInTrans(pTo)==0 );
  57801. copy_finished:
  57802. sqlite3BtreeLeave(pFrom);
  57803. sqlite3BtreeLeave(pTo);
  57804. return rc;
  57805. }
  57806. #endif /* SQLITE_OMIT_VACUUM */
  57807. /************** End of backup.c **********************************************/
  57808. /************** Begin file vdbemem.c *****************************************/
  57809. /*
  57810. ** 2004 May 26
  57811. **
  57812. ** The author disclaims copyright to this source code. In place of
  57813. ** a legal notice, here is a blessing:
  57814. **
  57815. ** May you do good and not evil.
  57816. ** May you find forgiveness for yourself and forgive others.
  57817. ** May you share freely, never taking more than you give.
  57818. **
  57819. *************************************************************************
  57820. **
  57821. ** This file contains code use to manipulate "Mem" structure. A "Mem"
  57822. ** stores a single value in the VDBE. Mem is an opaque structure visible
  57823. ** only within the VDBE. Interface routines refer to a Mem using the
  57824. ** name sqlite_value
  57825. */
  57826. #ifdef SQLITE_DEBUG
  57827. /*
  57828. ** Check invariants on a Mem object.
  57829. **
  57830. ** This routine is intended for use inside of assert() statements, like
  57831. ** this: assert( sqlite3VdbeCheckMemInvariants(pMem) );
  57832. */
  57833. SQLITE_PRIVATE int sqlite3VdbeCheckMemInvariants(Mem *p){
  57834. /* If MEM_Dyn is set then Mem.xDel!=0.
  57835. ** Mem.xDel is might not be initialized if MEM_Dyn is clear.
  57836. */
  57837. assert( (p->flags & MEM_Dyn)==0 || p->xDel!=0 );
  57838. /* MEM_Dyn may only be set if Mem.szMalloc==0. In this way we
  57839. ** ensure that if Mem.szMalloc>0 then it is safe to do
  57840. ** Mem.z = Mem.zMalloc without having to check Mem.flags&MEM_Dyn.
  57841. ** That saves a few cycles in inner loops. */
  57842. assert( (p->flags & MEM_Dyn)==0 || p->szMalloc==0 );
  57843. /* Cannot be both MEM_Int and MEM_Real at the same time */
  57844. assert( (p->flags & (MEM_Int|MEM_Real))!=(MEM_Int|MEM_Real) );
  57845. /* The szMalloc field holds the correct memory allocation size */
  57846. assert( p->szMalloc==0
  57847. || p->szMalloc==sqlite3DbMallocSize(p->db,p->zMalloc) );
  57848. /* If p holds a string or blob, the Mem.z must point to exactly
  57849. ** one of the following:
  57850. **
  57851. ** (1) Memory in Mem.zMalloc and managed by the Mem object
  57852. ** (2) Memory to be freed using Mem.xDel
  57853. ** (3) An ephemeral string or blob
  57854. ** (4) A static string or blob
  57855. */
  57856. if( (p->flags & (MEM_Str|MEM_Blob)) && p->n>0 ){
  57857. assert(
  57858. ((p->szMalloc>0 && p->z==p->zMalloc)? 1 : 0) +
  57859. ((p->flags&MEM_Dyn)!=0 ? 1 : 0) +
  57860. ((p->flags&MEM_Ephem)!=0 ? 1 : 0) +
  57861. ((p->flags&MEM_Static)!=0 ? 1 : 0) == 1
  57862. );
  57863. }
  57864. return 1;
  57865. }
  57866. #endif
  57867. /*
  57868. ** If pMem is an object with a valid string representation, this routine
  57869. ** ensures the internal encoding for the string representation is
  57870. ** 'desiredEnc', one of SQLITE_UTF8, SQLITE_UTF16LE or SQLITE_UTF16BE.
  57871. **
  57872. ** If pMem is not a string object, or the encoding of the string
  57873. ** representation is already stored using the requested encoding, then this
  57874. ** routine is a no-op.
  57875. **
  57876. ** SQLITE_OK is returned if the conversion is successful (or not required).
  57877. ** SQLITE_NOMEM may be returned if a malloc() fails during conversion
  57878. ** between formats.
  57879. */
  57880. SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *pMem, int desiredEnc){
  57881. #ifndef SQLITE_OMIT_UTF16
  57882. int rc;
  57883. #endif
  57884. assert( (pMem->flags&MEM_RowSet)==0 );
  57885. assert( desiredEnc==SQLITE_UTF8 || desiredEnc==SQLITE_UTF16LE
  57886. || desiredEnc==SQLITE_UTF16BE );
  57887. if( !(pMem->flags&MEM_Str) || pMem->enc==desiredEnc ){
  57888. return SQLITE_OK;
  57889. }
  57890. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  57891. #ifdef SQLITE_OMIT_UTF16
  57892. return SQLITE_ERROR;
  57893. #else
  57894. /* MemTranslate() may return SQLITE_OK or SQLITE_NOMEM. If NOMEM is returned,
  57895. ** then the encoding of the value may not have changed.
  57896. */
  57897. rc = sqlite3VdbeMemTranslate(pMem, (u8)desiredEnc);
  57898. assert(rc==SQLITE_OK || rc==SQLITE_NOMEM);
  57899. assert(rc==SQLITE_OK || pMem->enc!=desiredEnc);
  57900. assert(rc==SQLITE_NOMEM || pMem->enc==desiredEnc);
  57901. return rc;
  57902. #endif
  57903. }
  57904. /*
  57905. ** Make sure pMem->z points to a writable allocation of at least
  57906. ** min(n,32) bytes.
  57907. **
  57908. ** If the bPreserve argument is true, then copy of the content of
  57909. ** pMem->z into the new allocation. pMem must be either a string or
  57910. ** blob if bPreserve is true. If bPreserve is false, any prior content
  57911. ** in pMem->z is discarded.
  57912. */
  57913. SQLITE_PRIVATE SQLITE_NOINLINE int sqlite3VdbeMemGrow(Mem *pMem, int n, int bPreserve){
  57914. assert( sqlite3VdbeCheckMemInvariants(pMem) );
  57915. assert( (pMem->flags&MEM_RowSet)==0 );
  57916. /* If the bPreserve flag is set to true, then the memory cell must already
  57917. ** contain a valid string or blob value. */
  57918. assert( bPreserve==0 || pMem->flags&(MEM_Blob|MEM_Str) );
  57919. testcase( bPreserve && pMem->z==0 );
  57920. assert( pMem->szMalloc==0
  57921. || pMem->szMalloc==sqlite3DbMallocSize(pMem->db, pMem->zMalloc) );
  57922. if( pMem->szMalloc<n ){
  57923. if( n<32 ) n = 32;
  57924. if( bPreserve && pMem->szMalloc>0 && pMem->z==pMem->zMalloc ){
  57925. pMem->z = pMem->zMalloc = sqlite3DbReallocOrFree(pMem->db, pMem->z, n);
  57926. bPreserve = 0;
  57927. }else{
  57928. if( pMem->szMalloc>0 ) sqlite3DbFree(pMem->db, pMem->zMalloc);
  57929. pMem->zMalloc = sqlite3DbMallocRaw(pMem->db, n);
  57930. }
  57931. if( pMem->zMalloc==0 ){
  57932. sqlite3VdbeMemSetNull(pMem);
  57933. pMem->z = 0;
  57934. pMem->szMalloc = 0;
  57935. return SQLITE_NOMEM;
  57936. }else{
  57937. pMem->szMalloc = sqlite3DbMallocSize(pMem->db, pMem->zMalloc);
  57938. }
  57939. }
  57940. if( bPreserve && pMem->z && pMem->z!=pMem->zMalloc ){
  57941. memcpy(pMem->zMalloc, pMem->z, pMem->n);
  57942. }
  57943. if( (pMem->flags&MEM_Dyn)!=0 ){
  57944. assert( pMem->xDel!=0 && pMem->xDel!=SQLITE_DYNAMIC );
  57945. pMem->xDel((void *)(pMem->z));
  57946. }
  57947. pMem->z = pMem->zMalloc;
  57948. pMem->flags &= ~(MEM_Dyn|MEM_Ephem|MEM_Static);
  57949. return SQLITE_OK;
  57950. }
  57951. /*
  57952. ** Change the pMem->zMalloc allocation to be at least szNew bytes.
  57953. ** If pMem->zMalloc already meets or exceeds the requested size, this
  57954. ** routine is a no-op.
  57955. **
  57956. ** Any prior string or blob content in the pMem object may be discarded.
  57957. ** The pMem->xDel destructor is called, if it exists. Though MEM_Str
  57958. ** and MEM_Blob values may be discarded, MEM_Int, MEM_Real, and MEM_Null
  57959. ** values are preserved.
  57960. **
  57961. ** Return SQLITE_OK on success or an error code (probably SQLITE_NOMEM)
  57962. ** if unable to complete the resizing.
  57963. */
  57964. SQLITE_PRIVATE int sqlite3VdbeMemClearAndResize(Mem *pMem, int szNew){
  57965. assert( szNew>0 );
  57966. assert( (pMem->flags & MEM_Dyn)==0 || pMem->szMalloc==0 );
  57967. if( pMem->szMalloc<szNew ){
  57968. return sqlite3VdbeMemGrow(pMem, szNew, 0);
  57969. }
  57970. assert( (pMem->flags & MEM_Dyn)==0 );
  57971. pMem->z = pMem->zMalloc;
  57972. pMem->flags &= (MEM_Null|MEM_Int|MEM_Real);
  57973. return SQLITE_OK;
  57974. }
  57975. /*
  57976. ** Change pMem so that its MEM_Str or MEM_Blob value is stored in
  57977. ** MEM.zMalloc, where it can be safely written.
  57978. **
  57979. ** Return SQLITE_OK on success or SQLITE_NOMEM if malloc fails.
  57980. */
  57981. SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem *pMem){
  57982. int f;
  57983. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  57984. assert( (pMem->flags&MEM_RowSet)==0 );
  57985. ExpandBlob(pMem);
  57986. f = pMem->flags;
  57987. if( (f&(MEM_Str|MEM_Blob)) && (pMem->szMalloc==0 || pMem->z!=pMem->zMalloc) ){
  57988. if( sqlite3VdbeMemGrow(pMem, pMem->n + 2, 1) ){
  57989. return SQLITE_NOMEM;
  57990. }
  57991. pMem->z[pMem->n] = 0;
  57992. pMem->z[pMem->n+1] = 0;
  57993. pMem->flags |= MEM_Term;
  57994. #ifdef SQLITE_DEBUG
  57995. pMem->pScopyFrom = 0;
  57996. #endif
  57997. }
  57998. return SQLITE_OK;
  57999. }
  58000. /*
  58001. ** If the given Mem* has a zero-filled tail, turn it into an ordinary
  58002. ** blob stored in dynamically allocated space.
  58003. */
  58004. #ifndef SQLITE_OMIT_INCRBLOB
  58005. SQLITE_PRIVATE int sqlite3VdbeMemExpandBlob(Mem *pMem){
  58006. if( pMem->flags & MEM_Zero ){
  58007. int nByte;
  58008. assert( pMem->flags&MEM_Blob );
  58009. assert( (pMem->flags&MEM_RowSet)==0 );
  58010. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  58011. /* Set nByte to the number of bytes required to store the expanded blob. */
  58012. nByte = pMem->n + pMem->u.nZero;
  58013. if( nByte<=0 ){
  58014. nByte = 1;
  58015. }
  58016. if( sqlite3VdbeMemGrow(pMem, nByte, 1) ){
  58017. return SQLITE_NOMEM;
  58018. }
  58019. memset(&pMem->z[pMem->n], 0, pMem->u.nZero);
  58020. pMem->n += pMem->u.nZero;
  58021. pMem->flags &= ~(MEM_Zero|MEM_Term);
  58022. }
  58023. return SQLITE_OK;
  58024. }
  58025. #endif
  58026. /*
  58027. ** It is already known that pMem contains an unterminated string.
  58028. ** Add the zero terminator.
  58029. */
  58030. static SQLITE_NOINLINE int vdbeMemAddTerminator(Mem *pMem){
  58031. if( sqlite3VdbeMemGrow(pMem, pMem->n+2, 1) ){
  58032. return SQLITE_NOMEM;
  58033. }
  58034. pMem->z[pMem->n] = 0;
  58035. pMem->z[pMem->n+1] = 0;
  58036. pMem->flags |= MEM_Term;
  58037. return SQLITE_OK;
  58038. }
  58039. /*
  58040. ** Make sure the given Mem is \u0000 terminated.
  58041. */
  58042. SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem *pMem){
  58043. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  58044. testcase( (pMem->flags & (MEM_Term|MEM_Str))==(MEM_Term|MEM_Str) );
  58045. testcase( (pMem->flags & (MEM_Term|MEM_Str))==0 );
  58046. if( (pMem->flags & (MEM_Term|MEM_Str))!=MEM_Str ){
  58047. return SQLITE_OK; /* Nothing to do */
  58048. }else{
  58049. return vdbeMemAddTerminator(pMem);
  58050. }
  58051. }
  58052. /*
  58053. ** Add MEM_Str to the set of representations for the given Mem. Numbers
  58054. ** are converted using sqlite3_snprintf(). Converting a BLOB to a string
  58055. ** is a no-op.
  58056. **
  58057. ** Existing representations MEM_Int and MEM_Real are invalidated if
  58058. ** bForce is true but are retained if bForce is false.
  58059. **
  58060. ** A MEM_Null value will never be passed to this function. This function is
  58061. ** used for converting values to text for returning to the user (i.e. via
  58062. ** sqlite3_value_text()), or for ensuring that values to be used as btree
  58063. ** keys are strings. In the former case a NULL pointer is returned the
  58064. ** user and the latter is an internal programming error.
  58065. */
  58066. SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem *pMem, u8 enc, u8 bForce){
  58067. int fg = pMem->flags;
  58068. const int nByte = 32;
  58069. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  58070. assert( !(fg&MEM_Zero) );
  58071. assert( !(fg&(MEM_Str|MEM_Blob)) );
  58072. assert( fg&(MEM_Int|MEM_Real) );
  58073. assert( (pMem->flags&MEM_RowSet)==0 );
  58074. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  58075. if( sqlite3VdbeMemClearAndResize(pMem, nByte) ){
  58076. return SQLITE_NOMEM;
  58077. }
  58078. /* For a Real or Integer, use sqlite3_snprintf() to produce the UTF-8
  58079. ** string representation of the value. Then, if the required encoding
  58080. ** is UTF-16le or UTF-16be do a translation.
  58081. **
  58082. ** FIX ME: It would be better if sqlite3_snprintf() could do UTF-16.
  58083. */
  58084. if( fg & MEM_Int ){
  58085. sqlite3_snprintf(nByte, pMem->z, "%lld", pMem->u.i);
  58086. }else{
  58087. assert( fg & MEM_Real );
  58088. sqlite3_snprintf(nByte, pMem->z, "%!.15g", pMem->u.r);
  58089. }
  58090. pMem->n = sqlite3Strlen30(pMem->z);
  58091. pMem->enc = SQLITE_UTF8;
  58092. pMem->flags |= MEM_Str|MEM_Term;
  58093. if( bForce ) pMem->flags &= ~(MEM_Int|MEM_Real);
  58094. sqlite3VdbeChangeEncoding(pMem, enc);
  58095. return SQLITE_OK;
  58096. }
  58097. /*
  58098. ** Memory cell pMem contains the context of an aggregate function.
  58099. ** This routine calls the finalize method for that function. The
  58100. ** result of the aggregate is stored back into pMem.
  58101. **
  58102. ** Return SQLITE_ERROR if the finalizer reports an error. SQLITE_OK
  58103. ** otherwise.
  58104. */
  58105. SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem *pMem, FuncDef *pFunc){
  58106. int rc = SQLITE_OK;
  58107. if( ALWAYS(pFunc && pFunc->xFinalize) ){
  58108. sqlite3_context ctx;
  58109. Mem t;
  58110. assert( (pMem->flags & MEM_Null)!=0 || pFunc==pMem->u.pDef );
  58111. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  58112. memset(&ctx, 0, sizeof(ctx));
  58113. memset(&t, 0, sizeof(t));
  58114. t.flags = MEM_Null;
  58115. t.db = pMem->db;
  58116. ctx.pOut = &t;
  58117. ctx.pMem = pMem;
  58118. ctx.pFunc = pFunc;
  58119. pFunc->xFinalize(&ctx); /* IMP: R-24505-23230 */
  58120. assert( (pMem->flags & MEM_Dyn)==0 );
  58121. if( pMem->szMalloc>0 ) sqlite3DbFree(pMem->db, pMem->zMalloc);
  58122. memcpy(pMem, &t, sizeof(t));
  58123. rc = ctx.isError;
  58124. }
  58125. return rc;
  58126. }
  58127. /*
  58128. ** If the memory cell contains a value that must be freed by
  58129. ** invoking the external callback in Mem.xDel, then this routine
  58130. ** will free that value. It also sets Mem.flags to MEM_Null.
  58131. **
  58132. ** This is a helper routine for sqlite3VdbeMemSetNull() and
  58133. ** for sqlite3VdbeMemRelease(). Use those other routines as the
  58134. ** entry point for releasing Mem resources.
  58135. */
  58136. static SQLITE_NOINLINE void vdbeMemClearExternAndSetNull(Mem *p){
  58137. assert( p->db==0 || sqlite3_mutex_held(p->db->mutex) );
  58138. assert( VdbeMemDynamic(p) );
  58139. if( p->flags&MEM_Agg ){
  58140. sqlite3VdbeMemFinalize(p, p->u.pDef);
  58141. assert( (p->flags & MEM_Agg)==0 );
  58142. testcase( p->flags & MEM_Dyn );
  58143. }
  58144. if( p->flags&MEM_Dyn ){
  58145. assert( (p->flags&MEM_RowSet)==0 );
  58146. assert( p->xDel!=SQLITE_DYNAMIC && p->xDel!=0 );
  58147. p->xDel((void *)p->z);
  58148. }else if( p->flags&MEM_RowSet ){
  58149. sqlite3RowSetClear(p->u.pRowSet);
  58150. }else if( p->flags&MEM_Frame ){
  58151. VdbeFrame *pFrame = p->u.pFrame;
  58152. pFrame->pParent = pFrame->v->pDelFrame;
  58153. pFrame->v->pDelFrame = pFrame;
  58154. }
  58155. p->flags = MEM_Null;
  58156. }
  58157. /*
  58158. ** Release memory held by the Mem p, both external memory cleared
  58159. ** by p->xDel and memory in p->zMalloc.
  58160. **
  58161. ** This is a helper routine invoked by sqlite3VdbeMemRelease() in
  58162. ** the unusual case where there really is memory in p that needs
  58163. ** to be freed.
  58164. */
  58165. static SQLITE_NOINLINE void vdbeMemClear(Mem *p){
  58166. if( VdbeMemDynamic(p) ){
  58167. vdbeMemClearExternAndSetNull(p);
  58168. }
  58169. if( p->szMalloc ){
  58170. sqlite3DbFree(p->db, p->zMalloc);
  58171. p->szMalloc = 0;
  58172. }
  58173. p->z = 0;
  58174. }
  58175. /*
  58176. ** Release any memory resources held by the Mem. Both the memory that is
  58177. ** free by Mem.xDel and the Mem.zMalloc allocation are freed.
  58178. **
  58179. ** Use this routine prior to clean up prior to abandoning a Mem, or to
  58180. ** reset a Mem back to its minimum memory utilization.
  58181. **
  58182. ** Use sqlite3VdbeMemSetNull() to release just the Mem.xDel space
  58183. ** prior to inserting new content into the Mem.
  58184. */
  58185. SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p){
  58186. assert( sqlite3VdbeCheckMemInvariants(p) );
  58187. if( VdbeMemDynamic(p) || p->szMalloc ){
  58188. vdbeMemClear(p);
  58189. }
  58190. }
  58191. /*
  58192. ** Convert a 64-bit IEEE double into a 64-bit signed integer.
  58193. ** If the double is out of range of a 64-bit signed integer then
  58194. ** return the closest available 64-bit signed integer.
  58195. */
  58196. static i64 doubleToInt64(double r){
  58197. #ifdef SQLITE_OMIT_FLOATING_POINT
  58198. /* When floating-point is omitted, double and int64 are the same thing */
  58199. return r;
  58200. #else
  58201. /*
  58202. ** Many compilers we encounter do not define constants for the
  58203. ** minimum and maximum 64-bit integers, or they define them
  58204. ** inconsistently. And many do not understand the "LL" notation.
  58205. ** So we define our own static constants here using nothing
  58206. ** larger than a 32-bit integer constant.
  58207. */
  58208. static const i64 maxInt = LARGEST_INT64;
  58209. static const i64 minInt = SMALLEST_INT64;
  58210. if( r<=(double)minInt ){
  58211. return minInt;
  58212. }else if( r>=(double)maxInt ){
  58213. return maxInt;
  58214. }else{
  58215. return (i64)r;
  58216. }
  58217. #endif
  58218. }
  58219. /*
  58220. ** Return some kind of integer value which is the best we can do
  58221. ** at representing the value that *pMem describes as an integer.
  58222. ** If pMem is an integer, then the value is exact. If pMem is
  58223. ** a floating-point then the value returned is the integer part.
  58224. ** If pMem is a string or blob, then we make an attempt to convert
  58225. ** it into an integer and return that. If pMem represents an
  58226. ** an SQL-NULL value, return 0.
  58227. **
  58228. ** If pMem represents a string value, its encoding might be changed.
  58229. */
  58230. SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem *pMem){
  58231. int flags;
  58232. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  58233. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  58234. flags = pMem->flags;
  58235. if( flags & MEM_Int ){
  58236. return pMem->u.i;
  58237. }else if( flags & MEM_Real ){
  58238. return doubleToInt64(pMem->u.r);
  58239. }else if( flags & (MEM_Str|MEM_Blob) ){
  58240. i64 value = 0;
  58241. assert( pMem->z || pMem->n==0 );
  58242. sqlite3Atoi64(pMem->z, &value, pMem->n, pMem->enc);
  58243. return value;
  58244. }else{
  58245. return 0;
  58246. }
  58247. }
  58248. /*
  58249. ** Return the best representation of pMem that we can get into a
  58250. ** double. If pMem is already a double or an integer, return its
  58251. ** value. If it is a string or blob, try to convert it to a double.
  58252. ** If it is a NULL, return 0.0.
  58253. */
  58254. SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem *pMem){
  58255. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  58256. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  58257. if( pMem->flags & MEM_Real ){
  58258. return pMem->u.r;
  58259. }else if( pMem->flags & MEM_Int ){
  58260. return (double)pMem->u.i;
  58261. }else if( pMem->flags & (MEM_Str|MEM_Blob) ){
  58262. /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
  58263. double val = (double)0;
  58264. sqlite3AtoF(pMem->z, &val, pMem->n, pMem->enc);
  58265. return val;
  58266. }else{
  58267. /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
  58268. return (double)0;
  58269. }
  58270. }
  58271. /*
  58272. ** The MEM structure is already a MEM_Real. Try to also make it a
  58273. ** MEM_Int if we can.
  58274. */
  58275. SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem *pMem){
  58276. i64 ix;
  58277. assert( pMem->flags & MEM_Real );
  58278. assert( (pMem->flags & MEM_RowSet)==0 );
  58279. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  58280. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  58281. ix = doubleToInt64(pMem->u.r);
  58282. /* Only mark the value as an integer if
  58283. **
  58284. ** (1) the round-trip conversion real->int->real is a no-op, and
  58285. ** (2) The integer is neither the largest nor the smallest
  58286. ** possible integer (ticket #3922)
  58287. **
  58288. ** The second and third terms in the following conditional enforces
  58289. ** the second condition under the assumption that addition overflow causes
  58290. ** values to wrap around.
  58291. */
  58292. if( pMem->u.r==ix && ix>SMALLEST_INT64 && ix<LARGEST_INT64 ){
  58293. pMem->u.i = ix;
  58294. MemSetTypeFlag(pMem, MEM_Int);
  58295. }
  58296. }
  58297. /*
  58298. ** Convert pMem to type integer. Invalidate any prior representations.
  58299. */
  58300. SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem *pMem){
  58301. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  58302. assert( (pMem->flags & MEM_RowSet)==0 );
  58303. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  58304. pMem->u.i = sqlite3VdbeIntValue(pMem);
  58305. MemSetTypeFlag(pMem, MEM_Int);
  58306. return SQLITE_OK;
  58307. }
  58308. /*
  58309. ** Convert pMem so that it is of type MEM_Real.
  58310. ** Invalidate any prior representations.
  58311. */
  58312. SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem *pMem){
  58313. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  58314. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  58315. pMem->u.r = sqlite3VdbeRealValue(pMem);
  58316. MemSetTypeFlag(pMem, MEM_Real);
  58317. return SQLITE_OK;
  58318. }
  58319. /*
  58320. ** Convert pMem so that it has types MEM_Real or MEM_Int or both.
  58321. ** Invalidate any prior representations.
  58322. **
  58323. ** Every effort is made to force the conversion, even if the input
  58324. ** is a string that does not look completely like a number. Convert
  58325. ** as much of the string as we can and ignore the rest.
  58326. */
  58327. SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem *pMem){
  58328. if( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))==0 ){
  58329. assert( (pMem->flags & (MEM_Blob|MEM_Str))!=0 );
  58330. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  58331. if( 0==sqlite3Atoi64(pMem->z, &pMem->u.i, pMem->n, pMem->enc) ){
  58332. MemSetTypeFlag(pMem, MEM_Int);
  58333. }else{
  58334. pMem->u.r = sqlite3VdbeRealValue(pMem);
  58335. MemSetTypeFlag(pMem, MEM_Real);
  58336. sqlite3VdbeIntegerAffinity(pMem);
  58337. }
  58338. }
  58339. assert( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))!=0 );
  58340. pMem->flags &= ~(MEM_Str|MEM_Blob);
  58341. return SQLITE_OK;
  58342. }
  58343. /*
  58344. ** Cast the datatype of the value in pMem according to the affinity
  58345. ** "aff". Casting is different from applying affinity in that a cast
  58346. ** is forced. In other words, the value is converted into the desired
  58347. ** affinity even if that results in loss of data. This routine is
  58348. ** used (for example) to implement the SQL "cast()" operator.
  58349. */
  58350. SQLITE_PRIVATE void sqlite3VdbeMemCast(Mem *pMem, u8 aff, u8 encoding){
  58351. if( pMem->flags & MEM_Null ) return;
  58352. switch( aff ){
  58353. case SQLITE_AFF_NONE: { /* Really a cast to BLOB */
  58354. if( (pMem->flags & MEM_Blob)==0 ){
  58355. sqlite3ValueApplyAffinity(pMem, SQLITE_AFF_TEXT, encoding);
  58356. assert( pMem->flags & MEM_Str || pMem->db->mallocFailed );
  58357. MemSetTypeFlag(pMem, MEM_Blob);
  58358. }else{
  58359. pMem->flags &= ~(MEM_TypeMask&~MEM_Blob);
  58360. }
  58361. break;
  58362. }
  58363. case SQLITE_AFF_NUMERIC: {
  58364. sqlite3VdbeMemNumerify(pMem);
  58365. break;
  58366. }
  58367. case SQLITE_AFF_INTEGER: {
  58368. sqlite3VdbeMemIntegerify(pMem);
  58369. break;
  58370. }
  58371. case SQLITE_AFF_REAL: {
  58372. sqlite3VdbeMemRealify(pMem);
  58373. break;
  58374. }
  58375. default: {
  58376. assert( aff==SQLITE_AFF_TEXT );
  58377. assert( MEM_Str==(MEM_Blob>>3) );
  58378. pMem->flags |= (pMem->flags&MEM_Blob)>>3;
  58379. sqlite3ValueApplyAffinity(pMem, SQLITE_AFF_TEXT, encoding);
  58380. assert( pMem->flags & MEM_Str || pMem->db->mallocFailed );
  58381. pMem->flags &= ~(MEM_Int|MEM_Real|MEM_Blob|MEM_Zero);
  58382. break;
  58383. }
  58384. }
  58385. }
  58386. /*
  58387. ** Initialize bulk memory to be a consistent Mem object.
  58388. **
  58389. ** The minimum amount of initialization feasible is performed.
  58390. */
  58391. SQLITE_PRIVATE void sqlite3VdbeMemInit(Mem *pMem, sqlite3 *db, u16 flags){
  58392. assert( (flags & ~MEM_TypeMask)==0 );
  58393. pMem->flags = flags;
  58394. pMem->db = db;
  58395. pMem->szMalloc = 0;
  58396. }
  58397. /*
  58398. ** Delete any previous value and set the value stored in *pMem to NULL.
  58399. **
  58400. ** This routine calls the Mem.xDel destructor to dispose of values that
  58401. ** require the destructor. But it preserves the Mem.zMalloc memory allocation.
  58402. ** To free all resources, use sqlite3VdbeMemRelease(), which both calls this
  58403. ** routine to invoke the destructor and deallocates Mem.zMalloc.
  58404. **
  58405. ** Use this routine to reset the Mem prior to insert a new value.
  58406. **
  58407. ** Use sqlite3VdbeMemRelease() to complete erase the Mem prior to abandoning it.
  58408. */
  58409. SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem *pMem){
  58410. if( VdbeMemDynamic(pMem) ){
  58411. vdbeMemClearExternAndSetNull(pMem);
  58412. }else{
  58413. pMem->flags = MEM_Null;
  58414. }
  58415. }
  58416. SQLITE_PRIVATE void sqlite3ValueSetNull(sqlite3_value *p){
  58417. sqlite3VdbeMemSetNull((Mem*)p);
  58418. }
  58419. /*
  58420. ** Delete any previous value and set the value to be a BLOB of length
  58421. ** n containing all zeros.
  58422. */
  58423. SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem *pMem, int n){
  58424. sqlite3VdbeMemRelease(pMem);
  58425. pMem->flags = MEM_Blob|MEM_Zero;
  58426. pMem->n = 0;
  58427. if( n<0 ) n = 0;
  58428. pMem->u.nZero = n;
  58429. pMem->enc = SQLITE_UTF8;
  58430. pMem->z = 0;
  58431. }
  58432. /*
  58433. ** The pMem is known to contain content that needs to be destroyed prior
  58434. ** to a value change. So invoke the destructor, then set the value to
  58435. ** a 64-bit integer.
  58436. */
  58437. static SQLITE_NOINLINE void vdbeReleaseAndSetInt64(Mem *pMem, i64 val){
  58438. sqlite3VdbeMemSetNull(pMem);
  58439. pMem->u.i = val;
  58440. pMem->flags = MEM_Int;
  58441. }
  58442. /*
  58443. ** Delete any previous value and set the value stored in *pMem to val,
  58444. ** manifest type INTEGER.
  58445. */
  58446. SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem *pMem, i64 val){
  58447. if( VdbeMemDynamic(pMem) ){
  58448. vdbeReleaseAndSetInt64(pMem, val);
  58449. }else{
  58450. pMem->u.i = val;
  58451. pMem->flags = MEM_Int;
  58452. }
  58453. }
  58454. #ifndef SQLITE_OMIT_FLOATING_POINT
  58455. /*
  58456. ** Delete any previous value and set the value stored in *pMem to val,
  58457. ** manifest type REAL.
  58458. */
  58459. SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem *pMem, double val){
  58460. sqlite3VdbeMemSetNull(pMem);
  58461. if( !sqlite3IsNaN(val) ){
  58462. pMem->u.r = val;
  58463. pMem->flags = MEM_Real;
  58464. }
  58465. }
  58466. #endif
  58467. /*
  58468. ** Delete any previous value and set the value of pMem to be an
  58469. ** empty boolean index.
  58470. */
  58471. SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem *pMem){
  58472. sqlite3 *db = pMem->db;
  58473. assert( db!=0 );
  58474. assert( (pMem->flags & MEM_RowSet)==0 );
  58475. sqlite3VdbeMemRelease(pMem);
  58476. pMem->zMalloc = sqlite3DbMallocRaw(db, 64);
  58477. if( db->mallocFailed ){
  58478. pMem->flags = MEM_Null;
  58479. pMem->szMalloc = 0;
  58480. }else{
  58481. assert( pMem->zMalloc );
  58482. pMem->szMalloc = sqlite3DbMallocSize(db, pMem->zMalloc);
  58483. pMem->u.pRowSet = sqlite3RowSetInit(db, pMem->zMalloc, pMem->szMalloc);
  58484. assert( pMem->u.pRowSet!=0 );
  58485. pMem->flags = MEM_RowSet;
  58486. }
  58487. }
  58488. /*
  58489. ** Return true if the Mem object contains a TEXT or BLOB that is
  58490. ** too large - whose size exceeds SQLITE_MAX_LENGTH.
  58491. */
  58492. SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem *p){
  58493. assert( p->db!=0 );
  58494. if( p->flags & (MEM_Str|MEM_Blob) ){
  58495. int n = p->n;
  58496. if( p->flags & MEM_Zero ){
  58497. n += p->u.nZero;
  58498. }
  58499. return n>p->db->aLimit[SQLITE_LIMIT_LENGTH];
  58500. }
  58501. return 0;
  58502. }
  58503. #ifdef SQLITE_DEBUG
  58504. /*
  58505. ** This routine prepares a memory cell for modification by breaking
  58506. ** its link to a shallow copy and by marking any current shallow
  58507. ** copies of this cell as invalid.
  58508. **
  58509. ** This is used for testing and debugging only - to make sure shallow
  58510. ** copies are not misused.
  58511. */
  58512. SQLITE_PRIVATE void sqlite3VdbeMemAboutToChange(Vdbe *pVdbe, Mem *pMem){
  58513. int i;
  58514. Mem *pX;
  58515. for(i=1, pX=&pVdbe->aMem[1]; i<=pVdbe->nMem; i++, pX++){
  58516. if( pX->pScopyFrom==pMem ){
  58517. pX->flags |= MEM_Undefined;
  58518. pX->pScopyFrom = 0;
  58519. }
  58520. }
  58521. pMem->pScopyFrom = 0;
  58522. }
  58523. #endif /* SQLITE_DEBUG */
  58524. /*
  58525. ** Size of struct Mem not including the Mem.zMalloc member.
  58526. */
  58527. #define MEMCELLSIZE offsetof(Mem,zMalloc)
  58528. /*
  58529. ** Make an shallow copy of pFrom into pTo. Prior contents of
  58530. ** pTo are freed. The pFrom->z field is not duplicated. If
  58531. ** pFrom->z is used, then pTo->z points to the same thing as pFrom->z
  58532. ** and flags gets srcType (either MEM_Ephem or MEM_Static).
  58533. */
  58534. SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem *pTo, const Mem *pFrom, int srcType){
  58535. assert( (pFrom->flags & MEM_RowSet)==0 );
  58536. assert( pTo->db==pFrom->db );
  58537. if( VdbeMemDynamic(pTo) ) vdbeMemClearExternAndSetNull(pTo);
  58538. memcpy(pTo, pFrom, MEMCELLSIZE);
  58539. if( (pFrom->flags&MEM_Static)==0 ){
  58540. pTo->flags &= ~(MEM_Dyn|MEM_Static|MEM_Ephem);
  58541. assert( srcType==MEM_Ephem || srcType==MEM_Static );
  58542. pTo->flags |= srcType;
  58543. }
  58544. }
  58545. /*
  58546. ** Make a full copy of pFrom into pTo. Prior contents of pTo are
  58547. ** freed before the copy is made.
  58548. */
  58549. SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem *pTo, const Mem *pFrom){
  58550. int rc = SQLITE_OK;
  58551. assert( pTo->db==pFrom->db );
  58552. assert( (pFrom->flags & MEM_RowSet)==0 );
  58553. if( VdbeMemDynamic(pTo) ) vdbeMemClearExternAndSetNull(pTo);
  58554. memcpy(pTo, pFrom, MEMCELLSIZE);
  58555. pTo->flags &= ~MEM_Dyn;
  58556. if( pTo->flags&(MEM_Str|MEM_Blob) ){
  58557. if( 0==(pFrom->flags&MEM_Static) ){
  58558. pTo->flags |= MEM_Ephem;
  58559. rc = sqlite3VdbeMemMakeWriteable(pTo);
  58560. }
  58561. }
  58562. return rc;
  58563. }
  58564. /*
  58565. ** Transfer the contents of pFrom to pTo. Any existing value in pTo is
  58566. ** freed. If pFrom contains ephemeral data, a copy is made.
  58567. **
  58568. ** pFrom contains an SQL NULL when this routine returns.
  58569. */
  58570. SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem *pTo, Mem *pFrom){
  58571. assert( pFrom->db==0 || sqlite3_mutex_held(pFrom->db->mutex) );
  58572. assert( pTo->db==0 || sqlite3_mutex_held(pTo->db->mutex) );
  58573. assert( pFrom->db==0 || pTo->db==0 || pFrom->db==pTo->db );
  58574. sqlite3VdbeMemRelease(pTo);
  58575. memcpy(pTo, pFrom, sizeof(Mem));
  58576. pFrom->flags = MEM_Null;
  58577. pFrom->szMalloc = 0;
  58578. }
  58579. /*
  58580. ** Change the value of a Mem to be a string or a BLOB.
  58581. **
  58582. ** The memory management strategy depends on the value of the xDel
  58583. ** parameter. If the value passed is SQLITE_TRANSIENT, then the
  58584. ** string is copied into a (possibly existing) buffer managed by the
  58585. ** Mem structure. Otherwise, any existing buffer is freed and the
  58586. ** pointer copied.
  58587. **
  58588. ** If the string is too large (if it exceeds the SQLITE_LIMIT_LENGTH
  58589. ** size limit) then no memory allocation occurs. If the string can be
  58590. ** stored without allocating memory, then it is. If a memory allocation
  58591. ** is required to store the string, then value of pMem is unchanged. In
  58592. ** either case, SQLITE_TOOBIG is returned.
  58593. */
  58594. SQLITE_PRIVATE int sqlite3VdbeMemSetStr(
  58595. Mem *pMem, /* Memory cell to set to string value */
  58596. const char *z, /* String pointer */
  58597. int n, /* Bytes in string, or negative */
  58598. u8 enc, /* Encoding of z. 0 for BLOBs */
  58599. void (*xDel)(void*) /* Destructor function */
  58600. ){
  58601. int nByte = n; /* New value for pMem->n */
  58602. int iLimit; /* Maximum allowed string or blob size */
  58603. u16 flags = 0; /* New value for pMem->flags */
  58604. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  58605. assert( (pMem->flags & MEM_RowSet)==0 );
  58606. /* If z is a NULL pointer, set pMem to contain an SQL NULL. */
  58607. if( !z ){
  58608. sqlite3VdbeMemSetNull(pMem);
  58609. return SQLITE_OK;
  58610. }
  58611. if( pMem->db ){
  58612. iLimit = pMem->db->aLimit[SQLITE_LIMIT_LENGTH];
  58613. }else{
  58614. iLimit = SQLITE_MAX_LENGTH;
  58615. }
  58616. flags = (enc==0?MEM_Blob:MEM_Str);
  58617. if( nByte<0 ){
  58618. assert( enc!=0 );
  58619. if( enc==SQLITE_UTF8 ){
  58620. nByte = sqlite3Strlen30(z);
  58621. if( nByte>iLimit ) nByte = iLimit+1;
  58622. }else{
  58623. for(nByte=0; nByte<=iLimit && (z[nByte] | z[nByte+1]); nByte+=2){}
  58624. }
  58625. flags |= MEM_Term;
  58626. }
  58627. /* The following block sets the new values of Mem.z and Mem.xDel. It
  58628. ** also sets a flag in local variable "flags" to indicate the memory
  58629. ** management (one of MEM_Dyn or MEM_Static).
  58630. */
  58631. if( xDel==SQLITE_TRANSIENT ){
  58632. int nAlloc = nByte;
  58633. if( flags&MEM_Term ){
  58634. nAlloc += (enc==SQLITE_UTF8?1:2);
  58635. }
  58636. if( nByte>iLimit ){
  58637. return SQLITE_TOOBIG;
  58638. }
  58639. testcase( nAlloc==0 );
  58640. testcase( nAlloc==31 );
  58641. testcase( nAlloc==32 );
  58642. if( sqlite3VdbeMemClearAndResize(pMem, MAX(nAlloc,32)) ){
  58643. return SQLITE_NOMEM;
  58644. }
  58645. memcpy(pMem->z, z, nAlloc);
  58646. }else if( xDel==SQLITE_DYNAMIC ){
  58647. sqlite3VdbeMemRelease(pMem);
  58648. pMem->zMalloc = pMem->z = (char *)z;
  58649. pMem->szMalloc = sqlite3DbMallocSize(pMem->db, pMem->zMalloc);
  58650. }else{
  58651. sqlite3VdbeMemRelease(pMem);
  58652. pMem->z = (char *)z;
  58653. pMem->xDel = xDel;
  58654. flags |= ((xDel==SQLITE_STATIC)?MEM_Static:MEM_Dyn);
  58655. }
  58656. pMem->n = nByte;
  58657. pMem->flags = flags;
  58658. pMem->enc = (enc==0 ? SQLITE_UTF8 : enc);
  58659. #ifndef SQLITE_OMIT_UTF16
  58660. if( pMem->enc!=SQLITE_UTF8 && sqlite3VdbeMemHandleBom(pMem) ){
  58661. return SQLITE_NOMEM;
  58662. }
  58663. #endif
  58664. if( nByte>iLimit ){
  58665. return SQLITE_TOOBIG;
  58666. }
  58667. return SQLITE_OK;
  58668. }
  58669. /*
  58670. ** Move data out of a btree key or data field and into a Mem structure.
  58671. ** The data or key is taken from the entry that pCur is currently pointing
  58672. ** to. offset and amt determine what portion of the data or key to retrieve.
  58673. ** key is true to get the key or false to get data. The result is written
  58674. ** into the pMem element.
  58675. **
  58676. ** The pMem object must have been initialized. This routine will use
  58677. ** pMem->zMalloc to hold the content from the btree, if possible. New
  58678. ** pMem->zMalloc space will be allocated if necessary. The calling routine
  58679. ** is responsible for making sure that the pMem object is eventually
  58680. ** destroyed.
  58681. **
  58682. ** If this routine fails for any reason (malloc returns NULL or unable
  58683. ** to read from the disk) then the pMem is left in an inconsistent state.
  58684. */
  58685. SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(
  58686. BtCursor *pCur, /* Cursor pointing at record to retrieve. */
  58687. u32 offset, /* Offset from the start of data to return bytes from. */
  58688. u32 amt, /* Number of bytes to return. */
  58689. int key, /* If true, retrieve from the btree key, not data. */
  58690. Mem *pMem /* OUT: Return data in this Mem structure. */
  58691. ){
  58692. char *zData; /* Data from the btree layer */
  58693. u32 available = 0; /* Number of bytes available on the local btree page */
  58694. int rc = SQLITE_OK; /* Return code */
  58695. assert( sqlite3BtreeCursorIsValid(pCur) );
  58696. assert( !VdbeMemDynamic(pMem) );
  58697. /* Note: the calls to BtreeKeyFetch() and DataFetch() below assert()
  58698. ** that both the BtShared and database handle mutexes are held. */
  58699. assert( (pMem->flags & MEM_RowSet)==0 );
  58700. if( key ){
  58701. zData = (char *)sqlite3BtreeKeyFetch(pCur, &available);
  58702. }else{
  58703. zData = (char *)sqlite3BtreeDataFetch(pCur, &available);
  58704. }
  58705. assert( zData!=0 );
  58706. if( offset+amt<=available ){
  58707. pMem->z = &zData[offset];
  58708. pMem->flags = MEM_Blob|MEM_Ephem;
  58709. pMem->n = (int)amt;
  58710. }else{
  58711. pMem->flags = MEM_Null;
  58712. if( SQLITE_OK==(rc = sqlite3VdbeMemClearAndResize(pMem, amt+2)) ){
  58713. if( key ){
  58714. rc = sqlite3BtreeKey(pCur, offset, amt, pMem->z);
  58715. }else{
  58716. rc = sqlite3BtreeData(pCur, offset, amt, pMem->z);
  58717. }
  58718. if( rc==SQLITE_OK ){
  58719. pMem->z[amt] = 0;
  58720. pMem->z[amt+1] = 0;
  58721. pMem->flags = MEM_Blob|MEM_Term;
  58722. pMem->n = (int)amt;
  58723. }else{
  58724. sqlite3VdbeMemRelease(pMem);
  58725. }
  58726. }
  58727. }
  58728. return rc;
  58729. }
  58730. /*
  58731. ** The pVal argument is known to be a value other than NULL.
  58732. ** Convert it into a string with encoding enc and return a pointer
  58733. ** to a zero-terminated version of that string.
  58734. */
  58735. static SQLITE_NOINLINE const void *valueToText(sqlite3_value* pVal, u8 enc){
  58736. assert( pVal!=0 );
  58737. assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) );
  58738. assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) );
  58739. assert( (pVal->flags & MEM_RowSet)==0 );
  58740. assert( (pVal->flags & (MEM_Null))==0 );
  58741. if( pVal->flags & (MEM_Blob|MEM_Str) ){
  58742. pVal->flags |= MEM_Str;
  58743. if( pVal->flags & MEM_Zero ){
  58744. sqlite3VdbeMemExpandBlob(pVal);
  58745. }
  58746. if( pVal->enc != (enc & ~SQLITE_UTF16_ALIGNED) ){
  58747. sqlite3VdbeChangeEncoding(pVal, enc & ~SQLITE_UTF16_ALIGNED);
  58748. }
  58749. if( (enc & SQLITE_UTF16_ALIGNED)!=0 && 1==(1&SQLITE_PTR_TO_INT(pVal->z)) ){
  58750. assert( (pVal->flags & (MEM_Ephem|MEM_Static))!=0 );
  58751. if( sqlite3VdbeMemMakeWriteable(pVal)!=SQLITE_OK ){
  58752. return 0;
  58753. }
  58754. }
  58755. sqlite3VdbeMemNulTerminate(pVal); /* IMP: R-31275-44060 */
  58756. }else{
  58757. sqlite3VdbeMemStringify(pVal, enc, 0);
  58758. assert( 0==(1&SQLITE_PTR_TO_INT(pVal->z)) );
  58759. }
  58760. assert(pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) || pVal->db==0
  58761. || pVal->db->mallocFailed );
  58762. if( pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) ){
  58763. return pVal->z;
  58764. }else{
  58765. return 0;
  58766. }
  58767. }
  58768. /* This function is only available internally, it is not part of the
  58769. ** external API. It works in a similar way to sqlite3_value_text(),
  58770. ** except the data returned is in the encoding specified by the second
  58771. ** parameter, which must be one of SQLITE_UTF16BE, SQLITE_UTF16LE or
  58772. ** SQLITE_UTF8.
  58773. **
  58774. ** (2006-02-16:) The enc value can be or-ed with SQLITE_UTF16_ALIGNED.
  58775. ** If that is the case, then the result must be aligned on an even byte
  58776. ** boundary.
  58777. */
  58778. SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value* pVal, u8 enc){
  58779. if( !pVal ) return 0;
  58780. assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) );
  58781. assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) );
  58782. assert( (pVal->flags & MEM_RowSet)==0 );
  58783. if( (pVal->flags&(MEM_Str|MEM_Term))==(MEM_Str|MEM_Term) && pVal->enc==enc ){
  58784. return pVal->z;
  58785. }
  58786. if( pVal->flags&MEM_Null ){
  58787. return 0;
  58788. }
  58789. return valueToText(pVal, enc);
  58790. }
  58791. /*
  58792. ** Create a new sqlite3_value object.
  58793. */
  58794. SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *db){
  58795. Mem *p = sqlite3DbMallocZero(db, sizeof(*p));
  58796. if( p ){
  58797. p->flags = MEM_Null;
  58798. p->db = db;
  58799. }
  58800. return p;
  58801. }
  58802. /*
  58803. ** Context object passed by sqlite3Stat4ProbeSetValue() through to
  58804. ** valueNew(). See comments above valueNew() for details.
  58805. */
  58806. struct ValueNewStat4Ctx {
  58807. Parse *pParse;
  58808. Index *pIdx;
  58809. UnpackedRecord **ppRec;
  58810. int iVal;
  58811. };
  58812. /*
  58813. ** Allocate and return a pointer to a new sqlite3_value object. If
  58814. ** the second argument to this function is NULL, the object is allocated
  58815. ** by calling sqlite3ValueNew().
  58816. **
  58817. ** Otherwise, if the second argument is non-zero, then this function is
  58818. ** being called indirectly by sqlite3Stat4ProbeSetValue(). If it has not
  58819. ** already been allocated, allocate the UnpackedRecord structure that
  58820. ** that function will return to its caller here. Then return a pointer
  58821. ** an sqlite3_value within the UnpackedRecord.a[] array.
  58822. */
  58823. static sqlite3_value *valueNew(sqlite3 *db, struct ValueNewStat4Ctx *p){
  58824. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  58825. if( p ){
  58826. UnpackedRecord *pRec = p->ppRec[0];
  58827. if( pRec==0 ){
  58828. Index *pIdx = p->pIdx; /* Index being probed */
  58829. int nByte; /* Bytes of space to allocate */
  58830. int i; /* Counter variable */
  58831. int nCol = pIdx->nColumn; /* Number of index columns including rowid */
  58832. nByte = sizeof(Mem) * nCol + ROUND8(sizeof(UnpackedRecord));
  58833. pRec = (UnpackedRecord*)sqlite3DbMallocZero(db, nByte);
  58834. if( pRec ){
  58835. pRec->pKeyInfo = sqlite3KeyInfoOfIndex(p->pParse, pIdx);
  58836. if( pRec->pKeyInfo ){
  58837. assert( pRec->pKeyInfo->nField+pRec->pKeyInfo->nXField==nCol );
  58838. assert( pRec->pKeyInfo->enc==ENC(db) );
  58839. pRec->aMem = (Mem *)((u8*)pRec + ROUND8(sizeof(UnpackedRecord)));
  58840. for(i=0; i<nCol; i++){
  58841. pRec->aMem[i].flags = MEM_Null;
  58842. pRec->aMem[i].db = db;
  58843. }
  58844. }else{
  58845. sqlite3DbFree(db, pRec);
  58846. pRec = 0;
  58847. }
  58848. }
  58849. if( pRec==0 ) return 0;
  58850. p->ppRec[0] = pRec;
  58851. }
  58852. pRec->nField = p->iVal+1;
  58853. return &pRec->aMem[p->iVal];
  58854. }
  58855. #else
  58856. UNUSED_PARAMETER(p);
  58857. #endif /* defined(SQLITE_ENABLE_STAT3_OR_STAT4) */
  58858. return sqlite3ValueNew(db);
  58859. }
  58860. /*
  58861. ** Extract a value from the supplied expression in the manner described
  58862. ** above sqlite3ValueFromExpr(). Allocate the sqlite3_value object
  58863. ** using valueNew().
  58864. **
  58865. ** If pCtx is NULL and an error occurs after the sqlite3_value object
  58866. ** has been allocated, it is freed before returning. Or, if pCtx is not
  58867. ** NULL, it is assumed that the caller will free any allocated object
  58868. ** in all cases.
  58869. */
  58870. static int valueFromExpr(
  58871. sqlite3 *db, /* The database connection */
  58872. Expr *pExpr, /* The expression to evaluate */
  58873. u8 enc, /* Encoding to use */
  58874. u8 affinity, /* Affinity to use */
  58875. sqlite3_value **ppVal, /* Write the new value here */
  58876. struct ValueNewStat4Ctx *pCtx /* Second argument for valueNew() */
  58877. ){
  58878. int op;
  58879. char *zVal = 0;
  58880. sqlite3_value *pVal = 0;
  58881. int negInt = 1;
  58882. const char *zNeg = "";
  58883. int rc = SQLITE_OK;
  58884. if( !pExpr ){
  58885. *ppVal = 0;
  58886. return SQLITE_OK;
  58887. }
  58888. while( (op = pExpr->op)==TK_UPLUS ) pExpr = pExpr->pLeft;
  58889. if( NEVER(op==TK_REGISTER) ) op = pExpr->op2;
  58890. if( op==TK_CAST ){
  58891. u8 aff = sqlite3AffinityType(pExpr->u.zToken,0);
  58892. rc = valueFromExpr(db, pExpr->pLeft, enc, aff, ppVal, pCtx);
  58893. testcase( rc!=SQLITE_OK );
  58894. if( *ppVal ){
  58895. sqlite3VdbeMemCast(*ppVal, aff, SQLITE_UTF8);
  58896. sqlite3ValueApplyAffinity(*ppVal, affinity, SQLITE_UTF8);
  58897. }
  58898. return rc;
  58899. }
  58900. /* Handle negative integers in a single step. This is needed in the
  58901. ** case when the value is -9223372036854775808.
  58902. */
  58903. if( op==TK_UMINUS
  58904. && (pExpr->pLeft->op==TK_INTEGER || pExpr->pLeft->op==TK_FLOAT) ){
  58905. pExpr = pExpr->pLeft;
  58906. op = pExpr->op;
  58907. negInt = -1;
  58908. zNeg = "-";
  58909. }
  58910. if( op==TK_STRING || op==TK_FLOAT || op==TK_INTEGER ){
  58911. pVal = valueNew(db, pCtx);
  58912. if( pVal==0 ) goto no_mem;
  58913. if( ExprHasProperty(pExpr, EP_IntValue) ){
  58914. sqlite3VdbeMemSetInt64(pVal, (i64)pExpr->u.iValue*negInt);
  58915. }else{
  58916. zVal = sqlite3MPrintf(db, "%s%s", zNeg, pExpr->u.zToken);
  58917. if( zVal==0 ) goto no_mem;
  58918. sqlite3ValueSetStr(pVal, -1, zVal, SQLITE_UTF8, SQLITE_DYNAMIC);
  58919. }
  58920. if( (op==TK_INTEGER || op==TK_FLOAT ) && affinity==SQLITE_AFF_NONE ){
  58921. sqlite3ValueApplyAffinity(pVal, SQLITE_AFF_NUMERIC, SQLITE_UTF8);
  58922. }else{
  58923. sqlite3ValueApplyAffinity(pVal, affinity, SQLITE_UTF8);
  58924. }
  58925. if( pVal->flags & (MEM_Int|MEM_Real) ) pVal->flags &= ~MEM_Str;
  58926. if( enc!=SQLITE_UTF8 ){
  58927. rc = sqlite3VdbeChangeEncoding(pVal, enc);
  58928. }
  58929. }else if( op==TK_UMINUS ) {
  58930. /* This branch happens for multiple negative signs. Ex: -(-5) */
  58931. if( SQLITE_OK==sqlite3ValueFromExpr(db,pExpr->pLeft,enc,affinity,&pVal)
  58932. && pVal!=0
  58933. ){
  58934. sqlite3VdbeMemNumerify(pVal);
  58935. if( pVal->flags & MEM_Real ){
  58936. pVal->u.r = -pVal->u.r;
  58937. }else if( pVal->u.i==SMALLEST_INT64 ){
  58938. pVal->u.r = -(double)SMALLEST_INT64;
  58939. MemSetTypeFlag(pVal, MEM_Real);
  58940. }else{
  58941. pVal->u.i = -pVal->u.i;
  58942. }
  58943. sqlite3ValueApplyAffinity(pVal, affinity, enc);
  58944. }
  58945. }else if( op==TK_NULL ){
  58946. pVal = valueNew(db, pCtx);
  58947. if( pVal==0 ) goto no_mem;
  58948. }
  58949. #ifndef SQLITE_OMIT_BLOB_LITERAL
  58950. else if( op==TK_BLOB ){
  58951. int nVal;
  58952. assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
  58953. assert( pExpr->u.zToken[1]=='\'' );
  58954. pVal = valueNew(db, pCtx);
  58955. if( !pVal ) goto no_mem;
  58956. zVal = &pExpr->u.zToken[2];
  58957. nVal = sqlite3Strlen30(zVal)-1;
  58958. assert( zVal[nVal]=='\'' );
  58959. sqlite3VdbeMemSetStr(pVal, sqlite3HexToBlob(db, zVal, nVal), nVal/2,
  58960. 0, SQLITE_DYNAMIC);
  58961. }
  58962. #endif
  58963. *ppVal = pVal;
  58964. return rc;
  58965. no_mem:
  58966. db->mallocFailed = 1;
  58967. sqlite3DbFree(db, zVal);
  58968. assert( *ppVal==0 );
  58969. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  58970. if( pCtx==0 ) sqlite3ValueFree(pVal);
  58971. #else
  58972. assert( pCtx==0 ); sqlite3ValueFree(pVal);
  58973. #endif
  58974. return SQLITE_NOMEM;
  58975. }
  58976. /*
  58977. ** Create a new sqlite3_value object, containing the value of pExpr.
  58978. **
  58979. ** This only works for very simple expressions that consist of one constant
  58980. ** token (i.e. "5", "5.1", "'a string'"). If the expression can
  58981. ** be converted directly into a value, then the value is allocated and
  58982. ** a pointer written to *ppVal. The caller is responsible for deallocating
  58983. ** the value by passing it to sqlite3ValueFree() later on. If the expression
  58984. ** cannot be converted to a value, then *ppVal is set to NULL.
  58985. */
  58986. SQLITE_PRIVATE int sqlite3ValueFromExpr(
  58987. sqlite3 *db, /* The database connection */
  58988. Expr *pExpr, /* The expression to evaluate */
  58989. u8 enc, /* Encoding to use */
  58990. u8 affinity, /* Affinity to use */
  58991. sqlite3_value **ppVal /* Write the new value here */
  58992. ){
  58993. return valueFromExpr(db, pExpr, enc, affinity, ppVal, 0);
  58994. }
  58995. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  58996. /*
  58997. ** The implementation of the sqlite_record() function. This function accepts
  58998. ** a single argument of any type. The return value is a formatted database
  58999. ** record (a blob) containing the argument value.
  59000. **
  59001. ** This is used to convert the value stored in the 'sample' column of the
  59002. ** sqlite_stat3 table to the record format SQLite uses internally.
  59003. */
  59004. static void recordFunc(
  59005. sqlite3_context *context,
  59006. int argc,
  59007. sqlite3_value **argv
  59008. ){
  59009. const int file_format = 1;
  59010. int iSerial; /* Serial type */
  59011. int nSerial; /* Bytes of space for iSerial as varint */
  59012. int nVal; /* Bytes of space required for argv[0] */
  59013. int nRet;
  59014. sqlite3 *db;
  59015. u8 *aRet;
  59016. UNUSED_PARAMETER( argc );
  59017. iSerial = sqlite3VdbeSerialType(argv[0], file_format);
  59018. nSerial = sqlite3VarintLen(iSerial);
  59019. nVal = sqlite3VdbeSerialTypeLen(iSerial);
  59020. db = sqlite3_context_db_handle(context);
  59021. nRet = 1 + nSerial + nVal;
  59022. aRet = sqlite3DbMallocRaw(db, nRet);
  59023. if( aRet==0 ){
  59024. sqlite3_result_error_nomem(context);
  59025. }else{
  59026. aRet[0] = nSerial+1;
  59027. putVarint32(&aRet[1], iSerial);
  59028. sqlite3VdbeSerialPut(&aRet[1+nSerial], argv[0], iSerial);
  59029. sqlite3_result_blob(context, aRet, nRet, SQLITE_TRANSIENT);
  59030. sqlite3DbFree(db, aRet);
  59031. }
  59032. }
  59033. /*
  59034. ** Register built-in functions used to help read ANALYZE data.
  59035. */
  59036. SQLITE_PRIVATE void sqlite3AnalyzeFunctions(void){
  59037. static SQLITE_WSD FuncDef aAnalyzeTableFuncs[] = {
  59038. FUNCTION(sqlite_record, 1, 0, 0, recordFunc),
  59039. };
  59040. int i;
  59041. FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
  59042. FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aAnalyzeTableFuncs);
  59043. for(i=0; i<ArraySize(aAnalyzeTableFuncs); i++){
  59044. sqlite3FuncDefInsert(pHash, &aFunc[i]);
  59045. }
  59046. }
  59047. /*
  59048. ** Attempt to extract a value from pExpr and use it to construct *ppVal.
  59049. **
  59050. ** If pAlloc is not NULL, then an UnpackedRecord object is created for
  59051. ** pAlloc if one does not exist and the new value is added to the
  59052. ** UnpackedRecord object.
  59053. **
  59054. ** A value is extracted in the following cases:
  59055. **
  59056. ** * (pExpr==0). In this case the value is assumed to be an SQL NULL,
  59057. **
  59058. ** * The expression is a bound variable, and this is a reprepare, or
  59059. **
  59060. ** * The expression is a literal value.
  59061. **
  59062. ** On success, *ppVal is made to point to the extracted value. The caller
  59063. ** is responsible for ensuring that the value is eventually freed.
  59064. */
  59065. static int stat4ValueFromExpr(
  59066. Parse *pParse, /* Parse context */
  59067. Expr *pExpr, /* The expression to extract a value from */
  59068. u8 affinity, /* Affinity to use */
  59069. struct ValueNewStat4Ctx *pAlloc,/* How to allocate space. Or NULL */
  59070. sqlite3_value **ppVal /* OUT: New value object (or NULL) */
  59071. ){
  59072. int rc = SQLITE_OK;
  59073. sqlite3_value *pVal = 0;
  59074. sqlite3 *db = pParse->db;
  59075. /* Skip over any TK_COLLATE nodes */
  59076. pExpr = sqlite3ExprSkipCollate(pExpr);
  59077. if( !pExpr ){
  59078. pVal = valueNew(db, pAlloc);
  59079. if( pVal ){
  59080. sqlite3VdbeMemSetNull((Mem*)pVal);
  59081. }
  59082. }else if( pExpr->op==TK_VARIABLE
  59083. || NEVER(pExpr->op==TK_REGISTER && pExpr->op2==TK_VARIABLE)
  59084. ){
  59085. Vdbe *v;
  59086. int iBindVar = pExpr->iColumn;
  59087. sqlite3VdbeSetVarmask(pParse->pVdbe, iBindVar);
  59088. if( (v = pParse->pReprepare)!=0 ){
  59089. pVal = valueNew(db, pAlloc);
  59090. if( pVal ){
  59091. rc = sqlite3VdbeMemCopy((Mem*)pVal, &v->aVar[iBindVar-1]);
  59092. if( rc==SQLITE_OK ){
  59093. sqlite3ValueApplyAffinity(pVal, affinity, ENC(db));
  59094. }
  59095. pVal->db = pParse->db;
  59096. }
  59097. }
  59098. }else{
  59099. rc = valueFromExpr(db, pExpr, ENC(db), affinity, &pVal, pAlloc);
  59100. }
  59101. assert( pVal==0 || pVal->db==db );
  59102. *ppVal = pVal;
  59103. return rc;
  59104. }
  59105. /*
  59106. ** This function is used to allocate and populate UnpackedRecord
  59107. ** structures intended to be compared against sample index keys stored
  59108. ** in the sqlite_stat4 table.
  59109. **
  59110. ** A single call to this function attempts to populates field iVal (leftmost
  59111. ** is 0 etc.) of the unpacked record with a value extracted from expression
  59112. ** pExpr. Extraction of values is possible if:
  59113. **
  59114. ** * (pExpr==0). In this case the value is assumed to be an SQL NULL,
  59115. **
  59116. ** * The expression is a bound variable, and this is a reprepare, or
  59117. **
  59118. ** * The sqlite3ValueFromExpr() function is able to extract a value
  59119. ** from the expression (i.e. the expression is a literal value).
  59120. **
  59121. ** If a value can be extracted, the affinity passed as the 5th argument
  59122. ** is applied to it before it is copied into the UnpackedRecord. Output
  59123. ** parameter *pbOk is set to true if a value is extracted, or false
  59124. ** otherwise.
  59125. **
  59126. ** When this function is called, *ppRec must either point to an object
  59127. ** allocated by an earlier call to this function, or must be NULL. If it
  59128. ** is NULL and a value can be successfully extracted, a new UnpackedRecord
  59129. ** is allocated (and *ppRec set to point to it) before returning.
  59130. **
  59131. ** Unless an error is encountered, SQLITE_OK is returned. It is not an
  59132. ** error if a value cannot be extracted from pExpr. If an error does
  59133. ** occur, an SQLite error code is returned.
  59134. */
  59135. SQLITE_PRIVATE int sqlite3Stat4ProbeSetValue(
  59136. Parse *pParse, /* Parse context */
  59137. Index *pIdx, /* Index being probed */
  59138. UnpackedRecord **ppRec, /* IN/OUT: Probe record */
  59139. Expr *pExpr, /* The expression to extract a value from */
  59140. u8 affinity, /* Affinity to use */
  59141. int iVal, /* Array element to populate */
  59142. int *pbOk /* OUT: True if value was extracted */
  59143. ){
  59144. int rc;
  59145. sqlite3_value *pVal = 0;
  59146. struct ValueNewStat4Ctx alloc;
  59147. alloc.pParse = pParse;
  59148. alloc.pIdx = pIdx;
  59149. alloc.ppRec = ppRec;
  59150. alloc.iVal = iVal;
  59151. rc = stat4ValueFromExpr(pParse, pExpr, affinity, &alloc, &pVal);
  59152. assert( pVal==0 || pVal->db==pParse->db );
  59153. *pbOk = (pVal!=0);
  59154. return rc;
  59155. }
  59156. /*
  59157. ** Attempt to extract a value from expression pExpr using the methods
  59158. ** as described for sqlite3Stat4ProbeSetValue() above.
  59159. **
  59160. ** If successful, set *ppVal to point to a new value object and return
  59161. ** SQLITE_OK. If no value can be extracted, but no other error occurs
  59162. ** (e.g. OOM), return SQLITE_OK and set *ppVal to NULL. Or, if an error
  59163. ** does occur, return an SQLite error code. The final value of *ppVal
  59164. ** is undefined in this case.
  59165. */
  59166. SQLITE_PRIVATE int sqlite3Stat4ValueFromExpr(
  59167. Parse *pParse, /* Parse context */
  59168. Expr *pExpr, /* The expression to extract a value from */
  59169. u8 affinity, /* Affinity to use */
  59170. sqlite3_value **ppVal /* OUT: New value object (or NULL) */
  59171. ){
  59172. return stat4ValueFromExpr(pParse, pExpr, affinity, 0, ppVal);
  59173. }
  59174. /*
  59175. ** Extract the iCol-th column from the nRec-byte record in pRec. Write
  59176. ** the column value into *ppVal. If *ppVal is initially NULL then a new
  59177. ** sqlite3_value object is allocated.
  59178. **
  59179. ** If *ppVal is initially NULL then the caller is responsible for
  59180. ** ensuring that the value written into *ppVal is eventually freed.
  59181. */
  59182. SQLITE_PRIVATE int sqlite3Stat4Column(
  59183. sqlite3 *db, /* Database handle */
  59184. const void *pRec, /* Pointer to buffer containing record */
  59185. int nRec, /* Size of buffer pRec in bytes */
  59186. int iCol, /* Column to extract */
  59187. sqlite3_value **ppVal /* OUT: Extracted value */
  59188. ){
  59189. u32 t; /* a column type code */
  59190. int nHdr; /* Size of the header in the record */
  59191. int iHdr; /* Next unread header byte */
  59192. int iField; /* Next unread data byte */
  59193. int szField; /* Size of the current data field */
  59194. int i; /* Column index */
  59195. u8 *a = (u8*)pRec; /* Typecast byte array */
  59196. Mem *pMem = *ppVal; /* Write result into this Mem object */
  59197. assert( iCol>0 );
  59198. iHdr = getVarint32(a, nHdr);
  59199. if( nHdr>nRec || iHdr>=nHdr ) return SQLITE_CORRUPT_BKPT;
  59200. iField = nHdr;
  59201. for(i=0; i<=iCol; i++){
  59202. iHdr += getVarint32(&a[iHdr], t);
  59203. testcase( iHdr==nHdr );
  59204. testcase( iHdr==nHdr+1 );
  59205. if( iHdr>nHdr ) return SQLITE_CORRUPT_BKPT;
  59206. szField = sqlite3VdbeSerialTypeLen(t);
  59207. iField += szField;
  59208. }
  59209. testcase( iField==nRec );
  59210. testcase( iField==nRec+1 );
  59211. if( iField>nRec ) return SQLITE_CORRUPT_BKPT;
  59212. if( pMem==0 ){
  59213. pMem = *ppVal = sqlite3ValueNew(db);
  59214. if( pMem==0 ) return SQLITE_NOMEM;
  59215. }
  59216. sqlite3VdbeSerialGet(&a[iField-szField], t, pMem);
  59217. pMem->enc = ENC(db);
  59218. return SQLITE_OK;
  59219. }
  59220. /*
  59221. ** Unless it is NULL, the argument must be an UnpackedRecord object returned
  59222. ** by an earlier call to sqlite3Stat4ProbeSetValue(). This call deletes
  59223. ** the object.
  59224. */
  59225. SQLITE_PRIVATE void sqlite3Stat4ProbeFree(UnpackedRecord *pRec){
  59226. if( pRec ){
  59227. int i;
  59228. int nCol = pRec->pKeyInfo->nField+pRec->pKeyInfo->nXField;
  59229. Mem *aMem = pRec->aMem;
  59230. sqlite3 *db = aMem[0].db;
  59231. for(i=0; i<nCol; i++){
  59232. if( aMem[i].szMalloc ) sqlite3DbFree(db, aMem[i].zMalloc);
  59233. }
  59234. sqlite3KeyInfoUnref(pRec->pKeyInfo);
  59235. sqlite3DbFree(db, pRec);
  59236. }
  59237. }
  59238. #endif /* ifdef SQLITE_ENABLE_STAT4 */
  59239. /*
  59240. ** Change the string value of an sqlite3_value object
  59241. */
  59242. SQLITE_PRIVATE void sqlite3ValueSetStr(
  59243. sqlite3_value *v, /* Value to be set */
  59244. int n, /* Length of string z */
  59245. const void *z, /* Text of the new string */
  59246. u8 enc, /* Encoding to use */
  59247. void (*xDel)(void*) /* Destructor for the string */
  59248. ){
  59249. if( v ) sqlite3VdbeMemSetStr((Mem *)v, z, n, enc, xDel);
  59250. }
  59251. /*
  59252. ** Free an sqlite3_value object
  59253. */
  59254. SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value *v){
  59255. if( !v ) return;
  59256. sqlite3VdbeMemRelease((Mem *)v);
  59257. sqlite3DbFree(((Mem*)v)->db, v);
  59258. }
  59259. /*
  59260. ** Return the number of bytes in the sqlite3_value object assuming
  59261. ** that it uses the encoding "enc"
  59262. */
  59263. SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value *pVal, u8 enc){
  59264. Mem *p = (Mem*)pVal;
  59265. if( (p->flags & MEM_Blob)!=0 || sqlite3ValueText(pVal, enc) ){
  59266. if( p->flags & MEM_Zero ){
  59267. return p->n + p->u.nZero;
  59268. }else{
  59269. return p->n;
  59270. }
  59271. }
  59272. return 0;
  59273. }
  59274. /************** End of vdbemem.c *********************************************/
  59275. /************** Begin file vdbeaux.c *****************************************/
  59276. /*
  59277. ** 2003 September 6
  59278. **
  59279. ** The author disclaims copyright to this source code. In place of
  59280. ** a legal notice, here is a blessing:
  59281. **
  59282. ** May you do good and not evil.
  59283. ** May you find forgiveness for yourself and forgive others.
  59284. ** May you share freely, never taking more than you give.
  59285. **
  59286. *************************************************************************
  59287. ** This file contains code used for creating, destroying, and populating
  59288. ** a VDBE (or an "sqlite3_stmt" as it is known to the outside world.)
  59289. */
  59290. /*
  59291. ** Create a new virtual database engine.
  59292. */
  59293. SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(Parse *pParse){
  59294. sqlite3 *db = pParse->db;
  59295. Vdbe *p;
  59296. p = sqlite3DbMallocZero(db, sizeof(Vdbe) );
  59297. if( p==0 ) return 0;
  59298. p->db = db;
  59299. if( db->pVdbe ){
  59300. db->pVdbe->pPrev = p;
  59301. }
  59302. p->pNext = db->pVdbe;
  59303. p->pPrev = 0;
  59304. db->pVdbe = p;
  59305. p->magic = VDBE_MAGIC_INIT;
  59306. p->pParse = pParse;
  59307. assert( pParse->aLabel==0 );
  59308. assert( pParse->nLabel==0 );
  59309. assert( pParse->nOpAlloc==0 );
  59310. return p;
  59311. }
  59312. /*
  59313. ** Remember the SQL string for a prepared statement.
  59314. */
  59315. SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe *p, const char *z, int n, int isPrepareV2){
  59316. assert( isPrepareV2==1 || isPrepareV2==0 );
  59317. if( p==0 ) return;
  59318. #if defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_ENABLE_SQLLOG)
  59319. if( !isPrepareV2 ) return;
  59320. #endif
  59321. assert( p->zSql==0 );
  59322. p->zSql = sqlite3DbStrNDup(p->db, z, n);
  59323. p->isPrepareV2 = (u8)isPrepareV2;
  59324. }
  59325. /*
  59326. ** Return the SQL associated with a prepared statement
  59327. */
  59328. SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt){
  59329. Vdbe *p = (Vdbe *)pStmt;
  59330. return (p && p->isPrepareV2) ? p->zSql : 0;
  59331. }
  59332. /*
  59333. ** Swap all content between two VDBE structures.
  59334. */
  59335. SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe *pA, Vdbe *pB){
  59336. Vdbe tmp, *pTmp;
  59337. char *zTmp;
  59338. tmp = *pA;
  59339. *pA = *pB;
  59340. *pB = tmp;
  59341. pTmp = pA->pNext;
  59342. pA->pNext = pB->pNext;
  59343. pB->pNext = pTmp;
  59344. pTmp = pA->pPrev;
  59345. pA->pPrev = pB->pPrev;
  59346. pB->pPrev = pTmp;
  59347. zTmp = pA->zSql;
  59348. pA->zSql = pB->zSql;
  59349. pB->zSql = zTmp;
  59350. pB->isPrepareV2 = pA->isPrepareV2;
  59351. }
  59352. /*
  59353. ** Resize the Vdbe.aOp array so that it is at least nOp elements larger
  59354. ** than its current size. nOp is guaranteed to be less than or equal
  59355. ** to 1024/sizeof(Op).
  59356. **
  59357. ** If an out-of-memory error occurs while resizing the array, return
  59358. ** SQLITE_NOMEM. In this case Vdbe.aOp and Parse.nOpAlloc remain
  59359. ** unchanged (this is so that any opcodes already allocated can be
  59360. ** correctly deallocated along with the rest of the Vdbe).
  59361. */
  59362. static int growOpArray(Vdbe *v, int nOp){
  59363. VdbeOp *pNew;
  59364. Parse *p = v->pParse;
  59365. /* The SQLITE_TEST_REALLOC_STRESS compile-time option is designed to force
  59366. ** more frequent reallocs and hence provide more opportunities for
  59367. ** simulated OOM faults. SQLITE_TEST_REALLOC_STRESS is generally used
  59368. ** during testing only. With SQLITE_TEST_REALLOC_STRESS grow the op array
  59369. ** by the minimum* amount required until the size reaches 512. Normal
  59370. ** operation (without SQLITE_TEST_REALLOC_STRESS) is to double the current
  59371. ** size of the op array or add 1KB of space, whichever is smaller. */
  59372. #ifdef SQLITE_TEST_REALLOC_STRESS
  59373. int nNew = (p->nOpAlloc>=512 ? p->nOpAlloc*2 : p->nOpAlloc+nOp);
  59374. #else
  59375. int nNew = (p->nOpAlloc ? p->nOpAlloc*2 : (int)(1024/sizeof(Op)));
  59376. UNUSED_PARAMETER(nOp);
  59377. #endif
  59378. assert( nOp<=(1024/sizeof(Op)) );
  59379. assert( nNew>=(p->nOpAlloc+nOp) );
  59380. pNew = sqlite3DbRealloc(p->db, v->aOp, nNew*sizeof(Op));
  59381. if( pNew ){
  59382. p->nOpAlloc = sqlite3DbMallocSize(p->db, pNew)/sizeof(Op);
  59383. v->aOp = pNew;
  59384. }
  59385. return (pNew ? SQLITE_OK : SQLITE_NOMEM);
  59386. }
  59387. #ifdef SQLITE_DEBUG
  59388. /* This routine is just a convenient place to set a breakpoint that will
  59389. ** fire after each opcode is inserted and displayed using
  59390. ** "PRAGMA vdbe_addoptrace=on".
  59391. */
  59392. static void test_addop_breakpoint(void){
  59393. static int n = 0;
  59394. n++;
  59395. }
  59396. #endif
  59397. /*
  59398. ** Add a new instruction to the list of instructions current in the
  59399. ** VDBE. Return the address of the new instruction.
  59400. **
  59401. ** Parameters:
  59402. **
  59403. ** p Pointer to the VDBE
  59404. **
  59405. ** op The opcode for this instruction
  59406. **
  59407. ** p1, p2, p3 Operands
  59408. **
  59409. ** Use the sqlite3VdbeResolveLabel() function to fix an address and
  59410. ** the sqlite3VdbeChangeP4() function to change the value of the P4
  59411. ** operand.
  59412. */
  59413. SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe *p, int op, int p1, int p2, int p3){
  59414. int i;
  59415. VdbeOp *pOp;
  59416. i = p->nOp;
  59417. assert( p->magic==VDBE_MAGIC_INIT );
  59418. assert( op>0 && op<0xff );
  59419. if( p->pParse->nOpAlloc<=i ){
  59420. if( growOpArray(p, 1) ){
  59421. return 1;
  59422. }
  59423. }
  59424. p->nOp++;
  59425. pOp = &p->aOp[i];
  59426. pOp->opcode = (u8)op;
  59427. pOp->p5 = 0;
  59428. pOp->p1 = p1;
  59429. pOp->p2 = p2;
  59430. pOp->p3 = p3;
  59431. pOp->p4.p = 0;
  59432. pOp->p4type = P4_NOTUSED;
  59433. #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  59434. pOp->zComment = 0;
  59435. #endif
  59436. #ifdef SQLITE_DEBUG
  59437. if( p->db->flags & SQLITE_VdbeAddopTrace ){
  59438. int jj, kk;
  59439. Parse *pParse = p->pParse;
  59440. for(jj=kk=0; jj<SQLITE_N_COLCACHE; jj++){
  59441. struct yColCache *x = pParse->aColCache + jj;
  59442. if( x->iLevel>pParse->iCacheLevel || x->iReg==0 ) continue;
  59443. printf(" r[%d]={%d:%d}", x->iReg, x->iTable, x->iColumn);
  59444. kk++;
  59445. }
  59446. if( kk ) printf("\n");
  59447. sqlite3VdbePrintOp(0, i, &p->aOp[i]);
  59448. test_addop_breakpoint();
  59449. }
  59450. #endif
  59451. #ifdef VDBE_PROFILE
  59452. pOp->cycles = 0;
  59453. pOp->cnt = 0;
  59454. #endif
  59455. #ifdef SQLITE_VDBE_COVERAGE
  59456. pOp->iSrcLine = 0;
  59457. #endif
  59458. return i;
  59459. }
  59460. SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe *p, int op){
  59461. return sqlite3VdbeAddOp3(p, op, 0, 0, 0);
  59462. }
  59463. SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe *p, int op, int p1){
  59464. return sqlite3VdbeAddOp3(p, op, p1, 0, 0);
  59465. }
  59466. SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe *p, int op, int p1, int p2){
  59467. return sqlite3VdbeAddOp3(p, op, p1, p2, 0);
  59468. }
  59469. /*
  59470. ** Add an opcode that includes the p4 value as a pointer.
  59471. */
  59472. SQLITE_PRIVATE int sqlite3VdbeAddOp4(
  59473. Vdbe *p, /* Add the opcode to this VM */
  59474. int op, /* The new opcode */
  59475. int p1, /* The P1 operand */
  59476. int p2, /* The P2 operand */
  59477. int p3, /* The P3 operand */
  59478. const char *zP4, /* The P4 operand */
  59479. int p4type /* P4 operand type */
  59480. ){
  59481. int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
  59482. sqlite3VdbeChangeP4(p, addr, zP4, p4type);
  59483. return addr;
  59484. }
  59485. /*
  59486. ** Add an OP_ParseSchema opcode. This routine is broken out from
  59487. ** sqlite3VdbeAddOp4() since it needs to also needs to mark all btrees
  59488. ** as having been used.
  59489. **
  59490. ** The zWhere string must have been obtained from sqlite3_malloc().
  59491. ** This routine will take ownership of the allocated memory.
  59492. */
  59493. SQLITE_PRIVATE void sqlite3VdbeAddParseSchemaOp(Vdbe *p, int iDb, char *zWhere){
  59494. int j;
  59495. int addr = sqlite3VdbeAddOp3(p, OP_ParseSchema, iDb, 0, 0);
  59496. sqlite3VdbeChangeP4(p, addr, zWhere, P4_DYNAMIC);
  59497. for(j=0; j<p->db->nDb; j++) sqlite3VdbeUsesBtree(p, j);
  59498. }
  59499. /*
  59500. ** Add an opcode that includes the p4 value as an integer.
  59501. */
  59502. SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(
  59503. Vdbe *p, /* Add the opcode to this VM */
  59504. int op, /* The new opcode */
  59505. int p1, /* The P1 operand */
  59506. int p2, /* The P2 operand */
  59507. int p3, /* The P3 operand */
  59508. int p4 /* The P4 operand as an integer */
  59509. ){
  59510. int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
  59511. sqlite3VdbeChangeP4(p, addr, SQLITE_INT_TO_PTR(p4), P4_INT32);
  59512. return addr;
  59513. }
  59514. /*
  59515. ** Create a new symbolic label for an instruction that has yet to be
  59516. ** coded. The symbolic label is really just a negative number. The
  59517. ** label can be used as the P2 value of an operation. Later, when
  59518. ** the label is resolved to a specific address, the VDBE will scan
  59519. ** through its operation list and change all values of P2 which match
  59520. ** the label into the resolved address.
  59521. **
  59522. ** The VDBE knows that a P2 value is a label because labels are
  59523. ** always negative and P2 values are suppose to be non-negative.
  59524. ** Hence, a negative P2 value is a label that has yet to be resolved.
  59525. **
  59526. ** Zero is returned if a malloc() fails.
  59527. */
  59528. SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe *v){
  59529. Parse *p = v->pParse;
  59530. int i = p->nLabel++;
  59531. assert( v->magic==VDBE_MAGIC_INIT );
  59532. if( (i & (i-1))==0 ){
  59533. p->aLabel = sqlite3DbReallocOrFree(p->db, p->aLabel,
  59534. (i*2+1)*sizeof(p->aLabel[0]));
  59535. }
  59536. if( p->aLabel ){
  59537. p->aLabel[i] = -1;
  59538. }
  59539. return -1-i;
  59540. }
  59541. /*
  59542. ** Resolve label "x" to be the address of the next instruction to
  59543. ** be inserted. The parameter "x" must have been obtained from
  59544. ** a prior call to sqlite3VdbeMakeLabel().
  59545. */
  59546. SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe *v, int x){
  59547. Parse *p = v->pParse;
  59548. int j = -1-x;
  59549. assert( v->magic==VDBE_MAGIC_INIT );
  59550. assert( j<p->nLabel );
  59551. if( ALWAYS(j>=0) && p->aLabel ){
  59552. p->aLabel[j] = v->nOp;
  59553. }
  59554. p->iFixedOp = v->nOp - 1;
  59555. }
  59556. /*
  59557. ** Mark the VDBE as one that can only be run one time.
  59558. */
  59559. SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe *p){
  59560. p->runOnlyOnce = 1;
  59561. }
  59562. #ifdef SQLITE_DEBUG /* sqlite3AssertMayAbort() logic */
  59563. /*
  59564. ** The following type and function are used to iterate through all opcodes
  59565. ** in a Vdbe main program and each of the sub-programs (triggers) it may
  59566. ** invoke directly or indirectly. It should be used as follows:
  59567. **
  59568. ** Op *pOp;
  59569. ** VdbeOpIter sIter;
  59570. **
  59571. ** memset(&sIter, 0, sizeof(sIter));
  59572. ** sIter.v = v; // v is of type Vdbe*
  59573. ** while( (pOp = opIterNext(&sIter)) ){
  59574. ** // Do something with pOp
  59575. ** }
  59576. ** sqlite3DbFree(v->db, sIter.apSub);
  59577. **
  59578. */
  59579. typedef struct VdbeOpIter VdbeOpIter;
  59580. struct VdbeOpIter {
  59581. Vdbe *v; /* Vdbe to iterate through the opcodes of */
  59582. SubProgram **apSub; /* Array of subprograms */
  59583. int nSub; /* Number of entries in apSub */
  59584. int iAddr; /* Address of next instruction to return */
  59585. int iSub; /* 0 = main program, 1 = first sub-program etc. */
  59586. };
  59587. static Op *opIterNext(VdbeOpIter *p){
  59588. Vdbe *v = p->v;
  59589. Op *pRet = 0;
  59590. Op *aOp;
  59591. int nOp;
  59592. if( p->iSub<=p->nSub ){
  59593. if( p->iSub==0 ){
  59594. aOp = v->aOp;
  59595. nOp = v->nOp;
  59596. }else{
  59597. aOp = p->apSub[p->iSub-1]->aOp;
  59598. nOp = p->apSub[p->iSub-1]->nOp;
  59599. }
  59600. assert( p->iAddr<nOp );
  59601. pRet = &aOp[p->iAddr];
  59602. p->iAddr++;
  59603. if( p->iAddr==nOp ){
  59604. p->iSub++;
  59605. p->iAddr = 0;
  59606. }
  59607. if( pRet->p4type==P4_SUBPROGRAM ){
  59608. int nByte = (p->nSub+1)*sizeof(SubProgram*);
  59609. int j;
  59610. for(j=0; j<p->nSub; j++){
  59611. if( p->apSub[j]==pRet->p4.pProgram ) break;
  59612. }
  59613. if( j==p->nSub ){
  59614. p->apSub = sqlite3DbReallocOrFree(v->db, p->apSub, nByte);
  59615. if( !p->apSub ){
  59616. pRet = 0;
  59617. }else{
  59618. p->apSub[p->nSub++] = pRet->p4.pProgram;
  59619. }
  59620. }
  59621. }
  59622. }
  59623. return pRet;
  59624. }
  59625. /*
  59626. ** Check if the program stored in the VM associated with pParse may
  59627. ** throw an ABORT exception (causing the statement, but not entire transaction
  59628. ** to be rolled back). This condition is true if the main program or any
  59629. ** sub-programs contains any of the following:
  59630. **
  59631. ** * OP_Halt with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
  59632. ** * OP_HaltIfNull with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
  59633. ** * OP_Destroy
  59634. ** * OP_VUpdate
  59635. ** * OP_VRename
  59636. ** * OP_FkCounter with P2==0 (immediate foreign key constraint)
  59637. **
  59638. ** Then check that the value of Parse.mayAbort is true if an
  59639. ** ABORT may be thrown, or false otherwise. Return true if it does
  59640. ** match, or false otherwise. This function is intended to be used as
  59641. ** part of an assert statement in the compiler. Similar to:
  59642. **
  59643. ** assert( sqlite3VdbeAssertMayAbort(pParse->pVdbe, pParse->mayAbort) );
  59644. */
  59645. SQLITE_PRIVATE int sqlite3VdbeAssertMayAbort(Vdbe *v, int mayAbort){
  59646. int hasAbort = 0;
  59647. Op *pOp;
  59648. VdbeOpIter sIter;
  59649. memset(&sIter, 0, sizeof(sIter));
  59650. sIter.v = v;
  59651. while( (pOp = opIterNext(&sIter))!=0 ){
  59652. int opcode = pOp->opcode;
  59653. if( opcode==OP_Destroy || opcode==OP_VUpdate || opcode==OP_VRename
  59654. #ifndef SQLITE_OMIT_FOREIGN_KEY
  59655. || (opcode==OP_FkCounter && pOp->p1==0 && pOp->p2==1)
  59656. #endif
  59657. || ((opcode==OP_Halt || opcode==OP_HaltIfNull)
  59658. && ((pOp->p1&0xff)==SQLITE_CONSTRAINT && pOp->p2==OE_Abort))
  59659. ){
  59660. hasAbort = 1;
  59661. break;
  59662. }
  59663. }
  59664. sqlite3DbFree(v->db, sIter.apSub);
  59665. /* Return true if hasAbort==mayAbort. Or if a malloc failure occurred.
  59666. ** If malloc failed, then the while() loop above may not have iterated
  59667. ** through all opcodes and hasAbort may be set incorrectly. Return
  59668. ** true for this case to prevent the assert() in the callers frame
  59669. ** from failing. */
  59670. return ( v->db->mallocFailed || hasAbort==mayAbort );
  59671. }
  59672. #endif /* SQLITE_DEBUG - the sqlite3AssertMayAbort() function */
  59673. /*
  59674. ** Loop through the program looking for P2 values that are negative
  59675. ** on jump instructions. Each such value is a label. Resolve the
  59676. ** label by setting the P2 value to its correct non-zero value.
  59677. **
  59678. ** This routine is called once after all opcodes have been inserted.
  59679. **
  59680. ** Variable *pMaxFuncArgs is set to the maximum value of any P2 argument
  59681. ** to an OP_Function, OP_AggStep or OP_VFilter opcode. This is used by
  59682. ** sqlite3VdbeMakeReady() to size the Vdbe.apArg[] array.
  59683. **
  59684. ** The Op.opflags field is set on all opcodes.
  59685. */
  59686. static void resolveP2Values(Vdbe *p, int *pMaxFuncArgs){
  59687. int i;
  59688. int nMaxArgs = *pMaxFuncArgs;
  59689. Op *pOp;
  59690. Parse *pParse = p->pParse;
  59691. int *aLabel = pParse->aLabel;
  59692. p->readOnly = 1;
  59693. p->bIsReader = 0;
  59694. for(pOp=p->aOp, i=p->nOp-1; i>=0; i--, pOp++){
  59695. u8 opcode = pOp->opcode;
  59696. /* NOTE: Be sure to update mkopcodeh.awk when adding or removing
  59697. ** cases from this switch! */
  59698. switch( opcode ){
  59699. case OP_Function:
  59700. case OP_AggStep: {
  59701. if( pOp->p5>nMaxArgs ) nMaxArgs = pOp->p5;
  59702. break;
  59703. }
  59704. case OP_Transaction: {
  59705. if( pOp->p2!=0 ) p->readOnly = 0;
  59706. /* fall thru */
  59707. }
  59708. case OP_AutoCommit:
  59709. case OP_Savepoint: {
  59710. p->bIsReader = 1;
  59711. break;
  59712. }
  59713. #ifndef SQLITE_OMIT_WAL
  59714. case OP_Checkpoint:
  59715. #endif
  59716. case OP_Vacuum:
  59717. case OP_JournalMode: {
  59718. p->readOnly = 0;
  59719. p->bIsReader = 1;
  59720. break;
  59721. }
  59722. #ifndef SQLITE_OMIT_VIRTUALTABLE
  59723. case OP_VUpdate: {
  59724. if( pOp->p2>nMaxArgs ) nMaxArgs = pOp->p2;
  59725. break;
  59726. }
  59727. case OP_VFilter: {
  59728. int n;
  59729. assert( p->nOp - i >= 3 );
  59730. assert( pOp[-1].opcode==OP_Integer );
  59731. n = pOp[-1].p1;
  59732. if( n>nMaxArgs ) nMaxArgs = n;
  59733. break;
  59734. }
  59735. #endif
  59736. case OP_Next:
  59737. case OP_NextIfOpen:
  59738. case OP_SorterNext: {
  59739. pOp->p4.xAdvance = sqlite3BtreeNext;
  59740. pOp->p4type = P4_ADVANCE;
  59741. break;
  59742. }
  59743. case OP_Prev:
  59744. case OP_PrevIfOpen: {
  59745. pOp->p4.xAdvance = sqlite3BtreePrevious;
  59746. pOp->p4type = P4_ADVANCE;
  59747. break;
  59748. }
  59749. }
  59750. pOp->opflags = sqlite3OpcodeProperty[opcode];
  59751. if( (pOp->opflags & OPFLG_JUMP)!=0 && pOp->p2<0 ){
  59752. assert( -1-pOp->p2<pParse->nLabel );
  59753. pOp->p2 = aLabel[-1-pOp->p2];
  59754. }
  59755. }
  59756. sqlite3DbFree(p->db, pParse->aLabel);
  59757. pParse->aLabel = 0;
  59758. pParse->nLabel = 0;
  59759. *pMaxFuncArgs = nMaxArgs;
  59760. assert( p->bIsReader!=0 || DbMaskAllZero(p->btreeMask) );
  59761. }
  59762. /*
  59763. ** Return the address of the next instruction to be inserted.
  59764. */
  59765. SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe *p){
  59766. assert( p->magic==VDBE_MAGIC_INIT );
  59767. return p->nOp;
  59768. }
  59769. /*
  59770. ** This function returns a pointer to the array of opcodes associated with
  59771. ** the Vdbe passed as the first argument. It is the callers responsibility
  59772. ** to arrange for the returned array to be eventually freed using the
  59773. ** vdbeFreeOpArray() function.
  59774. **
  59775. ** Before returning, *pnOp is set to the number of entries in the returned
  59776. ** array. Also, *pnMaxArg is set to the larger of its current value and
  59777. ** the number of entries in the Vdbe.apArg[] array required to execute the
  59778. ** returned program.
  59779. */
  59780. SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe *p, int *pnOp, int *pnMaxArg){
  59781. VdbeOp *aOp = p->aOp;
  59782. assert( aOp && !p->db->mallocFailed );
  59783. /* Check that sqlite3VdbeUsesBtree() was not called on this VM */
  59784. assert( DbMaskAllZero(p->btreeMask) );
  59785. resolveP2Values(p, pnMaxArg);
  59786. *pnOp = p->nOp;
  59787. p->aOp = 0;
  59788. return aOp;
  59789. }
  59790. /*
  59791. ** Add a whole list of operations to the operation stack. Return the
  59792. ** address of the first operation added.
  59793. */
  59794. SQLITE_PRIVATE int sqlite3VdbeAddOpList(Vdbe *p, int nOp, VdbeOpList const *aOp, int iLineno){
  59795. int addr;
  59796. assert( p->magic==VDBE_MAGIC_INIT );
  59797. if( p->nOp + nOp > p->pParse->nOpAlloc && growOpArray(p, nOp) ){
  59798. return 0;
  59799. }
  59800. addr = p->nOp;
  59801. if( ALWAYS(nOp>0) ){
  59802. int i;
  59803. VdbeOpList const *pIn = aOp;
  59804. for(i=0; i<nOp; i++, pIn++){
  59805. int p2 = pIn->p2;
  59806. VdbeOp *pOut = &p->aOp[i+addr];
  59807. pOut->opcode = pIn->opcode;
  59808. pOut->p1 = pIn->p1;
  59809. if( p2<0 ){
  59810. assert( sqlite3OpcodeProperty[pOut->opcode] & OPFLG_JUMP );
  59811. pOut->p2 = addr + ADDR(p2);
  59812. }else{
  59813. pOut->p2 = p2;
  59814. }
  59815. pOut->p3 = pIn->p3;
  59816. pOut->p4type = P4_NOTUSED;
  59817. pOut->p4.p = 0;
  59818. pOut->p5 = 0;
  59819. #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  59820. pOut->zComment = 0;
  59821. #endif
  59822. #ifdef SQLITE_VDBE_COVERAGE
  59823. pOut->iSrcLine = iLineno+i;
  59824. #else
  59825. (void)iLineno;
  59826. #endif
  59827. #ifdef SQLITE_DEBUG
  59828. if( p->db->flags & SQLITE_VdbeAddopTrace ){
  59829. sqlite3VdbePrintOp(0, i+addr, &p->aOp[i+addr]);
  59830. }
  59831. #endif
  59832. }
  59833. p->nOp += nOp;
  59834. }
  59835. return addr;
  59836. }
  59837. /*
  59838. ** Change the value of the P1 operand for a specific instruction.
  59839. ** This routine is useful when a large program is loaded from a
  59840. ** static array using sqlite3VdbeAddOpList but we want to make a
  59841. ** few minor changes to the program.
  59842. */
  59843. SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe *p, u32 addr, int val){
  59844. assert( p!=0 );
  59845. if( ((u32)p->nOp)>addr ){
  59846. p->aOp[addr].p1 = val;
  59847. }
  59848. }
  59849. /*
  59850. ** Change the value of the P2 operand for a specific instruction.
  59851. ** This routine is useful for setting a jump destination.
  59852. */
  59853. SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe *p, u32 addr, int val){
  59854. assert( p!=0 );
  59855. if( ((u32)p->nOp)>addr ){
  59856. p->aOp[addr].p2 = val;
  59857. }
  59858. }
  59859. /*
  59860. ** Change the value of the P3 operand for a specific instruction.
  59861. */
  59862. SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe *p, u32 addr, int val){
  59863. assert( p!=0 );
  59864. if( ((u32)p->nOp)>addr ){
  59865. p->aOp[addr].p3 = val;
  59866. }
  59867. }
  59868. /*
  59869. ** Change the value of the P5 operand for the most recently
  59870. ** added operation.
  59871. */
  59872. SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe *p, u8 val){
  59873. assert( p!=0 );
  59874. if( p->aOp ){
  59875. assert( p->nOp>0 );
  59876. p->aOp[p->nOp-1].p5 = val;
  59877. }
  59878. }
  59879. /*
  59880. ** Change the P2 operand of instruction addr so that it points to
  59881. ** the address of the next instruction to be coded.
  59882. */
  59883. SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe *p, int addr){
  59884. sqlite3VdbeChangeP2(p, addr, p->nOp);
  59885. p->pParse->iFixedOp = p->nOp - 1;
  59886. }
  59887. /*
  59888. ** If the input FuncDef structure is ephemeral, then free it. If
  59889. ** the FuncDef is not ephermal, then do nothing.
  59890. */
  59891. static void freeEphemeralFunction(sqlite3 *db, FuncDef *pDef){
  59892. if( ALWAYS(pDef) && (pDef->funcFlags & SQLITE_FUNC_EPHEM)!=0 ){
  59893. sqlite3DbFree(db, pDef);
  59894. }
  59895. }
  59896. static void vdbeFreeOpArray(sqlite3 *, Op *, int);
  59897. /*
  59898. ** Delete a P4 value if necessary.
  59899. */
  59900. static void freeP4(sqlite3 *db, int p4type, void *p4){
  59901. if( p4 ){
  59902. assert( db );
  59903. switch( p4type ){
  59904. case P4_REAL:
  59905. case P4_INT64:
  59906. case P4_DYNAMIC:
  59907. case P4_INTARRAY: {
  59908. sqlite3DbFree(db, p4);
  59909. break;
  59910. }
  59911. case P4_KEYINFO: {
  59912. if( db->pnBytesFreed==0 ) sqlite3KeyInfoUnref((KeyInfo*)p4);
  59913. break;
  59914. }
  59915. case P4_MPRINTF: {
  59916. if( db->pnBytesFreed==0 ) sqlite3_free(p4);
  59917. break;
  59918. }
  59919. case P4_FUNCDEF: {
  59920. freeEphemeralFunction(db, (FuncDef*)p4);
  59921. break;
  59922. }
  59923. case P4_MEM: {
  59924. if( db->pnBytesFreed==0 ){
  59925. sqlite3ValueFree((sqlite3_value*)p4);
  59926. }else{
  59927. Mem *p = (Mem*)p4;
  59928. if( p->szMalloc ) sqlite3DbFree(db, p->zMalloc);
  59929. sqlite3DbFree(db, p);
  59930. }
  59931. break;
  59932. }
  59933. case P4_VTAB : {
  59934. if( db->pnBytesFreed==0 ) sqlite3VtabUnlock((VTable *)p4);
  59935. break;
  59936. }
  59937. }
  59938. }
  59939. }
  59940. /*
  59941. ** Free the space allocated for aOp and any p4 values allocated for the
  59942. ** opcodes contained within. If aOp is not NULL it is assumed to contain
  59943. ** nOp entries.
  59944. */
  59945. static void vdbeFreeOpArray(sqlite3 *db, Op *aOp, int nOp){
  59946. if( aOp ){
  59947. Op *pOp;
  59948. for(pOp=aOp; pOp<&aOp[nOp]; pOp++){
  59949. freeP4(db, pOp->p4type, pOp->p4.p);
  59950. #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  59951. sqlite3DbFree(db, pOp->zComment);
  59952. #endif
  59953. }
  59954. }
  59955. sqlite3DbFree(db, aOp);
  59956. }
  59957. /*
  59958. ** Link the SubProgram object passed as the second argument into the linked
  59959. ** list at Vdbe.pSubProgram. This list is used to delete all sub-program
  59960. ** objects when the VM is no longer required.
  59961. */
  59962. SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *pVdbe, SubProgram *p){
  59963. p->pNext = pVdbe->pProgram;
  59964. pVdbe->pProgram = p;
  59965. }
  59966. /*
  59967. ** Change the opcode at addr into OP_Noop
  59968. */
  59969. SQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe *p, int addr){
  59970. if( addr<p->nOp ){
  59971. VdbeOp *pOp = &p->aOp[addr];
  59972. sqlite3 *db = p->db;
  59973. freeP4(db, pOp->p4type, pOp->p4.p);
  59974. memset(pOp, 0, sizeof(pOp[0]));
  59975. pOp->opcode = OP_Noop;
  59976. if( addr==p->nOp-1 ) p->nOp--;
  59977. }
  59978. }
  59979. /*
  59980. ** If the last opcode is "op" and it is not a jump destination,
  59981. ** then remove it. Return true if and only if an opcode was removed.
  59982. */
  59983. SQLITE_PRIVATE int sqlite3VdbeDeletePriorOpcode(Vdbe *p, u8 op){
  59984. if( (p->nOp-1)>(p->pParse->iFixedOp) && p->aOp[p->nOp-1].opcode==op ){
  59985. sqlite3VdbeChangeToNoop(p, p->nOp-1);
  59986. return 1;
  59987. }else{
  59988. return 0;
  59989. }
  59990. }
  59991. /*
  59992. ** Change the value of the P4 operand for a specific instruction.
  59993. ** This routine is useful when a large program is loaded from a
  59994. ** static array using sqlite3VdbeAddOpList but we want to make a
  59995. ** few minor changes to the program.
  59996. **
  59997. ** If n>=0 then the P4 operand is dynamic, meaning that a copy of
  59998. ** the string is made into memory obtained from sqlite3_malloc().
  59999. ** A value of n==0 means copy bytes of zP4 up to and including the
  60000. ** first null byte. If n>0 then copy n+1 bytes of zP4.
  60001. **
  60002. ** Other values of n (P4_STATIC, P4_COLLSEQ etc.) indicate that zP4 points
  60003. ** to a string or structure that is guaranteed to exist for the lifetime of
  60004. ** the Vdbe. In these cases we can just copy the pointer.
  60005. **
  60006. ** If addr<0 then change P4 on the most recently inserted instruction.
  60007. */
  60008. SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe *p, int addr, const char *zP4, int n){
  60009. Op *pOp;
  60010. sqlite3 *db;
  60011. assert( p!=0 );
  60012. db = p->db;
  60013. assert( p->magic==VDBE_MAGIC_INIT );
  60014. if( p->aOp==0 || db->mallocFailed ){
  60015. if( n!=P4_VTAB ){
  60016. freeP4(db, n, (void*)*(char**)&zP4);
  60017. }
  60018. return;
  60019. }
  60020. assert( p->nOp>0 );
  60021. assert( addr<p->nOp );
  60022. if( addr<0 ){
  60023. addr = p->nOp - 1;
  60024. }
  60025. pOp = &p->aOp[addr];
  60026. assert( pOp->p4type==P4_NOTUSED
  60027. || pOp->p4type==P4_INT32
  60028. || pOp->p4type==P4_KEYINFO );
  60029. freeP4(db, pOp->p4type, pOp->p4.p);
  60030. pOp->p4.p = 0;
  60031. if( n==P4_INT32 ){
  60032. /* Note: this cast is safe, because the origin data point was an int
  60033. ** that was cast to a (const char *). */
  60034. pOp->p4.i = SQLITE_PTR_TO_INT(zP4);
  60035. pOp->p4type = P4_INT32;
  60036. }else if( zP4==0 ){
  60037. pOp->p4.p = 0;
  60038. pOp->p4type = P4_NOTUSED;
  60039. }else if( n==P4_KEYINFO ){
  60040. pOp->p4.p = (void*)zP4;
  60041. pOp->p4type = P4_KEYINFO;
  60042. }else if( n==P4_VTAB ){
  60043. pOp->p4.p = (void*)zP4;
  60044. pOp->p4type = P4_VTAB;
  60045. sqlite3VtabLock((VTable *)zP4);
  60046. assert( ((VTable *)zP4)->db==p->db );
  60047. }else if( n<0 ){
  60048. pOp->p4.p = (void*)zP4;
  60049. pOp->p4type = (signed char)n;
  60050. }else{
  60051. if( n==0 ) n = sqlite3Strlen30(zP4);
  60052. pOp->p4.z = sqlite3DbStrNDup(p->db, zP4, n);
  60053. pOp->p4type = P4_DYNAMIC;
  60054. }
  60055. }
  60056. /*
  60057. ** Set the P4 on the most recently added opcode to the KeyInfo for the
  60058. ** index given.
  60059. */
  60060. SQLITE_PRIVATE void sqlite3VdbeSetP4KeyInfo(Parse *pParse, Index *pIdx){
  60061. Vdbe *v = pParse->pVdbe;
  60062. assert( v!=0 );
  60063. assert( pIdx!=0 );
  60064. sqlite3VdbeChangeP4(v, -1, (char*)sqlite3KeyInfoOfIndex(pParse, pIdx),
  60065. P4_KEYINFO);
  60066. }
  60067. #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  60068. /*
  60069. ** Change the comment on the most recently coded instruction. Or
  60070. ** insert a No-op and add the comment to that new instruction. This
  60071. ** makes the code easier to read during debugging. None of this happens
  60072. ** in a production build.
  60073. */
  60074. static void vdbeVComment(Vdbe *p, const char *zFormat, va_list ap){
  60075. assert( p->nOp>0 || p->aOp==0 );
  60076. assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed );
  60077. if( p->nOp ){
  60078. assert( p->aOp );
  60079. sqlite3DbFree(p->db, p->aOp[p->nOp-1].zComment);
  60080. p->aOp[p->nOp-1].zComment = sqlite3VMPrintf(p->db, zFormat, ap);
  60081. }
  60082. }
  60083. SQLITE_PRIVATE void sqlite3VdbeComment(Vdbe *p, const char *zFormat, ...){
  60084. va_list ap;
  60085. if( p ){
  60086. va_start(ap, zFormat);
  60087. vdbeVComment(p, zFormat, ap);
  60088. va_end(ap);
  60089. }
  60090. }
  60091. SQLITE_PRIVATE void sqlite3VdbeNoopComment(Vdbe *p, const char *zFormat, ...){
  60092. va_list ap;
  60093. if( p ){
  60094. sqlite3VdbeAddOp0(p, OP_Noop);
  60095. va_start(ap, zFormat);
  60096. vdbeVComment(p, zFormat, ap);
  60097. va_end(ap);
  60098. }
  60099. }
  60100. #endif /* NDEBUG */
  60101. #ifdef SQLITE_VDBE_COVERAGE
  60102. /*
  60103. ** Set the value if the iSrcLine field for the previously coded instruction.
  60104. */
  60105. SQLITE_PRIVATE void sqlite3VdbeSetLineNumber(Vdbe *v, int iLine){
  60106. sqlite3VdbeGetOp(v,-1)->iSrcLine = iLine;
  60107. }
  60108. #endif /* SQLITE_VDBE_COVERAGE */
  60109. /*
  60110. ** Return the opcode for a given address. If the address is -1, then
  60111. ** return the most recently inserted opcode.
  60112. **
  60113. ** If a memory allocation error has occurred prior to the calling of this
  60114. ** routine, then a pointer to a dummy VdbeOp will be returned. That opcode
  60115. ** is readable but not writable, though it is cast to a writable value.
  60116. ** The return of a dummy opcode allows the call to continue functioning
  60117. ** after an OOM fault without having to check to see if the return from
  60118. ** this routine is a valid pointer. But because the dummy.opcode is 0,
  60119. ** dummy will never be written to. This is verified by code inspection and
  60120. ** by running with Valgrind.
  60121. */
  60122. SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe *p, int addr){
  60123. /* C89 specifies that the constant "dummy" will be initialized to all
  60124. ** zeros, which is correct. MSVC generates a warning, nevertheless. */
  60125. static VdbeOp dummy; /* Ignore the MSVC warning about no initializer */
  60126. assert( p->magic==VDBE_MAGIC_INIT );
  60127. if( addr<0 ){
  60128. addr = p->nOp - 1;
  60129. }
  60130. assert( (addr>=0 && addr<p->nOp) || p->db->mallocFailed );
  60131. if( p->db->mallocFailed ){
  60132. return (VdbeOp*)&dummy;
  60133. }else{
  60134. return &p->aOp[addr];
  60135. }
  60136. }
  60137. #if defined(SQLITE_ENABLE_EXPLAIN_COMMENTS)
  60138. /*
  60139. ** Return an integer value for one of the parameters to the opcode pOp
  60140. ** determined by character c.
  60141. */
  60142. static int translateP(char c, const Op *pOp){
  60143. if( c=='1' ) return pOp->p1;
  60144. if( c=='2' ) return pOp->p2;
  60145. if( c=='3' ) return pOp->p3;
  60146. if( c=='4' ) return pOp->p4.i;
  60147. return pOp->p5;
  60148. }
  60149. /*
  60150. ** Compute a string for the "comment" field of a VDBE opcode listing.
  60151. **
  60152. ** The Synopsis: field in comments in the vdbe.c source file gets converted
  60153. ** to an extra string that is appended to the sqlite3OpcodeName(). In the
  60154. ** absence of other comments, this synopsis becomes the comment on the opcode.
  60155. ** Some translation occurs:
  60156. **
  60157. ** "PX" -> "r[X]"
  60158. ** "PX@PY" -> "r[X..X+Y-1]" or "r[x]" if y is 0 or 1
  60159. ** "PX@PY+1" -> "r[X..X+Y]" or "r[x]" if y is 0
  60160. ** "PY..PY" -> "r[X..Y]" or "r[x]" if y<=x
  60161. */
  60162. static int displayComment(
  60163. const Op *pOp, /* The opcode to be commented */
  60164. const char *zP4, /* Previously obtained value for P4 */
  60165. char *zTemp, /* Write result here */
  60166. int nTemp /* Space available in zTemp[] */
  60167. ){
  60168. const char *zOpName;
  60169. const char *zSynopsis;
  60170. int nOpName;
  60171. int ii, jj;
  60172. zOpName = sqlite3OpcodeName(pOp->opcode);
  60173. nOpName = sqlite3Strlen30(zOpName);
  60174. if( zOpName[nOpName+1] ){
  60175. int seenCom = 0;
  60176. char c;
  60177. zSynopsis = zOpName += nOpName + 1;
  60178. for(ii=jj=0; jj<nTemp-1 && (c = zSynopsis[ii])!=0; ii++){
  60179. if( c=='P' ){
  60180. c = zSynopsis[++ii];
  60181. if( c=='4' ){
  60182. sqlite3_snprintf(nTemp-jj, zTemp+jj, "%s", zP4);
  60183. }else if( c=='X' ){
  60184. sqlite3_snprintf(nTemp-jj, zTemp+jj, "%s", pOp->zComment);
  60185. seenCom = 1;
  60186. }else{
  60187. int v1 = translateP(c, pOp);
  60188. int v2;
  60189. sqlite3_snprintf(nTemp-jj, zTemp+jj, "%d", v1);
  60190. if( strncmp(zSynopsis+ii+1, "@P", 2)==0 ){
  60191. ii += 3;
  60192. jj += sqlite3Strlen30(zTemp+jj);
  60193. v2 = translateP(zSynopsis[ii], pOp);
  60194. if( strncmp(zSynopsis+ii+1,"+1",2)==0 ){
  60195. ii += 2;
  60196. v2++;
  60197. }
  60198. if( v2>1 ){
  60199. sqlite3_snprintf(nTemp-jj, zTemp+jj, "..%d", v1+v2-1);
  60200. }
  60201. }else if( strncmp(zSynopsis+ii+1, "..P3", 4)==0 && pOp->p3==0 ){
  60202. ii += 4;
  60203. }
  60204. }
  60205. jj += sqlite3Strlen30(zTemp+jj);
  60206. }else{
  60207. zTemp[jj++] = c;
  60208. }
  60209. }
  60210. if( !seenCom && jj<nTemp-5 && pOp->zComment ){
  60211. sqlite3_snprintf(nTemp-jj, zTemp+jj, "; %s", pOp->zComment);
  60212. jj += sqlite3Strlen30(zTemp+jj);
  60213. }
  60214. if( jj<nTemp ) zTemp[jj] = 0;
  60215. }else if( pOp->zComment ){
  60216. sqlite3_snprintf(nTemp, zTemp, "%s", pOp->zComment);
  60217. jj = sqlite3Strlen30(zTemp);
  60218. }else{
  60219. zTemp[0] = 0;
  60220. jj = 0;
  60221. }
  60222. return jj;
  60223. }
  60224. #endif /* SQLITE_DEBUG */
  60225. #if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) \
  60226. || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
  60227. /*
  60228. ** Compute a string that describes the P4 parameter for an opcode.
  60229. ** Use zTemp for any required temporary buffer space.
  60230. */
  60231. static char *displayP4(Op *pOp, char *zTemp, int nTemp){
  60232. char *zP4 = zTemp;
  60233. assert( nTemp>=20 );
  60234. switch( pOp->p4type ){
  60235. case P4_KEYINFO: {
  60236. int i, j;
  60237. KeyInfo *pKeyInfo = pOp->p4.pKeyInfo;
  60238. assert( pKeyInfo->aSortOrder!=0 );
  60239. sqlite3_snprintf(nTemp, zTemp, "k(%d", pKeyInfo->nField);
  60240. i = sqlite3Strlen30(zTemp);
  60241. for(j=0; j<pKeyInfo->nField; j++){
  60242. CollSeq *pColl = pKeyInfo->aColl[j];
  60243. const char *zColl = pColl ? pColl->zName : "nil";
  60244. int n = sqlite3Strlen30(zColl);
  60245. if( n==6 && memcmp(zColl,"BINARY",6)==0 ){
  60246. zColl = "B";
  60247. n = 1;
  60248. }
  60249. if( i+n>nTemp-6 ){
  60250. memcpy(&zTemp[i],",...",4);
  60251. break;
  60252. }
  60253. zTemp[i++] = ',';
  60254. if( pKeyInfo->aSortOrder[j] ){
  60255. zTemp[i++] = '-';
  60256. }
  60257. memcpy(&zTemp[i], zColl, n+1);
  60258. i += n;
  60259. }
  60260. zTemp[i++] = ')';
  60261. zTemp[i] = 0;
  60262. assert( i<nTemp );
  60263. break;
  60264. }
  60265. case P4_COLLSEQ: {
  60266. CollSeq *pColl = pOp->p4.pColl;
  60267. sqlite3_snprintf(nTemp, zTemp, "(%.20s)", pColl->zName);
  60268. break;
  60269. }
  60270. case P4_FUNCDEF: {
  60271. FuncDef *pDef = pOp->p4.pFunc;
  60272. sqlite3_snprintf(nTemp, zTemp, "%s(%d)", pDef->zName, pDef->nArg);
  60273. break;
  60274. }
  60275. case P4_INT64: {
  60276. sqlite3_snprintf(nTemp, zTemp, "%lld", *pOp->p4.pI64);
  60277. break;
  60278. }
  60279. case P4_INT32: {
  60280. sqlite3_snprintf(nTemp, zTemp, "%d", pOp->p4.i);
  60281. break;
  60282. }
  60283. case P4_REAL: {
  60284. sqlite3_snprintf(nTemp, zTemp, "%.16g", *pOp->p4.pReal);
  60285. break;
  60286. }
  60287. case P4_MEM: {
  60288. Mem *pMem = pOp->p4.pMem;
  60289. if( pMem->flags & MEM_Str ){
  60290. zP4 = pMem->z;
  60291. }else if( pMem->flags & MEM_Int ){
  60292. sqlite3_snprintf(nTemp, zTemp, "%lld", pMem->u.i);
  60293. }else if( pMem->flags & MEM_Real ){
  60294. sqlite3_snprintf(nTemp, zTemp, "%.16g", pMem->u.r);
  60295. }else if( pMem->flags & MEM_Null ){
  60296. sqlite3_snprintf(nTemp, zTemp, "NULL");
  60297. }else{
  60298. assert( pMem->flags & MEM_Blob );
  60299. zP4 = "(blob)";
  60300. }
  60301. break;
  60302. }
  60303. #ifndef SQLITE_OMIT_VIRTUALTABLE
  60304. case P4_VTAB: {
  60305. sqlite3_vtab *pVtab = pOp->p4.pVtab->pVtab;
  60306. sqlite3_snprintf(nTemp, zTemp, "vtab:%p:%p", pVtab, pVtab->pModule);
  60307. break;
  60308. }
  60309. #endif
  60310. case P4_INTARRAY: {
  60311. sqlite3_snprintf(nTemp, zTemp, "intarray");
  60312. break;
  60313. }
  60314. case P4_SUBPROGRAM: {
  60315. sqlite3_snprintf(nTemp, zTemp, "program");
  60316. break;
  60317. }
  60318. case P4_ADVANCE: {
  60319. zTemp[0] = 0;
  60320. break;
  60321. }
  60322. default: {
  60323. zP4 = pOp->p4.z;
  60324. if( zP4==0 ){
  60325. zP4 = zTemp;
  60326. zTemp[0] = 0;
  60327. }
  60328. }
  60329. }
  60330. assert( zP4!=0 );
  60331. return zP4;
  60332. }
  60333. #endif
  60334. /*
  60335. ** Declare to the Vdbe that the BTree object at db->aDb[i] is used.
  60336. **
  60337. ** The prepared statements need to know in advance the complete set of
  60338. ** attached databases that will be use. A mask of these databases
  60339. ** is maintained in p->btreeMask. The p->lockMask value is the subset of
  60340. ** p->btreeMask of databases that will require a lock.
  60341. */
  60342. SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe *p, int i){
  60343. assert( i>=0 && i<p->db->nDb && i<(int)sizeof(yDbMask)*8 );
  60344. assert( i<(int)sizeof(p->btreeMask)*8 );
  60345. DbMaskSet(p->btreeMask, i);
  60346. if( i!=1 && sqlite3BtreeSharable(p->db->aDb[i].pBt) ){
  60347. DbMaskSet(p->lockMask, i);
  60348. }
  60349. }
  60350. #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
  60351. /*
  60352. ** If SQLite is compiled to support shared-cache mode and to be threadsafe,
  60353. ** this routine obtains the mutex associated with each BtShared structure
  60354. ** that may be accessed by the VM passed as an argument. In doing so it also
  60355. ** sets the BtShared.db member of each of the BtShared structures, ensuring
  60356. ** that the correct busy-handler callback is invoked if required.
  60357. **
  60358. ** If SQLite is not threadsafe but does support shared-cache mode, then
  60359. ** sqlite3BtreeEnter() is invoked to set the BtShared.db variables
  60360. ** of all of BtShared structures accessible via the database handle
  60361. ** associated with the VM.
  60362. **
  60363. ** If SQLite is not threadsafe and does not support shared-cache mode, this
  60364. ** function is a no-op.
  60365. **
  60366. ** The p->btreeMask field is a bitmask of all btrees that the prepared
  60367. ** statement p will ever use. Let N be the number of bits in p->btreeMask
  60368. ** corresponding to btrees that use shared cache. Then the runtime of
  60369. ** this routine is N*N. But as N is rarely more than 1, this should not
  60370. ** be a problem.
  60371. */
  60372. SQLITE_PRIVATE void sqlite3VdbeEnter(Vdbe *p){
  60373. int i;
  60374. sqlite3 *db;
  60375. Db *aDb;
  60376. int nDb;
  60377. if( DbMaskAllZero(p->lockMask) ) return; /* The common case */
  60378. db = p->db;
  60379. aDb = db->aDb;
  60380. nDb = db->nDb;
  60381. for(i=0; i<nDb; i++){
  60382. if( i!=1 && DbMaskTest(p->lockMask,i) && ALWAYS(aDb[i].pBt!=0) ){
  60383. sqlite3BtreeEnter(aDb[i].pBt);
  60384. }
  60385. }
  60386. }
  60387. #endif
  60388. #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
  60389. /*
  60390. ** Unlock all of the btrees previously locked by a call to sqlite3VdbeEnter().
  60391. */
  60392. SQLITE_PRIVATE void sqlite3VdbeLeave(Vdbe *p){
  60393. int i;
  60394. sqlite3 *db;
  60395. Db *aDb;
  60396. int nDb;
  60397. if( DbMaskAllZero(p->lockMask) ) return; /* The common case */
  60398. db = p->db;
  60399. aDb = db->aDb;
  60400. nDb = db->nDb;
  60401. for(i=0; i<nDb; i++){
  60402. if( i!=1 && DbMaskTest(p->lockMask,i) && ALWAYS(aDb[i].pBt!=0) ){
  60403. sqlite3BtreeLeave(aDb[i].pBt);
  60404. }
  60405. }
  60406. }
  60407. #endif
  60408. #if defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
  60409. /*
  60410. ** Print a single opcode. This routine is used for debugging only.
  60411. */
  60412. SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE *pOut, int pc, Op *pOp){
  60413. char *zP4;
  60414. char zPtr[50];
  60415. char zCom[100];
  60416. static const char *zFormat1 = "%4d %-13s %4d %4d %4d %-13s %.2X %s\n";
  60417. if( pOut==0 ) pOut = stdout;
  60418. zP4 = displayP4(pOp, zPtr, sizeof(zPtr));
  60419. #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  60420. displayComment(pOp, zP4, zCom, sizeof(zCom));
  60421. #else
  60422. zCom[0] = 0;
  60423. #endif
  60424. /* NB: The sqlite3OpcodeName() function is implemented by code created
  60425. ** by the mkopcodeh.awk and mkopcodec.awk scripts which extract the
  60426. ** information from the vdbe.c source text */
  60427. fprintf(pOut, zFormat1, pc,
  60428. sqlite3OpcodeName(pOp->opcode), pOp->p1, pOp->p2, pOp->p3, zP4, pOp->p5,
  60429. zCom
  60430. );
  60431. fflush(pOut);
  60432. }
  60433. #endif
  60434. /*
  60435. ** Release an array of N Mem elements
  60436. */
  60437. static void releaseMemArray(Mem *p, int N){
  60438. if( p && N ){
  60439. Mem *pEnd = &p[N];
  60440. sqlite3 *db = p->db;
  60441. u8 malloc_failed = db->mallocFailed;
  60442. if( db->pnBytesFreed ){
  60443. do{
  60444. if( p->szMalloc ) sqlite3DbFree(db, p->zMalloc);
  60445. }while( (++p)<pEnd );
  60446. return;
  60447. }
  60448. do{
  60449. assert( (&p[1])==pEnd || p[0].db==p[1].db );
  60450. assert( sqlite3VdbeCheckMemInvariants(p) );
  60451. /* This block is really an inlined version of sqlite3VdbeMemRelease()
  60452. ** that takes advantage of the fact that the memory cell value is
  60453. ** being set to NULL after releasing any dynamic resources.
  60454. **
  60455. ** The justification for duplicating code is that according to
  60456. ** callgrind, this causes a certain test case to hit the CPU 4.7
  60457. ** percent less (x86 linux, gcc version 4.1.2, -O6) than if
  60458. ** sqlite3MemRelease() were called from here. With -O2, this jumps
  60459. ** to 6.6 percent. The test case is inserting 1000 rows into a table
  60460. ** with no indexes using a single prepared INSERT statement, bind()
  60461. ** and reset(). Inserts are grouped into a transaction.
  60462. */
  60463. testcase( p->flags & MEM_Agg );
  60464. testcase( p->flags & MEM_Dyn );
  60465. testcase( p->flags & MEM_Frame );
  60466. testcase( p->flags & MEM_RowSet );
  60467. if( p->flags&(MEM_Agg|MEM_Dyn|MEM_Frame|MEM_RowSet) ){
  60468. sqlite3VdbeMemRelease(p);
  60469. }else if( p->szMalloc ){
  60470. sqlite3DbFree(db, p->zMalloc);
  60471. p->szMalloc = 0;
  60472. }
  60473. p->flags = MEM_Undefined;
  60474. }while( (++p)<pEnd );
  60475. db->mallocFailed = malloc_failed;
  60476. }
  60477. }
  60478. /*
  60479. ** Delete a VdbeFrame object and its contents. VdbeFrame objects are
  60480. ** allocated by the OP_Program opcode in sqlite3VdbeExec().
  60481. */
  60482. SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame *p){
  60483. int i;
  60484. Mem *aMem = VdbeFrameMem(p);
  60485. VdbeCursor **apCsr = (VdbeCursor **)&aMem[p->nChildMem];
  60486. for(i=0; i<p->nChildCsr; i++){
  60487. sqlite3VdbeFreeCursor(p->v, apCsr[i]);
  60488. }
  60489. releaseMemArray(aMem, p->nChildMem);
  60490. sqlite3DbFree(p->v->db, p);
  60491. }
  60492. #ifndef SQLITE_OMIT_EXPLAIN
  60493. /*
  60494. ** Give a listing of the program in the virtual machine.
  60495. **
  60496. ** The interface is the same as sqlite3VdbeExec(). But instead of
  60497. ** running the code, it invokes the callback once for each instruction.
  60498. ** This feature is used to implement "EXPLAIN".
  60499. **
  60500. ** When p->explain==1, each instruction is listed. When
  60501. ** p->explain==2, only OP_Explain instructions are listed and these
  60502. ** are shown in a different format. p->explain==2 is used to implement
  60503. ** EXPLAIN QUERY PLAN.
  60504. **
  60505. ** When p->explain==1, first the main program is listed, then each of
  60506. ** the trigger subprograms are listed one by one.
  60507. */
  60508. SQLITE_PRIVATE int sqlite3VdbeList(
  60509. Vdbe *p /* The VDBE */
  60510. ){
  60511. int nRow; /* Stop when row count reaches this */
  60512. int nSub = 0; /* Number of sub-vdbes seen so far */
  60513. SubProgram **apSub = 0; /* Array of sub-vdbes */
  60514. Mem *pSub = 0; /* Memory cell hold array of subprogs */
  60515. sqlite3 *db = p->db; /* The database connection */
  60516. int i; /* Loop counter */
  60517. int rc = SQLITE_OK; /* Return code */
  60518. Mem *pMem = &p->aMem[1]; /* First Mem of result set */
  60519. assert( p->explain );
  60520. assert( p->magic==VDBE_MAGIC_RUN );
  60521. assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY || p->rc==SQLITE_NOMEM );
  60522. /* Even though this opcode does not use dynamic strings for
  60523. ** the result, result columns may become dynamic if the user calls
  60524. ** sqlite3_column_text16(), causing a translation to UTF-16 encoding.
  60525. */
  60526. releaseMemArray(pMem, 8);
  60527. p->pResultSet = 0;
  60528. if( p->rc==SQLITE_NOMEM ){
  60529. /* This happens if a malloc() inside a call to sqlite3_column_text() or
  60530. ** sqlite3_column_text16() failed. */
  60531. db->mallocFailed = 1;
  60532. return SQLITE_ERROR;
  60533. }
  60534. /* When the number of output rows reaches nRow, that means the
  60535. ** listing has finished and sqlite3_step() should return SQLITE_DONE.
  60536. ** nRow is the sum of the number of rows in the main program, plus
  60537. ** the sum of the number of rows in all trigger subprograms encountered
  60538. ** so far. The nRow value will increase as new trigger subprograms are
  60539. ** encountered, but p->pc will eventually catch up to nRow.
  60540. */
  60541. nRow = p->nOp;
  60542. if( p->explain==1 ){
  60543. /* The first 8 memory cells are used for the result set. So we will
  60544. ** commandeer the 9th cell to use as storage for an array of pointers
  60545. ** to trigger subprograms. The VDBE is guaranteed to have at least 9
  60546. ** cells. */
  60547. assert( p->nMem>9 );
  60548. pSub = &p->aMem[9];
  60549. if( pSub->flags&MEM_Blob ){
  60550. /* On the first call to sqlite3_step(), pSub will hold a NULL. It is
  60551. ** initialized to a BLOB by the P4_SUBPROGRAM processing logic below */
  60552. nSub = pSub->n/sizeof(Vdbe*);
  60553. apSub = (SubProgram **)pSub->z;
  60554. }
  60555. for(i=0; i<nSub; i++){
  60556. nRow += apSub[i]->nOp;
  60557. }
  60558. }
  60559. do{
  60560. i = p->pc++;
  60561. }while( i<nRow && p->explain==2 && p->aOp[i].opcode!=OP_Explain );
  60562. if( i>=nRow ){
  60563. p->rc = SQLITE_OK;
  60564. rc = SQLITE_DONE;
  60565. }else if( db->u1.isInterrupted ){
  60566. p->rc = SQLITE_INTERRUPT;
  60567. rc = SQLITE_ERROR;
  60568. sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(p->rc));
  60569. }else{
  60570. char *zP4;
  60571. Op *pOp;
  60572. if( i<p->nOp ){
  60573. /* The output line number is small enough that we are still in the
  60574. ** main program. */
  60575. pOp = &p->aOp[i];
  60576. }else{
  60577. /* We are currently listing subprograms. Figure out which one and
  60578. ** pick up the appropriate opcode. */
  60579. int j;
  60580. i -= p->nOp;
  60581. for(j=0; i>=apSub[j]->nOp; j++){
  60582. i -= apSub[j]->nOp;
  60583. }
  60584. pOp = &apSub[j]->aOp[i];
  60585. }
  60586. if( p->explain==1 ){
  60587. pMem->flags = MEM_Int;
  60588. pMem->u.i = i; /* Program counter */
  60589. pMem++;
  60590. pMem->flags = MEM_Static|MEM_Str|MEM_Term;
  60591. pMem->z = (char*)sqlite3OpcodeName(pOp->opcode); /* Opcode */
  60592. assert( pMem->z!=0 );
  60593. pMem->n = sqlite3Strlen30(pMem->z);
  60594. pMem->enc = SQLITE_UTF8;
  60595. pMem++;
  60596. /* When an OP_Program opcode is encounter (the only opcode that has
  60597. ** a P4_SUBPROGRAM argument), expand the size of the array of subprograms
  60598. ** kept in p->aMem[9].z to hold the new program - assuming this subprogram
  60599. ** has not already been seen.
  60600. */
  60601. if( pOp->p4type==P4_SUBPROGRAM ){
  60602. int nByte = (nSub+1)*sizeof(SubProgram*);
  60603. int j;
  60604. for(j=0; j<nSub; j++){
  60605. if( apSub[j]==pOp->p4.pProgram ) break;
  60606. }
  60607. if( j==nSub && SQLITE_OK==sqlite3VdbeMemGrow(pSub, nByte, nSub!=0) ){
  60608. apSub = (SubProgram **)pSub->z;
  60609. apSub[nSub++] = pOp->p4.pProgram;
  60610. pSub->flags |= MEM_Blob;
  60611. pSub->n = nSub*sizeof(SubProgram*);
  60612. }
  60613. }
  60614. }
  60615. pMem->flags = MEM_Int;
  60616. pMem->u.i = pOp->p1; /* P1 */
  60617. pMem++;
  60618. pMem->flags = MEM_Int;
  60619. pMem->u.i = pOp->p2; /* P2 */
  60620. pMem++;
  60621. pMem->flags = MEM_Int;
  60622. pMem->u.i = pOp->p3; /* P3 */
  60623. pMem++;
  60624. if( sqlite3VdbeMemClearAndResize(pMem, 32) ){ /* P4 */
  60625. assert( p->db->mallocFailed );
  60626. return SQLITE_ERROR;
  60627. }
  60628. pMem->flags = MEM_Str|MEM_Term;
  60629. zP4 = displayP4(pOp, pMem->z, 32);
  60630. if( zP4!=pMem->z ){
  60631. sqlite3VdbeMemSetStr(pMem, zP4, -1, SQLITE_UTF8, 0);
  60632. }else{
  60633. assert( pMem->z!=0 );
  60634. pMem->n = sqlite3Strlen30(pMem->z);
  60635. pMem->enc = SQLITE_UTF8;
  60636. }
  60637. pMem++;
  60638. if( p->explain==1 ){
  60639. if( sqlite3VdbeMemClearAndResize(pMem, 4) ){
  60640. assert( p->db->mallocFailed );
  60641. return SQLITE_ERROR;
  60642. }
  60643. pMem->flags = MEM_Str|MEM_Term;
  60644. pMem->n = 2;
  60645. sqlite3_snprintf(3, pMem->z, "%.2x", pOp->p5); /* P5 */
  60646. pMem->enc = SQLITE_UTF8;
  60647. pMem++;
  60648. #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  60649. if( sqlite3VdbeMemClearAndResize(pMem, 500) ){
  60650. assert( p->db->mallocFailed );
  60651. return SQLITE_ERROR;
  60652. }
  60653. pMem->flags = MEM_Str|MEM_Term;
  60654. pMem->n = displayComment(pOp, zP4, pMem->z, 500);
  60655. pMem->enc = SQLITE_UTF8;
  60656. #else
  60657. pMem->flags = MEM_Null; /* Comment */
  60658. #endif
  60659. }
  60660. p->nResColumn = 8 - 4*(p->explain-1);
  60661. p->pResultSet = &p->aMem[1];
  60662. p->rc = SQLITE_OK;
  60663. rc = SQLITE_ROW;
  60664. }
  60665. return rc;
  60666. }
  60667. #endif /* SQLITE_OMIT_EXPLAIN */
  60668. #ifdef SQLITE_DEBUG
  60669. /*
  60670. ** Print the SQL that was used to generate a VDBE program.
  60671. */
  60672. SQLITE_PRIVATE void sqlite3VdbePrintSql(Vdbe *p){
  60673. const char *z = 0;
  60674. if( p->zSql ){
  60675. z = p->zSql;
  60676. }else if( p->nOp>=1 ){
  60677. const VdbeOp *pOp = &p->aOp[0];
  60678. if( pOp->opcode==OP_Init && pOp->p4.z!=0 ){
  60679. z = pOp->p4.z;
  60680. while( sqlite3Isspace(*z) ) z++;
  60681. }
  60682. }
  60683. if( z ) printf("SQL: [%s]\n", z);
  60684. }
  60685. #endif
  60686. #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
  60687. /*
  60688. ** Print an IOTRACE message showing SQL content.
  60689. */
  60690. SQLITE_PRIVATE void sqlite3VdbeIOTraceSql(Vdbe *p){
  60691. int nOp = p->nOp;
  60692. VdbeOp *pOp;
  60693. if( sqlite3IoTrace==0 ) return;
  60694. if( nOp<1 ) return;
  60695. pOp = &p->aOp[0];
  60696. if( pOp->opcode==OP_Init && pOp->p4.z!=0 ){
  60697. int i, j;
  60698. char z[1000];
  60699. sqlite3_snprintf(sizeof(z), z, "%s", pOp->p4.z);
  60700. for(i=0; sqlite3Isspace(z[i]); i++){}
  60701. for(j=0; z[i]; i++){
  60702. if( sqlite3Isspace(z[i]) ){
  60703. if( z[i-1]!=' ' ){
  60704. z[j++] = ' ';
  60705. }
  60706. }else{
  60707. z[j++] = z[i];
  60708. }
  60709. }
  60710. z[j] = 0;
  60711. sqlite3IoTrace("SQL %s\n", z);
  60712. }
  60713. }
  60714. #endif /* !SQLITE_OMIT_TRACE && SQLITE_ENABLE_IOTRACE */
  60715. /*
  60716. ** Allocate space from a fixed size buffer and return a pointer to
  60717. ** that space. If insufficient space is available, return NULL.
  60718. **
  60719. ** The pBuf parameter is the initial value of a pointer which will
  60720. ** receive the new memory. pBuf is normally NULL. If pBuf is not
  60721. ** NULL, it means that memory space has already been allocated and that
  60722. ** this routine should not allocate any new memory. When pBuf is not
  60723. ** NULL simply return pBuf. Only allocate new memory space when pBuf
  60724. ** is NULL.
  60725. **
  60726. ** nByte is the number of bytes of space needed.
  60727. **
  60728. ** *ppFrom points to available space and pEnd points to the end of the
  60729. ** available space. When space is allocated, *ppFrom is advanced past
  60730. ** the end of the allocated space.
  60731. **
  60732. ** *pnByte is a counter of the number of bytes of space that have failed
  60733. ** to allocate. If there is insufficient space in *ppFrom to satisfy the
  60734. ** request, then increment *pnByte by the amount of the request.
  60735. */
  60736. static void *allocSpace(
  60737. void *pBuf, /* Where return pointer will be stored */
  60738. int nByte, /* Number of bytes to allocate */
  60739. u8 **ppFrom, /* IN/OUT: Allocate from *ppFrom */
  60740. u8 *pEnd, /* Pointer to 1 byte past the end of *ppFrom buffer */
  60741. int *pnByte /* If allocation cannot be made, increment *pnByte */
  60742. ){
  60743. assert( EIGHT_BYTE_ALIGNMENT(*ppFrom) );
  60744. if( pBuf ) return pBuf;
  60745. nByte = ROUND8(nByte);
  60746. if( &(*ppFrom)[nByte] <= pEnd ){
  60747. pBuf = (void*)*ppFrom;
  60748. *ppFrom += nByte;
  60749. }else{
  60750. *pnByte += nByte;
  60751. }
  60752. return pBuf;
  60753. }
  60754. /*
  60755. ** Rewind the VDBE back to the beginning in preparation for
  60756. ** running it.
  60757. */
  60758. SQLITE_PRIVATE void sqlite3VdbeRewind(Vdbe *p){
  60759. #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
  60760. int i;
  60761. #endif
  60762. assert( p!=0 );
  60763. assert( p->magic==VDBE_MAGIC_INIT );
  60764. /* There should be at least one opcode.
  60765. */
  60766. assert( p->nOp>0 );
  60767. /* Set the magic to VDBE_MAGIC_RUN sooner rather than later. */
  60768. p->magic = VDBE_MAGIC_RUN;
  60769. #ifdef SQLITE_DEBUG
  60770. for(i=1; i<p->nMem; i++){
  60771. assert( p->aMem[i].db==p->db );
  60772. }
  60773. #endif
  60774. p->pc = -1;
  60775. p->rc = SQLITE_OK;
  60776. p->errorAction = OE_Abort;
  60777. p->magic = VDBE_MAGIC_RUN;
  60778. p->nChange = 0;
  60779. p->cacheCtr = 1;
  60780. p->minWriteFileFormat = 255;
  60781. p->iStatement = 0;
  60782. p->nFkConstraint = 0;
  60783. #ifdef VDBE_PROFILE
  60784. for(i=0; i<p->nOp; i++){
  60785. p->aOp[i].cnt = 0;
  60786. p->aOp[i].cycles = 0;
  60787. }
  60788. #endif
  60789. }
  60790. /*
  60791. ** Prepare a virtual machine for execution for the first time after
  60792. ** creating the virtual machine. This involves things such
  60793. ** as allocating registers and initializing the program counter.
  60794. ** After the VDBE has be prepped, it can be executed by one or more
  60795. ** calls to sqlite3VdbeExec().
  60796. **
  60797. ** This function may be called exactly once on each virtual machine.
  60798. ** After this routine is called the VM has been "packaged" and is ready
  60799. ** to run. After this routine is called, further calls to
  60800. ** sqlite3VdbeAddOp() functions are prohibited. This routine disconnects
  60801. ** the Vdbe from the Parse object that helped generate it so that the
  60802. ** the Vdbe becomes an independent entity and the Parse object can be
  60803. ** destroyed.
  60804. **
  60805. ** Use the sqlite3VdbeRewind() procedure to restore a virtual machine back
  60806. ** to its initial state after it has been run.
  60807. */
  60808. SQLITE_PRIVATE void sqlite3VdbeMakeReady(
  60809. Vdbe *p, /* The VDBE */
  60810. Parse *pParse /* Parsing context */
  60811. ){
  60812. sqlite3 *db; /* The database connection */
  60813. int nVar; /* Number of parameters */
  60814. int nMem; /* Number of VM memory registers */
  60815. int nCursor; /* Number of cursors required */
  60816. int nArg; /* Number of arguments in subprograms */
  60817. int nOnce; /* Number of OP_Once instructions */
  60818. int n; /* Loop counter */
  60819. u8 *zCsr; /* Memory available for allocation */
  60820. u8 *zEnd; /* First byte past allocated memory */
  60821. int nByte; /* How much extra memory is needed */
  60822. assert( p!=0 );
  60823. assert( p->nOp>0 );
  60824. assert( pParse!=0 );
  60825. assert( p->magic==VDBE_MAGIC_INIT );
  60826. assert( pParse==p->pParse );
  60827. db = p->db;
  60828. assert( db->mallocFailed==0 );
  60829. nVar = pParse->nVar;
  60830. nMem = pParse->nMem;
  60831. nCursor = pParse->nTab;
  60832. nArg = pParse->nMaxArg;
  60833. nOnce = pParse->nOnce;
  60834. if( nOnce==0 ) nOnce = 1; /* Ensure at least one byte in p->aOnceFlag[] */
  60835. /* For each cursor required, also allocate a memory cell. Memory
  60836. ** cells (nMem+1-nCursor)..nMem, inclusive, will never be used by
  60837. ** the vdbe program. Instead they are used to allocate space for
  60838. ** VdbeCursor/BtCursor structures. The blob of memory associated with
  60839. ** cursor 0 is stored in memory cell nMem. Memory cell (nMem-1)
  60840. ** stores the blob of memory associated with cursor 1, etc.
  60841. **
  60842. ** See also: allocateCursor().
  60843. */
  60844. nMem += nCursor;
  60845. /* Allocate space for memory registers, SQL variables, VDBE cursors and
  60846. ** an array to marshal SQL function arguments in.
  60847. */
  60848. zCsr = (u8*)&p->aOp[p->nOp]; /* Memory avaliable for allocation */
  60849. zEnd = (u8*)&p->aOp[pParse->nOpAlloc]; /* First byte past end of zCsr[] */
  60850. resolveP2Values(p, &nArg);
  60851. p->usesStmtJournal = (u8)(pParse->isMultiWrite && pParse->mayAbort);
  60852. if( pParse->explain && nMem<10 ){
  60853. nMem = 10;
  60854. }
  60855. memset(zCsr, 0, zEnd-zCsr);
  60856. zCsr += (zCsr - (u8*)0)&7;
  60857. assert( EIGHT_BYTE_ALIGNMENT(zCsr) );
  60858. p->expired = 0;
  60859. /* Memory for registers, parameters, cursor, etc, is allocated in two
  60860. ** passes. On the first pass, we try to reuse unused space at the
  60861. ** end of the opcode array. If we are unable to satisfy all memory
  60862. ** requirements by reusing the opcode array tail, then the second
  60863. ** pass will fill in the rest using a fresh allocation.
  60864. **
  60865. ** This two-pass approach that reuses as much memory as possible from
  60866. ** the leftover space at the end of the opcode array can significantly
  60867. ** reduce the amount of memory held by a prepared statement.
  60868. */
  60869. do {
  60870. nByte = 0;
  60871. p->aMem = allocSpace(p->aMem, nMem*sizeof(Mem), &zCsr, zEnd, &nByte);
  60872. p->aVar = allocSpace(p->aVar, nVar*sizeof(Mem), &zCsr, zEnd, &nByte);
  60873. p->apArg = allocSpace(p->apArg, nArg*sizeof(Mem*), &zCsr, zEnd, &nByte);
  60874. p->azVar = allocSpace(p->azVar, nVar*sizeof(char*), &zCsr, zEnd, &nByte);
  60875. p->apCsr = allocSpace(p->apCsr, nCursor*sizeof(VdbeCursor*),
  60876. &zCsr, zEnd, &nByte);
  60877. p->aOnceFlag = allocSpace(p->aOnceFlag, nOnce, &zCsr, zEnd, &nByte);
  60878. if( nByte ){
  60879. p->pFree = sqlite3DbMallocZero(db, nByte);
  60880. }
  60881. zCsr = p->pFree;
  60882. zEnd = &zCsr[nByte];
  60883. }while( nByte && !db->mallocFailed );
  60884. p->nCursor = nCursor;
  60885. p->nOnceFlag = nOnce;
  60886. if( p->aVar ){
  60887. p->nVar = (ynVar)nVar;
  60888. for(n=0; n<nVar; n++){
  60889. p->aVar[n].flags = MEM_Null;
  60890. p->aVar[n].db = db;
  60891. }
  60892. }
  60893. if( p->azVar ){
  60894. p->nzVar = pParse->nzVar;
  60895. memcpy(p->azVar, pParse->azVar, p->nzVar*sizeof(p->azVar[0]));
  60896. memset(pParse->azVar, 0, pParse->nzVar*sizeof(pParse->azVar[0]));
  60897. }
  60898. if( p->aMem ){
  60899. p->aMem--; /* aMem[] goes from 1..nMem */
  60900. p->nMem = nMem; /* not from 0..nMem-1 */
  60901. for(n=1; n<=nMem; n++){
  60902. p->aMem[n].flags = MEM_Undefined;
  60903. p->aMem[n].db = db;
  60904. }
  60905. }
  60906. p->explain = pParse->explain;
  60907. sqlite3VdbeRewind(p);
  60908. }
  60909. /*
  60910. ** Close a VDBE cursor and release all the resources that cursor
  60911. ** happens to hold.
  60912. */
  60913. SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *p, VdbeCursor *pCx){
  60914. if( pCx==0 ){
  60915. return;
  60916. }
  60917. sqlite3VdbeSorterClose(p->db, pCx);
  60918. if( pCx->pBt ){
  60919. sqlite3BtreeClose(pCx->pBt);
  60920. /* The pCx->pCursor will be close automatically, if it exists, by
  60921. ** the call above. */
  60922. }else if( pCx->pCursor ){
  60923. sqlite3BtreeCloseCursor(pCx->pCursor);
  60924. }
  60925. #ifndef SQLITE_OMIT_VIRTUALTABLE
  60926. else if( pCx->pVtabCursor ){
  60927. sqlite3_vtab_cursor *pVtabCursor = pCx->pVtabCursor;
  60928. const sqlite3_module *pModule = pVtabCursor->pVtab->pModule;
  60929. p->inVtabMethod = 1;
  60930. pModule->xClose(pVtabCursor);
  60931. p->inVtabMethod = 0;
  60932. }
  60933. #endif
  60934. }
  60935. /*
  60936. ** Copy the values stored in the VdbeFrame structure to its Vdbe. This
  60937. ** is used, for example, when a trigger sub-program is halted to restore
  60938. ** control to the main program.
  60939. */
  60940. SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *pFrame){
  60941. Vdbe *v = pFrame->v;
  60942. v->aOnceFlag = pFrame->aOnceFlag;
  60943. v->nOnceFlag = pFrame->nOnceFlag;
  60944. v->aOp = pFrame->aOp;
  60945. v->nOp = pFrame->nOp;
  60946. v->aMem = pFrame->aMem;
  60947. v->nMem = pFrame->nMem;
  60948. v->apCsr = pFrame->apCsr;
  60949. v->nCursor = pFrame->nCursor;
  60950. v->db->lastRowid = pFrame->lastRowid;
  60951. v->nChange = pFrame->nChange;
  60952. return pFrame->pc;
  60953. }
  60954. /*
  60955. ** Close all cursors.
  60956. **
  60957. ** Also release any dynamic memory held by the VM in the Vdbe.aMem memory
  60958. ** cell array. This is necessary as the memory cell array may contain
  60959. ** pointers to VdbeFrame objects, which may in turn contain pointers to
  60960. ** open cursors.
  60961. */
  60962. static void closeAllCursors(Vdbe *p){
  60963. if( p->pFrame ){
  60964. VdbeFrame *pFrame;
  60965. for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
  60966. sqlite3VdbeFrameRestore(pFrame);
  60967. p->pFrame = 0;
  60968. p->nFrame = 0;
  60969. }
  60970. assert( p->nFrame==0 );
  60971. if( p->apCsr ){
  60972. int i;
  60973. for(i=0; i<p->nCursor; i++){
  60974. VdbeCursor *pC = p->apCsr[i];
  60975. if( pC ){
  60976. sqlite3VdbeFreeCursor(p, pC);
  60977. p->apCsr[i] = 0;
  60978. }
  60979. }
  60980. }
  60981. if( p->aMem ){
  60982. releaseMemArray(&p->aMem[1], p->nMem);
  60983. }
  60984. while( p->pDelFrame ){
  60985. VdbeFrame *pDel = p->pDelFrame;
  60986. p->pDelFrame = pDel->pParent;
  60987. sqlite3VdbeFrameDelete(pDel);
  60988. }
  60989. /* Delete any auxdata allocations made by the VM */
  60990. if( p->pAuxData ) sqlite3VdbeDeleteAuxData(p, -1, 0);
  60991. assert( p->pAuxData==0 );
  60992. }
  60993. /*
  60994. ** Clean up the VM after a single run.
  60995. */
  60996. static void Cleanup(Vdbe *p){
  60997. sqlite3 *db = p->db;
  60998. #ifdef SQLITE_DEBUG
  60999. /* Execute assert() statements to ensure that the Vdbe.apCsr[] and
  61000. ** Vdbe.aMem[] arrays have already been cleaned up. */
  61001. int i;
  61002. if( p->apCsr ) for(i=0; i<p->nCursor; i++) assert( p->apCsr[i]==0 );
  61003. if( p->aMem ){
  61004. for(i=1; i<=p->nMem; i++) assert( p->aMem[i].flags==MEM_Undefined );
  61005. }
  61006. #endif
  61007. sqlite3DbFree(db, p->zErrMsg);
  61008. p->zErrMsg = 0;
  61009. p->pResultSet = 0;
  61010. }
  61011. /*
  61012. ** Set the number of result columns that will be returned by this SQL
  61013. ** statement. This is now set at compile time, rather than during
  61014. ** execution of the vdbe program so that sqlite3_column_count() can
  61015. ** be called on an SQL statement before sqlite3_step().
  61016. */
  61017. SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe *p, int nResColumn){
  61018. Mem *pColName;
  61019. int n;
  61020. sqlite3 *db = p->db;
  61021. releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
  61022. sqlite3DbFree(db, p->aColName);
  61023. n = nResColumn*COLNAME_N;
  61024. p->nResColumn = (u16)nResColumn;
  61025. p->aColName = pColName = (Mem*)sqlite3DbMallocZero(db, sizeof(Mem)*n );
  61026. if( p->aColName==0 ) return;
  61027. while( n-- > 0 ){
  61028. pColName->flags = MEM_Null;
  61029. pColName->db = p->db;
  61030. pColName++;
  61031. }
  61032. }
  61033. /*
  61034. ** Set the name of the idx'th column to be returned by the SQL statement.
  61035. ** zName must be a pointer to a nul terminated string.
  61036. **
  61037. ** This call must be made after a call to sqlite3VdbeSetNumCols().
  61038. **
  61039. ** The final parameter, xDel, must be one of SQLITE_DYNAMIC, SQLITE_STATIC
  61040. ** or SQLITE_TRANSIENT. If it is SQLITE_DYNAMIC, then the buffer pointed
  61041. ** to by zName will be freed by sqlite3DbFree() when the vdbe is destroyed.
  61042. */
  61043. SQLITE_PRIVATE int sqlite3VdbeSetColName(
  61044. Vdbe *p, /* Vdbe being configured */
  61045. int idx, /* Index of column zName applies to */
  61046. int var, /* One of the COLNAME_* constants */
  61047. const char *zName, /* Pointer to buffer containing name */
  61048. void (*xDel)(void*) /* Memory management strategy for zName */
  61049. ){
  61050. int rc;
  61051. Mem *pColName;
  61052. assert( idx<p->nResColumn );
  61053. assert( var<COLNAME_N );
  61054. if( p->db->mallocFailed ){
  61055. assert( !zName || xDel!=SQLITE_DYNAMIC );
  61056. return SQLITE_NOMEM;
  61057. }
  61058. assert( p->aColName!=0 );
  61059. pColName = &(p->aColName[idx+var*p->nResColumn]);
  61060. rc = sqlite3VdbeMemSetStr(pColName, zName, -1, SQLITE_UTF8, xDel);
  61061. assert( rc!=0 || !zName || (pColName->flags&MEM_Term)!=0 );
  61062. return rc;
  61063. }
  61064. /*
  61065. ** A read or write transaction may or may not be active on database handle
  61066. ** db. If a transaction is active, commit it. If there is a
  61067. ** write-transaction spanning more than one database file, this routine
  61068. ** takes care of the master journal trickery.
  61069. */
  61070. static int vdbeCommit(sqlite3 *db, Vdbe *p){
  61071. int i;
  61072. int nTrans = 0; /* Number of databases with an active write-transaction */
  61073. int rc = SQLITE_OK;
  61074. int needXcommit = 0;
  61075. #ifdef SQLITE_OMIT_VIRTUALTABLE
  61076. /* With this option, sqlite3VtabSync() is defined to be simply
  61077. ** SQLITE_OK so p is not used.
  61078. */
  61079. UNUSED_PARAMETER(p);
  61080. #endif
  61081. /* Before doing anything else, call the xSync() callback for any
  61082. ** virtual module tables written in this transaction. This has to
  61083. ** be done before determining whether a master journal file is
  61084. ** required, as an xSync() callback may add an attached database
  61085. ** to the transaction.
  61086. */
  61087. rc = sqlite3VtabSync(db, p);
  61088. /* This loop determines (a) if the commit hook should be invoked and
  61089. ** (b) how many database files have open write transactions, not
  61090. ** including the temp database. (b) is important because if more than
  61091. ** one database file has an open write transaction, a master journal
  61092. ** file is required for an atomic commit.
  61093. */
  61094. for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
  61095. Btree *pBt = db->aDb[i].pBt;
  61096. if( sqlite3BtreeIsInTrans(pBt) ){
  61097. needXcommit = 1;
  61098. if( i!=1 ) nTrans++;
  61099. sqlite3BtreeEnter(pBt);
  61100. rc = sqlite3PagerExclusiveLock(sqlite3BtreePager(pBt));
  61101. sqlite3BtreeLeave(pBt);
  61102. }
  61103. }
  61104. if( rc!=SQLITE_OK ){
  61105. return rc;
  61106. }
  61107. /* If there are any write-transactions at all, invoke the commit hook */
  61108. if( needXcommit && db->xCommitCallback ){
  61109. rc = db->xCommitCallback(db->pCommitArg);
  61110. if( rc ){
  61111. return SQLITE_CONSTRAINT_COMMITHOOK;
  61112. }
  61113. }
  61114. /* The simple case - no more than one database file (not counting the
  61115. ** TEMP database) has a transaction active. There is no need for the
  61116. ** master-journal.
  61117. **
  61118. ** If the return value of sqlite3BtreeGetFilename() is a zero length
  61119. ** string, it means the main database is :memory: or a temp file. In
  61120. ** that case we do not support atomic multi-file commits, so use the
  61121. ** simple case then too.
  61122. */
  61123. if( 0==sqlite3Strlen30(sqlite3BtreeGetFilename(db->aDb[0].pBt))
  61124. || nTrans<=1
  61125. ){
  61126. for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
  61127. Btree *pBt = db->aDb[i].pBt;
  61128. if( pBt ){
  61129. rc = sqlite3BtreeCommitPhaseOne(pBt, 0);
  61130. }
  61131. }
  61132. /* Do the commit only if all databases successfully complete phase 1.
  61133. ** If one of the BtreeCommitPhaseOne() calls fails, this indicates an
  61134. ** IO error while deleting or truncating a journal file. It is unlikely,
  61135. ** but could happen. In this case abandon processing and return the error.
  61136. */
  61137. for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
  61138. Btree *pBt = db->aDb[i].pBt;
  61139. if( pBt ){
  61140. rc = sqlite3BtreeCommitPhaseTwo(pBt, 0);
  61141. }
  61142. }
  61143. if( rc==SQLITE_OK ){
  61144. sqlite3VtabCommit(db);
  61145. }
  61146. }
  61147. /* The complex case - There is a multi-file write-transaction active.
  61148. ** This requires a master journal file to ensure the transaction is
  61149. ** committed atomically.
  61150. */
  61151. #ifndef SQLITE_OMIT_DISKIO
  61152. else{
  61153. sqlite3_vfs *pVfs = db->pVfs;
  61154. int needSync = 0;
  61155. char *zMaster = 0; /* File-name for the master journal */
  61156. char const *zMainFile = sqlite3BtreeGetFilename(db->aDb[0].pBt);
  61157. sqlite3_file *pMaster = 0;
  61158. i64 offset = 0;
  61159. int res;
  61160. int retryCount = 0;
  61161. int nMainFile;
  61162. /* Select a master journal file name */
  61163. nMainFile = sqlite3Strlen30(zMainFile);
  61164. zMaster = sqlite3MPrintf(db, "%s-mjXXXXXX9XXz", zMainFile);
  61165. if( zMaster==0 ) return SQLITE_NOMEM;
  61166. do {
  61167. u32 iRandom;
  61168. if( retryCount ){
  61169. if( retryCount>100 ){
  61170. sqlite3_log(SQLITE_FULL, "MJ delete: %s", zMaster);
  61171. sqlite3OsDelete(pVfs, zMaster, 0);
  61172. break;
  61173. }else if( retryCount==1 ){
  61174. sqlite3_log(SQLITE_FULL, "MJ collide: %s", zMaster);
  61175. }
  61176. }
  61177. retryCount++;
  61178. sqlite3_randomness(sizeof(iRandom), &iRandom);
  61179. sqlite3_snprintf(13, &zMaster[nMainFile], "-mj%06X9%02X",
  61180. (iRandom>>8)&0xffffff, iRandom&0xff);
  61181. /* The antipenultimate character of the master journal name must
  61182. ** be "9" to avoid name collisions when using 8+3 filenames. */
  61183. assert( zMaster[sqlite3Strlen30(zMaster)-3]=='9' );
  61184. sqlite3FileSuffix3(zMainFile, zMaster);
  61185. rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
  61186. }while( rc==SQLITE_OK && res );
  61187. if( rc==SQLITE_OK ){
  61188. /* Open the master journal. */
  61189. rc = sqlite3OsOpenMalloc(pVfs, zMaster, &pMaster,
  61190. SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
  61191. SQLITE_OPEN_EXCLUSIVE|SQLITE_OPEN_MASTER_JOURNAL, 0
  61192. );
  61193. }
  61194. if( rc!=SQLITE_OK ){
  61195. sqlite3DbFree(db, zMaster);
  61196. return rc;
  61197. }
  61198. /* Write the name of each database file in the transaction into the new
  61199. ** master journal file. If an error occurs at this point close
  61200. ** and delete the master journal file. All the individual journal files
  61201. ** still have 'null' as the master journal pointer, so they will roll
  61202. ** back independently if a failure occurs.
  61203. */
  61204. for(i=0; i<db->nDb; i++){
  61205. Btree *pBt = db->aDb[i].pBt;
  61206. if( sqlite3BtreeIsInTrans(pBt) ){
  61207. char const *zFile = sqlite3BtreeGetJournalname(pBt);
  61208. if( zFile==0 ){
  61209. continue; /* Ignore TEMP and :memory: databases */
  61210. }
  61211. assert( zFile[0]!=0 );
  61212. if( !needSync && !sqlite3BtreeSyncDisabled(pBt) ){
  61213. needSync = 1;
  61214. }
  61215. rc = sqlite3OsWrite(pMaster, zFile, sqlite3Strlen30(zFile)+1, offset);
  61216. offset += sqlite3Strlen30(zFile)+1;
  61217. if( rc!=SQLITE_OK ){
  61218. sqlite3OsCloseFree(pMaster);
  61219. sqlite3OsDelete(pVfs, zMaster, 0);
  61220. sqlite3DbFree(db, zMaster);
  61221. return rc;
  61222. }
  61223. }
  61224. }
  61225. /* Sync the master journal file. If the IOCAP_SEQUENTIAL device
  61226. ** flag is set this is not required.
  61227. */
  61228. if( needSync
  61229. && 0==(sqlite3OsDeviceCharacteristics(pMaster)&SQLITE_IOCAP_SEQUENTIAL)
  61230. && SQLITE_OK!=(rc = sqlite3OsSync(pMaster, SQLITE_SYNC_NORMAL))
  61231. ){
  61232. sqlite3OsCloseFree(pMaster);
  61233. sqlite3OsDelete(pVfs, zMaster, 0);
  61234. sqlite3DbFree(db, zMaster);
  61235. return rc;
  61236. }
  61237. /* Sync all the db files involved in the transaction. The same call
  61238. ** sets the master journal pointer in each individual journal. If
  61239. ** an error occurs here, do not delete the master journal file.
  61240. **
  61241. ** If the error occurs during the first call to
  61242. ** sqlite3BtreeCommitPhaseOne(), then there is a chance that the
  61243. ** master journal file will be orphaned. But we cannot delete it,
  61244. ** in case the master journal file name was written into the journal
  61245. ** file before the failure occurred.
  61246. */
  61247. for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
  61248. Btree *pBt = db->aDb[i].pBt;
  61249. if( pBt ){
  61250. rc = sqlite3BtreeCommitPhaseOne(pBt, zMaster);
  61251. }
  61252. }
  61253. sqlite3OsCloseFree(pMaster);
  61254. assert( rc!=SQLITE_BUSY );
  61255. if( rc!=SQLITE_OK ){
  61256. sqlite3DbFree(db, zMaster);
  61257. return rc;
  61258. }
  61259. /* Delete the master journal file. This commits the transaction. After
  61260. ** doing this the directory is synced again before any individual
  61261. ** transaction files are deleted.
  61262. */
  61263. rc = sqlite3OsDelete(pVfs, zMaster, 1);
  61264. sqlite3DbFree(db, zMaster);
  61265. zMaster = 0;
  61266. if( rc ){
  61267. return rc;
  61268. }
  61269. /* All files and directories have already been synced, so the following
  61270. ** calls to sqlite3BtreeCommitPhaseTwo() are only closing files and
  61271. ** deleting or truncating journals. If something goes wrong while
  61272. ** this is happening we don't really care. The integrity of the
  61273. ** transaction is already guaranteed, but some stray 'cold' journals
  61274. ** may be lying around. Returning an error code won't help matters.
  61275. */
  61276. disable_simulated_io_errors();
  61277. sqlite3BeginBenignMalloc();
  61278. for(i=0; i<db->nDb; i++){
  61279. Btree *pBt = db->aDb[i].pBt;
  61280. if( pBt ){
  61281. sqlite3BtreeCommitPhaseTwo(pBt, 1);
  61282. }
  61283. }
  61284. sqlite3EndBenignMalloc();
  61285. enable_simulated_io_errors();
  61286. sqlite3VtabCommit(db);
  61287. }
  61288. #endif
  61289. return rc;
  61290. }
  61291. /*
  61292. ** This routine checks that the sqlite3.nVdbeActive count variable
  61293. ** matches the number of vdbe's in the list sqlite3.pVdbe that are
  61294. ** currently active. An assertion fails if the two counts do not match.
  61295. ** This is an internal self-check only - it is not an essential processing
  61296. ** step.
  61297. **
  61298. ** This is a no-op if NDEBUG is defined.
  61299. */
  61300. #ifndef NDEBUG
  61301. static void checkActiveVdbeCnt(sqlite3 *db){
  61302. Vdbe *p;
  61303. int cnt = 0;
  61304. int nWrite = 0;
  61305. int nRead = 0;
  61306. p = db->pVdbe;
  61307. while( p ){
  61308. if( sqlite3_stmt_busy((sqlite3_stmt*)p) ){
  61309. cnt++;
  61310. if( p->readOnly==0 ) nWrite++;
  61311. if( p->bIsReader ) nRead++;
  61312. }
  61313. p = p->pNext;
  61314. }
  61315. assert( cnt==db->nVdbeActive );
  61316. assert( nWrite==db->nVdbeWrite );
  61317. assert( nRead==db->nVdbeRead );
  61318. }
  61319. #else
  61320. #define checkActiveVdbeCnt(x)
  61321. #endif
  61322. /*
  61323. ** If the Vdbe passed as the first argument opened a statement-transaction,
  61324. ** close it now. Argument eOp must be either SAVEPOINT_ROLLBACK or
  61325. ** SAVEPOINT_RELEASE. If it is SAVEPOINT_ROLLBACK, then the statement
  61326. ** transaction is rolled back. If eOp is SAVEPOINT_RELEASE, then the
  61327. ** statement transaction is committed.
  61328. **
  61329. ** If an IO error occurs, an SQLITE_IOERR_XXX error code is returned.
  61330. ** Otherwise SQLITE_OK.
  61331. */
  61332. SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *p, int eOp){
  61333. sqlite3 *const db = p->db;
  61334. int rc = SQLITE_OK;
  61335. /* If p->iStatement is greater than zero, then this Vdbe opened a
  61336. ** statement transaction that should be closed here. The only exception
  61337. ** is that an IO error may have occurred, causing an emergency rollback.
  61338. ** In this case (db->nStatement==0), and there is nothing to do.
  61339. */
  61340. if( db->nStatement && p->iStatement ){
  61341. int i;
  61342. const int iSavepoint = p->iStatement-1;
  61343. assert( eOp==SAVEPOINT_ROLLBACK || eOp==SAVEPOINT_RELEASE);
  61344. assert( db->nStatement>0 );
  61345. assert( p->iStatement==(db->nStatement+db->nSavepoint) );
  61346. for(i=0; i<db->nDb; i++){
  61347. int rc2 = SQLITE_OK;
  61348. Btree *pBt = db->aDb[i].pBt;
  61349. if( pBt ){
  61350. if( eOp==SAVEPOINT_ROLLBACK ){
  61351. rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_ROLLBACK, iSavepoint);
  61352. }
  61353. if( rc2==SQLITE_OK ){
  61354. rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_RELEASE, iSavepoint);
  61355. }
  61356. if( rc==SQLITE_OK ){
  61357. rc = rc2;
  61358. }
  61359. }
  61360. }
  61361. db->nStatement--;
  61362. p->iStatement = 0;
  61363. if( rc==SQLITE_OK ){
  61364. if( eOp==SAVEPOINT_ROLLBACK ){
  61365. rc = sqlite3VtabSavepoint(db, SAVEPOINT_ROLLBACK, iSavepoint);
  61366. }
  61367. if( rc==SQLITE_OK ){
  61368. rc = sqlite3VtabSavepoint(db, SAVEPOINT_RELEASE, iSavepoint);
  61369. }
  61370. }
  61371. /* If the statement transaction is being rolled back, also restore the
  61372. ** database handles deferred constraint counter to the value it had when
  61373. ** the statement transaction was opened. */
  61374. if( eOp==SAVEPOINT_ROLLBACK ){
  61375. db->nDeferredCons = p->nStmtDefCons;
  61376. db->nDeferredImmCons = p->nStmtDefImmCons;
  61377. }
  61378. }
  61379. return rc;
  61380. }
  61381. /*
  61382. ** This function is called when a transaction opened by the database
  61383. ** handle associated with the VM passed as an argument is about to be
  61384. ** committed. If there are outstanding deferred foreign key constraint
  61385. ** violations, return SQLITE_ERROR. Otherwise, SQLITE_OK.
  61386. **
  61387. ** If there are outstanding FK violations and this function returns
  61388. ** SQLITE_ERROR, set the result of the VM to SQLITE_CONSTRAINT_FOREIGNKEY
  61389. ** and write an error message to it. Then return SQLITE_ERROR.
  61390. */
  61391. #ifndef SQLITE_OMIT_FOREIGN_KEY
  61392. SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *p, int deferred){
  61393. sqlite3 *db = p->db;
  61394. if( (deferred && (db->nDeferredCons+db->nDeferredImmCons)>0)
  61395. || (!deferred && p->nFkConstraint>0)
  61396. ){
  61397. p->rc = SQLITE_CONSTRAINT_FOREIGNKEY;
  61398. p->errorAction = OE_Abort;
  61399. sqlite3SetString(&p->zErrMsg, db, "FOREIGN KEY constraint failed");
  61400. return SQLITE_ERROR;
  61401. }
  61402. return SQLITE_OK;
  61403. }
  61404. #endif
  61405. /*
  61406. ** This routine is called the when a VDBE tries to halt. If the VDBE
  61407. ** has made changes and is in autocommit mode, then commit those
  61408. ** changes. If a rollback is needed, then do the rollback.
  61409. **
  61410. ** This routine is the only way to move the state of a VM from
  61411. ** SQLITE_MAGIC_RUN to SQLITE_MAGIC_HALT. It is harmless to
  61412. ** call this on a VM that is in the SQLITE_MAGIC_HALT state.
  61413. **
  61414. ** Return an error code. If the commit could not complete because of
  61415. ** lock contention, return SQLITE_BUSY. If SQLITE_BUSY is returned, it
  61416. ** means the close did not happen and needs to be repeated.
  61417. */
  61418. SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe *p){
  61419. int rc; /* Used to store transient return codes */
  61420. sqlite3 *db = p->db;
  61421. /* This function contains the logic that determines if a statement or
  61422. ** transaction will be committed or rolled back as a result of the
  61423. ** execution of this virtual machine.
  61424. **
  61425. ** If any of the following errors occur:
  61426. **
  61427. ** SQLITE_NOMEM
  61428. ** SQLITE_IOERR
  61429. ** SQLITE_FULL
  61430. ** SQLITE_INTERRUPT
  61431. **
  61432. ** Then the internal cache might have been left in an inconsistent
  61433. ** state. We need to rollback the statement transaction, if there is
  61434. ** one, or the complete transaction if there is no statement transaction.
  61435. */
  61436. if( p->db->mallocFailed ){
  61437. p->rc = SQLITE_NOMEM;
  61438. }
  61439. if( p->aOnceFlag ) memset(p->aOnceFlag, 0, p->nOnceFlag);
  61440. closeAllCursors(p);
  61441. if( p->magic!=VDBE_MAGIC_RUN ){
  61442. return SQLITE_OK;
  61443. }
  61444. checkActiveVdbeCnt(db);
  61445. /* No commit or rollback needed if the program never started or if the
  61446. ** SQL statement does not read or write a database file. */
  61447. if( p->pc>=0 && p->bIsReader ){
  61448. int mrc; /* Primary error code from p->rc */
  61449. int eStatementOp = 0;
  61450. int isSpecialError; /* Set to true if a 'special' error */
  61451. /* Lock all btrees used by the statement */
  61452. sqlite3VdbeEnter(p);
  61453. /* Check for one of the special errors */
  61454. mrc = p->rc & 0xff;
  61455. isSpecialError = mrc==SQLITE_NOMEM || mrc==SQLITE_IOERR
  61456. || mrc==SQLITE_INTERRUPT || mrc==SQLITE_FULL;
  61457. if( isSpecialError ){
  61458. /* If the query was read-only and the error code is SQLITE_INTERRUPT,
  61459. ** no rollback is necessary. Otherwise, at least a savepoint
  61460. ** transaction must be rolled back to restore the database to a
  61461. ** consistent state.
  61462. **
  61463. ** Even if the statement is read-only, it is important to perform
  61464. ** a statement or transaction rollback operation. If the error
  61465. ** occurred while writing to the journal, sub-journal or database
  61466. ** file as part of an effort to free up cache space (see function
  61467. ** pagerStress() in pager.c), the rollback is required to restore
  61468. ** the pager to a consistent state.
  61469. */
  61470. if( !p->readOnly || mrc!=SQLITE_INTERRUPT ){
  61471. if( (mrc==SQLITE_NOMEM || mrc==SQLITE_FULL) && p->usesStmtJournal ){
  61472. eStatementOp = SAVEPOINT_ROLLBACK;
  61473. }else{
  61474. /* We are forced to roll back the active transaction. Before doing
  61475. ** so, abort any other statements this handle currently has active.
  61476. */
  61477. sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
  61478. sqlite3CloseSavepoints(db);
  61479. db->autoCommit = 1;
  61480. }
  61481. }
  61482. }
  61483. /* Check for immediate foreign key violations. */
  61484. if( p->rc==SQLITE_OK ){
  61485. sqlite3VdbeCheckFk(p, 0);
  61486. }
  61487. /* If the auto-commit flag is set and this is the only active writer
  61488. ** VM, then we do either a commit or rollback of the current transaction.
  61489. **
  61490. ** Note: This block also runs if one of the special errors handled
  61491. ** above has occurred.
  61492. */
  61493. if( !sqlite3VtabInSync(db)
  61494. && db->autoCommit
  61495. && db->nVdbeWrite==(p->readOnly==0)
  61496. ){
  61497. if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && !isSpecialError) ){
  61498. rc = sqlite3VdbeCheckFk(p, 1);
  61499. if( rc!=SQLITE_OK ){
  61500. if( NEVER(p->readOnly) ){
  61501. sqlite3VdbeLeave(p);
  61502. return SQLITE_ERROR;
  61503. }
  61504. rc = SQLITE_CONSTRAINT_FOREIGNKEY;
  61505. }else{
  61506. /* The auto-commit flag is true, the vdbe program was successful
  61507. ** or hit an 'OR FAIL' constraint and there are no deferred foreign
  61508. ** key constraints to hold up the transaction. This means a commit
  61509. ** is required. */
  61510. rc = vdbeCommit(db, p);
  61511. }
  61512. if( rc==SQLITE_BUSY && p->readOnly ){
  61513. sqlite3VdbeLeave(p);
  61514. return SQLITE_BUSY;
  61515. }else if( rc!=SQLITE_OK ){
  61516. p->rc = rc;
  61517. sqlite3RollbackAll(db, SQLITE_OK);
  61518. }else{
  61519. db->nDeferredCons = 0;
  61520. db->nDeferredImmCons = 0;
  61521. db->flags &= ~SQLITE_DeferFKs;
  61522. sqlite3CommitInternalChanges(db);
  61523. }
  61524. }else{
  61525. sqlite3RollbackAll(db, SQLITE_OK);
  61526. }
  61527. db->nStatement = 0;
  61528. }else if( eStatementOp==0 ){
  61529. if( p->rc==SQLITE_OK || p->errorAction==OE_Fail ){
  61530. eStatementOp = SAVEPOINT_RELEASE;
  61531. }else if( p->errorAction==OE_Abort ){
  61532. eStatementOp = SAVEPOINT_ROLLBACK;
  61533. }else{
  61534. sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
  61535. sqlite3CloseSavepoints(db);
  61536. db->autoCommit = 1;
  61537. }
  61538. }
  61539. /* If eStatementOp is non-zero, then a statement transaction needs to
  61540. ** be committed or rolled back. Call sqlite3VdbeCloseStatement() to
  61541. ** do so. If this operation returns an error, and the current statement
  61542. ** error code is SQLITE_OK or SQLITE_CONSTRAINT, then promote the
  61543. ** current statement error code.
  61544. */
  61545. if( eStatementOp ){
  61546. rc = sqlite3VdbeCloseStatement(p, eStatementOp);
  61547. if( rc ){
  61548. if( p->rc==SQLITE_OK || (p->rc&0xff)==SQLITE_CONSTRAINT ){
  61549. p->rc = rc;
  61550. sqlite3DbFree(db, p->zErrMsg);
  61551. p->zErrMsg = 0;
  61552. }
  61553. sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
  61554. sqlite3CloseSavepoints(db);
  61555. db->autoCommit = 1;
  61556. }
  61557. }
  61558. /* If this was an INSERT, UPDATE or DELETE and no statement transaction
  61559. ** has been rolled back, update the database connection change-counter.
  61560. */
  61561. if( p->changeCntOn ){
  61562. if( eStatementOp!=SAVEPOINT_ROLLBACK ){
  61563. sqlite3VdbeSetChanges(db, p->nChange);
  61564. }else{
  61565. sqlite3VdbeSetChanges(db, 0);
  61566. }
  61567. p->nChange = 0;
  61568. }
  61569. /* Release the locks */
  61570. sqlite3VdbeLeave(p);
  61571. }
  61572. /* We have successfully halted and closed the VM. Record this fact. */
  61573. if( p->pc>=0 ){
  61574. db->nVdbeActive--;
  61575. if( !p->readOnly ) db->nVdbeWrite--;
  61576. if( p->bIsReader ) db->nVdbeRead--;
  61577. assert( db->nVdbeActive>=db->nVdbeRead );
  61578. assert( db->nVdbeRead>=db->nVdbeWrite );
  61579. assert( db->nVdbeWrite>=0 );
  61580. }
  61581. p->magic = VDBE_MAGIC_HALT;
  61582. checkActiveVdbeCnt(db);
  61583. if( p->db->mallocFailed ){
  61584. p->rc = SQLITE_NOMEM;
  61585. }
  61586. /* If the auto-commit flag is set to true, then any locks that were held
  61587. ** by connection db have now been released. Call sqlite3ConnectionUnlocked()
  61588. ** to invoke any required unlock-notify callbacks.
  61589. */
  61590. if( db->autoCommit ){
  61591. sqlite3ConnectionUnlocked(db);
  61592. }
  61593. assert( db->nVdbeActive>0 || db->autoCommit==0 || db->nStatement==0 );
  61594. return (p->rc==SQLITE_BUSY ? SQLITE_BUSY : SQLITE_OK);
  61595. }
  61596. /*
  61597. ** Each VDBE holds the result of the most recent sqlite3_step() call
  61598. ** in p->rc. This routine sets that result back to SQLITE_OK.
  61599. */
  61600. SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe *p){
  61601. p->rc = SQLITE_OK;
  61602. }
  61603. /*
  61604. ** Copy the error code and error message belonging to the VDBE passed
  61605. ** as the first argument to its database handle (so that they will be
  61606. ** returned by calls to sqlite3_errcode() and sqlite3_errmsg()).
  61607. **
  61608. ** This function does not clear the VDBE error code or message, just
  61609. ** copies them to the database handle.
  61610. */
  61611. SQLITE_PRIVATE int sqlite3VdbeTransferError(Vdbe *p){
  61612. sqlite3 *db = p->db;
  61613. int rc = p->rc;
  61614. if( p->zErrMsg ){
  61615. u8 mallocFailed = db->mallocFailed;
  61616. sqlite3BeginBenignMalloc();
  61617. if( db->pErr==0 ) db->pErr = sqlite3ValueNew(db);
  61618. sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, SQLITE_TRANSIENT);
  61619. sqlite3EndBenignMalloc();
  61620. db->mallocFailed = mallocFailed;
  61621. db->errCode = rc;
  61622. }else{
  61623. sqlite3Error(db, rc);
  61624. }
  61625. return rc;
  61626. }
  61627. #ifdef SQLITE_ENABLE_SQLLOG
  61628. /*
  61629. ** If an SQLITE_CONFIG_SQLLOG hook is registered and the VM has been run,
  61630. ** invoke it.
  61631. */
  61632. static void vdbeInvokeSqllog(Vdbe *v){
  61633. if( sqlite3GlobalConfig.xSqllog && v->rc==SQLITE_OK && v->zSql && v->pc>=0 ){
  61634. char *zExpanded = sqlite3VdbeExpandSql(v, v->zSql);
  61635. assert( v->db->init.busy==0 );
  61636. if( zExpanded ){
  61637. sqlite3GlobalConfig.xSqllog(
  61638. sqlite3GlobalConfig.pSqllogArg, v->db, zExpanded, 1
  61639. );
  61640. sqlite3DbFree(v->db, zExpanded);
  61641. }
  61642. }
  61643. }
  61644. #else
  61645. # define vdbeInvokeSqllog(x)
  61646. #endif
  61647. /*
  61648. ** Clean up a VDBE after execution but do not delete the VDBE just yet.
  61649. ** Write any error messages into *pzErrMsg. Return the result code.
  61650. **
  61651. ** After this routine is run, the VDBE should be ready to be executed
  61652. ** again.
  61653. **
  61654. ** To look at it another way, this routine resets the state of the
  61655. ** virtual machine from VDBE_MAGIC_RUN or VDBE_MAGIC_HALT back to
  61656. ** VDBE_MAGIC_INIT.
  61657. */
  61658. SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe *p){
  61659. sqlite3 *db;
  61660. db = p->db;
  61661. /* If the VM did not run to completion or if it encountered an
  61662. ** error, then it might not have been halted properly. So halt
  61663. ** it now.
  61664. */
  61665. sqlite3VdbeHalt(p);
  61666. /* If the VDBE has be run even partially, then transfer the error code
  61667. ** and error message from the VDBE into the main database structure. But
  61668. ** if the VDBE has just been set to run but has not actually executed any
  61669. ** instructions yet, leave the main database error information unchanged.
  61670. */
  61671. if( p->pc>=0 ){
  61672. vdbeInvokeSqllog(p);
  61673. sqlite3VdbeTransferError(p);
  61674. sqlite3DbFree(db, p->zErrMsg);
  61675. p->zErrMsg = 0;
  61676. if( p->runOnlyOnce ) p->expired = 1;
  61677. }else if( p->rc && p->expired ){
  61678. /* The expired flag was set on the VDBE before the first call
  61679. ** to sqlite3_step(). For consistency (since sqlite3_step() was
  61680. ** called), set the database error in this case as well.
  61681. */
  61682. sqlite3ErrorWithMsg(db, p->rc, p->zErrMsg ? "%s" : 0, p->zErrMsg);
  61683. sqlite3DbFree(db, p->zErrMsg);
  61684. p->zErrMsg = 0;
  61685. }
  61686. /* Reclaim all memory used by the VDBE
  61687. */
  61688. Cleanup(p);
  61689. /* Save profiling information from this VDBE run.
  61690. */
  61691. #ifdef VDBE_PROFILE
  61692. {
  61693. FILE *out = fopen("vdbe_profile.out", "a");
  61694. if( out ){
  61695. int i;
  61696. fprintf(out, "---- ");
  61697. for(i=0; i<p->nOp; i++){
  61698. fprintf(out, "%02x", p->aOp[i].opcode);
  61699. }
  61700. fprintf(out, "\n");
  61701. if( p->zSql ){
  61702. char c, pc = 0;
  61703. fprintf(out, "-- ");
  61704. for(i=0; (c = p->zSql[i])!=0; i++){
  61705. if( pc=='\n' ) fprintf(out, "-- ");
  61706. putc(c, out);
  61707. pc = c;
  61708. }
  61709. if( pc!='\n' ) fprintf(out, "\n");
  61710. }
  61711. for(i=0; i<p->nOp; i++){
  61712. char zHdr[100];
  61713. sqlite3_snprintf(sizeof(zHdr), zHdr, "%6u %12llu %8llu ",
  61714. p->aOp[i].cnt,
  61715. p->aOp[i].cycles,
  61716. p->aOp[i].cnt>0 ? p->aOp[i].cycles/p->aOp[i].cnt : 0
  61717. );
  61718. fprintf(out, "%s", zHdr);
  61719. sqlite3VdbePrintOp(out, i, &p->aOp[i]);
  61720. }
  61721. fclose(out);
  61722. }
  61723. }
  61724. #endif
  61725. p->iCurrentTime = 0;
  61726. p->magic = VDBE_MAGIC_INIT;
  61727. return p->rc & db->errMask;
  61728. }
  61729. /*
  61730. ** Clean up and delete a VDBE after execution. Return an integer which is
  61731. ** the result code. Write any error message text into *pzErrMsg.
  61732. */
  61733. SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe *p){
  61734. int rc = SQLITE_OK;
  61735. if( p->magic==VDBE_MAGIC_RUN || p->magic==VDBE_MAGIC_HALT ){
  61736. rc = sqlite3VdbeReset(p);
  61737. assert( (rc & p->db->errMask)==rc );
  61738. }
  61739. sqlite3VdbeDelete(p);
  61740. return rc;
  61741. }
  61742. /*
  61743. ** If parameter iOp is less than zero, then invoke the destructor for
  61744. ** all auxiliary data pointers currently cached by the VM passed as
  61745. ** the first argument.
  61746. **
  61747. ** Or, if iOp is greater than or equal to zero, then the destructor is
  61748. ** only invoked for those auxiliary data pointers created by the user
  61749. ** function invoked by the OP_Function opcode at instruction iOp of
  61750. ** VM pVdbe, and only then if:
  61751. **
  61752. ** * the associated function parameter is the 32nd or later (counting
  61753. ** from left to right), or
  61754. **
  61755. ** * the corresponding bit in argument mask is clear (where the first
  61756. ** function parameter corresponds to bit 0 etc.).
  61757. */
  61758. SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(Vdbe *pVdbe, int iOp, int mask){
  61759. AuxData **pp = &pVdbe->pAuxData;
  61760. while( *pp ){
  61761. AuxData *pAux = *pp;
  61762. if( (iOp<0)
  61763. || (pAux->iOp==iOp && (pAux->iArg>31 || !(mask & MASKBIT32(pAux->iArg))))
  61764. ){
  61765. testcase( pAux->iArg==31 );
  61766. if( pAux->xDelete ){
  61767. pAux->xDelete(pAux->pAux);
  61768. }
  61769. *pp = pAux->pNext;
  61770. sqlite3DbFree(pVdbe->db, pAux);
  61771. }else{
  61772. pp= &pAux->pNext;
  61773. }
  61774. }
  61775. }
  61776. /*
  61777. ** Free all memory associated with the Vdbe passed as the second argument,
  61778. ** except for object itself, which is preserved.
  61779. **
  61780. ** The difference between this function and sqlite3VdbeDelete() is that
  61781. ** VdbeDelete() also unlinks the Vdbe from the list of VMs associated with
  61782. ** the database connection and frees the object itself.
  61783. */
  61784. SQLITE_PRIVATE void sqlite3VdbeClearObject(sqlite3 *db, Vdbe *p){
  61785. SubProgram *pSub, *pNext;
  61786. int i;
  61787. assert( p->db==0 || p->db==db );
  61788. releaseMemArray(p->aVar, p->nVar);
  61789. releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
  61790. for(pSub=p->pProgram; pSub; pSub=pNext){
  61791. pNext = pSub->pNext;
  61792. vdbeFreeOpArray(db, pSub->aOp, pSub->nOp);
  61793. sqlite3DbFree(db, pSub);
  61794. }
  61795. for(i=p->nzVar-1; i>=0; i--) sqlite3DbFree(db, p->azVar[i]);
  61796. vdbeFreeOpArray(db, p->aOp, p->nOp);
  61797. sqlite3DbFree(db, p->aColName);
  61798. sqlite3DbFree(db, p->zSql);
  61799. sqlite3DbFree(db, p->pFree);
  61800. }
  61801. /*
  61802. ** Delete an entire VDBE.
  61803. */
  61804. SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe *p){
  61805. sqlite3 *db;
  61806. if( NEVER(p==0) ) return;
  61807. db = p->db;
  61808. assert( sqlite3_mutex_held(db->mutex) );
  61809. sqlite3VdbeClearObject(db, p);
  61810. if( p->pPrev ){
  61811. p->pPrev->pNext = p->pNext;
  61812. }else{
  61813. assert( db->pVdbe==p );
  61814. db->pVdbe = p->pNext;
  61815. }
  61816. if( p->pNext ){
  61817. p->pNext->pPrev = p->pPrev;
  61818. }
  61819. p->magic = VDBE_MAGIC_DEAD;
  61820. p->db = 0;
  61821. sqlite3DbFree(db, p);
  61822. }
  61823. /*
  61824. ** The cursor "p" has a pending seek operation that has not yet been
  61825. ** carried out. Seek the cursor now. If an error occurs, return
  61826. ** the appropriate error code.
  61827. */
  61828. static int SQLITE_NOINLINE handleDeferredMoveto(VdbeCursor *p){
  61829. int res, rc;
  61830. #ifdef SQLITE_TEST
  61831. extern int sqlite3_search_count;
  61832. #endif
  61833. assert( p->deferredMoveto );
  61834. assert( p->isTable );
  61835. rc = sqlite3BtreeMovetoUnpacked(p->pCursor, 0, p->movetoTarget, 0, &res);
  61836. if( rc ) return rc;
  61837. if( res!=0 ) return SQLITE_CORRUPT_BKPT;
  61838. #ifdef SQLITE_TEST
  61839. sqlite3_search_count++;
  61840. #endif
  61841. p->deferredMoveto = 0;
  61842. p->cacheStatus = CACHE_STALE;
  61843. return SQLITE_OK;
  61844. }
  61845. /*
  61846. ** Something has moved cursor "p" out of place. Maybe the row it was
  61847. ** pointed to was deleted out from under it. Or maybe the btree was
  61848. ** rebalanced. Whatever the cause, try to restore "p" to the place it
  61849. ** is supposed to be pointing. If the row was deleted out from under the
  61850. ** cursor, set the cursor to point to a NULL row.
  61851. */
  61852. static int SQLITE_NOINLINE handleMovedCursor(VdbeCursor *p){
  61853. int isDifferentRow, rc;
  61854. assert( p->pCursor!=0 );
  61855. assert( sqlite3BtreeCursorHasMoved(p->pCursor) );
  61856. rc = sqlite3BtreeCursorRestore(p->pCursor, &isDifferentRow);
  61857. p->cacheStatus = CACHE_STALE;
  61858. if( isDifferentRow ) p->nullRow = 1;
  61859. return rc;
  61860. }
  61861. /*
  61862. ** Check to ensure that the cursor is valid. Restore the cursor
  61863. ** if need be. Return any I/O error from the restore operation.
  61864. */
  61865. SQLITE_PRIVATE int sqlite3VdbeCursorRestore(VdbeCursor *p){
  61866. if( sqlite3BtreeCursorHasMoved(p->pCursor) ){
  61867. return handleMovedCursor(p);
  61868. }
  61869. return SQLITE_OK;
  61870. }
  61871. /*
  61872. ** Make sure the cursor p is ready to read or write the row to which it
  61873. ** was last positioned. Return an error code if an OOM fault or I/O error
  61874. ** prevents us from positioning the cursor to its correct position.
  61875. **
  61876. ** If a MoveTo operation is pending on the given cursor, then do that
  61877. ** MoveTo now. If no move is pending, check to see if the row has been
  61878. ** deleted out from under the cursor and if it has, mark the row as
  61879. ** a NULL row.
  61880. **
  61881. ** If the cursor is already pointing to the correct row and that row has
  61882. ** not been deleted out from under the cursor, then this routine is a no-op.
  61883. */
  61884. SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor *p){
  61885. if( p->deferredMoveto ){
  61886. return handleDeferredMoveto(p);
  61887. }
  61888. if( p->pCursor && sqlite3BtreeCursorHasMoved(p->pCursor) ){
  61889. return handleMovedCursor(p);
  61890. }
  61891. return SQLITE_OK;
  61892. }
  61893. /*
  61894. ** The following functions:
  61895. **
  61896. ** sqlite3VdbeSerialType()
  61897. ** sqlite3VdbeSerialTypeLen()
  61898. ** sqlite3VdbeSerialLen()
  61899. ** sqlite3VdbeSerialPut()
  61900. ** sqlite3VdbeSerialGet()
  61901. **
  61902. ** encapsulate the code that serializes values for storage in SQLite
  61903. ** data and index records. Each serialized value consists of a
  61904. ** 'serial-type' and a blob of data. The serial type is an 8-byte unsigned
  61905. ** integer, stored as a varint.
  61906. **
  61907. ** In an SQLite index record, the serial type is stored directly before
  61908. ** the blob of data that it corresponds to. In a table record, all serial
  61909. ** types are stored at the start of the record, and the blobs of data at
  61910. ** the end. Hence these functions allow the caller to handle the
  61911. ** serial-type and data blob separately.
  61912. **
  61913. ** The following table describes the various storage classes for data:
  61914. **
  61915. ** serial type bytes of data type
  61916. ** -------------- --------------- ---------------
  61917. ** 0 0 NULL
  61918. ** 1 1 signed integer
  61919. ** 2 2 signed integer
  61920. ** 3 3 signed integer
  61921. ** 4 4 signed integer
  61922. ** 5 6 signed integer
  61923. ** 6 8 signed integer
  61924. ** 7 8 IEEE float
  61925. ** 8 0 Integer constant 0
  61926. ** 9 0 Integer constant 1
  61927. ** 10,11 reserved for expansion
  61928. ** N>=12 and even (N-12)/2 BLOB
  61929. ** N>=13 and odd (N-13)/2 text
  61930. **
  61931. ** The 8 and 9 types were added in 3.3.0, file format 4. Prior versions
  61932. ** of SQLite will not understand those serial types.
  61933. */
  61934. /*
  61935. ** Return the serial-type for the value stored in pMem.
  61936. */
  61937. SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem *pMem, int file_format){
  61938. int flags = pMem->flags;
  61939. u32 n;
  61940. if( flags&MEM_Null ){
  61941. return 0;
  61942. }
  61943. if( flags&MEM_Int ){
  61944. /* Figure out whether to use 1, 2, 4, 6 or 8 bytes. */
  61945. # define MAX_6BYTE ((((i64)0x00008000)<<32)-1)
  61946. i64 i = pMem->u.i;
  61947. u64 u;
  61948. if( i<0 ){
  61949. if( i<(-MAX_6BYTE) ) return 6;
  61950. /* Previous test prevents: u = -(-9223372036854775808) */
  61951. u = -i;
  61952. }else{
  61953. u = i;
  61954. }
  61955. if( u<=127 ){
  61956. return ((i&1)==i && file_format>=4) ? 8+(u32)u : 1;
  61957. }
  61958. if( u<=32767 ) return 2;
  61959. if( u<=8388607 ) return 3;
  61960. if( u<=2147483647 ) return 4;
  61961. if( u<=MAX_6BYTE ) return 5;
  61962. return 6;
  61963. }
  61964. if( flags&MEM_Real ){
  61965. return 7;
  61966. }
  61967. assert( pMem->db->mallocFailed || flags&(MEM_Str|MEM_Blob) );
  61968. assert( pMem->n>=0 );
  61969. n = (u32)pMem->n;
  61970. if( flags & MEM_Zero ){
  61971. n += pMem->u.nZero;
  61972. }
  61973. return ((n*2) + 12 + ((flags&MEM_Str)!=0));
  61974. }
  61975. /*
  61976. ** Return the length of the data corresponding to the supplied serial-type.
  61977. */
  61978. SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32 serial_type){
  61979. if( serial_type>=12 ){
  61980. return (serial_type-12)/2;
  61981. }else{
  61982. static const u8 aSize[] = { 0, 1, 2, 3, 4, 6, 8, 8, 0, 0, 0, 0 };
  61983. return aSize[serial_type];
  61984. }
  61985. }
  61986. /*
  61987. ** If we are on an architecture with mixed-endian floating
  61988. ** points (ex: ARM7) then swap the lower 4 bytes with the
  61989. ** upper 4 bytes. Return the result.
  61990. **
  61991. ** For most architectures, this is a no-op.
  61992. **
  61993. ** (later): It is reported to me that the mixed-endian problem
  61994. ** on ARM7 is an issue with GCC, not with the ARM7 chip. It seems
  61995. ** that early versions of GCC stored the two words of a 64-bit
  61996. ** float in the wrong order. And that error has been propagated
  61997. ** ever since. The blame is not necessarily with GCC, though.
  61998. ** GCC might have just copying the problem from a prior compiler.
  61999. ** I am also told that newer versions of GCC that follow a different
  62000. ** ABI get the byte order right.
  62001. **
  62002. ** Developers using SQLite on an ARM7 should compile and run their
  62003. ** application using -DSQLITE_DEBUG=1 at least once. With DEBUG
  62004. ** enabled, some asserts below will ensure that the byte order of
  62005. ** floating point values is correct.
  62006. **
  62007. ** (2007-08-30) Frank van Vugt has studied this problem closely
  62008. ** and has send his findings to the SQLite developers. Frank
  62009. ** writes that some Linux kernels offer floating point hardware
  62010. ** emulation that uses only 32-bit mantissas instead of a full
  62011. ** 48-bits as required by the IEEE standard. (This is the
  62012. ** CONFIG_FPE_FASTFPE option.) On such systems, floating point
  62013. ** byte swapping becomes very complicated. To avoid problems,
  62014. ** the necessary byte swapping is carried out using a 64-bit integer
  62015. ** rather than a 64-bit float. Frank assures us that the code here
  62016. ** works for him. We, the developers, have no way to independently
  62017. ** verify this, but Frank seems to know what he is talking about
  62018. ** so we trust him.
  62019. */
  62020. #ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
  62021. static u64 floatSwap(u64 in){
  62022. union {
  62023. u64 r;
  62024. u32 i[2];
  62025. } u;
  62026. u32 t;
  62027. u.r = in;
  62028. t = u.i[0];
  62029. u.i[0] = u.i[1];
  62030. u.i[1] = t;
  62031. return u.r;
  62032. }
  62033. # define swapMixedEndianFloat(X) X = floatSwap(X)
  62034. #else
  62035. # define swapMixedEndianFloat(X)
  62036. #endif
  62037. /*
  62038. ** Write the serialized data blob for the value stored in pMem into
  62039. ** buf. It is assumed that the caller has allocated sufficient space.
  62040. ** Return the number of bytes written.
  62041. **
  62042. ** nBuf is the amount of space left in buf[]. The caller is responsible
  62043. ** for allocating enough space to buf[] to hold the entire field, exclusive
  62044. ** of the pMem->u.nZero bytes for a MEM_Zero value.
  62045. **
  62046. ** Return the number of bytes actually written into buf[]. The number
  62047. ** of bytes in the zero-filled tail is included in the return value only
  62048. ** if those bytes were zeroed in buf[].
  62049. */
  62050. SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(u8 *buf, Mem *pMem, u32 serial_type){
  62051. u32 len;
  62052. /* Integer and Real */
  62053. if( serial_type<=7 && serial_type>0 ){
  62054. u64 v;
  62055. u32 i;
  62056. if( serial_type==7 ){
  62057. assert( sizeof(v)==sizeof(pMem->u.r) );
  62058. memcpy(&v, &pMem->u.r, sizeof(v));
  62059. swapMixedEndianFloat(v);
  62060. }else{
  62061. v = pMem->u.i;
  62062. }
  62063. len = i = sqlite3VdbeSerialTypeLen(serial_type);
  62064. assert( i>0 );
  62065. do{
  62066. buf[--i] = (u8)(v&0xFF);
  62067. v >>= 8;
  62068. }while( i );
  62069. return len;
  62070. }
  62071. /* String or blob */
  62072. if( serial_type>=12 ){
  62073. assert( pMem->n + ((pMem->flags & MEM_Zero)?pMem->u.nZero:0)
  62074. == (int)sqlite3VdbeSerialTypeLen(serial_type) );
  62075. len = pMem->n;
  62076. memcpy(buf, pMem->z, len);
  62077. return len;
  62078. }
  62079. /* NULL or constants 0 or 1 */
  62080. return 0;
  62081. }
  62082. /* Input "x" is a sequence of unsigned characters that represent a
  62083. ** big-endian integer. Return the equivalent native integer
  62084. */
  62085. #define ONE_BYTE_INT(x) ((i8)(x)[0])
  62086. #define TWO_BYTE_INT(x) (256*(i8)((x)[0])|(x)[1])
  62087. #define THREE_BYTE_INT(x) (65536*(i8)((x)[0])|((x)[1]<<8)|(x)[2])
  62088. #define FOUR_BYTE_UINT(x) (((u32)(x)[0]<<24)|((x)[1]<<16)|((x)[2]<<8)|(x)[3])
  62089. #define FOUR_BYTE_INT(x) (16777216*(i8)((x)[0])|((x)[1]<<16)|((x)[2]<<8)|(x)[3])
  62090. /*
  62091. ** Deserialize the data blob pointed to by buf as serial type serial_type
  62092. ** and store the result in pMem. Return the number of bytes read.
  62093. **
  62094. ** This function is implemented as two separate routines for performance.
  62095. ** The few cases that require local variables are broken out into a separate
  62096. ** routine so that in most cases the overhead of moving the stack pointer
  62097. ** is avoided.
  62098. */
  62099. static u32 SQLITE_NOINLINE serialGet(
  62100. const unsigned char *buf, /* Buffer to deserialize from */
  62101. u32 serial_type, /* Serial type to deserialize */
  62102. Mem *pMem /* Memory cell to write value into */
  62103. ){
  62104. u64 x = FOUR_BYTE_UINT(buf);
  62105. u32 y = FOUR_BYTE_UINT(buf+4);
  62106. x = (x<<32) + y;
  62107. if( serial_type==6 ){
  62108. pMem->u.i = *(i64*)&x;
  62109. pMem->flags = MEM_Int;
  62110. testcase( pMem->u.i<0 );
  62111. }else{
  62112. #if !defined(NDEBUG) && !defined(SQLITE_OMIT_FLOATING_POINT)
  62113. /* Verify that integers and floating point values use the same
  62114. ** byte order. Or, that if SQLITE_MIXED_ENDIAN_64BIT_FLOAT is
  62115. ** defined that 64-bit floating point values really are mixed
  62116. ** endian.
  62117. */
  62118. static const u64 t1 = ((u64)0x3ff00000)<<32;
  62119. static const double r1 = 1.0;
  62120. u64 t2 = t1;
  62121. swapMixedEndianFloat(t2);
  62122. assert( sizeof(r1)==sizeof(t2) && memcmp(&r1, &t2, sizeof(r1))==0 );
  62123. #endif
  62124. assert( sizeof(x)==8 && sizeof(pMem->u.r)==8 );
  62125. swapMixedEndianFloat(x);
  62126. memcpy(&pMem->u.r, &x, sizeof(x));
  62127. pMem->flags = sqlite3IsNaN(pMem->u.r) ? MEM_Null : MEM_Real;
  62128. }
  62129. return 8;
  62130. }
  62131. SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(
  62132. const unsigned char *buf, /* Buffer to deserialize from */
  62133. u32 serial_type, /* Serial type to deserialize */
  62134. Mem *pMem /* Memory cell to write value into */
  62135. ){
  62136. switch( serial_type ){
  62137. case 10: /* Reserved for future use */
  62138. case 11: /* Reserved for future use */
  62139. case 0: { /* NULL */
  62140. pMem->flags = MEM_Null;
  62141. break;
  62142. }
  62143. case 1: { /* 1-byte signed integer */
  62144. pMem->u.i = ONE_BYTE_INT(buf);
  62145. pMem->flags = MEM_Int;
  62146. testcase( pMem->u.i<0 );
  62147. return 1;
  62148. }
  62149. case 2: { /* 2-byte signed integer */
  62150. pMem->u.i = TWO_BYTE_INT(buf);
  62151. pMem->flags = MEM_Int;
  62152. testcase( pMem->u.i<0 );
  62153. return 2;
  62154. }
  62155. case 3: { /* 3-byte signed integer */
  62156. pMem->u.i = THREE_BYTE_INT(buf);
  62157. pMem->flags = MEM_Int;
  62158. testcase( pMem->u.i<0 );
  62159. return 3;
  62160. }
  62161. case 4: { /* 4-byte signed integer */
  62162. pMem->u.i = FOUR_BYTE_INT(buf);
  62163. pMem->flags = MEM_Int;
  62164. testcase( pMem->u.i<0 );
  62165. return 4;
  62166. }
  62167. case 5: { /* 6-byte signed integer */
  62168. pMem->u.i = FOUR_BYTE_UINT(buf+2) + (((i64)1)<<32)*TWO_BYTE_INT(buf);
  62169. pMem->flags = MEM_Int;
  62170. testcase( pMem->u.i<0 );
  62171. return 6;
  62172. }
  62173. case 6: /* 8-byte signed integer */
  62174. case 7: { /* IEEE floating point */
  62175. /* These use local variables, so do them in a separate routine
  62176. ** to avoid having to move the frame pointer in the common case */
  62177. return serialGet(buf,serial_type,pMem);
  62178. }
  62179. case 8: /* Integer 0 */
  62180. case 9: { /* Integer 1 */
  62181. pMem->u.i = serial_type-8;
  62182. pMem->flags = MEM_Int;
  62183. return 0;
  62184. }
  62185. default: {
  62186. static const u16 aFlag[] = { MEM_Blob|MEM_Ephem, MEM_Str|MEM_Ephem };
  62187. pMem->z = (char *)buf;
  62188. pMem->n = (serial_type-12)/2;
  62189. pMem->flags = aFlag[serial_type&1];
  62190. return pMem->n;
  62191. }
  62192. }
  62193. return 0;
  62194. }
  62195. /*
  62196. ** This routine is used to allocate sufficient space for an UnpackedRecord
  62197. ** structure large enough to be used with sqlite3VdbeRecordUnpack() if
  62198. ** the first argument is a pointer to KeyInfo structure pKeyInfo.
  62199. **
  62200. ** The space is either allocated using sqlite3DbMallocRaw() or from within
  62201. ** the unaligned buffer passed via the second and third arguments (presumably
  62202. ** stack space). If the former, then *ppFree is set to a pointer that should
  62203. ** be eventually freed by the caller using sqlite3DbFree(). Or, if the
  62204. ** allocation comes from the pSpace/szSpace buffer, *ppFree is set to NULL
  62205. ** before returning.
  62206. **
  62207. ** If an OOM error occurs, NULL is returned.
  62208. */
  62209. SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(
  62210. KeyInfo *pKeyInfo, /* Description of the record */
  62211. char *pSpace, /* Unaligned space available */
  62212. int szSpace, /* Size of pSpace[] in bytes */
  62213. char **ppFree /* OUT: Caller should free this pointer */
  62214. ){
  62215. UnpackedRecord *p; /* Unpacked record to return */
  62216. int nOff; /* Increment pSpace by nOff to align it */
  62217. int nByte; /* Number of bytes required for *p */
  62218. /* We want to shift the pointer pSpace up such that it is 8-byte aligned.
  62219. ** Thus, we need to calculate a value, nOff, between 0 and 7, to shift
  62220. ** it by. If pSpace is already 8-byte aligned, nOff should be zero.
  62221. */
  62222. nOff = (8 - (SQLITE_PTR_TO_INT(pSpace) & 7)) & 7;
  62223. nByte = ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*(pKeyInfo->nField+1);
  62224. if( nByte>szSpace+nOff ){
  62225. p = (UnpackedRecord *)sqlite3DbMallocRaw(pKeyInfo->db, nByte);
  62226. *ppFree = (char *)p;
  62227. if( !p ) return 0;
  62228. }else{
  62229. p = (UnpackedRecord*)&pSpace[nOff];
  62230. *ppFree = 0;
  62231. }
  62232. p->aMem = (Mem*)&((char*)p)[ROUND8(sizeof(UnpackedRecord))];
  62233. assert( pKeyInfo->aSortOrder!=0 );
  62234. p->pKeyInfo = pKeyInfo;
  62235. p->nField = pKeyInfo->nField + 1;
  62236. return p;
  62237. }
  62238. /*
  62239. ** Given the nKey-byte encoding of a record in pKey[], populate the
  62240. ** UnpackedRecord structure indicated by the fourth argument with the
  62241. ** contents of the decoded record.
  62242. */
  62243. SQLITE_PRIVATE void sqlite3VdbeRecordUnpack(
  62244. KeyInfo *pKeyInfo, /* Information about the record format */
  62245. int nKey, /* Size of the binary record */
  62246. const void *pKey, /* The binary record */
  62247. UnpackedRecord *p /* Populate this structure before returning. */
  62248. ){
  62249. const unsigned char *aKey = (const unsigned char *)pKey;
  62250. int d;
  62251. u32 idx; /* Offset in aKey[] to read from */
  62252. u16 u; /* Unsigned loop counter */
  62253. u32 szHdr;
  62254. Mem *pMem = p->aMem;
  62255. p->default_rc = 0;
  62256. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  62257. idx = getVarint32(aKey, szHdr);
  62258. d = szHdr;
  62259. u = 0;
  62260. while( idx<szHdr && d<=nKey ){
  62261. u32 serial_type;
  62262. idx += getVarint32(&aKey[idx], serial_type);
  62263. pMem->enc = pKeyInfo->enc;
  62264. pMem->db = pKeyInfo->db;
  62265. /* pMem->flags = 0; // sqlite3VdbeSerialGet() will set this for us */
  62266. pMem->szMalloc = 0;
  62267. d += sqlite3VdbeSerialGet(&aKey[d], serial_type, pMem);
  62268. pMem++;
  62269. if( (++u)>=p->nField ) break;
  62270. }
  62271. assert( u<=pKeyInfo->nField + 1 );
  62272. p->nField = u;
  62273. }
  62274. #if SQLITE_DEBUG
  62275. /*
  62276. ** This function compares two index or table record keys in the same way
  62277. ** as the sqlite3VdbeRecordCompare() routine. Unlike VdbeRecordCompare(),
  62278. ** this function deserializes and compares values using the
  62279. ** sqlite3VdbeSerialGet() and sqlite3MemCompare() functions. It is used
  62280. ** in assert() statements to ensure that the optimized code in
  62281. ** sqlite3VdbeRecordCompare() returns results with these two primitives.
  62282. **
  62283. ** Return true if the result of comparison is equivalent to desiredResult.
  62284. ** Return false if there is a disagreement.
  62285. */
  62286. static int vdbeRecordCompareDebug(
  62287. int nKey1, const void *pKey1, /* Left key */
  62288. const UnpackedRecord *pPKey2, /* Right key */
  62289. int desiredResult /* Correct answer */
  62290. ){
  62291. u32 d1; /* Offset into aKey[] of next data element */
  62292. u32 idx1; /* Offset into aKey[] of next header element */
  62293. u32 szHdr1; /* Number of bytes in header */
  62294. int i = 0;
  62295. int rc = 0;
  62296. const unsigned char *aKey1 = (const unsigned char *)pKey1;
  62297. KeyInfo *pKeyInfo;
  62298. Mem mem1;
  62299. pKeyInfo = pPKey2->pKeyInfo;
  62300. if( pKeyInfo->db==0 ) return 1;
  62301. mem1.enc = pKeyInfo->enc;
  62302. mem1.db = pKeyInfo->db;
  62303. /* mem1.flags = 0; // Will be initialized by sqlite3VdbeSerialGet() */
  62304. VVA_ONLY( mem1.szMalloc = 0; ) /* Only needed by assert() statements */
  62305. /* Compilers may complain that mem1.u.i is potentially uninitialized.
  62306. ** We could initialize it, as shown here, to silence those complaints.
  62307. ** But in fact, mem1.u.i will never actually be used uninitialized, and doing
  62308. ** the unnecessary initialization has a measurable negative performance
  62309. ** impact, since this routine is a very high runner. And so, we choose
  62310. ** to ignore the compiler warnings and leave this variable uninitialized.
  62311. */
  62312. /* mem1.u.i = 0; // not needed, here to silence compiler warning */
  62313. idx1 = getVarint32(aKey1, szHdr1);
  62314. d1 = szHdr1;
  62315. assert( pKeyInfo->nField+pKeyInfo->nXField>=pPKey2->nField || CORRUPT_DB );
  62316. assert( pKeyInfo->aSortOrder!=0 );
  62317. assert( pKeyInfo->nField>0 );
  62318. assert( idx1<=szHdr1 || CORRUPT_DB );
  62319. do{
  62320. u32 serial_type1;
  62321. /* Read the serial types for the next element in each key. */
  62322. idx1 += getVarint32( aKey1+idx1, serial_type1 );
  62323. /* Verify that there is enough key space remaining to avoid
  62324. ** a buffer overread. The "d1+serial_type1+2" subexpression will
  62325. ** always be greater than or equal to the amount of required key space.
  62326. ** Use that approximation to avoid the more expensive call to
  62327. ** sqlite3VdbeSerialTypeLen() in the common case.
  62328. */
  62329. if( d1+serial_type1+2>(u32)nKey1
  62330. && d1+sqlite3VdbeSerialTypeLen(serial_type1)>(u32)nKey1
  62331. ){
  62332. break;
  62333. }
  62334. /* Extract the values to be compared.
  62335. */
  62336. d1 += sqlite3VdbeSerialGet(&aKey1[d1], serial_type1, &mem1);
  62337. /* Do the comparison
  62338. */
  62339. rc = sqlite3MemCompare(&mem1, &pPKey2->aMem[i], pKeyInfo->aColl[i]);
  62340. if( rc!=0 ){
  62341. assert( mem1.szMalloc==0 ); /* See comment below */
  62342. if( pKeyInfo->aSortOrder[i] ){
  62343. rc = -rc; /* Invert the result for DESC sort order. */
  62344. }
  62345. goto debugCompareEnd;
  62346. }
  62347. i++;
  62348. }while( idx1<szHdr1 && i<pPKey2->nField );
  62349. /* No memory allocation is ever used on mem1. Prove this using
  62350. ** the following assert(). If the assert() fails, it indicates a
  62351. ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1).
  62352. */
  62353. assert( mem1.szMalloc==0 );
  62354. /* rc==0 here means that one of the keys ran out of fields and
  62355. ** all the fields up to that point were equal. Return the default_rc
  62356. ** value. */
  62357. rc = pPKey2->default_rc;
  62358. debugCompareEnd:
  62359. if( desiredResult==0 && rc==0 ) return 1;
  62360. if( desiredResult<0 && rc<0 ) return 1;
  62361. if( desiredResult>0 && rc>0 ) return 1;
  62362. if( CORRUPT_DB ) return 1;
  62363. if( pKeyInfo->db->mallocFailed ) return 1;
  62364. return 0;
  62365. }
  62366. #endif
  62367. /*
  62368. ** Both *pMem1 and *pMem2 contain string values. Compare the two values
  62369. ** using the collation sequence pColl. As usual, return a negative , zero
  62370. ** or positive value if *pMem1 is less than, equal to or greater than
  62371. ** *pMem2, respectively. Similar in spirit to "rc = (*pMem1) - (*pMem2);".
  62372. */
  62373. static int vdbeCompareMemString(
  62374. const Mem *pMem1,
  62375. const Mem *pMem2,
  62376. const CollSeq *pColl,
  62377. u8 *prcErr /* If an OOM occurs, set to SQLITE_NOMEM */
  62378. ){
  62379. if( pMem1->enc==pColl->enc ){
  62380. /* The strings are already in the correct encoding. Call the
  62381. ** comparison function directly */
  62382. return pColl->xCmp(pColl->pUser,pMem1->n,pMem1->z,pMem2->n,pMem2->z);
  62383. }else{
  62384. int rc;
  62385. const void *v1, *v2;
  62386. int n1, n2;
  62387. Mem c1;
  62388. Mem c2;
  62389. sqlite3VdbeMemInit(&c1, pMem1->db, MEM_Null);
  62390. sqlite3VdbeMemInit(&c2, pMem1->db, MEM_Null);
  62391. sqlite3VdbeMemShallowCopy(&c1, pMem1, MEM_Ephem);
  62392. sqlite3VdbeMemShallowCopy(&c2, pMem2, MEM_Ephem);
  62393. v1 = sqlite3ValueText((sqlite3_value*)&c1, pColl->enc);
  62394. n1 = v1==0 ? 0 : c1.n;
  62395. v2 = sqlite3ValueText((sqlite3_value*)&c2, pColl->enc);
  62396. n2 = v2==0 ? 0 : c2.n;
  62397. rc = pColl->xCmp(pColl->pUser, n1, v1, n2, v2);
  62398. sqlite3VdbeMemRelease(&c1);
  62399. sqlite3VdbeMemRelease(&c2);
  62400. if( (v1==0 || v2==0) && prcErr ) *prcErr = SQLITE_NOMEM;
  62401. return rc;
  62402. }
  62403. }
  62404. /*
  62405. ** Compare two blobs. Return negative, zero, or positive if the first
  62406. ** is less than, equal to, or greater than the second, respectively.
  62407. ** If one blob is a prefix of the other, then the shorter is the lessor.
  62408. */
  62409. static SQLITE_NOINLINE int sqlite3BlobCompare(const Mem *pB1, const Mem *pB2){
  62410. int c = memcmp(pB1->z, pB2->z, pB1->n>pB2->n ? pB2->n : pB1->n);
  62411. if( c ) return c;
  62412. return pB1->n - pB2->n;
  62413. }
  62414. /*
  62415. ** Compare the values contained by the two memory cells, returning
  62416. ** negative, zero or positive if pMem1 is less than, equal to, or greater
  62417. ** than pMem2. Sorting order is NULL's first, followed by numbers (integers
  62418. ** and reals) sorted numerically, followed by text ordered by the collating
  62419. ** sequence pColl and finally blob's ordered by memcmp().
  62420. **
  62421. ** Two NULL values are considered equal by this function.
  62422. */
  62423. SQLITE_PRIVATE int sqlite3MemCompare(const Mem *pMem1, const Mem *pMem2, const CollSeq *pColl){
  62424. int f1, f2;
  62425. int combined_flags;
  62426. f1 = pMem1->flags;
  62427. f2 = pMem2->flags;
  62428. combined_flags = f1|f2;
  62429. assert( (combined_flags & MEM_RowSet)==0 );
  62430. /* If one value is NULL, it is less than the other. If both values
  62431. ** are NULL, return 0.
  62432. */
  62433. if( combined_flags&MEM_Null ){
  62434. return (f2&MEM_Null) - (f1&MEM_Null);
  62435. }
  62436. /* If one value is a number and the other is not, the number is less.
  62437. ** If both are numbers, compare as reals if one is a real, or as integers
  62438. ** if both values are integers.
  62439. */
  62440. if( combined_flags&(MEM_Int|MEM_Real) ){
  62441. double r1, r2;
  62442. if( (f1 & f2 & MEM_Int)!=0 ){
  62443. if( pMem1->u.i < pMem2->u.i ) return -1;
  62444. if( pMem1->u.i > pMem2->u.i ) return 1;
  62445. return 0;
  62446. }
  62447. if( (f1&MEM_Real)!=0 ){
  62448. r1 = pMem1->u.r;
  62449. }else if( (f1&MEM_Int)!=0 ){
  62450. r1 = (double)pMem1->u.i;
  62451. }else{
  62452. return 1;
  62453. }
  62454. if( (f2&MEM_Real)!=0 ){
  62455. r2 = pMem2->u.r;
  62456. }else if( (f2&MEM_Int)!=0 ){
  62457. r2 = (double)pMem2->u.i;
  62458. }else{
  62459. return -1;
  62460. }
  62461. if( r1<r2 ) return -1;
  62462. if( r1>r2 ) return 1;
  62463. return 0;
  62464. }
  62465. /* If one value is a string and the other is a blob, the string is less.
  62466. ** If both are strings, compare using the collating functions.
  62467. */
  62468. if( combined_flags&MEM_Str ){
  62469. if( (f1 & MEM_Str)==0 ){
  62470. return 1;
  62471. }
  62472. if( (f2 & MEM_Str)==0 ){
  62473. return -1;
  62474. }
  62475. assert( pMem1->enc==pMem2->enc );
  62476. assert( pMem1->enc==SQLITE_UTF8 ||
  62477. pMem1->enc==SQLITE_UTF16LE || pMem1->enc==SQLITE_UTF16BE );
  62478. /* The collation sequence must be defined at this point, even if
  62479. ** the user deletes the collation sequence after the vdbe program is
  62480. ** compiled (this was not always the case).
  62481. */
  62482. assert( !pColl || pColl->xCmp );
  62483. if( pColl ){
  62484. return vdbeCompareMemString(pMem1, pMem2, pColl, 0);
  62485. }
  62486. /* If a NULL pointer was passed as the collate function, fall through
  62487. ** to the blob case and use memcmp(). */
  62488. }
  62489. /* Both values must be blobs. Compare using memcmp(). */
  62490. return sqlite3BlobCompare(pMem1, pMem2);
  62491. }
  62492. /*
  62493. ** The first argument passed to this function is a serial-type that
  62494. ** corresponds to an integer - all values between 1 and 9 inclusive
  62495. ** except 7. The second points to a buffer containing an integer value
  62496. ** serialized according to serial_type. This function deserializes
  62497. ** and returns the value.
  62498. */
  62499. static i64 vdbeRecordDecodeInt(u32 serial_type, const u8 *aKey){
  62500. u32 y;
  62501. assert( CORRUPT_DB || (serial_type>=1 && serial_type<=9 && serial_type!=7) );
  62502. switch( serial_type ){
  62503. case 0:
  62504. case 1:
  62505. testcase( aKey[0]&0x80 );
  62506. return ONE_BYTE_INT(aKey);
  62507. case 2:
  62508. testcase( aKey[0]&0x80 );
  62509. return TWO_BYTE_INT(aKey);
  62510. case 3:
  62511. testcase( aKey[0]&0x80 );
  62512. return THREE_BYTE_INT(aKey);
  62513. case 4: {
  62514. testcase( aKey[0]&0x80 );
  62515. y = FOUR_BYTE_UINT(aKey);
  62516. return (i64)*(int*)&y;
  62517. }
  62518. case 5: {
  62519. testcase( aKey[0]&0x80 );
  62520. return FOUR_BYTE_UINT(aKey+2) + (((i64)1)<<32)*TWO_BYTE_INT(aKey);
  62521. }
  62522. case 6: {
  62523. u64 x = FOUR_BYTE_UINT(aKey);
  62524. testcase( aKey[0]&0x80 );
  62525. x = (x<<32) | FOUR_BYTE_UINT(aKey+4);
  62526. return (i64)*(i64*)&x;
  62527. }
  62528. }
  62529. return (serial_type - 8);
  62530. }
  62531. /*
  62532. ** This function compares the two table rows or index records
  62533. ** specified by {nKey1, pKey1} and pPKey2. It returns a negative, zero
  62534. ** or positive integer if key1 is less than, equal to or
  62535. ** greater than key2. The {nKey1, pKey1} key must be a blob
  62536. ** created by the OP_MakeRecord opcode of the VDBE. The pPKey2
  62537. ** key must be a parsed key such as obtained from
  62538. ** sqlite3VdbeParseRecord.
  62539. **
  62540. ** If argument bSkip is non-zero, it is assumed that the caller has already
  62541. ** determined that the first fields of the keys are equal.
  62542. **
  62543. ** Key1 and Key2 do not have to contain the same number of fields. If all
  62544. ** fields that appear in both keys are equal, then pPKey2->default_rc is
  62545. ** returned.
  62546. **
  62547. ** If database corruption is discovered, set pPKey2->errCode to
  62548. ** SQLITE_CORRUPT and return 0. If an OOM error is encountered,
  62549. ** pPKey2->errCode is set to SQLITE_NOMEM and, if it is not NULL, the
  62550. ** malloc-failed flag set on database handle (pPKey2->pKeyInfo->db).
  62551. */
  62552. static int vdbeRecordCompareWithSkip(
  62553. int nKey1, const void *pKey1, /* Left key */
  62554. UnpackedRecord *pPKey2, /* Right key */
  62555. int bSkip /* If true, skip the first field */
  62556. ){
  62557. u32 d1; /* Offset into aKey[] of next data element */
  62558. int i; /* Index of next field to compare */
  62559. u32 szHdr1; /* Size of record header in bytes */
  62560. u32 idx1; /* Offset of first type in header */
  62561. int rc = 0; /* Return value */
  62562. Mem *pRhs = pPKey2->aMem; /* Next field of pPKey2 to compare */
  62563. KeyInfo *pKeyInfo = pPKey2->pKeyInfo;
  62564. const unsigned char *aKey1 = (const unsigned char *)pKey1;
  62565. Mem mem1;
  62566. /* If bSkip is true, then the caller has already determined that the first
  62567. ** two elements in the keys are equal. Fix the various stack variables so
  62568. ** that this routine begins comparing at the second field. */
  62569. if( bSkip ){
  62570. u32 s1;
  62571. idx1 = 1 + getVarint32(&aKey1[1], s1);
  62572. szHdr1 = aKey1[0];
  62573. d1 = szHdr1 + sqlite3VdbeSerialTypeLen(s1);
  62574. i = 1;
  62575. pRhs++;
  62576. }else{
  62577. idx1 = getVarint32(aKey1, szHdr1);
  62578. d1 = szHdr1;
  62579. if( d1>(unsigned)nKey1 ){
  62580. pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
  62581. return 0; /* Corruption */
  62582. }
  62583. i = 0;
  62584. }
  62585. VVA_ONLY( mem1.szMalloc = 0; ) /* Only needed by assert() statements */
  62586. assert( pPKey2->pKeyInfo->nField+pPKey2->pKeyInfo->nXField>=pPKey2->nField
  62587. || CORRUPT_DB );
  62588. assert( pPKey2->pKeyInfo->aSortOrder!=0 );
  62589. assert( pPKey2->pKeyInfo->nField>0 );
  62590. assert( idx1<=szHdr1 || CORRUPT_DB );
  62591. do{
  62592. u32 serial_type;
  62593. /* RHS is an integer */
  62594. if( pRhs->flags & MEM_Int ){
  62595. serial_type = aKey1[idx1];
  62596. testcase( serial_type==12 );
  62597. if( serial_type>=12 ){
  62598. rc = +1;
  62599. }else if( serial_type==0 ){
  62600. rc = -1;
  62601. }else if( serial_type==7 ){
  62602. double rhs = (double)pRhs->u.i;
  62603. sqlite3VdbeSerialGet(&aKey1[d1], serial_type, &mem1);
  62604. if( mem1.u.r<rhs ){
  62605. rc = -1;
  62606. }else if( mem1.u.r>rhs ){
  62607. rc = +1;
  62608. }
  62609. }else{
  62610. i64 lhs = vdbeRecordDecodeInt(serial_type, &aKey1[d1]);
  62611. i64 rhs = pRhs->u.i;
  62612. if( lhs<rhs ){
  62613. rc = -1;
  62614. }else if( lhs>rhs ){
  62615. rc = +1;
  62616. }
  62617. }
  62618. }
  62619. /* RHS is real */
  62620. else if( pRhs->flags & MEM_Real ){
  62621. serial_type = aKey1[idx1];
  62622. if( serial_type>=12 ){
  62623. rc = +1;
  62624. }else if( serial_type==0 ){
  62625. rc = -1;
  62626. }else{
  62627. double rhs = pRhs->u.r;
  62628. double lhs;
  62629. sqlite3VdbeSerialGet(&aKey1[d1], serial_type, &mem1);
  62630. if( serial_type==7 ){
  62631. lhs = mem1.u.r;
  62632. }else{
  62633. lhs = (double)mem1.u.i;
  62634. }
  62635. if( lhs<rhs ){
  62636. rc = -1;
  62637. }else if( lhs>rhs ){
  62638. rc = +1;
  62639. }
  62640. }
  62641. }
  62642. /* RHS is a string */
  62643. else if( pRhs->flags & MEM_Str ){
  62644. getVarint32(&aKey1[idx1], serial_type);
  62645. testcase( serial_type==12 );
  62646. if( serial_type<12 ){
  62647. rc = -1;
  62648. }else if( !(serial_type & 0x01) ){
  62649. rc = +1;
  62650. }else{
  62651. mem1.n = (serial_type - 12) / 2;
  62652. testcase( (d1+mem1.n)==(unsigned)nKey1 );
  62653. testcase( (d1+mem1.n+1)==(unsigned)nKey1 );
  62654. if( (d1+mem1.n) > (unsigned)nKey1 ){
  62655. pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
  62656. return 0; /* Corruption */
  62657. }else if( pKeyInfo->aColl[i] ){
  62658. mem1.enc = pKeyInfo->enc;
  62659. mem1.db = pKeyInfo->db;
  62660. mem1.flags = MEM_Str;
  62661. mem1.z = (char*)&aKey1[d1];
  62662. rc = vdbeCompareMemString(
  62663. &mem1, pRhs, pKeyInfo->aColl[i], &pPKey2->errCode
  62664. );
  62665. }else{
  62666. int nCmp = MIN(mem1.n, pRhs->n);
  62667. rc = memcmp(&aKey1[d1], pRhs->z, nCmp);
  62668. if( rc==0 ) rc = mem1.n - pRhs->n;
  62669. }
  62670. }
  62671. }
  62672. /* RHS is a blob */
  62673. else if( pRhs->flags & MEM_Blob ){
  62674. getVarint32(&aKey1[idx1], serial_type);
  62675. testcase( serial_type==12 );
  62676. if( serial_type<12 || (serial_type & 0x01) ){
  62677. rc = -1;
  62678. }else{
  62679. int nStr = (serial_type - 12) / 2;
  62680. testcase( (d1+nStr)==(unsigned)nKey1 );
  62681. testcase( (d1+nStr+1)==(unsigned)nKey1 );
  62682. if( (d1+nStr) > (unsigned)nKey1 ){
  62683. pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
  62684. return 0; /* Corruption */
  62685. }else{
  62686. int nCmp = MIN(nStr, pRhs->n);
  62687. rc = memcmp(&aKey1[d1], pRhs->z, nCmp);
  62688. if( rc==0 ) rc = nStr - pRhs->n;
  62689. }
  62690. }
  62691. }
  62692. /* RHS is null */
  62693. else{
  62694. serial_type = aKey1[idx1];
  62695. rc = (serial_type!=0);
  62696. }
  62697. if( rc!=0 ){
  62698. if( pKeyInfo->aSortOrder[i] ){
  62699. rc = -rc;
  62700. }
  62701. assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, rc) );
  62702. assert( mem1.szMalloc==0 ); /* See comment below */
  62703. return rc;
  62704. }
  62705. i++;
  62706. pRhs++;
  62707. d1 += sqlite3VdbeSerialTypeLen(serial_type);
  62708. idx1 += sqlite3VarintLen(serial_type);
  62709. }while( idx1<(unsigned)szHdr1 && i<pPKey2->nField && d1<=(unsigned)nKey1 );
  62710. /* No memory allocation is ever used on mem1. Prove this using
  62711. ** the following assert(). If the assert() fails, it indicates a
  62712. ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1). */
  62713. assert( mem1.szMalloc==0 );
  62714. /* rc==0 here means that one or both of the keys ran out of fields and
  62715. ** all the fields up to that point were equal. Return the default_rc
  62716. ** value. */
  62717. assert( CORRUPT_DB
  62718. || vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, pPKey2->default_rc)
  62719. || pKeyInfo->db->mallocFailed
  62720. );
  62721. return pPKey2->default_rc;
  62722. }
  62723. SQLITE_PRIVATE int sqlite3VdbeRecordCompare(
  62724. int nKey1, const void *pKey1, /* Left key */
  62725. UnpackedRecord *pPKey2 /* Right key */
  62726. ){
  62727. return vdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 0);
  62728. }
  62729. /*
  62730. ** This function is an optimized version of sqlite3VdbeRecordCompare()
  62731. ** that (a) the first field of pPKey2 is an integer, and (b) the
  62732. ** size-of-header varint at the start of (pKey1/nKey1) fits in a single
  62733. ** byte (i.e. is less than 128).
  62734. **
  62735. ** To avoid concerns about buffer overreads, this routine is only used
  62736. ** on schemas where the maximum valid header size is 63 bytes or less.
  62737. */
  62738. static int vdbeRecordCompareInt(
  62739. int nKey1, const void *pKey1, /* Left key */
  62740. UnpackedRecord *pPKey2 /* Right key */
  62741. ){
  62742. const u8 *aKey = &((const u8*)pKey1)[*(const u8*)pKey1 & 0x3F];
  62743. int serial_type = ((const u8*)pKey1)[1];
  62744. int res;
  62745. u32 y;
  62746. u64 x;
  62747. i64 v = pPKey2->aMem[0].u.i;
  62748. i64 lhs;
  62749. assert( (*(u8*)pKey1)<=0x3F || CORRUPT_DB );
  62750. switch( serial_type ){
  62751. case 1: { /* 1-byte signed integer */
  62752. lhs = ONE_BYTE_INT(aKey);
  62753. testcase( lhs<0 );
  62754. break;
  62755. }
  62756. case 2: { /* 2-byte signed integer */
  62757. lhs = TWO_BYTE_INT(aKey);
  62758. testcase( lhs<0 );
  62759. break;
  62760. }
  62761. case 3: { /* 3-byte signed integer */
  62762. lhs = THREE_BYTE_INT(aKey);
  62763. testcase( lhs<0 );
  62764. break;
  62765. }
  62766. case 4: { /* 4-byte signed integer */
  62767. y = FOUR_BYTE_UINT(aKey);
  62768. lhs = (i64)*(int*)&y;
  62769. testcase( lhs<0 );
  62770. break;
  62771. }
  62772. case 5: { /* 6-byte signed integer */
  62773. lhs = FOUR_BYTE_UINT(aKey+2) + (((i64)1)<<32)*TWO_BYTE_INT(aKey);
  62774. testcase( lhs<0 );
  62775. break;
  62776. }
  62777. case 6: { /* 8-byte signed integer */
  62778. x = FOUR_BYTE_UINT(aKey);
  62779. x = (x<<32) | FOUR_BYTE_UINT(aKey+4);
  62780. lhs = *(i64*)&x;
  62781. testcase( lhs<0 );
  62782. break;
  62783. }
  62784. case 8:
  62785. lhs = 0;
  62786. break;
  62787. case 9:
  62788. lhs = 1;
  62789. break;
  62790. /* This case could be removed without changing the results of running
  62791. ** this code. Including it causes gcc to generate a faster switch
  62792. ** statement (since the range of switch targets now starts at zero and
  62793. ** is contiguous) but does not cause any duplicate code to be generated
  62794. ** (as gcc is clever enough to combine the two like cases). Other
  62795. ** compilers might be similar. */
  62796. case 0: case 7:
  62797. return sqlite3VdbeRecordCompare(nKey1, pKey1, pPKey2);
  62798. default:
  62799. return sqlite3VdbeRecordCompare(nKey1, pKey1, pPKey2);
  62800. }
  62801. if( v>lhs ){
  62802. res = pPKey2->r1;
  62803. }else if( v<lhs ){
  62804. res = pPKey2->r2;
  62805. }else if( pPKey2->nField>1 ){
  62806. /* The first fields of the two keys are equal. Compare the trailing
  62807. ** fields. */
  62808. res = vdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 1);
  62809. }else{
  62810. /* The first fields of the two keys are equal and there are no trailing
  62811. ** fields. Return pPKey2->default_rc in this case. */
  62812. res = pPKey2->default_rc;
  62813. }
  62814. assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, res) );
  62815. return res;
  62816. }
  62817. /*
  62818. ** This function is an optimized version of sqlite3VdbeRecordCompare()
  62819. ** that (a) the first field of pPKey2 is a string, that (b) the first field
  62820. ** uses the collation sequence BINARY and (c) that the size-of-header varint
  62821. ** at the start of (pKey1/nKey1) fits in a single byte.
  62822. */
  62823. static int vdbeRecordCompareString(
  62824. int nKey1, const void *pKey1, /* Left key */
  62825. UnpackedRecord *pPKey2 /* Right key */
  62826. ){
  62827. const u8 *aKey1 = (const u8*)pKey1;
  62828. int serial_type;
  62829. int res;
  62830. getVarint32(&aKey1[1], serial_type);
  62831. if( serial_type<12 ){
  62832. res = pPKey2->r1; /* (pKey1/nKey1) is a number or a null */
  62833. }else if( !(serial_type & 0x01) ){
  62834. res = pPKey2->r2; /* (pKey1/nKey1) is a blob */
  62835. }else{
  62836. int nCmp;
  62837. int nStr;
  62838. int szHdr = aKey1[0];
  62839. nStr = (serial_type-12) / 2;
  62840. if( (szHdr + nStr) > nKey1 ){
  62841. pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
  62842. return 0; /* Corruption */
  62843. }
  62844. nCmp = MIN( pPKey2->aMem[0].n, nStr );
  62845. res = memcmp(&aKey1[szHdr], pPKey2->aMem[0].z, nCmp);
  62846. if( res==0 ){
  62847. res = nStr - pPKey2->aMem[0].n;
  62848. if( res==0 ){
  62849. if( pPKey2->nField>1 ){
  62850. res = vdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 1);
  62851. }else{
  62852. res = pPKey2->default_rc;
  62853. }
  62854. }else if( res>0 ){
  62855. res = pPKey2->r2;
  62856. }else{
  62857. res = pPKey2->r1;
  62858. }
  62859. }else if( res>0 ){
  62860. res = pPKey2->r2;
  62861. }else{
  62862. res = pPKey2->r1;
  62863. }
  62864. }
  62865. assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, res)
  62866. || CORRUPT_DB
  62867. || pPKey2->pKeyInfo->db->mallocFailed
  62868. );
  62869. return res;
  62870. }
  62871. /*
  62872. ** Return a pointer to an sqlite3VdbeRecordCompare() compatible function
  62873. ** suitable for comparing serialized records to the unpacked record passed
  62874. ** as the only argument.
  62875. */
  62876. SQLITE_PRIVATE RecordCompare sqlite3VdbeFindCompare(UnpackedRecord *p){
  62877. /* varintRecordCompareInt() and varintRecordCompareString() both assume
  62878. ** that the size-of-header varint that occurs at the start of each record
  62879. ** fits in a single byte (i.e. is 127 or less). varintRecordCompareInt()
  62880. ** also assumes that it is safe to overread a buffer by at least the
  62881. ** maximum possible legal header size plus 8 bytes. Because there is
  62882. ** guaranteed to be at least 74 (but not 136) bytes of padding following each
  62883. ** buffer passed to varintRecordCompareInt() this makes it convenient to
  62884. ** limit the size of the header to 64 bytes in cases where the first field
  62885. ** is an integer.
  62886. **
  62887. ** The easiest way to enforce this limit is to consider only records with
  62888. ** 13 fields or less. If the first field is an integer, the maximum legal
  62889. ** header size is (12*5 + 1 + 1) bytes. */
  62890. if( (p->pKeyInfo->nField + p->pKeyInfo->nXField)<=13 ){
  62891. int flags = p->aMem[0].flags;
  62892. if( p->pKeyInfo->aSortOrder[0] ){
  62893. p->r1 = 1;
  62894. p->r2 = -1;
  62895. }else{
  62896. p->r1 = -1;
  62897. p->r2 = 1;
  62898. }
  62899. if( (flags & MEM_Int) ){
  62900. return vdbeRecordCompareInt;
  62901. }
  62902. testcase( flags & MEM_Real );
  62903. testcase( flags & MEM_Null );
  62904. testcase( flags & MEM_Blob );
  62905. if( (flags & (MEM_Real|MEM_Null|MEM_Blob))==0 && p->pKeyInfo->aColl[0]==0 ){
  62906. assert( flags & MEM_Str );
  62907. return vdbeRecordCompareString;
  62908. }
  62909. }
  62910. return sqlite3VdbeRecordCompare;
  62911. }
  62912. /*
  62913. ** pCur points at an index entry created using the OP_MakeRecord opcode.
  62914. ** Read the rowid (the last field in the record) and store it in *rowid.
  62915. ** Return SQLITE_OK if everything works, or an error code otherwise.
  62916. **
  62917. ** pCur might be pointing to text obtained from a corrupt database file.
  62918. ** So the content cannot be trusted. Do appropriate checks on the content.
  62919. */
  62920. SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3 *db, BtCursor *pCur, i64 *rowid){
  62921. i64 nCellKey = 0;
  62922. int rc;
  62923. u32 szHdr; /* Size of the header */
  62924. u32 typeRowid; /* Serial type of the rowid */
  62925. u32 lenRowid; /* Size of the rowid */
  62926. Mem m, v;
  62927. /* Get the size of the index entry. Only indices entries of less
  62928. ** than 2GiB are support - anything large must be database corruption.
  62929. ** Any corruption is detected in sqlite3BtreeParseCellPtr(), though, so
  62930. ** this code can safely assume that nCellKey is 32-bits
  62931. */
  62932. assert( sqlite3BtreeCursorIsValid(pCur) );
  62933. VVA_ONLY(rc =) sqlite3BtreeKeySize(pCur, &nCellKey);
  62934. assert( rc==SQLITE_OK ); /* pCur is always valid so KeySize cannot fail */
  62935. assert( (nCellKey & SQLITE_MAX_U32)==(u64)nCellKey );
  62936. /* Read in the complete content of the index entry */
  62937. sqlite3VdbeMemInit(&m, db, 0);
  62938. rc = sqlite3VdbeMemFromBtree(pCur, 0, (u32)nCellKey, 1, &m);
  62939. if( rc ){
  62940. return rc;
  62941. }
  62942. /* The index entry must begin with a header size */
  62943. (void)getVarint32((u8*)m.z, szHdr);
  62944. testcase( szHdr==3 );
  62945. testcase( szHdr==m.n );
  62946. if( unlikely(szHdr<3 || (int)szHdr>m.n) ){
  62947. goto idx_rowid_corruption;
  62948. }
  62949. /* The last field of the index should be an integer - the ROWID.
  62950. ** Verify that the last entry really is an integer. */
  62951. (void)getVarint32((u8*)&m.z[szHdr-1], typeRowid);
  62952. testcase( typeRowid==1 );
  62953. testcase( typeRowid==2 );
  62954. testcase( typeRowid==3 );
  62955. testcase( typeRowid==4 );
  62956. testcase( typeRowid==5 );
  62957. testcase( typeRowid==6 );
  62958. testcase( typeRowid==8 );
  62959. testcase( typeRowid==9 );
  62960. if( unlikely(typeRowid<1 || typeRowid>9 || typeRowid==7) ){
  62961. goto idx_rowid_corruption;
  62962. }
  62963. lenRowid = sqlite3VdbeSerialTypeLen(typeRowid);
  62964. testcase( (u32)m.n==szHdr+lenRowid );
  62965. if( unlikely((u32)m.n<szHdr+lenRowid) ){
  62966. goto idx_rowid_corruption;
  62967. }
  62968. /* Fetch the integer off the end of the index record */
  62969. sqlite3VdbeSerialGet((u8*)&m.z[m.n-lenRowid], typeRowid, &v);
  62970. *rowid = v.u.i;
  62971. sqlite3VdbeMemRelease(&m);
  62972. return SQLITE_OK;
  62973. /* Jump here if database corruption is detected after m has been
  62974. ** allocated. Free the m object and return SQLITE_CORRUPT. */
  62975. idx_rowid_corruption:
  62976. testcase( m.szMalloc!=0 );
  62977. sqlite3VdbeMemRelease(&m);
  62978. return SQLITE_CORRUPT_BKPT;
  62979. }
  62980. /*
  62981. ** Compare the key of the index entry that cursor pC is pointing to against
  62982. ** the key string in pUnpacked. Write into *pRes a number
  62983. ** that is negative, zero, or positive if pC is less than, equal to,
  62984. ** or greater than pUnpacked. Return SQLITE_OK on success.
  62985. **
  62986. ** pUnpacked is either created without a rowid or is truncated so that it
  62987. ** omits the rowid at the end. The rowid at the end of the index entry
  62988. ** is ignored as well. Hence, this routine only compares the prefixes
  62989. ** of the keys prior to the final rowid, not the entire key.
  62990. */
  62991. SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(
  62992. sqlite3 *db, /* Database connection */
  62993. VdbeCursor *pC, /* The cursor to compare against */
  62994. UnpackedRecord *pUnpacked, /* Unpacked version of key */
  62995. int *res /* Write the comparison result here */
  62996. ){
  62997. i64 nCellKey = 0;
  62998. int rc;
  62999. BtCursor *pCur = pC->pCursor;
  63000. Mem m;
  63001. assert( sqlite3BtreeCursorIsValid(pCur) );
  63002. VVA_ONLY(rc =) sqlite3BtreeKeySize(pCur, &nCellKey);
  63003. assert( rc==SQLITE_OK ); /* pCur is always valid so KeySize cannot fail */
  63004. /* nCellKey will always be between 0 and 0xffffffff because of the way
  63005. ** that btreeParseCellPtr() and sqlite3GetVarint32() are implemented */
  63006. if( nCellKey<=0 || nCellKey>0x7fffffff ){
  63007. *res = 0;
  63008. return SQLITE_CORRUPT_BKPT;
  63009. }
  63010. sqlite3VdbeMemInit(&m, db, 0);
  63011. rc = sqlite3VdbeMemFromBtree(pC->pCursor, 0, (u32)nCellKey, 1, &m);
  63012. if( rc ){
  63013. return rc;
  63014. }
  63015. *res = sqlite3VdbeRecordCompare(m.n, m.z, pUnpacked);
  63016. sqlite3VdbeMemRelease(&m);
  63017. return SQLITE_OK;
  63018. }
  63019. /*
  63020. ** This routine sets the value to be returned by subsequent calls to
  63021. ** sqlite3_changes() on the database handle 'db'.
  63022. */
  63023. SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *db, int nChange){
  63024. assert( sqlite3_mutex_held(db->mutex) );
  63025. db->nChange = nChange;
  63026. db->nTotalChange += nChange;
  63027. }
  63028. /*
  63029. ** Set a flag in the vdbe to update the change counter when it is finalised
  63030. ** or reset.
  63031. */
  63032. SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe *v){
  63033. v->changeCntOn = 1;
  63034. }
  63035. /*
  63036. ** Mark every prepared statement associated with a database connection
  63037. ** as expired.
  63038. **
  63039. ** An expired statement means that recompilation of the statement is
  63040. ** recommend. Statements expire when things happen that make their
  63041. ** programs obsolete. Removing user-defined functions or collating
  63042. ** sequences, or changing an authorization function are the types of
  63043. ** things that make prepared statements obsolete.
  63044. */
  63045. SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3 *db){
  63046. Vdbe *p;
  63047. for(p = db->pVdbe; p; p=p->pNext){
  63048. p->expired = 1;
  63049. }
  63050. }
  63051. /*
  63052. ** Return the database associated with the Vdbe.
  63053. */
  63054. SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe *v){
  63055. return v->db;
  63056. }
  63057. /*
  63058. ** Return a pointer to an sqlite3_value structure containing the value bound
  63059. ** parameter iVar of VM v. Except, if the value is an SQL NULL, return
  63060. ** 0 instead. Unless it is NULL, apply affinity aff (one of the SQLITE_AFF_*
  63061. ** constants) to the value before returning it.
  63062. **
  63063. ** The returned value must be freed by the caller using sqlite3ValueFree().
  63064. */
  63065. SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetBoundValue(Vdbe *v, int iVar, u8 aff){
  63066. assert( iVar>0 );
  63067. if( v ){
  63068. Mem *pMem = &v->aVar[iVar-1];
  63069. if( 0==(pMem->flags & MEM_Null) ){
  63070. sqlite3_value *pRet = sqlite3ValueNew(v->db);
  63071. if( pRet ){
  63072. sqlite3VdbeMemCopy((Mem *)pRet, pMem);
  63073. sqlite3ValueApplyAffinity(pRet, aff, SQLITE_UTF8);
  63074. }
  63075. return pRet;
  63076. }
  63077. }
  63078. return 0;
  63079. }
  63080. /*
  63081. ** Configure SQL variable iVar so that binding a new value to it signals
  63082. ** to sqlite3_reoptimize() that re-preparing the statement may result
  63083. ** in a better query plan.
  63084. */
  63085. SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe *v, int iVar){
  63086. assert( iVar>0 );
  63087. if( iVar>32 ){
  63088. v->expmask = 0xffffffff;
  63089. }else{
  63090. v->expmask |= ((u32)1 << (iVar-1));
  63091. }
  63092. }
  63093. #ifndef SQLITE_OMIT_VIRTUALTABLE
  63094. /*
  63095. ** Transfer error message text from an sqlite3_vtab.zErrMsg (text stored
  63096. ** in memory obtained from sqlite3_malloc) into a Vdbe.zErrMsg (text stored
  63097. ** in memory obtained from sqlite3DbMalloc).
  63098. */
  63099. SQLITE_PRIVATE void sqlite3VtabImportErrmsg(Vdbe *p, sqlite3_vtab *pVtab){
  63100. sqlite3 *db = p->db;
  63101. sqlite3DbFree(db, p->zErrMsg);
  63102. p->zErrMsg = sqlite3DbStrDup(db, pVtab->zErrMsg);
  63103. sqlite3_free(pVtab->zErrMsg);
  63104. pVtab->zErrMsg = 0;
  63105. }
  63106. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  63107. /************** End of vdbeaux.c *********************************************/
  63108. /************** Begin file vdbeapi.c *****************************************/
  63109. /*
  63110. ** 2004 May 26
  63111. **
  63112. ** The author disclaims copyright to this source code. In place of
  63113. ** a legal notice, here is a blessing:
  63114. **
  63115. ** May you do good and not evil.
  63116. ** May you find forgiveness for yourself and forgive others.
  63117. ** May you share freely, never taking more than you give.
  63118. **
  63119. *************************************************************************
  63120. **
  63121. ** This file contains code use to implement APIs that are part of the
  63122. ** VDBE.
  63123. */
  63124. #ifndef SQLITE_OMIT_DEPRECATED
  63125. /*
  63126. ** Return TRUE (non-zero) of the statement supplied as an argument needs
  63127. ** to be recompiled. A statement needs to be recompiled whenever the
  63128. ** execution environment changes in a way that would alter the program
  63129. ** that sqlite3_prepare() generates. For example, if new functions or
  63130. ** collating sequences are registered or if an authorizer function is
  63131. ** added or changed.
  63132. */
  63133. SQLITE_API int sqlite3_expired(sqlite3_stmt *pStmt){
  63134. Vdbe *p = (Vdbe*)pStmt;
  63135. return p==0 || p->expired;
  63136. }
  63137. #endif
  63138. /*
  63139. ** Check on a Vdbe to make sure it has not been finalized. Log
  63140. ** an error and return true if it has been finalized (or is otherwise
  63141. ** invalid). Return false if it is ok.
  63142. */
  63143. static int vdbeSafety(Vdbe *p){
  63144. if( p->db==0 ){
  63145. sqlite3_log(SQLITE_MISUSE, "API called with finalized prepared statement");
  63146. return 1;
  63147. }else{
  63148. return 0;
  63149. }
  63150. }
  63151. static int vdbeSafetyNotNull(Vdbe *p){
  63152. if( p==0 ){
  63153. sqlite3_log(SQLITE_MISUSE, "API called with NULL prepared statement");
  63154. return 1;
  63155. }else{
  63156. return vdbeSafety(p);
  63157. }
  63158. }
  63159. /*
  63160. ** The following routine destroys a virtual machine that is created by
  63161. ** the sqlite3_compile() routine. The integer returned is an SQLITE_
  63162. ** success/failure code that describes the result of executing the virtual
  63163. ** machine.
  63164. **
  63165. ** This routine sets the error code and string returned by
  63166. ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
  63167. */
  63168. SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt){
  63169. int rc;
  63170. if( pStmt==0 ){
  63171. /* IMPLEMENTATION-OF: R-57228-12904 Invoking sqlite3_finalize() on a NULL
  63172. ** pointer is a harmless no-op. */
  63173. rc = SQLITE_OK;
  63174. }else{
  63175. Vdbe *v = (Vdbe*)pStmt;
  63176. sqlite3 *db = v->db;
  63177. if( vdbeSafety(v) ) return SQLITE_MISUSE_BKPT;
  63178. sqlite3_mutex_enter(db->mutex);
  63179. rc = sqlite3VdbeFinalize(v);
  63180. rc = sqlite3ApiExit(db, rc);
  63181. sqlite3LeaveMutexAndCloseZombie(db);
  63182. }
  63183. return rc;
  63184. }
  63185. /*
  63186. ** Terminate the current execution of an SQL statement and reset it
  63187. ** back to its starting state so that it can be reused. A success code from
  63188. ** the prior execution is returned.
  63189. **
  63190. ** This routine sets the error code and string returned by
  63191. ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
  63192. */
  63193. SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt){
  63194. int rc;
  63195. if( pStmt==0 ){
  63196. rc = SQLITE_OK;
  63197. }else{
  63198. Vdbe *v = (Vdbe*)pStmt;
  63199. sqlite3_mutex_enter(v->db->mutex);
  63200. rc = sqlite3VdbeReset(v);
  63201. sqlite3VdbeRewind(v);
  63202. assert( (rc & (v->db->errMask))==rc );
  63203. rc = sqlite3ApiExit(v->db, rc);
  63204. sqlite3_mutex_leave(v->db->mutex);
  63205. }
  63206. return rc;
  63207. }
  63208. /*
  63209. ** Set all the parameters in the compiled SQL statement to NULL.
  63210. */
  63211. SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt *pStmt){
  63212. int i;
  63213. int rc = SQLITE_OK;
  63214. Vdbe *p = (Vdbe*)pStmt;
  63215. #if SQLITE_THREADSAFE
  63216. sqlite3_mutex *mutex = ((Vdbe*)pStmt)->db->mutex;
  63217. #endif
  63218. sqlite3_mutex_enter(mutex);
  63219. for(i=0; i<p->nVar; i++){
  63220. sqlite3VdbeMemRelease(&p->aVar[i]);
  63221. p->aVar[i].flags = MEM_Null;
  63222. }
  63223. if( p->isPrepareV2 && p->expmask ){
  63224. p->expired = 1;
  63225. }
  63226. sqlite3_mutex_leave(mutex);
  63227. return rc;
  63228. }
  63229. /**************************** sqlite3_value_ *******************************
  63230. ** The following routines extract information from a Mem or sqlite3_value
  63231. ** structure.
  63232. */
  63233. SQLITE_API const void *sqlite3_value_blob(sqlite3_value *pVal){
  63234. Mem *p = (Mem*)pVal;
  63235. if( p->flags & (MEM_Blob|MEM_Str) ){
  63236. sqlite3VdbeMemExpandBlob(p);
  63237. p->flags |= MEM_Blob;
  63238. return p->n ? p->z : 0;
  63239. }else{
  63240. return sqlite3_value_text(pVal);
  63241. }
  63242. }
  63243. SQLITE_API int sqlite3_value_bytes(sqlite3_value *pVal){
  63244. return sqlite3ValueBytes(pVal, SQLITE_UTF8);
  63245. }
  63246. SQLITE_API int sqlite3_value_bytes16(sqlite3_value *pVal){
  63247. return sqlite3ValueBytes(pVal, SQLITE_UTF16NATIVE);
  63248. }
  63249. SQLITE_API double sqlite3_value_double(sqlite3_value *pVal){
  63250. return sqlite3VdbeRealValue((Mem*)pVal);
  63251. }
  63252. SQLITE_API int sqlite3_value_int(sqlite3_value *pVal){
  63253. return (int)sqlite3VdbeIntValue((Mem*)pVal);
  63254. }
  63255. SQLITE_API sqlite_int64 sqlite3_value_int64(sqlite3_value *pVal){
  63256. return sqlite3VdbeIntValue((Mem*)pVal);
  63257. }
  63258. SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value *pVal){
  63259. return (const unsigned char *)sqlite3ValueText(pVal, SQLITE_UTF8);
  63260. }
  63261. #ifndef SQLITE_OMIT_UTF16
  63262. SQLITE_API const void *sqlite3_value_text16(sqlite3_value* pVal){
  63263. return sqlite3ValueText(pVal, SQLITE_UTF16NATIVE);
  63264. }
  63265. SQLITE_API const void *sqlite3_value_text16be(sqlite3_value *pVal){
  63266. return sqlite3ValueText(pVal, SQLITE_UTF16BE);
  63267. }
  63268. SQLITE_API const void *sqlite3_value_text16le(sqlite3_value *pVal){
  63269. return sqlite3ValueText(pVal, SQLITE_UTF16LE);
  63270. }
  63271. #endif /* SQLITE_OMIT_UTF16 */
  63272. SQLITE_API int sqlite3_value_type(sqlite3_value* pVal){
  63273. static const u8 aType[] = {
  63274. SQLITE_BLOB, /* 0x00 */
  63275. SQLITE_NULL, /* 0x01 */
  63276. SQLITE_TEXT, /* 0x02 */
  63277. SQLITE_NULL, /* 0x03 */
  63278. SQLITE_INTEGER, /* 0x04 */
  63279. SQLITE_NULL, /* 0x05 */
  63280. SQLITE_INTEGER, /* 0x06 */
  63281. SQLITE_NULL, /* 0x07 */
  63282. SQLITE_FLOAT, /* 0x08 */
  63283. SQLITE_NULL, /* 0x09 */
  63284. SQLITE_FLOAT, /* 0x0a */
  63285. SQLITE_NULL, /* 0x0b */
  63286. SQLITE_INTEGER, /* 0x0c */
  63287. SQLITE_NULL, /* 0x0d */
  63288. SQLITE_INTEGER, /* 0x0e */
  63289. SQLITE_NULL, /* 0x0f */
  63290. SQLITE_BLOB, /* 0x10 */
  63291. SQLITE_NULL, /* 0x11 */
  63292. SQLITE_TEXT, /* 0x12 */
  63293. SQLITE_NULL, /* 0x13 */
  63294. SQLITE_INTEGER, /* 0x14 */
  63295. SQLITE_NULL, /* 0x15 */
  63296. SQLITE_INTEGER, /* 0x16 */
  63297. SQLITE_NULL, /* 0x17 */
  63298. SQLITE_FLOAT, /* 0x18 */
  63299. SQLITE_NULL, /* 0x19 */
  63300. SQLITE_FLOAT, /* 0x1a */
  63301. SQLITE_NULL, /* 0x1b */
  63302. SQLITE_INTEGER, /* 0x1c */
  63303. SQLITE_NULL, /* 0x1d */
  63304. SQLITE_INTEGER, /* 0x1e */
  63305. SQLITE_NULL, /* 0x1f */
  63306. };
  63307. return aType[pVal->flags&MEM_AffMask];
  63308. }
  63309. /**************************** sqlite3_result_ *******************************
  63310. ** The following routines are used by user-defined functions to specify
  63311. ** the function result.
  63312. **
  63313. ** The setStrOrError() function calls sqlite3VdbeMemSetStr() to store the
  63314. ** result as a string or blob but if the string or blob is too large, it
  63315. ** then sets the error code to SQLITE_TOOBIG
  63316. **
  63317. ** The invokeValueDestructor(P,X) routine invokes destructor function X()
  63318. ** on value P is not going to be used and need to be destroyed.
  63319. */
  63320. static void setResultStrOrError(
  63321. sqlite3_context *pCtx, /* Function context */
  63322. const char *z, /* String pointer */
  63323. int n, /* Bytes in string, or negative */
  63324. u8 enc, /* Encoding of z. 0 for BLOBs */
  63325. void (*xDel)(void*) /* Destructor function */
  63326. ){
  63327. if( sqlite3VdbeMemSetStr(pCtx->pOut, z, n, enc, xDel)==SQLITE_TOOBIG ){
  63328. sqlite3_result_error_toobig(pCtx);
  63329. }
  63330. }
  63331. static int invokeValueDestructor(
  63332. const void *p, /* Value to destroy */
  63333. void (*xDel)(void*), /* The destructor */
  63334. sqlite3_context *pCtx /* Set a SQLITE_TOOBIG error if no NULL */
  63335. ){
  63336. assert( xDel!=SQLITE_DYNAMIC );
  63337. if( xDel==0 ){
  63338. /* noop */
  63339. }else if( xDel==SQLITE_TRANSIENT ){
  63340. /* noop */
  63341. }else{
  63342. xDel((void*)p);
  63343. }
  63344. if( pCtx ) sqlite3_result_error_toobig(pCtx);
  63345. return SQLITE_TOOBIG;
  63346. }
  63347. SQLITE_API void sqlite3_result_blob(
  63348. sqlite3_context *pCtx,
  63349. const void *z,
  63350. int n,
  63351. void (*xDel)(void *)
  63352. ){
  63353. assert( n>=0 );
  63354. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  63355. setResultStrOrError(pCtx, z, n, 0, xDel);
  63356. }
  63357. SQLITE_API void sqlite3_result_blob64(
  63358. sqlite3_context *pCtx,
  63359. const void *z,
  63360. sqlite3_uint64 n,
  63361. void (*xDel)(void *)
  63362. ){
  63363. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  63364. assert( xDel!=SQLITE_DYNAMIC );
  63365. if( n>0x7fffffff ){
  63366. (void)invokeValueDestructor(z, xDel, pCtx);
  63367. }else{
  63368. setResultStrOrError(pCtx, z, (int)n, 0, xDel);
  63369. }
  63370. }
  63371. SQLITE_API void sqlite3_result_double(sqlite3_context *pCtx, double rVal){
  63372. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  63373. sqlite3VdbeMemSetDouble(pCtx->pOut, rVal);
  63374. }
  63375. SQLITE_API void sqlite3_result_error(sqlite3_context *pCtx, const char *z, int n){
  63376. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  63377. pCtx->isError = SQLITE_ERROR;
  63378. pCtx->fErrorOrAux = 1;
  63379. sqlite3VdbeMemSetStr(pCtx->pOut, z, n, SQLITE_UTF8, SQLITE_TRANSIENT);
  63380. }
  63381. #ifndef SQLITE_OMIT_UTF16
  63382. SQLITE_API void sqlite3_result_error16(sqlite3_context *pCtx, const void *z, int n){
  63383. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  63384. pCtx->isError = SQLITE_ERROR;
  63385. pCtx->fErrorOrAux = 1;
  63386. sqlite3VdbeMemSetStr(pCtx->pOut, z, n, SQLITE_UTF16NATIVE, SQLITE_TRANSIENT);
  63387. }
  63388. #endif
  63389. SQLITE_API void sqlite3_result_int(sqlite3_context *pCtx, int iVal){
  63390. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  63391. sqlite3VdbeMemSetInt64(pCtx->pOut, (i64)iVal);
  63392. }
  63393. SQLITE_API void sqlite3_result_int64(sqlite3_context *pCtx, i64 iVal){
  63394. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  63395. sqlite3VdbeMemSetInt64(pCtx->pOut, iVal);
  63396. }
  63397. SQLITE_API void sqlite3_result_null(sqlite3_context *pCtx){
  63398. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  63399. sqlite3VdbeMemSetNull(pCtx->pOut);
  63400. }
  63401. SQLITE_API void sqlite3_result_text(
  63402. sqlite3_context *pCtx,
  63403. const char *z,
  63404. int n,
  63405. void (*xDel)(void *)
  63406. ){
  63407. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  63408. setResultStrOrError(pCtx, z, n, SQLITE_UTF8, xDel);
  63409. }
  63410. SQLITE_API void sqlite3_result_text64(
  63411. sqlite3_context *pCtx,
  63412. const char *z,
  63413. sqlite3_uint64 n,
  63414. void (*xDel)(void *),
  63415. unsigned char enc
  63416. ){
  63417. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  63418. assert( xDel!=SQLITE_DYNAMIC );
  63419. if( enc==SQLITE_UTF16 ) enc = SQLITE_UTF16NATIVE;
  63420. if( n>0x7fffffff ){
  63421. (void)invokeValueDestructor(z, xDel, pCtx);
  63422. }else{
  63423. setResultStrOrError(pCtx, z, (int)n, enc, xDel);
  63424. }
  63425. }
  63426. #ifndef SQLITE_OMIT_UTF16
  63427. SQLITE_API void sqlite3_result_text16(
  63428. sqlite3_context *pCtx,
  63429. const void *z,
  63430. int n,
  63431. void (*xDel)(void *)
  63432. ){
  63433. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  63434. setResultStrOrError(pCtx, z, n, SQLITE_UTF16NATIVE, xDel);
  63435. }
  63436. SQLITE_API void sqlite3_result_text16be(
  63437. sqlite3_context *pCtx,
  63438. const void *z,
  63439. int n,
  63440. void (*xDel)(void *)
  63441. ){
  63442. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  63443. setResultStrOrError(pCtx, z, n, SQLITE_UTF16BE, xDel);
  63444. }
  63445. SQLITE_API void sqlite3_result_text16le(
  63446. sqlite3_context *pCtx,
  63447. const void *z,
  63448. int n,
  63449. void (*xDel)(void *)
  63450. ){
  63451. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  63452. setResultStrOrError(pCtx, z, n, SQLITE_UTF16LE, xDel);
  63453. }
  63454. #endif /* SQLITE_OMIT_UTF16 */
  63455. SQLITE_API void sqlite3_result_value(sqlite3_context *pCtx, sqlite3_value *pValue){
  63456. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  63457. sqlite3VdbeMemCopy(pCtx->pOut, pValue);
  63458. }
  63459. SQLITE_API void sqlite3_result_zeroblob(sqlite3_context *pCtx, int n){
  63460. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  63461. sqlite3VdbeMemSetZeroBlob(pCtx->pOut, n);
  63462. }
  63463. SQLITE_API void sqlite3_result_error_code(sqlite3_context *pCtx, int errCode){
  63464. pCtx->isError = errCode;
  63465. pCtx->fErrorOrAux = 1;
  63466. if( pCtx->pOut->flags & MEM_Null ){
  63467. sqlite3VdbeMemSetStr(pCtx->pOut, sqlite3ErrStr(errCode), -1,
  63468. SQLITE_UTF8, SQLITE_STATIC);
  63469. }
  63470. }
  63471. /* Force an SQLITE_TOOBIG error. */
  63472. SQLITE_API void sqlite3_result_error_toobig(sqlite3_context *pCtx){
  63473. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  63474. pCtx->isError = SQLITE_TOOBIG;
  63475. pCtx->fErrorOrAux = 1;
  63476. sqlite3VdbeMemSetStr(pCtx->pOut, "string or blob too big", -1,
  63477. SQLITE_UTF8, SQLITE_STATIC);
  63478. }
  63479. /* An SQLITE_NOMEM error. */
  63480. SQLITE_API void sqlite3_result_error_nomem(sqlite3_context *pCtx){
  63481. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  63482. sqlite3VdbeMemSetNull(pCtx->pOut);
  63483. pCtx->isError = SQLITE_NOMEM;
  63484. pCtx->fErrorOrAux = 1;
  63485. pCtx->pOut->db->mallocFailed = 1;
  63486. }
  63487. /*
  63488. ** This function is called after a transaction has been committed. It
  63489. ** invokes callbacks registered with sqlite3_wal_hook() as required.
  63490. */
  63491. static int doWalCallbacks(sqlite3 *db){
  63492. int rc = SQLITE_OK;
  63493. #ifndef SQLITE_OMIT_WAL
  63494. int i;
  63495. for(i=0; i<db->nDb; i++){
  63496. Btree *pBt = db->aDb[i].pBt;
  63497. if( pBt ){
  63498. int nEntry = sqlite3PagerWalCallback(sqlite3BtreePager(pBt));
  63499. if( db->xWalCallback && nEntry>0 && rc==SQLITE_OK ){
  63500. rc = db->xWalCallback(db->pWalArg, db, db->aDb[i].zName, nEntry);
  63501. }
  63502. }
  63503. }
  63504. #endif
  63505. return rc;
  63506. }
  63507. /*
  63508. ** Execute the statement pStmt, either until a row of data is ready, the
  63509. ** statement is completely executed or an error occurs.
  63510. **
  63511. ** This routine implements the bulk of the logic behind the sqlite_step()
  63512. ** API. The only thing omitted is the automatic recompile if a
  63513. ** schema change has occurred. That detail is handled by the
  63514. ** outer sqlite3_step() wrapper procedure.
  63515. */
  63516. static int sqlite3Step(Vdbe *p){
  63517. sqlite3 *db;
  63518. int rc;
  63519. assert(p);
  63520. if( p->magic!=VDBE_MAGIC_RUN ){
  63521. /* We used to require that sqlite3_reset() be called before retrying
  63522. ** sqlite3_step() after any error or after SQLITE_DONE. But beginning
  63523. ** with version 3.7.0, we changed this so that sqlite3_reset() would
  63524. ** be called automatically instead of throwing the SQLITE_MISUSE error.
  63525. ** This "automatic-reset" change is not technically an incompatibility,
  63526. ** since any application that receives an SQLITE_MISUSE is broken by
  63527. ** definition.
  63528. **
  63529. ** Nevertheless, some published applications that were originally written
  63530. ** for version 3.6.23 or earlier do in fact depend on SQLITE_MISUSE
  63531. ** returns, and those were broken by the automatic-reset change. As a
  63532. ** a work-around, the SQLITE_OMIT_AUTORESET compile-time restores the
  63533. ** legacy behavior of returning SQLITE_MISUSE for cases where the
  63534. ** previous sqlite3_step() returned something other than a SQLITE_LOCKED
  63535. ** or SQLITE_BUSY error.
  63536. */
  63537. #ifdef SQLITE_OMIT_AUTORESET
  63538. if( p->rc==SQLITE_BUSY || p->rc==SQLITE_LOCKED ){
  63539. sqlite3_reset((sqlite3_stmt*)p);
  63540. }else{
  63541. return SQLITE_MISUSE_BKPT;
  63542. }
  63543. #else
  63544. sqlite3_reset((sqlite3_stmt*)p);
  63545. #endif
  63546. }
  63547. /* Check that malloc() has not failed. If it has, return early. */
  63548. db = p->db;
  63549. if( db->mallocFailed ){
  63550. p->rc = SQLITE_NOMEM;
  63551. return SQLITE_NOMEM;
  63552. }
  63553. if( p->pc<=0 && p->expired ){
  63554. p->rc = SQLITE_SCHEMA;
  63555. rc = SQLITE_ERROR;
  63556. goto end_of_step;
  63557. }
  63558. if( p->pc<0 ){
  63559. /* If there are no other statements currently running, then
  63560. ** reset the interrupt flag. This prevents a call to sqlite3_interrupt
  63561. ** from interrupting a statement that has not yet started.
  63562. */
  63563. if( db->nVdbeActive==0 ){
  63564. db->u1.isInterrupted = 0;
  63565. }
  63566. assert( db->nVdbeWrite>0 || db->autoCommit==0
  63567. || (db->nDeferredCons==0 && db->nDeferredImmCons==0)
  63568. );
  63569. #ifndef SQLITE_OMIT_TRACE
  63570. if( db->xProfile && !db->init.busy ){
  63571. sqlite3OsCurrentTimeInt64(db->pVfs, &p->startTime);
  63572. }
  63573. #endif
  63574. db->nVdbeActive++;
  63575. if( p->readOnly==0 ) db->nVdbeWrite++;
  63576. if( p->bIsReader ) db->nVdbeRead++;
  63577. p->pc = 0;
  63578. }
  63579. #ifndef SQLITE_OMIT_EXPLAIN
  63580. if( p->explain ){
  63581. rc = sqlite3VdbeList(p);
  63582. }else
  63583. #endif /* SQLITE_OMIT_EXPLAIN */
  63584. {
  63585. db->nVdbeExec++;
  63586. rc = sqlite3VdbeExec(p);
  63587. db->nVdbeExec--;
  63588. }
  63589. #ifndef SQLITE_OMIT_TRACE
  63590. /* Invoke the profile callback if there is one
  63591. */
  63592. if( rc!=SQLITE_ROW && db->xProfile && !db->init.busy && p->zSql ){
  63593. sqlite3_int64 iNow;
  63594. sqlite3OsCurrentTimeInt64(db->pVfs, &iNow);
  63595. db->xProfile(db->pProfileArg, p->zSql, (iNow - p->startTime)*1000000);
  63596. }
  63597. #endif
  63598. if( rc==SQLITE_DONE ){
  63599. assert( p->rc==SQLITE_OK );
  63600. p->rc = doWalCallbacks(db);
  63601. if( p->rc!=SQLITE_OK ){
  63602. rc = SQLITE_ERROR;
  63603. }
  63604. }
  63605. db->errCode = rc;
  63606. if( SQLITE_NOMEM==sqlite3ApiExit(p->db, p->rc) ){
  63607. p->rc = SQLITE_NOMEM;
  63608. }
  63609. end_of_step:
  63610. /* At this point local variable rc holds the value that should be
  63611. ** returned if this statement was compiled using the legacy
  63612. ** sqlite3_prepare() interface. According to the docs, this can only
  63613. ** be one of the values in the first assert() below. Variable p->rc
  63614. ** contains the value that would be returned if sqlite3_finalize()
  63615. ** were called on statement p.
  63616. */
  63617. assert( rc==SQLITE_ROW || rc==SQLITE_DONE || rc==SQLITE_ERROR
  63618. || rc==SQLITE_BUSY || rc==SQLITE_MISUSE
  63619. );
  63620. assert( p->rc!=SQLITE_ROW && p->rc!=SQLITE_DONE );
  63621. if( p->isPrepareV2 && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
  63622. /* If this statement was prepared using sqlite3_prepare_v2(), and an
  63623. ** error has occurred, then return the error code in p->rc to the
  63624. ** caller. Set the error code in the database handle to the same value.
  63625. */
  63626. rc = sqlite3VdbeTransferError(p);
  63627. }
  63628. return (rc&db->errMask);
  63629. }
  63630. /*
  63631. ** This is the top-level implementation of sqlite3_step(). Call
  63632. ** sqlite3Step() to do most of the work. If a schema error occurs,
  63633. ** call sqlite3Reprepare() and try again.
  63634. */
  63635. SQLITE_API int sqlite3_step(sqlite3_stmt *pStmt){
  63636. int rc = SQLITE_OK; /* Result from sqlite3Step() */
  63637. int rc2 = SQLITE_OK; /* Result from sqlite3Reprepare() */
  63638. Vdbe *v = (Vdbe*)pStmt; /* the prepared statement */
  63639. int cnt = 0; /* Counter to prevent infinite loop of reprepares */
  63640. sqlite3 *db; /* The database connection */
  63641. if( vdbeSafetyNotNull(v) ){
  63642. return SQLITE_MISUSE_BKPT;
  63643. }
  63644. db = v->db;
  63645. sqlite3_mutex_enter(db->mutex);
  63646. v->doingRerun = 0;
  63647. while( (rc = sqlite3Step(v))==SQLITE_SCHEMA
  63648. && cnt++ < SQLITE_MAX_SCHEMA_RETRY ){
  63649. int savedPc = v->pc;
  63650. rc2 = rc = sqlite3Reprepare(v);
  63651. if( rc!=SQLITE_OK) break;
  63652. sqlite3_reset(pStmt);
  63653. if( savedPc>=0 ) v->doingRerun = 1;
  63654. assert( v->expired==0 );
  63655. }
  63656. if( rc2!=SQLITE_OK ){
  63657. /* This case occurs after failing to recompile an sql statement.
  63658. ** The error message from the SQL compiler has already been loaded
  63659. ** into the database handle. This block copies the error message
  63660. ** from the database handle into the statement and sets the statement
  63661. ** program counter to 0 to ensure that when the statement is
  63662. ** finalized or reset the parser error message is available via
  63663. ** sqlite3_errmsg() and sqlite3_errcode().
  63664. */
  63665. const char *zErr = (const char *)sqlite3_value_text(db->pErr);
  63666. assert( zErr!=0 || db->mallocFailed );
  63667. sqlite3DbFree(db, v->zErrMsg);
  63668. if( !db->mallocFailed ){
  63669. v->zErrMsg = sqlite3DbStrDup(db, zErr);
  63670. v->rc = rc2;
  63671. } else {
  63672. v->zErrMsg = 0;
  63673. v->rc = rc = SQLITE_NOMEM;
  63674. }
  63675. }
  63676. rc = sqlite3ApiExit(db, rc);
  63677. sqlite3_mutex_leave(db->mutex);
  63678. return rc;
  63679. }
  63680. /*
  63681. ** Extract the user data from a sqlite3_context structure and return a
  63682. ** pointer to it.
  63683. */
  63684. SQLITE_API void *sqlite3_user_data(sqlite3_context *p){
  63685. assert( p && p->pFunc );
  63686. return p->pFunc->pUserData;
  63687. }
  63688. /*
  63689. ** Extract the user data from a sqlite3_context structure and return a
  63690. ** pointer to it.
  63691. **
  63692. ** IMPLEMENTATION-OF: R-46798-50301 The sqlite3_context_db_handle() interface
  63693. ** returns a copy of the pointer to the database connection (the 1st
  63694. ** parameter) of the sqlite3_create_function() and
  63695. ** sqlite3_create_function16() routines that originally registered the
  63696. ** application defined function.
  63697. */
  63698. SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context *p){
  63699. assert( p && p->pFunc );
  63700. return p->pOut->db;
  63701. }
  63702. /*
  63703. ** Return the current time for a statement
  63704. */
  63705. SQLITE_PRIVATE sqlite3_int64 sqlite3StmtCurrentTime(sqlite3_context *p){
  63706. Vdbe *v = p->pVdbe;
  63707. int rc;
  63708. if( v->iCurrentTime==0 ){
  63709. rc = sqlite3OsCurrentTimeInt64(p->pOut->db->pVfs, &v->iCurrentTime);
  63710. if( rc ) v->iCurrentTime = 0;
  63711. }
  63712. return v->iCurrentTime;
  63713. }
  63714. /*
  63715. ** The following is the implementation of an SQL function that always
  63716. ** fails with an error message stating that the function is used in the
  63717. ** wrong context. The sqlite3_overload_function() API might construct
  63718. ** SQL function that use this routine so that the functions will exist
  63719. ** for name resolution but are actually overloaded by the xFindFunction
  63720. ** method of virtual tables.
  63721. */
  63722. SQLITE_PRIVATE void sqlite3InvalidFunction(
  63723. sqlite3_context *context, /* The function calling context */
  63724. int NotUsed, /* Number of arguments to the function */
  63725. sqlite3_value **NotUsed2 /* Value of each argument */
  63726. ){
  63727. const char *zName = context->pFunc->zName;
  63728. char *zErr;
  63729. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  63730. zErr = sqlite3_mprintf(
  63731. "unable to use function %s in the requested context", zName);
  63732. sqlite3_result_error(context, zErr, -1);
  63733. sqlite3_free(zErr);
  63734. }
  63735. /*
  63736. ** Create a new aggregate context for p and return a pointer to
  63737. ** its pMem->z element.
  63738. */
  63739. static SQLITE_NOINLINE void *createAggContext(sqlite3_context *p, int nByte){
  63740. Mem *pMem = p->pMem;
  63741. assert( (pMem->flags & MEM_Agg)==0 );
  63742. if( nByte<=0 ){
  63743. sqlite3VdbeMemSetNull(pMem);
  63744. pMem->z = 0;
  63745. }else{
  63746. sqlite3VdbeMemClearAndResize(pMem, nByte);
  63747. pMem->flags = MEM_Agg;
  63748. pMem->u.pDef = p->pFunc;
  63749. if( pMem->z ){
  63750. memset(pMem->z, 0, nByte);
  63751. }
  63752. }
  63753. return (void*)pMem->z;
  63754. }
  63755. /*
  63756. ** Allocate or return the aggregate context for a user function. A new
  63757. ** context is allocated on the first call. Subsequent calls return the
  63758. ** same context that was returned on prior calls.
  63759. */
  63760. SQLITE_API void *sqlite3_aggregate_context(sqlite3_context *p, int nByte){
  63761. assert( p && p->pFunc && p->pFunc->xStep );
  63762. assert( sqlite3_mutex_held(p->pOut->db->mutex) );
  63763. testcase( nByte<0 );
  63764. if( (p->pMem->flags & MEM_Agg)==0 ){
  63765. return createAggContext(p, nByte);
  63766. }else{
  63767. return (void*)p->pMem->z;
  63768. }
  63769. }
  63770. /*
  63771. ** Return the auxiliary data pointer, if any, for the iArg'th argument to
  63772. ** the user-function defined by pCtx.
  63773. */
  63774. SQLITE_API void *sqlite3_get_auxdata(sqlite3_context *pCtx, int iArg){
  63775. AuxData *pAuxData;
  63776. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  63777. for(pAuxData=pCtx->pVdbe->pAuxData; pAuxData; pAuxData=pAuxData->pNext){
  63778. if( pAuxData->iOp==pCtx->iOp && pAuxData->iArg==iArg ) break;
  63779. }
  63780. return (pAuxData ? pAuxData->pAux : 0);
  63781. }
  63782. /*
  63783. ** Set the auxiliary data pointer and delete function, for the iArg'th
  63784. ** argument to the user-function defined by pCtx. Any previous value is
  63785. ** deleted by calling the delete function specified when it was set.
  63786. */
  63787. SQLITE_API void sqlite3_set_auxdata(
  63788. sqlite3_context *pCtx,
  63789. int iArg,
  63790. void *pAux,
  63791. void (*xDelete)(void*)
  63792. ){
  63793. AuxData *pAuxData;
  63794. Vdbe *pVdbe = pCtx->pVdbe;
  63795. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  63796. if( iArg<0 ) goto failed;
  63797. for(pAuxData=pVdbe->pAuxData; pAuxData; pAuxData=pAuxData->pNext){
  63798. if( pAuxData->iOp==pCtx->iOp && pAuxData->iArg==iArg ) break;
  63799. }
  63800. if( pAuxData==0 ){
  63801. pAuxData = sqlite3DbMallocZero(pVdbe->db, sizeof(AuxData));
  63802. if( !pAuxData ) goto failed;
  63803. pAuxData->iOp = pCtx->iOp;
  63804. pAuxData->iArg = iArg;
  63805. pAuxData->pNext = pVdbe->pAuxData;
  63806. pVdbe->pAuxData = pAuxData;
  63807. if( pCtx->fErrorOrAux==0 ){
  63808. pCtx->isError = 0;
  63809. pCtx->fErrorOrAux = 1;
  63810. }
  63811. }else if( pAuxData->xDelete ){
  63812. pAuxData->xDelete(pAuxData->pAux);
  63813. }
  63814. pAuxData->pAux = pAux;
  63815. pAuxData->xDelete = xDelete;
  63816. return;
  63817. failed:
  63818. if( xDelete ){
  63819. xDelete(pAux);
  63820. }
  63821. }
  63822. #ifndef SQLITE_OMIT_DEPRECATED
  63823. /*
  63824. ** Return the number of times the Step function of an aggregate has been
  63825. ** called.
  63826. **
  63827. ** This function is deprecated. Do not use it for new code. It is
  63828. ** provide only to avoid breaking legacy code. New aggregate function
  63829. ** implementations should keep their own counts within their aggregate
  63830. ** context.
  63831. */
  63832. SQLITE_API int sqlite3_aggregate_count(sqlite3_context *p){
  63833. assert( p && p->pMem && p->pFunc && p->pFunc->xStep );
  63834. return p->pMem->n;
  63835. }
  63836. #endif
  63837. /*
  63838. ** Return the number of columns in the result set for the statement pStmt.
  63839. */
  63840. SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt){
  63841. Vdbe *pVm = (Vdbe *)pStmt;
  63842. return pVm ? pVm->nResColumn : 0;
  63843. }
  63844. /*
  63845. ** Return the number of values available from the current row of the
  63846. ** currently executing statement pStmt.
  63847. */
  63848. SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt){
  63849. Vdbe *pVm = (Vdbe *)pStmt;
  63850. if( pVm==0 || pVm->pResultSet==0 ) return 0;
  63851. return pVm->nResColumn;
  63852. }
  63853. /*
  63854. ** Return a pointer to static memory containing an SQL NULL value.
  63855. */
  63856. static const Mem *columnNullValue(void){
  63857. /* Even though the Mem structure contains an element
  63858. ** of type i64, on certain architectures (x86) with certain compiler
  63859. ** switches (-Os), gcc may align this Mem object on a 4-byte boundary
  63860. ** instead of an 8-byte one. This all works fine, except that when
  63861. ** running with SQLITE_DEBUG defined the SQLite code sometimes assert()s
  63862. ** that a Mem structure is located on an 8-byte boundary. To prevent
  63863. ** these assert()s from failing, when building with SQLITE_DEBUG defined
  63864. ** using gcc, we force nullMem to be 8-byte aligned using the magical
  63865. ** __attribute__((aligned(8))) macro. */
  63866. static const Mem nullMem
  63867. #if defined(SQLITE_DEBUG) && defined(__GNUC__)
  63868. __attribute__((aligned(8)))
  63869. #endif
  63870. = {
  63871. /* .u = */ {0},
  63872. /* .flags = */ MEM_Null,
  63873. /* .enc = */ 0,
  63874. /* .n = */ 0,
  63875. /* .z = */ 0,
  63876. /* .zMalloc = */ 0,
  63877. /* .szMalloc = */ 0,
  63878. /* .iPadding1 = */ 0,
  63879. /* .db = */ 0,
  63880. /* .xDel = */ 0,
  63881. #ifdef SQLITE_DEBUG
  63882. /* .pScopyFrom = */ 0,
  63883. /* .pFiller = */ 0,
  63884. #endif
  63885. };
  63886. return &nullMem;
  63887. }
  63888. /*
  63889. ** Check to see if column iCol of the given statement is valid. If
  63890. ** it is, return a pointer to the Mem for the value of that column.
  63891. ** If iCol is not valid, return a pointer to a Mem which has a value
  63892. ** of NULL.
  63893. */
  63894. static Mem *columnMem(sqlite3_stmt *pStmt, int i){
  63895. Vdbe *pVm;
  63896. Mem *pOut;
  63897. pVm = (Vdbe *)pStmt;
  63898. if( pVm && pVm->pResultSet!=0 && i<pVm->nResColumn && i>=0 ){
  63899. sqlite3_mutex_enter(pVm->db->mutex);
  63900. pOut = &pVm->pResultSet[i];
  63901. }else{
  63902. if( pVm && ALWAYS(pVm->db) ){
  63903. sqlite3_mutex_enter(pVm->db->mutex);
  63904. sqlite3Error(pVm->db, SQLITE_RANGE);
  63905. }
  63906. pOut = (Mem*)columnNullValue();
  63907. }
  63908. return pOut;
  63909. }
  63910. /*
  63911. ** This function is called after invoking an sqlite3_value_XXX function on a
  63912. ** column value (i.e. a value returned by evaluating an SQL expression in the
  63913. ** select list of a SELECT statement) that may cause a malloc() failure. If
  63914. ** malloc() has failed, the threads mallocFailed flag is cleared and the result
  63915. ** code of statement pStmt set to SQLITE_NOMEM.
  63916. **
  63917. ** Specifically, this is called from within:
  63918. **
  63919. ** sqlite3_column_int()
  63920. ** sqlite3_column_int64()
  63921. ** sqlite3_column_text()
  63922. ** sqlite3_column_text16()
  63923. ** sqlite3_column_real()
  63924. ** sqlite3_column_bytes()
  63925. ** sqlite3_column_bytes16()
  63926. ** sqiite3_column_blob()
  63927. */
  63928. static void columnMallocFailure(sqlite3_stmt *pStmt)
  63929. {
  63930. /* If malloc() failed during an encoding conversion within an
  63931. ** sqlite3_column_XXX API, then set the return code of the statement to
  63932. ** SQLITE_NOMEM. The next call to _step() (if any) will return SQLITE_ERROR
  63933. ** and _finalize() will return NOMEM.
  63934. */
  63935. Vdbe *p = (Vdbe *)pStmt;
  63936. if( p ){
  63937. p->rc = sqlite3ApiExit(p->db, p->rc);
  63938. sqlite3_mutex_leave(p->db->mutex);
  63939. }
  63940. }
  63941. /**************************** sqlite3_column_ *******************************
  63942. ** The following routines are used to access elements of the current row
  63943. ** in the result set.
  63944. */
  63945. SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt *pStmt, int i){
  63946. const void *val;
  63947. val = sqlite3_value_blob( columnMem(pStmt,i) );
  63948. /* Even though there is no encoding conversion, value_blob() might
  63949. ** need to call malloc() to expand the result of a zeroblob()
  63950. ** expression.
  63951. */
  63952. columnMallocFailure(pStmt);
  63953. return val;
  63954. }
  63955. SQLITE_API int sqlite3_column_bytes(sqlite3_stmt *pStmt, int i){
  63956. int val = sqlite3_value_bytes( columnMem(pStmt,i) );
  63957. columnMallocFailure(pStmt);
  63958. return val;
  63959. }
  63960. SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt *pStmt, int i){
  63961. int val = sqlite3_value_bytes16( columnMem(pStmt,i) );
  63962. columnMallocFailure(pStmt);
  63963. return val;
  63964. }
  63965. SQLITE_API double sqlite3_column_double(sqlite3_stmt *pStmt, int i){
  63966. double val = sqlite3_value_double( columnMem(pStmt,i) );
  63967. columnMallocFailure(pStmt);
  63968. return val;
  63969. }
  63970. SQLITE_API int sqlite3_column_int(sqlite3_stmt *pStmt, int i){
  63971. int val = sqlite3_value_int( columnMem(pStmt,i) );
  63972. columnMallocFailure(pStmt);
  63973. return val;
  63974. }
  63975. SQLITE_API sqlite_int64 sqlite3_column_int64(sqlite3_stmt *pStmt, int i){
  63976. sqlite_int64 val = sqlite3_value_int64( columnMem(pStmt,i) );
  63977. columnMallocFailure(pStmt);
  63978. return val;
  63979. }
  63980. SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt *pStmt, int i){
  63981. const unsigned char *val = sqlite3_value_text( columnMem(pStmt,i) );
  63982. columnMallocFailure(pStmt);
  63983. return val;
  63984. }
  63985. SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt *pStmt, int i){
  63986. Mem *pOut = columnMem(pStmt, i);
  63987. if( pOut->flags&MEM_Static ){
  63988. pOut->flags &= ~MEM_Static;
  63989. pOut->flags |= MEM_Ephem;
  63990. }
  63991. columnMallocFailure(pStmt);
  63992. return (sqlite3_value *)pOut;
  63993. }
  63994. #ifndef SQLITE_OMIT_UTF16
  63995. SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt *pStmt, int i){
  63996. const void *val = sqlite3_value_text16( columnMem(pStmt,i) );
  63997. columnMallocFailure(pStmt);
  63998. return val;
  63999. }
  64000. #endif /* SQLITE_OMIT_UTF16 */
  64001. SQLITE_API int sqlite3_column_type(sqlite3_stmt *pStmt, int i){
  64002. int iType = sqlite3_value_type( columnMem(pStmt,i) );
  64003. columnMallocFailure(pStmt);
  64004. return iType;
  64005. }
  64006. /*
  64007. ** Convert the N-th element of pStmt->pColName[] into a string using
  64008. ** xFunc() then return that string. If N is out of range, return 0.
  64009. **
  64010. ** There are up to 5 names for each column. useType determines which
  64011. ** name is returned. Here are the names:
  64012. **
  64013. ** 0 The column name as it should be displayed for output
  64014. ** 1 The datatype name for the column
  64015. ** 2 The name of the database that the column derives from
  64016. ** 3 The name of the table that the column derives from
  64017. ** 4 The name of the table column that the result column derives from
  64018. **
  64019. ** If the result is not a simple column reference (if it is an expression
  64020. ** or a constant) then useTypes 2, 3, and 4 return NULL.
  64021. */
  64022. static const void *columnName(
  64023. sqlite3_stmt *pStmt,
  64024. int N,
  64025. const void *(*xFunc)(Mem*),
  64026. int useType
  64027. ){
  64028. const void *ret;
  64029. Vdbe *p;
  64030. int n;
  64031. sqlite3 *db;
  64032. #ifdef SQLITE_ENABLE_API_ARMOR
  64033. if( pStmt==0 ){
  64034. (void)SQLITE_MISUSE_BKPT;
  64035. return 0;
  64036. }
  64037. #endif
  64038. ret = 0;
  64039. p = (Vdbe *)pStmt;
  64040. db = p->db;
  64041. assert( db!=0 );
  64042. n = sqlite3_column_count(pStmt);
  64043. if( N<n && N>=0 ){
  64044. N += useType*n;
  64045. sqlite3_mutex_enter(db->mutex);
  64046. assert( db->mallocFailed==0 );
  64047. ret = xFunc(&p->aColName[N]);
  64048. /* A malloc may have failed inside of the xFunc() call. If this
  64049. ** is the case, clear the mallocFailed flag and return NULL.
  64050. */
  64051. if( db->mallocFailed ){
  64052. db->mallocFailed = 0;
  64053. ret = 0;
  64054. }
  64055. sqlite3_mutex_leave(db->mutex);
  64056. }
  64057. return ret;
  64058. }
  64059. /*
  64060. ** Return the name of the Nth column of the result set returned by SQL
  64061. ** statement pStmt.
  64062. */
  64063. SQLITE_API const char *sqlite3_column_name(sqlite3_stmt *pStmt, int N){
  64064. return columnName(
  64065. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_NAME);
  64066. }
  64067. #ifndef SQLITE_OMIT_UTF16
  64068. SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt *pStmt, int N){
  64069. return columnName(
  64070. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_NAME);
  64071. }
  64072. #endif
  64073. /*
  64074. ** Constraint: If you have ENABLE_COLUMN_METADATA then you must
  64075. ** not define OMIT_DECLTYPE.
  64076. */
  64077. #if defined(SQLITE_OMIT_DECLTYPE) && defined(SQLITE_ENABLE_COLUMN_METADATA)
  64078. # error "Must not define both SQLITE_OMIT_DECLTYPE \
  64079. and SQLITE_ENABLE_COLUMN_METADATA"
  64080. #endif
  64081. #ifndef SQLITE_OMIT_DECLTYPE
  64082. /*
  64083. ** Return the column declaration type (if applicable) of the 'i'th column
  64084. ** of the result set of SQL statement pStmt.
  64085. */
  64086. SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt *pStmt, int N){
  64087. return columnName(
  64088. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DECLTYPE);
  64089. }
  64090. #ifndef SQLITE_OMIT_UTF16
  64091. SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt *pStmt, int N){
  64092. return columnName(
  64093. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DECLTYPE);
  64094. }
  64095. #endif /* SQLITE_OMIT_UTF16 */
  64096. #endif /* SQLITE_OMIT_DECLTYPE */
  64097. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  64098. /*
  64099. ** Return the name of the database from which a result column derives.
  64100. ** NULL is returned if the result column is an expression or constant or
  64101. ** anything else which is not an unambiguous reference to a database column.
  64102. */
  64103. SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt *pStmt, int N){
  64104. return columnName(
  64105. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DATABASE);
  64106. }
  64107. #ifndef SQLITE_OMIT_UTF16
  64108. SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt *pStmt, int N){
  64109. return columnName(
  64110. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DATABASE);
  64111. }
  64112. #endif /* SQLITE_OMIT_UTF16 */
  64113. /*
  64114. ** Return the name of the table from which a result column derives.
  64115. ** NULL is returned if the result column is an expression or constant or
  64116. ** anything else which is not an unambiguous reference to a database column.
  64117. */
  64118. SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt *pStmt, int N){
  64119. return columnName(
  64120. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_TABLE);
  64121. }
  64122. #ifndef SQLITE_OMIT_UTF16
  64123. SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt *pStmt, int N){
  64124. return columnName(
  64125. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_TABLE);
  64126. }
  64127. #endif /* SQLITE_OMIT_UTF16 */
  64128. /*
  64129. ** Return the name of the table column from which a result column derives.
  64130. ** NULL is returned if the result column is an expression or constant or
  64131. ** anything else which is not an unambiguous reference to a database column.
  64132. */
  64133. SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt *pStmt, int N){
  64134. return columnName(
  64135. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_COLUMN);
  64136. }
  64137. #ifndef SQLITE_OMIT_UTF16
  64138. SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt *pStmt, int N){
  64139. return columnName(
  64140. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_COLUMN);
  64141. }
  64142. #endif /* SQLITE_OMIT_UTF16 */
  64143. #endif /* SQLITE_ENABLE_COLUMN_METADATA */
  64144. /******************************* sqlite3_bind_ ***************************
  64145. **
  64146. ** Routines used to attach values to wildcards in a compiled SQL statement.
  64147. */
  64148. /*
  64149. ** Unbind the value bound to variable i in virtual machine p. This is the
  64150. ** the same as binding a NULL value to the column. If the "i" parameter is
  64151. ** out of range, then SQLITE_RANGE is returned. Othewise SQLITE_OK.
  64152. **
  64153. ** A successful evaluation of this routine acquires the mutex on p.
  64154. ** the mutex is released if any kind of error occurs.
  64155. **
  64156. ** The error code stored in database p->db is overwritten with the return
  64157. ** value in any case.
  64158. */
  64159. static int vdbeUnbind(Vdbe *p, int i){
  64160. Mem *pVar;
  64161. if( vdbeSafetyNotNull(p) ){
  64162. return SQLITE_MISUSE_BKPT;
  64163. }
  64164. sqlite3_mutex_enter(p->db->mutex);
  64165. if( p->magic!=VDBE_MAGIC_RUN || p->pc>=0 ){
  64166. sqlite3Error(p->db, SQLITE_MISUSE);
  64167. sqlite3_mutex_leave(p->db->mutex);
  64168. sqlite3_log(SQLITE_MISUSE,
  64169. "bind on a busy prepared statement: [%s]", p->zSql);
  64170. return SQLITE_MISUSE_BKPT;
  64171. }
  64172. if( i<1 || i>p->nVar ){
  64173. sqlite3Error(p->db, SQLITE_RANGE);
  64174. sqlite3_mutex_leave(p->db->mutex);
  64175. return SQLITE_RANGE;
  64176. }
  64177. i--;
  64178. pVar = &p->aVar[i];
  64179. sqlite3VdbeMemRelease(pVar);
  64180. pVar->flags = MEM_Null;
  64181. sqlite3Error(p->db, SQLITE_OK);
  64182. /* If the bit corresponding to this variable in Vdbe.expmask is set, then
  64183. ** binding a new value to this variable invalidates the current query plan.
  64184. **
  64185. ** IMPLEMENTATION-OF: R-48440-37595 If the specific value bound to host
  64186. ** parameter in the WHERE clause might influence the choice of query plan
  64187. ** for a statement, then the statement will be automatically recompiled,
  64188. ** as if there had been a schema change, on the first sqlite3_step() call
  64189. ** following any change to the bindings of that parameter.
  64190. */
  64191. if( p->isPrepareV2 &&
  64192. ((i<32 && p->expmask & ((u32)1 << i)) || p->expmask==0xffffffff)
  64193. ){
  64194. p->expired = 1;
  64195. }
  64196. return SQLITE_OK;
  64197. }
  64198. /*
  64199. ** Bind a text or BLOB value.
  64200. */
  64201. static int bindText(
  64202. sqlite3_stmt *pStmt, /* The statement to bind against */
  64203. int i, /* Index of the parameter to bind */
  64204. const void *zData, /* Pointer to the data to be bound */
  64205. int nData, /* Number of bytes of data to be bound */
  64206. void (*xDel)(void*), /* Destructor for the data */
  64207. u8 encoding /* Encoding for the data */
  64208. ){
  64209. Vdbe *p = (Vdbe *)pStmt;
  64210. Mem *pVar;
  64211. int rc;
  64212. rc = vdbeUnbind(p, i);
  64213. if( rc==SQLITE_OK ){
  64214. if( zData!=0 ){
  64215. pVar = &p->aVar[i-1];
  64216. rc = sqlite3VdbeMemSetStr(pVar, zData, nData, encoding, xDel);
  64217. if( rc==SQLITE_OK && encoding!=0 ){
  64218. rc = sqlite3VdbeChangeEncoding(pVar, ENC(p->db));
  64219. }
  64220. sqlite3Error(p->db, rc);
  64221. rc = sqlite3ApiExit(p->db, rc);
  64222. }
  64223. sqlite3_mutex_leave(p->db->mutex);
  64224. }else if( xDel!=SQLITE_STATIC && xDel!=SQLITE_TRANSIENT ){
  64225. xDel((void*)zData);
  64226. }
  64227. return rc;
  64228. }
  64229. /*
  64230. ** Bind a blob value to an SQL statement variable.
  64231. */
  64232. SQLITE_API int sqlite3_bind_blob(
  64233. sqlite3_stmt *pStmt,
  64234. int i,
  64235. const void *zData,
  64236. int nData,
  64237. void (*xDel)(void*)
  64238. ){
  64239. return bindText(pStmt, i, zData, nData, xDel, 0);
  64240. }
  64241. SQLITE_API int sqlite3_bind_blob64(
  64242. sqlite3_stmt *pStmt,
  64243. int i,
  64244. const void *zData,
  64245. sqlite3_uint64 nData,
  64246. void (*xDel)(void*)
  64247. ){
  64248. assert( xDel!=SQLITE_DYNAMIC );
  64249. if( nData>0x7fffffff ){
  64250. return invokeValueDestructor(zData, xDel, 0);
  64251. }else{
  64252. return bindText(pStmt, i, zData, (int)nData, xDel, 0);
  64253. }
  64254. }
  64255. SQLITE_API int sqlite3_bind_double(sqlite3_stmt *pStmt, int i, double rValue){
  64256. int rc;
  64257. Vdbe *p = (Vdbe *)pStmt;
  64258. rc = vdbeUnbind(p, i);
  64259. if( rc==SQLITE_OK ){
  64260. sqlite3VdbeMemSetDouble(&p->aVar[i-1], rValue);
  64261. sqlite3_mutex_leave(p->db->mutex);
  64262. }
  64263. return rc;
  64264. }
  64265. SQLITE_API int sqlite3_bind_int(sqlite3_stmt *p, int i, int iValue){
  64266. return sqlite3_bind_int64(p, i, (i64)iValue);
  64267. }
  64268. SQLITE_API int sqlite3_bind_int64(sqlite3_stmt *pStmt, int i, sqlite_int64 iValue){
  64269. int rc;
  64270. Vdbe *p = (Vdbe *)pStmt;
  64271. rc = vdbeUnbind(p, i);
  64272. if( rc==SQLITE_OK ){
  64273. sqlite3VdbeMemSetInt64(&p->aVar[i-1], iValue);
  64274. sqlite3_mutex_leave(p->db->mutex);
  64275. }
  64276. return rc;
  64277. }
  64278. SQLITE_API int sqlite3_bind_null(sqlite3_stmt *pStmt, int i){
  64279. int rc;
  64280. Vdbe *p = (Vdbe*)pStmt;
  64281. rc = vdbeUnbind(p, i);
  64282. if( rc==SQLITE_OK ){
  64283. sqlite3_mutex_leave(p->db->mutex);
  64284. }
  64285. return rc;
  64286. }
  64287. SQLITE_API int sqlite3_bind_text(
  64288. sqlite3_stmt *pStmt,
  64289. int i,
  64290. const char *zData,
  64291. int nData,
  64292. void (*xDel)(void*)
  64293. ){
  64294. return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF8);
  64295. }
  64296. SQLITE_API int sqlite3_bind_text64(
  64297. sqlite3_stmt *pStmt,
  64298. int i,
  64299. const char *zData,
  64300. sqlite3_uint64 nData,
  64301. void (*xDel)(void*),
  64302. unsigned char enc
  64303. ){
  64304. assert( xDel!=SQLITE_DYNAMIC );
  64305. if( nData>0x7fffffff ){
  64306. return invokeValueDestructor(zData, xDel, 0);
  64307. }else{
  64308. if( enc==SQLITE_UTF16 ) enc = SQLITE_UTF16NATIVE;
  64309. return bindText(pStmt, i, zData, (int)nData, xDel, enc);
  64310. }
  64311. }
  64312. #ifndef SQLITE_OMIT_UTF16
  64313. SQLITE_API int sqlite3_bind_text16(
  64314. sqlite3_stmt *pStmt,
  64315. int i,
  64316. const void *zData,
  64317. int nData,
  64318. void (*xDel)(void*)
  64319. ){
  64320. return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF16NATIVE);
  64321. }
  64322. #endif /* SQLITE_OMIT_UTF16 */
  64323. SQLITE_API int sqlite3_bind_value(sqlite3_stmt *pStmt, int i, const sqlite3_value *pValue){
  64324. int rc;
  64325. switch( sqlite3_value_type((sqlite3_value*)pValue) ){
  64326. case SQLITE_INTEGER: {
  64327. rc = sqlite3_bind_int64(pStmt, i, pValue->u.i);
  64328. break;
  64329. }
  64330. case SQLITE_FLOAT: {
  64331. rc = sqlite3_bind_double(pStmt, i, pValue->u.r);
  64332. break;
  64333. }
  64334. case SQLITE_BLOB: {
  64335. if( pValue->flags & MEM_Zero ){
  64336. rc = sqlite3_bind_zeroblob(pStmt, i, pValue->u.nZero);
  64337. }else{
  64338. rc = sqlite3_bind_blob(pStmt, i, pValue->z, pValue->n,SQLITE_TRANSIENT);
  64339. }
  64340. break;
  64341. }
  64342. case SQLITE_TEXT: {
  64343. rc = bindText(pStmt,i, pValue->z, pValue->n, SQLITE_TRANSIENT,
  64344. pValue->enc);
  64345. break;
  64346. }
  64347. default: {
  64348. rc = sqlite3_bind_null(pStmt, i);
  64349. break;
  64350. }
  64351. }
  64352. return rc;
  64353. }
  64354. SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt *pStmt, int i, int n){
  64355. int rc;
  64356. Vdbe *p = (Vdbe *)pStmt;
  64357. rc = vdbeUnbind(p, i);
  64358. if( rc==SQLITE_OK ){
  64359. sqlite3VdbeMemSetZeroBlob(&p->aVar[i-1], n);
  64360. sqlite3_mutex_leave(p->db->mutex);
  64361. }
  64362. return rc;
  64363. }
  64364. /*
  64365. ** Return the number of wildcards that can be potentially bound to.
  64366. ** This routine is added to support DBD::SQLite.
  64367. */
  64368. SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt *pStmt){
  64369. Vdbe *p = (Vdbe*)pStmt;
  64370. return p ? p->nVar : 0;
  64371. }
  64372. /*
  64373. ** Return the name of a wildcard parameter. Return NULL if the index
  64374. ** is out of range or if the wildcard is unnamed.
  64375. **
  64376. ** The result is always UTF-8.
  64377. */
  64378. SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt *pStmt, int i){
  64379. Vdbe *p = (Vdbe*)pStmt;
  64380. if( p==0 || i<1 || i>p->nzVar ){
  64381. return 0;
  64382. }
  64383. return p->azVar[i-1];
  64384. }
  64385. /*
  64386. ** Given a wildcard parameter name, return the index of the variable
  64387. ** with that name. If there is no variable with the given name,
  64388. ** return 0.
  64389. */
  64390. SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe *p, const char *zName, int nName){
  64391. int i;
  64392. if( p==0 ){
  64393. return 0;
  64394. }
  64395. if( zName ){
  64396. for(i=0; i<p->nzVar; i++){
  64397. const char *z = p->azVar[i];
  64398. if( z && strncmp(z,zName,nName)==0 && z[nName]==0 ){
  64399. return i+1;
  64400. }
  64401. }
  64402. }
  64403. return 0;
  64404. }
  64405. SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt *pStmt, const char *zName){
  64406. return sqlite3VdbeParameterIndex((Vdbe*)pStmt, zName, sqlite3Strlen30(zName));
  64407. }
  64408. /*
  64409. ** Transfer all bindings from the first statement over to the second.
  64410. */
  64411. SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
  64412. Vdbe *pFrom = (Vdbe*)pFromStmt;
  64413. Vdbe *pTo = (Vdbe*)pToStmt;
  64414. int i;
  64415. assert( pTo->db==pFrom->db );
  64416. assert( pTo->nVar==pFrom->nVar );
  64417. sqlite3_mutex_enter(pTo->db->mutex);
  64418. for(i=0; i<pFrom->nVar; i++){
  64419. sqlite3VdbeMemMove(&pTo->aVar[i], &pFrom->aVar[i]);
  64420. }
  64421. sqlite3_mutex_leave(pTo->db->mutex);
  64422. return SQLITE_OK;
  64423. }
  64424. #ifndef SQLITE_OMIT_DEPRECATED
  64425. /*
  64426. ** Deprecated external interface. Internal/core SQLite code
  64427. ** should call sqlite3TransferBindings.
  64428. **
  64429. ** It is misuse to call this routine with statements from different
  64430. ** database connections. But as this is a deprecated interface, we
  64431. ** will not bother to check for that condition.
  64432. **
  64433. ** If the two statements contain a different number of bindings, then
  64434. ** an SQLITE_ERROR is returned. Nothing else can go wrong, so otherwise
  64435. ** SQLITE_OK is returned.
  64436. */
  64437. SQLITE_API int sqlite3_transfer_bindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
  64438. Vdbe *pFrom = (Vdbe*)pFromStmt;
  64439. Vdbe *pTo = (Vdbe*)pToStmt;
  64440. if( pFrom->nVar!=pTo->nVar ){
  64441. return SQLITE_ERROR;
  64442. }
  64443. if( pTo->isPrepareV2 && pTo->expmask ){
  64444. pTo->expired = 1;
  64445. }
  64446. if( pFrom->isPrepareV2 && pFrom->expmask ){
  64447. pFrom->expired = 1;
  64448. }
  64449. return sqlite3TransferBindings(pFromStmt, pToStmt);
  64450. }
  64451. #endif
  64452. /*
  64453. ** Return the sqlite3* database handle to which the prepared statement given
  64454. ** in the argument belongs. This is the same database handle that was
  64455. ** the first argument to the sqlite3_prepare() that was used to create
  64456. ** the statement in the first place.
  64457. */
  64458. SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt *pStmt){
  64459. return pStmt ? ((Vdbe*)pStmt)->db : 0;
  64460. }
  64461. /*
  64462. ** Return true if the prepared statement is guaranteed to not modify the
  64463. ** database.
  64464. */
  64465. SQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt){
  64466. return pStmt ? ((Vdbe*)pStmt)->readOnly : 1;
  64467. }
  64468. /*
  64469. ** Return true if the prepared statement is in need of being reset.
  64470. */
  64471. SQLITE_API int sqlite3_stmt_busy(sqlite3_stmt *pStmt){
  64472. Vdbe *v = (Vdbe*)pStmt;
  64473. return v!=0 && v->pc>=0 && v->magic==VDBE_MAGIC_RUN;
  64474. }
  64475. /*
  64476. ** Return a pointer to the next prepared statement after pStmt associated
  64477. ** with database connection pDb. If pStmt is NULL, return the first
  64478. ** prepared statement for the database connection. Return NULL if there
  64479. ** are no more.
  64480. */
  64481. SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt){
  64482. sqlite3_stmt *pNext;
  64483. #ifdef SQLITE_ENABLE_API_ARMOR
  64484. if( !sqlite3SafetyCheckOk(pDb) ){
  64485. (void)SQLITE_MISUSE_BKPT;
  64486. return 0;
  64487. }
  64488. #endif
  64489. sqlite3_mutex_enter(pDb->mutex);
  64490. if( pStmt==0 ){
  64491. pNext = (sqlite3_stmt*)pDb->pVdbe;
  64492. }else{
  64493. pNext = (sqlite3_stmt*)((Vdbe*)pStmt)->pNext;
  64494. }
  64495. sqlite3_mutex_leave(pDb->mutex);
  64496. return pNext;
  64497. }
  64498. /*
  64499. ** Return the value of a status counter for a prepared statement
  64500. */
  64501. SQLITE_API int sqlite3_stmt_status(sqlite3_stmt *pStmt, int op, int resetFlag){
  64502. Vdbe *pVdbe = (Vdbe*)pStmt;
  64503. u32 v;
  64504. #ifdef SQLITE_ENABLE_API_ARMOR
  64505. if( !pStmt ){
  64506. (void)SQLITE_MISUSE_BKPT;
  64507. return 0;
  64508. }
  64509. #endif
  64510. v = pVdbe->aCounter[op];
  64511. if( resetFlag ) pVdbe->aCounter[op] = 0;
  64512. return (int)v;
  64513. }
  64514. /************** End of vdbeapi.c *********************************************/
  64515. /************** Begin file vdbetrace.c ***************************************/
  64516. /*
  64517. ** 2009 November 25
  64518. **
  64519. ** The author disclaims copyright to this source code. In place of
  64520. ** a legal notice, here is a blessing:
  64521. **
  64522. ** May you do good and not evil.
  64523. ** May you find forgiveness for yourself and forgive others.
  64524. ** May you share freely, never taking more than you give.
  64525. **
  64526. *************************************************************************
  64527. **
  64528. ** This file contains code used to insert the values of host parameters
  64529. ** (aka "wildcards") into the SQL text output by sqlite3_trace().
  64530. **
  64531. ** The Vdbe parse-tree explainer is also found here.
  64532. */
  64533. #ifndef SQLITE_OMIT_TRACE
  64534. /*
  64535. ** zSql is a zero-terminated string of UTF-8 SQL text. Return the number of
  64536. ** bytes in this text up to but excluding the first character in
  64537. ** a host parameter. If the text contains no host parameters, return
  64538. ** the total number of bytes in the text.
  64539. */
  64540. static int findNextHostParameter(const char *zSql, int *pnToken){
  64541. int tokenType;
  64542. int nTotal = 0;
  64543. int n;
  64544. *pnToken = 0;
  64545. while( zSql[0] ){
  64546. n = sqlite3GetToken((u8*)zSql, &tokenType);
  64547. assert( n>0 && tokenType!=TK_ILLEGAL );
  64548. if( tokenType==TK_VARIABLE ){
  64549. *pnToken = n;
  64550. break;
  64551. }
  64552. nTotal += n;
  64553. zSql += n;
  64554. }
  64555. return nTotal;
  64556. }
  64557. /*
  64558. ** This function returns a pointer to a nul-terminated string in memory
  64559. ** obtained from sqlite3DbMalloc(). If sqlite3.nVdbeExec is 1, then the
  64560. ** string contains a copy of zRawSql but with host parameters expanded to
  64561. ** their current bindings. Or, if sqlite3.nVdbeExec is greater than 1,
  64562. ** then the returned string holds a copy of zRawSql with "-- " prepended
  64563. ** to each line of text.
  64564. **
  64565. ** If the SQLITE_TRACE_SIZE_LIMIT macro is defined to an integer, then
  64566. ** then long strings and blobs are truncated to that many bytes. This
  64567. ** can be used to prevent unreasonably large trace strings when dealing
  64568. ** with large (multi-megabyte) strings and blobs.
  64569. **
  64570. ** The calling function is responsible for making sure the memory returned
  64571. ** is eventually freed.
  64572. **
  64573. ** ALGORITHM: Scan the input string looking for host parameters in any of
  64574. ** these forms: ?, ?N, $A, @A, :A. Take care to avoid text within
  64575. ** string literals, quoted identifier names, and comments. For text forms,
  64576. ** the host parameter index is found by scanning the prepared
  64577. ** statement for the corresponding OP_Variable opcode. Once the host
  64578. ** parameter index is known, locate the value in p->aVar[]. Then render
  64579. ** the value as a literal in place of the host parameter name.
  64580. */
  64581. SQLITE_PRIVATE char *sqlite3VdbeExpandSql(
  64582. Vdbe *p, /* The prepared statement being evaluated */
  64583. const char *zRawSql /* Raw text of the SQL statement */
  64584. ){
  64585. sqlite3 *db; /* The database connection */
  64586. int idx = 0; /* Index of a host parameter */
  64587. int nextIndex = 1; /* Index of next ? host parameter */
  64588. int n; /* Length of a token prefix */
  64589. int nToken; /* Length of the parameter token */
  64590. int i; /* Loop counter */
  64591. Mem *pVar; /* Value of a host parameter */
  64592. StrAccum out; /* Accumulate the output here */
  64593. char zBase[100]; /* Initial working space */
  64594. db = p->db;
  64595. sqlite3StrAccumInit(&out, zBase, sizeof(zBase),
  64596. db->aLimit[SQLITE_LIMIT_LENGTH]);
  64597. out.db = db;
  64598. if( db->nVdbeExec>1 ){
  64599. while( *zRawSql ){
  64600. const char *zStart = zRawSql;
  64601. while( *(zRawSql++)!='\n' && *zRawSql );
  64602. sqlite3StrAccumAppend(&out, "-- ", 3);
  64603. assert( (zRawSql - zStart) > 0 );
  64604. sqlite3StrAccumAppend(&out, zStart, (int)(zRawSql-zStart));
  64605. }
  64606. }else{
  64607. while( zRawSql[0] ){
  64608. n = findNextHostParameter(zRawSql, &nToken);
  64609. assert( n>0 );
  64610. sqlite3StrAccumAppend(&out, zRawSql, n);
  64611. zRawSql += n;
  64612. assert( zRawSql[0] || nToken==0 );
  64613. if( nToken==0 ) break;
  64614. if( zRawSql[0]=='?' ){
  64615. if( nToken>1 ){
  64616. assert( sqlite3Isdigit(zRawSql[1]) );
  64617. sqlite3GetInt32(&zRawSql[1], &idx);
  64618. }else{
  64619. idx = nextIndex;
  64620. }
  64621. }else{
  64622. assert( zRawSql[0]==':' || zRawSql[0]=='$' || zRawSql[0]=='@' );
  64623. testcase( zRawSql[0]==':' );
  64624. testcase( zRawSql[0]=='$' );
  64625. testcase( zRawSql[0]=='@' );
  64626. idx = sqlite3VdbeParameterIndex(p, zRawSql, nToken);
  64627. assert( idx>0 );
  64628. }
  64629. zRawSql += nToken;
  64630. nextIndex = idx + 1;
  64631. assert( idx>0 && idx<=p->nVar );
  64632. pVar = &p->aVar[idx-1];
  64633. if( pVar->flags & MEM_Null ){
  64634. sqlite3StrAccumAppend(&out, "NULL", 4);
  64635. }else if( pVar->flags & MEM_Int ){
  64636. sqlite3XPrintf(&out, 0, "%lld", pVar->u.i);
  64637. }else if( pVar->flags & MEM_Real ){
  64638. sqlite3XPrintf(&out, 0, "%!.15g", pVar->u.r);
  64639. }else if( pVar->flags & MEM_Str ){
  64640. int nOut; /* Number of bytes of the string text to include in output */
  64641. #ifndef SQLITE_OMIT_UTF16
  64642. u8 enc = ENC(db);
  64643. Mem utf8;
  64644. if( enc!=SQLITE_UTF8 ){
  64645. memset(&utf8, 0, sizeof(utf8));
  64646. utf8.db = db;
  64647. sqlite3VdbeMemSetStr(&utf8, pVar->z, pVar->n, enc, SQLITE_STATIC);
  64648. sqlite3VdbeChangeEncoding(&utf8, SQLITE_UTF8);
  64649. pVar = &utf8;
  64650. }
  64651. #endif
  64652. nOut = pVar->n;
  64653. #ifdef SQLITE_TRACE_SIZE_LIMIT
  64654. if( nOut>SQLITE_TRACE_SIZE_LIMIT ){
  64655. nOut = SQLITE_TRACE_SIZE_LIMIT;
  64656. while( nOut<pVar->n && (pVar->z[nOut]&0xc0)==0x80 ){ nOut++; }
  64657. }
  64658. #endif
  64659. sqlite3XPrintf(&out, 0, "'%.*q'", nOut, pVar->z);
  64660. #ifdef SQLITE_TRACE_SIZE_LIMIT
  64661. if( nOut<pVar->n ){
  64662. sqlite3XPrintf(&out, 0, "/*+%d bytes*/", pVar->n-nOut);
  64663. }
  64664. #endif
  64665. #ifndef SQLITE_OMIT_UTF16
  64666. if( enc!=SQLITE_UTF8 ) sqlite3VdbeMemRelease(&utf8);
  64667. #endif
  64668. }else if( pVar->flags & MEM_Zero ){
  64669. sqlite3XPrintf(&out, 0, "zeroblob(%d)", pVar->u.nZero);
  64670. }else{
  64671. int nOut; /* Number of bytes of the blob to include in output */
  64672. assert( pVar->flags & MEM_Blob );
  64673. sqlite3StrAccumAppend(&out, "x'", 2);
  64674. nOut = pVar->n;
  64675. #ifdef SQLITE_TRACE_SIZE_LIMIT
  64676. if( nOut>SQLITE_TRACE_SIZE_LIMIT ) nOut = SQLITE_TRACE_SIZE_LIMIT;
  64677. #endif
  64678. for(i=0; i<nOut; i++){
  64679. sqlite3XPrintf(&out, 0, "%02x", pVar->z[i]&0xff);
  64680. }
  64681. sqlite3StrAccumAppend(&out, "'", 1);
  64682. #ifdef SQLITE_TRACE_SIZE_LIMIT
  64683. if( nOut<pVar->n ){
  64684. sqlite3XPrintf(&out, 0, "/*+%d bytes*/", pVar->n-nOut);
  64685. }
  64686. #endif
  64687. }
  64688. }
  64689. }
  64690. return sqlite3StrAccumFinish(&out);
  64691. }
  64692. #endif /* #ifndef SQLITE_OMIT_TRACE */
  64693. /************** End of vdbetrace.c *******************************************/
  64694. /************** Begin file vdbe.c ********************************************/
  64695. /*
  64696. ** 2001 September 15
  64697. **
  64698. ** The author disclaims copyright to this source code. In place of
  64699. ** a legal notice, here is a blessing:
  64700. **
  64701. ** May you do good and not evil.
  64702. ** May you find forgiveness for yourself and forgive others.
  64703. ** May you share freely, never taking more than you give.
  64704. **
  64705. *************************************************************************
  64706. ** The code in this file implements the function that runs the
  64707. ** bytecode of a prepared statement.
  64708. **
  64709. ** Various scripts scan this source file in order to generate HTML
  64710. ** documentation, headers files, or other derived files. The formatting
  64711. ** of the code in this file is, therefore, important. See other comments
  64712. ** in this file for details. If in doubt, do not deviate from existing
  64713. ** commenting and indentation practices when changing or adding code.
  64714. */
  64715. /*
  64716. ** Invoke this macro on memory cells just prior to changing the
  64717. ** value of the cell. This macro verifies that shallow copies are
  64718. ** not misused. A shallow copy of a string or blob just copies a
  64719. ** pointer to the string or blob, not the content. If the original
  64720. ** is changed while the copy is still in use, the string or blob might
  64721. ** be changed out from under the copy. This macro verifies that nothing
  64722. ** like that ever happens.
  64723. */
  64724. #ifdef SQLITE_DEBUG
  64725. # define memAboutToChange(P,M) sqlite3VdbeMemAboutToChange(P,M)
  64726. #else
  64727. # define memAboutToChange(P,M)
  64728. #endif
  64729. /*
  64730. ** The following global variable is incremented every time a cursor
  64731. ** moves, either by the OP_SeekXX, OP_Next, or OP_Prev opcodes. The test
  64732. ** procedures use this information to make sure that indices are
  64733. ** working correctly. This variable has no function other than to
  64734. ** help verify the correct operation of the library.
  64735. */
  64736. #ifdef SQLITE_TEST
  64737. SQLITE_API int sqlite3_search_count = 0;
  64738. #endif
  64739. /*
  64740. ** When this global variable is positive, it gets decremented once before
  64741. ** each instruction in the VDBE. When it reaches zero, the u1.isInterrupted
  64742. ** field of the sqlite3 structure is set in order to simulate an interrupt.
  64743. **
  64744. ** This facility is used for testing purposes only. It does not function
  64745. ** in an ordinary build.
  64746. */
  64747. #ifdef SQLITE_TEST
  64748. SQLITE_API int sqlite3_interrupt_count = 0;
  64749. #endif
  64750. /*
  64751. ** The next global variable is incremented each type the OP_Sort opcode
  64752. ** is executed. The test procedures use this information to make sure that
  64753. ** sorting is occurring or not occurring at appropriate times. This variable
  64754. ** has no function other than to help verify the correct operation of the
  64755. ** library.
  64756. */
  64757. #ifdef SQLITE_TEST
  64758. SQLITE_API int sqlite3_sort_count = 0;
  64759. #endif
  64760. /*
  64761. ** The next global variable records the size of the largest MEM_Blob
  64762. ** or MEM_Str that has been used by a VDBE opcode. The test procedures
  64763. ** use this information to make sure that the zero-blob functionality
  64764. ** is working correctly. This variable has no function other than to
  64765. ** help verify the correct operation of the library.
  64766. */
  64767. #ifdef SQLITE_TEST
  64768. SQLITE_API int sqlite3_max_blobsize = 0;
  64769. static void updateMaxBlobsize(Mem *p){
  64770. if( (p->flags & (MEM_Str|MEM_Blob))!=0 && p->n>sqlite3_max_blobsize ){
  64771. sqlite3_max_blobsize = p->n;
  64772. }
  64773. }
  64774. #endif
  64775. /*
  64776. ** The next global variable is incremented each time the OP_Found opcode
  64777. ** is executed. This is used to test whether or not the foreign key
  64778. ** operation implemented using OP_FkIsZero is working. This variable
  64779. ** has no function other than to help verify the correct operation of the
  64780. ** library.
  64781. */
  64782. #ifdef SQLITE_TEST
  64783. SQLITE_API int sqlite3_found_count = 0;
  64784. #endif
  64785. /*
  64786. ** Test a register to see if it exceeds the current maximum blob size.
  64787. ** If it does, record the new maximum blob size.
  64788. */
  64789. #if defined(SQLITE_TEST) && !defined(SQLITE_OMIT_BUILTIN_TEST)
  64790. # define UPDATE_MAX_BLOBSIZE(P) updateMaxBlobsize(P)
  64791. #else
  64792. # define UPDATE_MAX_BLOBSIZE(P)
  64793. #endif
  64794. /*
  64795. ** Invoke the VDBE coverage callback, if that callback is defined. This
  64796. ** feature is used for test suite validation only and does not appear an
  64797. ** production builds.
  64798. **
  64799. ** M is an integer, 2 or 3, that indices how many different ways the
  64800. ** branch can go. It is usually 2. "I" is the direction the branch
  64801. ** goes. 0 means falls through. 1 means branch is taken. 2 means the
  64802. ** second alternative branch is taken.
  64803. **
  64804. ** iSrcLine is the source code line (from the __LINE__ macro) that
  64805. ** generated the VDBE instruction. This instrumentation assumes that all
  64806. ** source code is in a single file (the amalgamation). Special values 1
  64807. ** and 2 for the iSrcLine parameter mean that this particular branch is
  64808. ** always taken or never taken, respectively.
  64809. */
  64810. #if !defined(SQLITE_VDBE_COVERAGE)
  64811. # define VdbeBranchTaken(I,M)
  64812. #else
  64813. # define VdbeBranchTaken(I,M) vdbeTakeBranch(pOp->iSrcLine,I,M)
  64814. static void vdbeTakeBranch(int iSrcLine, u8 I, u8 M){
  64815. if( iSrcLine<=2 && ALWAYS(iSrcLine>0) ){
  64816. M = iSrcLine;
  64817. /* Assert the truth of VdbeCoverageAlwaysTaken() and
  64818. ** VdbeCoverageNeverTaken() */
  64819. assert( (M & I)==I );
  64820. }else{
  64821. if( sqlite3GlobalConfig.xVdbeBranch==0 ) return; /*NO_TEST*/
  64822. sqlite3GlobalConfig.xVdbeBranch(sqlite3GlobalConfig.pVdbeBranchArg,
  64823. iSrcLine,I,M);
  64824. }
  64825. }
  64826. #endif
  64827. /*
  64828. ** Convert the given register into a string if it isn't one
  64829. ** already. Return non-zero if a malloc() fails.
  64830. */
  64831. #define Stringify(P, enc) \
  64832. if(((P)->flags&(MEM_Str|MEM_Blob))==0 && sqlite3VdbeMemStringify(P,enc,0)) \
  64833. { goto no_mem; }
  64834. /*
  64835. ** An ephemeral string value (signified by the MEM_Ephem flag) contains
  64836. ** a pointer to a dynamically allocated string where some other entity
  64837. ** is responsible for deallocating that string. Because the register
  64838. ** does not control the string, it might be deleted without the register
  64839. ** knowing it.
  64840. **
  64841. ** This routine converts an ephemeral string into a dynamically allocated
  64842. ** string that the register itself controls. In other words, it
  64843. ** converts an MEM_Ephem string into a string with P.z==P.zMalloc.
  64844. */
  64845. #define Deephemeralize(P) \
  64846. if( ((P)->flags&MEM_Ephem)!=0 \
  64847. && sqlite3VdbeMemMakeWriteable(P) ){ goto no_mem;}
  64848. /* Return true if the cursor was opened using the OP_OpenSorter opcode. */
  64849. #define isSorter(x) ((x)->pSorter!=0)
  64850. /*
  64851. ** Allocate VdbeCursor number iCur. Return a pointer to it. Return NULL
  64852. ** if we run out of memory.
  64853. */
  64854. static VdbeCursor *allocateCursor(
  64855. Vdbe *p, /* The virtual machine */
  64856. int iCur, /* Index of the new VdbeCursor */
  64857. int nField, /* Number of fields in the table or index */
  64858. int iDb, /* Database the cursor belongs to, or -1 */
  64859. int isBtreeCursor /* True for B-Tree. False for pseudo-table or vtab */
  64860. ){
  64861. /* Find the memory cell that will be used to store the blob of memory
  64862. ** required for this VdbeCursor structure. It is convenient to use a
  64863. ** vdbe memory cell to manage the memory allocation required for a
  64864. ** VdbeCursor structure for the following reasons:
  64865. **
  64866. ** * Sometimes cursor numbers are used for a couple of different
  64867. ** purposes in a vdbe program. The different uses might require
  64868. ** different sized allocations. Memory cells provide growable
  64869. ** allocations.
  64870. **
  64871. ** * When using ENABLE_MEMORY_MANAGEMENT, memory cell buffers can
  64872. ** be freed lazily via the sqlite3_release_memory() API. This
  64873. ** minimizes the number of malloc calls made by the system.
  64874. **
  64875. ** Memory cells for cursors are allocated at the top of the address
  64876. ** space. Memory cell (p->nMem) corresponds to cursor 0. Space for
  64877. ** cursor 1 is managed by memory cell (p->nMem-1), etc.
  64878. */
  64879. Mem *pMem = &p->aMem[p->nMem-iCur];
  64880. int nByte;
  64881. VdbeCursor *pCx = 0;
  64882. nByte =
  64883. ROUND8(sizeof(VdbeCursor)) + 2*sizeof(u32)*nField +
  64884. (isBtreeCursor?sqlite3BtreeCursorSize():0);
  64885. assert( iCur<p->nCursor );
  64886. if( p->apCsr[iCur] ){
  64887. sqlite3VdbeFreeCursor(p, p->apCsr[iCur]);
  64888. p->apCsr[iCur] = 0;
  64889. }
  64890. if( SQLITE_OK==sqlite3VdbeMemClearAndResize(pMem, nByte) ){
  64891. p->apCsr[iCur] = pCx = (VdbeCursor*)pMem->z;
  64892. memset(pCx, 0, sizeof(VdbeCursor));
  64893. pCx->iDb = iDb;
  64894. pCx->nField = nField;
  64895. pCx->aOffset = &pCx->aType[nField];
  64896. if( isBtreeCursor ){
  64897. pCx->pCursor = (BtCursor*)
  64898. &pMem->z[ROUND8(sizeof(VdbeCursor))+2*sizeof(u32)*nField];
  64899. sqlite3BtreeCursorZero(pCx->pCursor);
  64900. }
  64901. }
  64902. return pCx;
  64903. }
  64904. /*
  64905. ** Try to convert a value into a numeric representation if we can
  64906. ** do so without loss of information. In other words, if the string
  64907. ** looks like a number, convert it into a number. If it does not
  64908. ** look like a number, leave it alone.
  64909. **
  64910. ** If the bTryForInt flag is true, then extra effort is made to give
  64911. ** an integer representation. Strings that look like floating point
  64912. ** values but which have no fractional component (example: '48.00')
  64913. ** will have a MEM_Int representation when bTryForInt is true.
  64914. **
  64915. ** If bTryForInt is false, then if the input string contains a decimal
  64916. ** point or exponential notation, the result is only MEM_Real, even
  64917. ** if there is an exact integer representation of the quantity.
  64918. */
  64919. static void applyNumericAffinity(Mem *pRec, int bTryForInt){
  64920. double rValue;
  64921. i64 iValue;
  64922. u8 enc = pRec->enc;
  64923. assert( (pRec->flags & (MEM_Str|MEM_Int|MEM_Real))==MEM_Str );
  64924. if( sqlite3AtoF(pRec->z, &rValue, pRec->n, enc)==0 ) return;
  64925. if( 0==sqlite3Atoi64(pRec->z, &iValue, pRec->n, enc) ){
  64926. pRec->u.i = iValue;
  64927. pRec->flags |= MEM_Int;
  64928. }else{
  64929. pRec->u.r = rValue;
  64930. pRec->flags |= MEM_Real;
  64931. if( bTryForInt ) sqlite3VdbeIntegerAffinity(pRec);
  64932. }
  64933. }
  64934. /*
  64935. ** Processing is determine by the affinity parameter:
  64936. **
  64937. ** SQLITE_AFF_INTEGER:
  64938. ** SQLITE_AFF_REAL:
  64939. ** SQLITE_AFF_NUMERIC:
  64940. ** Try to convert pRec to an integer representation or a
  64941. ** floating-point representation if an integer representation
  64942. ** is not possible. Note that the integer representation is
  64943. ** always preferred, even if the affinity is REAL, because
  64944. ** an integer representation is more space efficient on disk.
  64945. **
  64946. ** SQLITE_AFF_TEXT:
  64947. ** Convert pRec to a text representation.
  64948. **
  64949. ** SQLITE_AFF_NONE:
  64950. ** No-op. pRec is unchanged.
  64951. */
  64952. static void applyAffinity(
  64953. Mem *pRec, /* The value to apply affinity to */
  64954. char affinity, /* The affinity to be applied */
  64955. u8 enc /* Use this text encoding */
  64956. ){
  64957. if( affinity>=SQLITE_AFF_NUMERIC ){
  64958. assert( affinity==SQLITE_AFF_INTEGER || affinity==SQLITE_AFF_REAL
  64959. || affinity==SQLITE_AFF_NUMERIC );
  64960. if( (pRec->flags & MEM_Int)==0 ){
  64961. if( (pRec->flags & MEM_Real)==0 ){
  64962. if( pRec->flags & MEM_Str ) applyNumericAffinity(pRec,1);
  64963. }else{
  64964. sqlite3VdbeIntegerAffinity(pRec);
  64965. }
  64966. }
  64967. }else if( affinity==SQLITE_AFF_TEXT ){
  64968. /* Only attempt the conversion to TEXT if there is an integer or real
  64969. ** representation (blob and NULL do not get converted) but no string
  64970. ** representation.
  64971. */
  64972. if( 0==(pRec->flags&MEM_Str) && (pRec->flags&(MEM_Real|MEM_Int)) ){
  64973. sqlite3VdbeMemStringify(pRec, enc, 1);
  64974. }
  64975. }
  64976. }
  64977. /*
  64978. ** Try to convert the type of a function argument or a result column
  64979. ** into a numeric representation. Use either INTEGER or REAL whichever
  64980. ** is appropriate. But only do the conversion if it is possible without
  64981. ** loss of information and return the revised type of the argument.
  64982. */
  64983. SQLITE_API int sqlite3_value_numeric_type(sqlite3_value *pVal){
  64984. int eType = sqlite3_value_type(pVal);
  64985. if( eType==SQLITE_TEXT ){
  64986. Mem *pMem = (Mem*)pVal;
  64987. applyNumericAffinity(pMem, 0);
  64988. eType = sqlite3_value_type(pVal);
  64989. }
  64990. return eType;
  64991. }
  64992. /*
  64993. ** Exported version of applyAffinity(). This one works on sqlite3_value*,
  64994. ** not the internal Mem* type.
  64995. */
  64996. SQLITE_PRIVATE void sqlite3ValueApplyAffinity(
  64997. sqlite3_value *pVal,
  64998. u8 affinity,
  64999. u8 enc
  65000. ){
  65001. applyAffinity((Mem *)pVal, affinity, enc);
  65002. }
  65003. /*
  65004. ** pMem currently only holds a string type (or maybe a BLOB that we can
  65005. ** interpret as a string if we want to). Compute its corresponding
  65006. ** numeric type, if has one. Set the pMem->u.r and pMem->u.i fields
  65007. ** accordingly.
  65008. */
  65009. static u16 SQLITE_NOINLINE computeNumericType(Mem *pMem){
  65010. assert( (pMem->flags & (MEM_Int|MEM_Real))==0 );
  65011. assert( (pMem->flags & (MEM_Str|MEM_Blob))!=0 );
  65012. if( sqlite3AtoF(pMem->z, &pMem->u.r, pMem->n, pMem->enc)==0 ){
  65013. return 0;
  65014. }
  65015. if( sqlite3Atoi64(pMem->z, &pMem->u.i, pMem->n, pMem->enc)==SQLITE_OK ){
  65016. return MEM_Int;
  65017. }
  65018. return MEM_Real;
  65019. }
  65020. /*
  65021. ** Return the numeric type for pMem, either MEM_Int or MEM_Real or both or
  65022. ** none.
  65023. **
  65024. ** Unlike applyNumericAffinity(), this routine does not modify pMem->flags.
  65025. ** But it does set pMem->u.r and pMem->u.i appropriately.
  65026. */
  65027. static u16 numericType(Mem *pMem){
  65028. if( pMem->flags & (MEM_Int|MEM_Real) ){
  65029. return pMem->flags & (MEM_Int|MEM_Real);
  65030. }
  65031. if( pMem->flags & (MEM_Str|MEM_Blob) ){
  65032. return computeNumericType(pMem);
  65033. }
  65034. return 0;
  65035. }
  65036. #ifdef SQLITE_DEBUG
  65037. /*
  65038. ** Write a nice string representation of the contents of cell pMem
  65039. ** into buffer zBuf, length nBuf.
  65040. */
  65041. SQLITE_PRIVATE void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf){
  65042. char *zCsr = zBuf;
  65043. int f = pMem->flags;
  65044. static const char *const encnames[] = {"(X)", "(8)", "(16LE)", "(16BE)"};
  65045. if( f&MEM_Blob ){
  65046. int i;
  65047. char c;
  65048. if( f & MEM_Dyn ){
  65049. c = 'z';
  65050. assert( (f & (MEM_Static|MEM_Ephem))==0 );
  65051. }else if( f & MEM_Static ){
  65052. c = 't';
  65053. assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
  65054. }else if( f & MEM_Ephem ){
  65055. c = 'e';
  65056. assert( (f & (MEM_Static|MEM_Dyn))==0 );
  65057. }else{
  65058. c = 's';
  65059. }
  65060. sqlite3_snprintf(100, zCsr, "%c", c);
  65061. zCsr += sqlite3Strlen30(zCsr);
  65062. sqlite3_snprintf(100, zCsr, "%d[", pMem->n);
  65063. zCsr += sqlite3Strlen30(zCsr);
  65064. for(i=0; i<16 && i<pMem->n; i++){
  65065. sqlite3_snprintf(100, zCsr, "%02X", ((int)pMem->z[i] & 0xFF));
  65066. zCsr += sqlite3Strlen30(zCsr);
  65067. }
  65068. for(i=0; i<16 && i<pMem->n; i++){
  65069. char z = pMem->z[i];
  65070. if( z<32 || z>126 ) *zCsr++ = '.';
  65071. else *zCsr++ = z;
  65072. }
  65073. sqlite3_snprintf(100, zCsr, "]%s", encnames[pMem->enc]);
  65074. zCsr += sqlite3Strlen30(zCsr);
  65075. if( f & MEM_Zero ){
  65076. sqlite3_snprintf(100, zCsr,"+%dz",pMem->u.nZero);
  65077. zCsr += sqlite3Strlen30(zCsr);
  65078. }
  65079. *zCsr = '\0';
  65080. }else if( f & MEM_Str ){
  65081. int j, k;
  65082. zBuf[0] = ' ';
  65083. if( f & MEM_Dyn ){
  65084. zBuf[1] = 'z';
  65085. assert( (f & (MEM_Static|MEM_Ephem))==0 );
  65086. }else if( f & MEM_Static ){
  65087. zBuf[1] = 't';
  65088. assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
  65089. }else if( f & MEM_Ephem ){
  65090. zBuf[1] = 'e';
  65091. assert( (f & (MEM_Static|MEM_Dyn))==0 );
  65092. }else{
  65093. zBuf[1] = 's';
  65094. }
  65095. k = 2;
  65096. sqlite3_snprintf(100, &zBuf[k], "%d", pMem->n);
  65097. k += sqlite3Strlen30(&zBuf[k]);
  65098. zBuf[k++] = '[';
  65099. for(j=0; j<15 && j<pMem->n; j++){
  65100. u8 c = pMem->z[j];
  65101. if( c>=0x20 && c<0x7f ){
  65102. zBuf[k++] = c;
  65103. }else{
  65104. zBuf[k++] = '.';
  65105. }
  65106. }
  65107. zBuf[k++] = ']';
  65108. sqlite3_snprintf(100,&zBuf[k], encnames[pMem->enc]);
  65109. k += sqlite3Strlen30(&zBuf[k]);
  65110. zBuf[k++] = 0;
  65111. }
  65112. }
  65113. #endif
  65114. #ifdef SQLITE_DEBUG
  65115. /*
  65116. ** Print the value of a register for tracing purposes:
  65117. */
  65118. static void memTracePrint(Mem *p){
  65119. if( p->flags & MEM_Undefined ){
  65120. printf(" undefined");
  65121. }else if( p->flags & MEM_Null ){
  65122. printf(" NULL");
  65123. }else if( (p->flags & (MEM_Int|MEM_Str))==(MEM_Int|MEM_Str) ){
  65124. printf(" si:%lld", p->u.i);
  65125. }else if( p->flags & MEM_Int ){
  65126. printf(" i:%lld", p->u.i);
  65127. #ifndef SQLITE_OMIT_FLOATING_POINT
  65128. }else if( p->flags & MEM_Real ){
  65129. printf(" r:%g", p->u.r);
  65130. #endif
  65131. }else if( p->flags & MEM_RowSet ){
  65132. printf(" (rowset)");
  65133. }else{
  65134. char zBuf[200];
  65135. sqlite3VdbeMemPrettyPrint(p, zBuf);
  65136. printf(" %s", zBuf);
  65137. }
  65138. }
  65139. static void registerTrace(int iReg, Mem *p){
  65140. printf("REG[%d] = ", iReg);
  65141. memTracePrint(p);
  65142. printf("\n");
  65143. }
  65144. #endif
  65145. #ifdef SQLITE_DEBUG
  65146. # define REGISTER_TRACE(R,M) if(db->flags&SQLITE_VdbeTrace)registerTrace(R,M)
  65147. #else
  65148. # define REGISTER_TRACE(R,M)
  65149. #endif
  65150. #ifdef VDBE_PROFILE
  65151. /*
  65152. ** hwtime.h contains inline assembler code for implementing
  65153. ** high-performance timing routines.
  65154. */
  65155. /************** Include hwtime.h in the middle of vdbe.c *********************/
  65156. /************** Begin file hwtime.h ******************************************/
  65157. /*
  65158. ** 2008 May 27
  65159. **
  65160. ** The author disclaims copyright to this source code. In place of
  65161. ** a legal notice, here is a blessing:
  65162. **
  65163. ** May you do good and not evil.
  65164. ** May you find forgiveness for yourself and forgive others.
  65165. ** May you share freely, never taking more than you give.
  65166. **
  65167. ******************************************************************************
  65168. **
  65169. ** This file contains inline asm code for retrieving "high-performance"
  65170. ** counters for x86 class CPUs.
  65171. */
  65172. #ifndef _HWTIME_H_
  65173. #define _HWTIME_H_
  65174. /*
  65175. ** The following routine only works on pentium-class (or newer) processors.
  65176. ** It uses the RDTSC opcode to read the cycle count value out of the
  65177. ** processor and returns that value. This can be used for high-res
  65178. ** profiling.
  65179. */
  65180. #if (defined(__GNUC__) || defined(_MSC_VER)) && \
  65181. (defined(i386) || defined(__i386__) || defined(_M_IX86))
  65182. #if defined(__GNUC__)
  65183. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  65184. unsigned int lo, hi;
  65185. __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
  65186. return (sqlite_uint64)hi << 32 | lo;
  65187. }
  65188. #elif defined(_MSC_VER)
  65189. __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
  65190. __asm {
  65191. rdtsc
  65192. ret ; return value at EDX:EAX
  65193. }
  65194. }
  65195. #endif
  65196. #elif (defined(__GNUC__) && defined(__x86_64__))
  65197. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  65198. unsigned long val;
  65199. __asm__ __volatile__ ("rdtsc" : "=A" (val));
  65200. return val;
  65201. }
  65202. #elif (defined(__GNUC__) && defined(__ppc__))
  65203. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  65204. unsigned long long retval;
  65205. unsigned long junk;
  65206. __asm__ __volatile__ ("\n\
  65207. 1: mftbu %1\n\
  65208. mftb %L0\n\
  65209. mftbu %0\n\
  65210. cmpw %0,%1\n\
  65211. bne 1b"
  65212. : "=r" (retval), "=r" (junk));
  65213. return retval;
  65214. }
  65215. #else
  65216. #error Need implementation of sqlite3Hwtime() for your platform.
  65217. /*
  65218. ** To compile without implementing sqlite3Hwtime() for your platform,
  65219. ** you can remove the above #error and use the following
  65220. ** stub function. You will lose timing support for many
  65221. ** of the debugging and testing utilities, but it should at
  65222. ** least compile and run.
  65223. */
  65224. SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
  65225. #endif
  65226. #endif /* !defined(_HWTIME_H_) */
  65227. /************** End of hwtime.h **********************************************/
  65228. /************** Continuing where we left off in vdbe.c ***********************/
  65229. #endif
  65230. #ifndef NDEBUG
  65231. /*
  65232. ** This function is only called from within an assert() expression. It
  65233. ** checks that the sqlite3.nTransaction variable is correctly set to
  65234. ** the number of non-transaction savepoints currently in the
  65235. ** linked list starting at sqlite3.pSavepoint.
  65236. **
  65237. ** Usage:
  65238. **
  65239. ** assert( checkSavepointCount(db) );
  65240. */
  65241. static int checkSavepointCount(sqlite3 *db){
  65242. int n = 0;
  65243. Savepoint *p;
  65244. for(p=db->pSavepoint; p; p=p->pNext) n++;
  65245. assert( n==(db->nSavepoint + db->isTransactionSavepoint) );
  65246. return 1;
  65247. }
  65248. #endif
  65249. /*
  65250. ** Execute as much of a VDBE program as we can.
  65251. ** This is the core of sqlite3_step().
  65252. */
  65253. SQLITE_PRIVATE int sqlite3VdbeExec(
  65254. Vdbe *p /* The VDBE */
  65255. ){
  65256. int pc=0; /* The program counter */
  65257. Op *aOp = p->aOp; /* Copy of p->aOp */
  65258. Op *pOp; /* Current operation */
  65259. int rc = SQLITE_OK; /* Value to return */
  65260. sqlite3 *db = p->db; /* The database */
  65261. u8 resetSchemaOnFault = 0; /* Reset schema after an error if positive */
  65262. u8 encoding = ENC(db); /* The database encoding */
  65263. int iCompare = 0; /* Result of last OP_Compare operation */
  65264. unsigned nVmStep = 0; /* Number of virtual machine steps */
  65265. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  65266. unsigned nProgressLimit = 0;/* Invoke xProgress() when nVmStep reaches this */
  65267. #endif
  65268. Mem *aMem = p->aMem; /* Copy of p->aMem */
  65269. Mem *pIn1 = 0; /* 1st input operand */
  65270. Mem *pIn2 = 0; /* 2nd input operand */
  65271. Mem *pIn3 = 0; /* 3rd input operand */
  65272. Mem *pOut = 0; /* Output operand */
  65273. int *aPermute = 0; /* Permutation of columns for OP_Compare */
  65274. i64 lastRowid = db->lastRowid; /* Saved value of the last insert ROWID */
  65275. #ifdef VDBE_PROFILE
  65276. u64 start; /* CPU clock count at start of opcode */
  65277. #endif
  65278. /*** INSERT STACK UNION HERE ***/
  65279. assert( p->magic==VDBE_MAGIC_RUN ); /* sqlite3_step() verifies this */
  65280. sqlite3VdbeEnter(p);
  65281. if( p->rc==SQLITE_NOMEM ){
  65282. /* This happens if a malloc() inside a call to sqlite3_column_text() or
  65283. ** sqlite3_column_text16() failed. */
  65284. goto no_mem;
  65285. }
  65286. assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY );
  65287. assert( p->bIsReader || p->readOnly!=0 );
  65288. p->rc = SQLITE_OK;
  65289. p->iCurrentTime = 0;
  65290. assert( p->explain==0 );
  65291. p->pResultSet = 0;
  65292. db->busyHandler.nBusy = 0;
  65293. if( db->u1.isInterrupted ) goto abort_due_to_interrupt;
  65294. sqlite3VdbeIOTraceSql(p);
  65295. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  65296. if( db->xProgress ){
  65297. assert( 0 < db->nProgressOps );
  65298. nProgressLimit = (unsigned)p->aCounter[SQLITE_STMTSTATUS_VM_STEP];
  65299. if( nProgressLimit==0 ){
  65300. nProgressLimit = db->nProgressOps;
  65301. }else{
  65302. nProgressLimit %= (unsigned)db->nProgressOps;
  65303. }
  65304. }
  65305. #endif
  65306. #ifdef SQLITE_DEBUG
  65307. sqlite3BeginBenignMalloc();
  65308. if( p->pc==0
  65309. && (p->db->flags & (SQLITE_VdbeListing|SQLITE_VdbeEQP|SQLITE_VdbeTrace))!=0
  65310. ){
  65311. int i;
  65312. int once = 1;
  65313. sqlite3VdbePrintSql(p);
  65314. if( p->db->flags & SQLITE_VdbeListing ){
  65315. printf("VDBE Program Listing:\n");
  65316. for(i=0; i<p->nOp; i++){
  65317. sqlite3VdbePrintOp(stdout, i, &aOp[i]);
  65318. }
  65319. }
  65320. if( p->db->flags & SQLITE_VdbeEQP ){
  65321. for(i=0; i<p->nOp; i++){
  65322. if( aOp[i].opcode==OP_Explain ){
  65323. if( once ) printf("VDBE Query Plan:\n");
  65324. printf("%s\n", aOp[i].p4.z);
  65325. once = 0;
  65326. }
  65327. }
  65328. }
  65329. if( p->db->flags & SQLITE_VdbeTrace ) printf("VDBE Trace:\n");
  65330. }
  65331. sqlite3EndBenignMalloc();
  65332. #endif
  65333. for(pc=p->pc; rc==SQLITE_OK; pc++){
  65334. assert( pc>=0 && pc<p->nOp );
  65335. if( db->mallocFailed ) goto no_mem;
  65336. #ifdef VDBE_PROFILE
  65337. start = sqlite3Hwtime();
  65338. #endif
  65339. nVmStep++;
  65340. pOp = &aOp[pc];
  65341. /* Only allow tracing if SQLITE_DEBUG is defined.
  65342. */
  65343. #ifdef SQLITE_DEBUG
  65344. if( db->flags & SQLITE_VdbeTrace ){
  65345. sqlite3VdbePrintOp(stdout, pc, pOp);
  65346. }
  65347. #endif
  65348. /* Check to see if we need to simulate an interrupt. This only happens
  65349. ** if we have a special test build.
  65350. */
  65351. #ifdef SQLITE_TEST
  65352. if( sqlite3_interrupt_count>0 ){
  65353. sqlite3_interrupt_count--;
  65354. if( sqlite3_interrupt_count==0 ){
  65355. sqlite3_interrupt(db);
  65356. }
  65357. }
  65358. #endif
  65359. /* On any opcode with the "out2-prerelease" tag, free any
  65360. ** external allocations out of mem[p2] and set mem[p2] to be
  65361. ** an undefined integer. Opcodes will either fill in the integer
  65362. ** value or convert mem[p2] to a different type.
  65363. */
  65364. assert( pOp->opflags==sqlite3OpcodeProperty[pOp->opcode] );
  65365. if( pOp->opflags & OPFLG_OUT2_PRERELEASE ){
  65366. assert( pOp->p2>0 );
  65367. assert( pOp->p2<=(p->nMem-p->nCursor) );
  65368. pOut = &aMem[pOp->p2];
  65369. memAboutToChange(p, pOut);
  65370. if( VdbeMemDynamic(pOut) ) sqlite3VdbeMemSetNull(pOut);
  65371. pOut->flags = MEM_Int;
  65372. }
  65373. /* Sanity checking on other operands */
  65374. #ifdef SQLITE_DEBUG
  65375. if( (pOp->opflags & OPFLG_IN1)!=0 ){
  65376. assert( pOp->p1>0 );
  65377. assert( pOp->p1<=(p->nMem-p->nCursor) );
  65378. assert( memIsValid(&aMem[pOp->p1]) );
  65379. assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p1]) );
  65380. REGISTER_TRACE(pOp->p1, &aMem[pOp->p1]);
  65381. }
  65382. if( (pOp->opflags & OPFLG_IN2)!=0 ){
  65383. assert( pOp->p2>0 );
  65384. assert( pOp->p2<=(p->nMem-p->nCursor) );
  65385. assert( memIsValid(&aMem[pOp->p2]) );
  65386. assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p2]) );
  65387. REGISTER_TRACE(pOp->p2, &aMem[pOp->p2]);
  65388. }
  65389. if( (pOp->opflags & OPFLG_IN3)!=0 ){
  65390. assert( pOp->p3>0 );
  65391. assert( pOp->p3<=(p->nMem-p->nCursor) );
  65392. assert( memIsValid(&aMem[pOp->p3]) );
  65393. assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p3]) );
  65394. REGISTER_TRACE(pOp->p3, &aMem[pOp->p3]);
  65395. }
  65396. if( (pOp->opflags & OPFLG_OUT2)!=0 ){
  65397. assert( pOp->p2>0 );
  65398. assert( pOp->p2<=(p->nMem-p->nCursor) );
  65399. memAboutToChange(p, &aMem[pOp->p2]);
  65400. }
  65401. if( (pOp->opflags & OPFLG_OUT3)!=0 ){
  65402. assert( pOp->p3>0 );
  65403. assert( pOp->p3<=(p->nMem-p->nCursor) );
  65404. memAboutToChange(p, &aMem[pOp->p3]);
  65405. }
  65406. #endif
  65407. switch( pOp->opcode ){
  65408. /*****************************************************************************
  65409. ** What follows is a massive switch statement where each case implements a
  65410. ** separate instruction in the virtual machine. If we follow the usual
  65411. ** indentation conventions, each case should be indented by 6 spaces. But
  65412. ** that is a lot of wasted space on the left margin. So the code within
  65413. ** the switch statement will break with convention and be flush-left. Another
  65414. ** big comment (similar to this one) will mark the point in the code where
  65415. ** we transition back to normal indentation.
  65416. **
  65417. ** The formatting of each case is important. The makefile for SQLite
  65418. ** generates two C files "opcodes.h" and "opcodes.c" by scanning this
  65419. ** file looking for lines that begin with "case OP_". The opcodes.h files
  65420. ** will be filled with #defines that give unique integer values to each
  65421. ** opcode and the opcodes.c file is filled with an array of strings where
  65422. ** each string is the symbolic name for the corresponding opcode. If the
  65423. ** case statement is followed by a comment of the form "/# same as ... #/"
  65424. ** that comment is used to determine the particular value of the opcode.
  65425. **
  65426. ** Other keywords in the comment that follows each case are used to
  65427. ** construct the OPFLG_INITIALIZER value that initializes opcodeProperty[].
  65428. ** Keywords include: in1, in2, in3, out2_prerelease, out2, out3. See
  65429. ** the mkopcodeh.awk script for additional information.
  65430. **
  65431. ** Documentation about VDBE opcodes is generated by scanning this file
  65432. ** for lines of that contain "Opcode:". That line and all subsequent
  65433. ** comment lines are used in the generation of the opcode.html documentation
  65434. ** file.
  65435. **
  65436. ** SUMMARY:
  65437. **
  65438. ** Formatting is important to scripts that scan this file.
  65439. ** Do not deviate from the formatting style currently in use.
  65440. **
  65441. *****************************************************************************/
  65442. /* Opcode: Goto * P2 * * *
  65443. **
  65444. ** An unconditional jump to address P2.
  65445. ** The next instruction executed will be
  65446. ** the one at index P2 from the beginning of
  65447. ** the program.
  65448. **
  65449. ** The P1 parameter is not actually used by this opcode. However, it
  65450. ** is sometimes set to 1 instead of 0 as a hint to the command-line shell
  65451. ** that this Goto is the bottom of a loop and that the lines from P2 down
  65452. ** to the current line should be indented for EXPLAIN output.
  65453. */
  65454. case OP_Goto: { /* jump */
  65455. pc = pOp->p2 - 1;
  65456. /* Opcodes that are used as the bottom of a loop (OP_Next, OP_Prev,
  65457. ** OP_VNext, OP_RowSetNext, or OP_SorterNext) all jump here upon
  65458. ** completion. Check to see if sqlite3_interrupt() has been called
  65459. ** or if the progress callback needs to be invoked.
  65460. **
  65461. ** This code uses unstructured "goto" statements and does not look clean.
  65462. ** But that is not due to sloppy coding habits. The code is written this
  65463. ** way for performance, to avoid having to run the interrupt and progress
  65464. ** checks on every opcode. This helps sqlite3_step() to run about 1.5%
  65465. ** faster according to "valgrind --tool=cachegrind" */
  65466. check_for_interrupt:
  65467. if( db->u1.isInterrupted ) goto abort_due_to_interrupt;
  65468. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  65469. /* Call the progress callback if it is configured and the required number
  65470. ** of VDBE ops have been executed (either since this invocation of
  65471. ** sqlite3VdbeExec() or since last time the progress callback was called).
  65472. ** If the progress callback returns non-zero, exit the virtual machine with
  65473. ** a return code SQLITE_ABORT.
  65474. */
  65475. if( db->xProgress!=0 && nVmStep>=nProgressLimit ){
  65476. assert( db->nProgressOps!=0 );
  65477. nProgressLimit = nVmStep + db->nProgressOps - (nVmStep%db->nProgressOps);
  65478. if( db->xProgress(db->pProgressArg) ){
  65479. rc = SQLITE_INTERRUPT;
  65480. goto vdbe_error_halt;
  65481. }
  65482. }
  65483. #endif
  65484. break;
  65485. }
  65486. /* Opcode: Gosub P1 P2 * * *
  65487. **
  65488. ** Write the current address onto register P1
  65489. ** and then jump to address P2.
  65490. */
  65491. case OP_Gosub: { /* jump */
  65492. assert( pOp->p1>0 && pOp->p1<=(p->nMem-p->nCursor) );
  65493. pIn1 = &aMem[pOp->p1];
  65494. assert( VdbeMemDynamic(pIn1)==0 );
  65495. memAboutToChange(p, pIn1);
  65496. pIn1->flags = MEM_Int;
  65497. pIn1->u.i = pc;
  65498. REGISTER_TRACE(pOp->p1, pIn1);
  65499. pc = pOp->p2 - 1;
  65500. break;
  65501. }
  65502. /* Opcode: Return P1 * * * *
  65503. **
  65504. ** Jump to the next instruction after the address in register P1. After
  65505. ** the jump, register P1 becomes undefined.
  65506. */
  65507. case OP_Return: { /* in1 */
  65508. pIn1 = &aMem[pOp->p1];
  65509. assert( pIn1->flags==MEM_Int );
  65510. pc = (int)pIn1->u.i;
  65511. pIn1->flags = MEM_Undefined;
  65512. break;
  65513. }
  65514. /* Opcode: InitCoroutine P1 P2 P3 * *
  65515. **
  65516. ** Set up register P1 so that it will Yield to the coroutine
  65517. ** located at address P3.
  65518. **
  65519. ** If P2!=0 then the coroutine implementation immediately follows
  65520. ** this opcode. So jump over the coroutine implementation to
  65521. ** address P2.
  65522. **
  65523. ** See also: EndCoroutine
  65524. */
  65525. case OP_InitCoroutine: { /* jump */
  65526. assert( pOp->p1>0 && pOp->p1<=(p->nMem-p->nCursor) );
  65527. assert( pOp->p2>=0 && pOp->p2<p->nOp );
  65528. assert( pOp->p3>=0 && pOp->p3<p->nOp );
  65529. pOut = &aMem[pOp->p1];
  65530. assert( !VdbeMemDynamic(pOut) );
  65531. pOut->u.i = pOp->p3 - 1;
  65532. pOut->flags = MEM_Int;
  65533. if( pOp->p2 ) pc = pOp->p2 - 1;
  65534. break;
  65535. }
  65536. /* Opcode: EndCoroutine P1 * * * *
  65537. **
  65538. ** The instruction at the address in register P1 is a Yield.
  65539. ** Jump to the P2 parameter of that Yield.
  65540. ** After the jump, register P1 becomes undefined.
  65541. **
  65542. ** See also: InitCoroutine
  65543. */
  65544. case OP_EndCoroutine: { /* in1 */
  65545. VdbeOp *pCaller;
  65546. pIn1 = &aMem[pOp->p1];
  65547. assert( pIn1->flags==MEM_Int );
  65548. assert( pIn1->u.i>=0 && pIn1->u.i<p->nOp );
  65549. pCaller = &aOp[pIn1->u.i];
  65550. assert( pCaller->opcode==OP_Yield );
  65551. assert( pCaller->p2>=0 && pCaller->p2<p->nOp );
  65552. pc = pCaller->p2 - 1;
  65553. pIn1->flags = MEM_Undefined;
  65554. break;
  65555. }
  65556. /* Opcode: Yield P1 P2 * * *
  65557. **
  65558. ** Swap the program counter with the value in register P1. This
  65559. ** has the effect of yielding to a coroutine.
  65560. **
  65561. ** If the coroutine that is launched by this instruction ends with
  65562. ** Yield or Return then continue to the next instruction. But if
  65563. ** the coroutine launched by this instruction ends with
  65564. ** EndCoroutine, then jump to P2 rather than continuing with the
  65565. ** next instruction.
  65566. **
  65567. ** See also: InitCoroutine
  65568. */
  65569. case OP_Yield: { /* in1, jump */
  65570. int pcDest;
  65571. pIn1 = &aMem[pOp->p1];
  65572. assert( VdbeMemDynamic(pIn1)==0 );
  65573. pIn1->flags = MEM_Int;
  65574. pcDest = (int)pIn1->u.i;
  65575. pIn1->u.i = pc;
  65576. REGISTER_TRACE(pOp->p1, pIn1);
  65577. pc = pcDest;
  65578. break;
  65579. }
  65580. /* Opcode: HaltIfNull P1 P2 P3 P4 P5
  65581. ** Synopsis: if r[P3]=null halt
  65582. **
  65583. ** Check the value in register P3. If it is NULL then Halt using
  65584. ** parameter P1, P2, and P4 as if this were a Halt instruction. If the
  65585. ** value in register P3 is not NULL, then this routine is a no-op.
  65586. ** The P5 parameter should be 1.
  65587. */
  65588. case OP_HaltIfNull: { /* in3 */
  65589. pIn3 = &aMem[pOp->p3];
  65590. if( (pIn3->flags & MEM_Null)==0 ) break;
  65591. /* Fall through into OP_Halt */
  65592. }
  65593. /* Opcode: Halt P1 P2 * P4 P5
  65594. **
  65595. ** Exit immediately. All open cursors, etc are closed
  65596. ** automatically.
  65597. **
  65598. ** P1 is the result code returned by sqlite3_exec(), sqlite3_reset(),
  65599. ** or sqlite3_finalize(). For a normal halt, this should be SQLITE_OK (0).
  65600. ** For errors, it can be some other value. If P1!=0 then P2 will determine
  65601. ** whether or not to rollback the current transaction. Do not rollback
  65602. ** if P2==OE_Fail. Do the rollback if P2==OE_Rollback. If P2==OE_Abort,
  65603. ** then back out all changes that have occurred during this execution of the
  65604. ** VDBE, but do not rollback the transaction.
  65605. **
  65606. ** If P4 is not null then it is an error message string.
  65607. **
  65608. ** P5 is a value between 0 and 4, inclusive, that modifies the P4 string.
  65609. **
  65610. ** 0: (no change)
  65611. ** 1: NOT NULL contraint failed: P4
  65612. ** 2: UNIQUE constraint failed: P4
  65613. ** 3: CHECK constraint failed: P4
  65614. ** 4: FOREIGN KEY constraint failed: P4
  65615. **
  65616. ** If P5 is not zero and P4 is NULL, then everything after the ":" is
  65617. ** omitted.
  65618. **
  65619. ** There is an implied "Halt 0 0 0" instruction inserted at the very end of
  65620. ** every program. So a jump past the last instruction of the program
  65621. ** is the same as executing Halt.
  65622. */
  65623. case OP_Halt: {
  65624. const char *zType;
  65625. const char *zLogFmt;
  65626. if( pOp->p1==SQLITE_OK && p->pFrame ){
  65627. /* Halt the sub-program. Return control to the parent frame. */
  65628. VdbeFrame *pFrame = p->pFrame;
  65629. p->pFrame = pFrame->pParent;
  65630. p->nFrame--;
  65631. sqlite3VdbeSetChanges(db, p->nChange);
  65632. pc = sqlite3VdbeFrameRestore(pFrame);
  65633. lastRowid = db->lastRowid;
  65634. if( pOp->p2==OE_Ignore ){
  65635. /* Instruction pc is the OP_Program that invoked the sub-program
  65636. ** currently being halted. If the p2 instruction of this OP_Halt
  65637. ** instruction is set to OE_Ignore, then the sub-program is throwing
  65638. ** an IGNORE exception. In this case jump to the address specified
  65639. ** as the p2 of the calling OP_Program. */
  65640. pc = p->aOp[pc].p2-1;
  65641. }
  65642. aOp = p->aOp;
  65643. aMem = p->aMem;
  65644. break;
  65645. }
  65646. p->rc = pOp->p1;
  65647. p->errorAction = (u8)pOp->p2;
  65648. p->pc = pc;
  65649. if( p->rc ){
  65650. if( pOp->p5 ){
  65651. static const char * const azType[] = { "NOT NULL", "UNIQUE", "CHECK",
  65652. "FOREIGN KEY" };
  65653. assert( pOp->p5>=1 && pOp->p5<=4 );
  65654. testcase( pOp->p5==1 );
  65655. testcase( pOp->p5==2 );
  65656. testcase( pOp->p5==3 );
  65657. testcase( pOp->p5==4 );
  65658. zType = azType[pOp->p5-1];
  65659. }else{
  65660. zType = 0;
  65661. }
  65662. assert( zType!=0 || pOp->p4.z!=0 );
  65663. zLogFmt = "abort at %d in [%s]: %s";
  65664. if( zType && pOp->p4.z ){
  65665. sqlite3SetString(&p->zErrMsg, db, "%s constraint failed: %s",
  65666. zType, pOp->p4.z);
  65667. }else if( pOp->p4.z ){
  65668. sqlite3SetString(&p->zErrMsg, db, "%s", pOp->p4.z);
  65669. }else{
  65670. sqlite3SetString(&p->zErrMsg, db, "%s constraint failed", zType);
  65671. }
  65672. sqlite3_log(pOp->p1, zLogFmt, pc, p->zSql, p->zErrMsg);
  65673. }
  65674. rc = sqlite3VdbeHalt(p);
  65675. assert( rc==SQLITE_BUSY || rc==SQLITE_OK || rc==SQLITE_ERROR );
  65676. if( rc==SQLITE_BUSY ){
  65677. p->rc = rc = SQLITE_BUSY;
  65678. }else{
  65679. assert( rc==SQLITE_OK || (p->rc&0xff)==SQLITE_CONSTRAINT );
  65680. assert( rc==SQLITE_OK || db->nDeferredCons>0 || db->nDeferredImmCons>0 );
  65681. rc = p->rc ? SQLITE_ERROR : SQLITE_DONE;
  65682. }
  65683. goto vdbe_return;
  65684. }
  65685. /* Opcode: Integer P1 P2 * * *
  65686. ** Synopsis: r[P2]=P1
  65687. **
  65688. ** The 32-bit integer value P1 is written into register P2.
  65689. */
  65690. case OP_Integer: { /* out2-prerelease */
  65691. pOut->u.i = pOp->p1;
  65692. break;
  65693. }
  65694. /* Opcode: Int64 * P2 * P4 *
  65695. ** Synopsis: r[P2]=P4
  65696. **
  65697. ** P4 is a pointer to a 64-bit integer value.
  65698. ** Write that value into register P2.
  65699. */
  65700. case OP_Int64: { /* out2-prerelease */
  65701. assert( pOp->p4.pI64!=0 );
  65702. pOut->u.i = *pOp->p4.pI64;
  65703. break;
  65704. }
  65705. #ifndef SQLITE_OMIT_FLOATING_POINT
  65706. /* Opcode: Real * P2 * P4 *
  65707. ** Synopsis: r[P2]=P4
  65708. **
  65709. ** P4 is a pointer to a 64-bit floating point value.
  65710. ** Write that value into register P2.
  65711. */
  65712. case OP_Real: { /* same as TK_FLOAT, out2-prerelease */
  65713. pOut->flags = MEM_Real;
  65714. assert( !sqlite3IsNaN(*pOp->p4.pReal) );
  65715. pOut->u.r = *pOp->p4.pReal;
  65716. break;
  65717. }
  65718. #endif
  65719. /* Opcode: String8 * P2 * P4 *
  65720. ** Synopsis: r[P2]='P4'
  65721. **
  65722. ** P4 points to a nul terminated UTF-8 string. This opcode is transformed
  65723. ** into a String before it is executed for the first time. During
  65724. ** this transformation, the length of string P4 is computed and stored
  65725. ** as the P1 parameter.
  65726. */
  65727. case OP_String8: { /* same as TK_STRING, out2-prerelease */
  65728. assert( pOp->p4.z!=0 );
  65729. pOp->opcode = OP_String;
  65730. pOp->p1 = sqlite3Strlen30(pOp->p4.z);
  65731. #ifndef SQLITE_OMIT_UTF16
  65732. if( encoding!=SQLITE_UTF8 ){
  65733. rc = sqlite3VdbeMemSetStr(pOut, pOp->p4.z, -1, SQLITE_UTF8, SQLITE_STATIC);
  65734. if( rc==SQLITE_TOOBIG ) goto too_big;
  65735. if( SQLITE_OK!=sqlite3VdbeChangeEncoding(pOut, encoding) ) goto no_mem;
  65736. assert( pOut->szMalloc>0 && pOut->zMalloc==pOut->z );
  65737. assert( VdbeMemDynamic(pOut)==0 );
  65738. pOut->szMalloc = 0;
  65739. pOut->flags |= MEM_Static;
  65740. if( pOp->p4type==P4_DYNAMIC ){
  65741. sqlite3DbFree(db, pOp->p4.z);
  65742. }
  65743. pOp->p4type = P4_DYNAMIC;
  65744. pOp->p4.z = pOut->z;
  65745. pOp->p1 = pOut->n;
  65746. }
  65747. #endif
  65748. if( pOp->p1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  65749. goto too_big;
  65750. }
  65751. /* Fall through to the next case, OP_String */
  65752. }
  65753. /* Opcode: String P1 P2 * P4 *
  65754. ** Synopsis: r[P2]='P4' (len=P1)
  65755. **
  65756. ** The string value P4 of length P1 (bytes) is stored in register P2.
  65757. */
  65758. case OP_String: { /* out2-prerelease */
  65759. assert( pOp->p4.z!=0 );
  65760. pOut->flags = MEM_Str|MEM_Static|MEM_Term;
  65761. pOut->z = pOp->p4.z;
  65762. pOut->n = pOp->p1;
  65763. pOut->enc = encoding;
  65764. UPDATE_MAX_BLOBSIZE(pOut);
  65765. break;
  65766. }
  65767. /* Opcode: Null P1 P2 P3 * *
  65768. ** Synopsis: r[P2..P3]=NULL
  65769. **
  65770. ** Write a NULL into registers P2. If P3 greater than P2, then also write
  65771. ** NULL into register P3 and every register in between P2 and P3. If P3
  65772. ** is less than P2 (typically P3 is zero) then only register P2 is
  65773. ** set to NULL.
  65774. **
  65775. ** If the P1 value is non-zero, then also set the MEM_Cleared flag so that
  65776. ** NULL values will not compare equal even if SQLITE_NULLEQ is set on
  65777. ** OP_Ne or OP_Eq.
  65778. */
  65779. case OP_Null: { /* out2-prerelease */
  65780. int cnt;
  65781. u16 nullFlag;
  65782. cnt = pOp->p3-pOp->p2;
  65783. assert( pOp->p3<=(p->nMem-p->nCursor) );
  65784. pOut->flags = nullFlag = pOp->p1 ? (MEM_Null|MEM_Cleared) : MEM_Null;
  65785. while( cnt>0 ){
  65786. pOut++;
  65787. memAboutToChange(p, pOut);
  65788. sqlite3VdbeMemSetNull(pOut);
  65789. pOut->flags = nullFlag;
  65790. cnt--;
  65791. }
  65792. break;
  65793. }
  65794. /* Opcode: SoftNull P1 * * * *
  65795. ** Synopsis: r[P1]=NULL
  65796. **
  65797. ** Set register P1 to have the value NULL as seen by the OP_MakeRecord
  65798. ** instruction, but do not free any string or blob memory associated with
  65799. ** the register, so that if the value was a string or blob that was
  65800. ** previously copied using OP_SCopy, the copies will continue to be valid.
  65801. */
  65802. case OP_SoftNull: {
  65803. assert( pOp->p1>0 && pOp->p1<=(p->nMem-p->nCursor) );
  65804. pOut = &aMem[pOp->p1];
  65805. pOut->flags = (pOut->flags|MEM_Null)&~MEM_Undefined;
  65806. break;
  65807. }
  65808. /* Opcode: Blob P1 P2 * P4 *
  65809. ** Synopsis: r[P2]=P4 (len=P1)
  65810. **
  65811. ** P4 points to a blob of data P1 bytes long. Store this
  65812. ** blob in register P2.
  65813. */
  65814. case OP_Blob: { /* out2-prerelease */
  65815. assert( pOp->p1 <= SQLITE_MAX_LENGTH );
  65816. sqlite3VdbeMemSetStr(pOut, pOp->p4.z, pOp->p1, 0, 0);
  65817. pOut->enc = encoding;
  65818. UPDATE_MAX_BLOBSIZE(pOut);
  65819. break;
  65820. }
  65821. /* Opcode: Variable P1 P2 * P4 *
  65822. ** Synopsis: r[P2]=parameter(P1,P4)
  65823. **
  65824. ** Transfer the values of bound parameter P1 into register P2
  65825. **
  65826. ** If the parameter is named, then its name appears in P4.
  65827. ** The P4 value is used by sqlite3_bind_parameter_name().
  65828. */
  65829. case OP_Variable: { /* out2-prerelease */
  65830. Mem *pVar; /* Value being transferred */
  65831. assert( pOp->p1>0 && pOp->p1<=p->nVar );
  65832. assert( pOp->p4.z==0 || pOp->p4.z==p->azVar[pOp->p1-1] );
  65833. pVar = &p->aVar[pOp->p1 - 1];
  65834. if( sqlite3VdbeMemTooBig(pVar) ){
  65835. goto too_big;
  65836. }
  65837. sqlite3VdbeMemShallowCopy(pOut, pVar, MEM_Static);
  65838. UPDATE_MAX_BLOBSIZE(pOut);
  65839. break;
  65840. }
  65841. /* Opcode: Move P1 P2 P3 * *
  65842. ** Synopsis: r[P2@P3]=r[P1@P3]
  65843. **
  65844. ** Move the P3 values in register P1..P1+P3-1 over into
  65845. ** registers P2..P2+P3-1. Registers P1..P1+P3-1 are
  65846. ** left holding a NULL. It is an error for register ranges
  65847. ** P1..P1+P3-1 and P2..P2+P3-1 to overlap. It is an error
  65848. ** for P3 to be less than 1.
  65849. */
  65850. case OP_Move: {
  65851. int n; /* Number of registers left to copy */
  65852. int p1; /* Register to copy from */
  65853. int p2; /* Register to copy to */
  65854. n = pOp->p3;
  65855. p1 = pOp->p1;
  65856. p2 = pOp->p2;
  65857. assert( n>0 && p1>0 && p2>0 );
  65858. assert( p1+n<=p2 || p2+n<=p1 );
  65859. pIn1 = &aMem[p1];
  65860. pOut = &aMem[p2];
  65861. do{
  65862. assert( pOut<=&aMem[(p->nMem-p->nCursor)] );
  65863. assert( pIn1<=&aMem[(p->nMem-p->nCursor)] );
  65864. assert( memIsValid(pIn1) );
  65865. memAboutToChange(p, pOut);
  65866. sqlite3VdbeMemMove(pOut, pIn1);
  65867. #ifdef SQLITE_DEBUG
  65868. if( pOut->pScopyFrom>=&aMem[p1] && pOut->pScopyFrom<&aMem[p1+pOp->p3] ){
  65869. pOut->pScopyFrom += p1 - pOp->p2;
  65870. }
  65871. #endif
  65872. REGISTER_TRACE(p2++, pOut);
  65873. pIn1++;
  65874. pOut++;
  65875. }while( --n );
  65876. break;
  65877. }
  65878. /* Opcode: Copy P1 P2 P3 * *
  65879. ** Synopsis: r[P2@P3+1]=r[P1@P3+1]
  65880. **
  65881. ** Make a copy of registers P1..P1+P3 into registers P2..P2+P3.
  65882. **
  65883. ** This instruction makes a deep copy of the value. A duplicate
  65884. ** is made of any string or blob constant. See also OP_SCopy.
  65885. */
  65886. case OP_Copy: {
  65887. int n;
  65888. n = pOp->p3;
  65889. pIn1 = &aMem[pOp->p1];
  65890. pOut = &aMem[pOp->p2];
  65891. assert( pOut!=pIn1 );
  65892. while( 1 ){
  65893. sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
  65894. Deephemeralize(pOut);
  65895. #ifdef SQLITE_DEBUG
  65896. pOut->pScopyFrom = 0;
  65897. #endif
  65898. REGISTER_TRACE(pOp->p2+pOp->p3-n, pOut);
  65899. if( (n--)==0 ) break;
  65900. pOut++;
  65901. pIn1++;
  65902. }
  65903. break;
  65904. }
  65905. /* Opcode: SCopy P1 P2 * * *
  65906. ** Synopsis: r[P2]=r[P1]
  65907. **
  65908. ** Make a shallow copy of register P1 into register P2.
  65909. **
  65910. ** This instruction makes a shallow copy of the value. If the value
  65911. ** is a string or blob, then the copy is only a pointer to the
  65912. ** original and hence if the original changes so will the copy.
  65913. ** Worse, if the original is deallocated, the copy becomes invalid.
  65914. ** Thus the program must guarantee that the original will not change
  65915. ** during the lifetime of the copy. Use OP_Copy to make a complete
  65916. ** copy.
  65917. */
  65918. case OP_SCopy: { /* out2 */
  65919. pIn1 = &aMem[pOp->p1];
  65920. pOut = &aMem[pOp->p2];
  65921. assert( pOut!=pIn1 );
  65922. sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
  65923. #ifdef SQLITE_DEBUG
  65924. if( pOut->pScopyFrom==0 ) pOut->pScopyFrom = pIn1;
  65925. #endif
  65926. break;
  65927. }
  65928. /* Opcode: ResultRow P1 P2 * * *
  65929. ** Synopsis: output=r[P1@P2]
  65930. **
  65931. ** The registers P1 through P1+P2-1 contain a single row of
  65932. ** results. This opcode causes the sqlite3_step() call to terminate
  65933. ** with an SQLITE_ROW return code and it sets up the sqlite3_stmt
  65934. ** structure to provide access to the r(P1)..r(P1+P2-1) values as
  65935. ** the result row.
  65936. */
  65937. case OP_ResultRow: {
  65938. Mem *pMem;
  65939. int i;
  65940. assert( p->nResColumn==pOp->p2 );
  65941. assert( pOp->p1>0 );
  65942. assert( pOp->p1+pOp->p2<=(p->nMem-p->nCursor)+1 );
  65943. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  65944. /* Run the progress counter just before returning.
  65945. */
  65946. if( db->xProgress!=0
  65947. && nVmStep>=nProgressLimit
  65948. && db->xProgress(db->pProgressArg)!=0
  65949. ){
  65950. rc = SQLITE_INTERRUPT;
  65951. goto vdbe_error_halt;
  65952. }
  65953. #endif
  65954. /* If this statement has violated immediate foreign key constraints, do
  65955. ** not return the number of rows modified. And do not RELEASE the statement
  65956. ** transaction. It needs to be rolled back. */
  65957. if( SQLITE_OK!=(rc = sqlite3VdbeCheckFk(p, 0)) ){
  65958. assert( db->flags&SQLITE_CountRows );
  65959. assert( p->usesStmtJournal );
  65960. break;
  65961. }
  65962. /* If the SQLITE_CountRows flag is set in sqlite3.flags mask, then
  65963. ** DML statements invoke this opcode to return the number of rows
  65964. ** modified to the user. This is the only way that a VM that
  65965. ** opens a statement transaction may invoke this opcode.
  65966. **
  65967. ** In case this is such a statement, close any statement transaction
  65968. ** opened by this VM before returning control to the user. This is to
  65969. ** ensure that statement-transactions are always nested, not overlapping.
  65970. ** If the open statement-transaction is not closed here, then the user
  65971. ** may step another VM that opens its own statement transaction. This
  65972. ** may lead to overlapping statement transactions.
  65973. **
  65974. ** The statement transaction is never a top-level transaction. Hence
  65975. ** the RELEASE call below can never fail.
  65976. */
  65977. assert( p->iStatement==0 || db->flags&SQLITE_CountRows );
  65978. rc = sqlite3VdbeCloseStatement(p, SAVEPOINT_RELEASE);
  65979. if( NEVER(rc!=SQLITE_OK) ){
  65980. break;
  65981. }
  65982. /* Invalidate all ephemeral cursor row caches */
  65983. p->cacheCtr = (p->cacheCtr + 2)|1;
  65984. /* Make sure the results of the current row are \000 terminated
  65985. ** and have an assigned type. The results are de-ephemeralized as
  65986. ** a side effect.
  65987. */
  65988. pMem = p->pResultSet = &aMem[pOp->p1];
  65989. for(i=0; i<pOp->p2; i++){
  65990. assert( memIsValid(&pMem[i]) );
  65991. Deephemeralize(&pMem[i]);
  65992. assert( (pMem[i].flags & MEM_Ephem)==0
  65993. || (pMem[i].flags & (MEM_Str|MEM_Blob))==0 );
  65994. sqlite3VdbeMemNulTerminate(&pMem[i]);
  65995. REGISTER_TRACE(pOp->p1+i, &pMem[i]);
  65996. }
  65997. if( db->mallocFailed ) goto no_mem;
  65998. /* Return SQLITE_ROW
  65999. */
  66000. p->pc = pc + 1;
  66001. rc = SQLITE_ROW;
  66002. goto vdbe_return;
  66003. }
  66004. /* Opcode: Concat P1 P2 P3 * *
  66005. ** Synopsis: r[P3]=r[P2]+r[P1]
  66006. **
  66007. ** Add the text in register P1 onto the end of the text in
  66008. ** register P2 and store the result in register P3.
  66009. ** If either the P1 or P2 text are NULL then store NULL in P3.
  66010. **
  66011. ** P3 = P2 || P1
  66012. **
  66013. ** It is illegal for P1 and P3 to be the same register. Sometimes,
  66014. ** if P3 is the same register as P2, the implementation is able
  66015. ** to avoid a memcpy().
  66016. */
  66017. case OP_Concat: { /* same as TK_CONCAT, in1, in2, out3 */
  66018. i64 nByte;
  66019. pIn1 = &aMem[pOp->p1];
  66020. pIn2 = &aMem[pOp->p2];
  66021. pOut = &aMem[pOp->p3];
  66022. assert( pIn1!=pOut );
  66023. if( (pIn1->flags | pIn2->flags) & MEM_Null ){
  66024. sqlite3VdbeMemSetNull(pOut);
  66025. break;
  66026. }
  66027. if( ExpandBlob(pIn1) || ExpandBlob(pIn2) ) goto no_mem;
  66028. Stringify(pIn1, encoding);
  66029. Stringify(pIn2, encoding);
  66030. nByte = pIn1->n + pIn2->n;
  66031. if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  66032. goto too_big;
  66033. }
  66034. if( sqlite3VdbeMemGrow(pOut, (int)nByte+2, pOut==pIn2) ){
  66035. goto no_mem;
  66036. }
  66037. MemSetTypeFlag(pOut, MEM_Str);
  66038. if( pOut!=pIn2 ){
  66039. memcpy(pOut->z, pIn2->z, pIn2->n);
  66040. }
  66041. memcpy(&pOut->z[pIn2->n], pIn1->z, pIn1->n);
  66042. pOut->z[nByte]=0;
  66043. pOut->z[nByte+1] = 0;
  66044. pOut->flags |= MEM_Term;
  66045. pOut->n = (int)nByte;
  66046. pOut->enc = encoding;
  66047. UPDATE_MAX_BLOBSIZE(pOut);
  66048. break;
  66049. }
  66050. /* Opcode: Add P1 P2 P3 * *
  66051. ** Synopsis: r[P3]=r[P1]+r[P2]
  66052. **
  66053. ** Add the value in register P1 to the value in register P2
  66054. ** and store the result in register P3.
  66055. ** If either input is NULL, the result is NULL.
  66056. */
  66057. /* Opcode: Multiply P1 P2 P3 * *
  66058. ** Synopsis: r[P3]=r[P1]*r[P2]
  66059. **
  66060. **
  66061. ** Multiply the value in register P1 by the value in register P2
  66062. ** and store the result in register P3.
  66063. ** If either input is NULL, the result is NULL.
  66064. */
  66065. /* Opcode: Subtract P1 P2 P3 * *
  66066. ** Synopsis: r[P3]=r[P2]-r[P1]
  66067. **
  66068. ** Subtract the value in register P1 from the value in register P2
  66069. ** and store the result in register P3.
  66070. ** If either input is NULL, the result is NULL.
  66071. */
  66072. /* Opcode: Divide P1 P2 P3 * *
  66073. ** Synopsis: r[P3]=r[P2]/r[P1]
  66074. **
  66075. ** Divide the value in register P1 by the value in register P2
  66076. ** and store the result in register P3 (P3=P2/P1). If the value in
  66077. ** register P1 is zero, then the result is NULL. If either input is
  66078. ** NULL, the result is NULL.
  66079. */
  66080. /* Opcode: Remainder P1 P2 P3 * *
  66081. ** Synopsis: r[P3]=r[P2]%r[P1]
  66082. **
  66083. ** Compute the remainder after integer register P2 is divided by
  66084. ** register P1 and store the result in register P3.
  66085. ** If the value in register P1 is zero the result is NULL.
  66086. ** If either operand is NULL, the result is NULL.
  66087. */
  66088. case OP_Add: /* same as TK_PLUS, in1, in2, out3 */
  66089. case OP_Subtract: /* same as TK_MINUS, in1, in2, out3 */
  66090. case OP_Multiply: /* same as TK_STAR, in1, in2, out3 */
  66091. case OP_Divide: /* same as TK_SLASH, in1, in2, out3 */
  66092. case OP_Remainder: { /* same as TK_REM, in1, in2, out3 */
  66093. char bIntint; /* Started out as two integer operands */
  66094. u16 flags; /* Combined MEM_* flags from both inputs */
  66095. u16 type1; /* Numeric type of left operand */
  66096. u16 type2; /* Numeric type of right operand */
  66097. i64 iA; /* Integer value of left operand */
  66098. i64 iB; /* Integer value of right operand */
  66099. double rA; /* Real value of left operand */
  66100. double rB; /* Real value of right operand */
  66101. pIn1 = &aMem[pOp->p1];
  66102. type1 = numericType(pIn1);
  66103. pIn2 = &aMem[pOp->p2];
  66104. type2 = numericType(pIn2);
  66105. pOut = &aMem[pOp->p3];
  66106. flags = pIn1->flags | pIn2->flags;
  66107. if( (flags & MEM_Null)!=0 ) goto arithmetic_result_is_null;
  66108. if( (type1 & type2 & MEM_Int)!=0 ){
  66109. iA = pIn1->u.i;
  66110. iB = pIn2->u.i;
  66111. bIntint = 1;
  66112. switch( pOp->opcode ){
  66113. case OP_Add: if( sqlite3AddInt64(&iB,iA) ) goto fp_math; break;
  66114. case OP_Subtract: if( sqlite3SubInt64(&iB,iA) ) goto fp_math; break;
  66115. case OP_Multiply: if( sqlite3MulInt64(&iB,iA) ) goto fp_math; break;
  66116. case OP_Divide: {
  66117. if( iA==0 ) goto arithmetic_result_is_null;
  66118. if( iA==-1 && iB==SMALLEST_INT64 ) goto fp_math;
  66119. iB /= iA;
  66120. break;
  66121. }
  66122. default: {
  66123. if( iA==0 ) goto arithmetic_result_is_null;
  66124. if( iA==-1 ) iA = 1;
  66125. iB %= iA;
  66126. break;
  66127. }
  66128. }
  66129. pOut->u.i = iB;
  66130. MemSetTypeFlag(pOut, MEM_Int);
  66131. }else{
  66132. bIntint = 0;
  66133. fp_math:
  66134. rA = sqlite3VdbeRealValue(pIn1);
  66135. rB = sqlite3VdbeRealValue(pIn2);
  66136. switch( pOp->opcode ){
  66137. case OP_Add: rB += rA; break;
  66138. case OP_Subtract: rB -= rA; break;
  66139. case OP_Multiply: rB *= rA; break;
  66140. case OP_Divide: {
  66141. /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
  66142. if( rA==(double)0 ) goto arithmetic_result_is_null;
  66143. rB /= rA;
  66144. break;
  66145. }
  66146. default: {
  66147. iA = (i64)rA;
  66148. iB = (i64)rB;
  66149. if( iA==0 ) goto arithmetic_result_is_null;
  66150. if( iA==-1 ) iA = 1;
  66151. rB = (double)(iB % iA);
  66152. break;
  66153. }
  66154. }
  66155. #ifdef SQLITE_OMIT_FLOATING_POINT
  66156. pOut->u.i = rB;
  66157. MemSetTypeFlag(pOut, MEM_Int);
  66158. #else
  66159. if( sqlite3IsNaN(rB) ){
  66160. goto arithmetic_result_is_null;
  66161. }
  66162. pOut->u.r = rB;
  66163. MemSetTypeFlag(pOut, MEM_Real);
  66164. if( ((type1|type2)&MEM_Real)==0 && !bIntint ){
  66165. sqlite3VdbeIntegerAffinity(pOut);
  66166. }
  66167. #endif
  66168. }
  66169. break;
  66170. arithmetic_result_is_null:
  66171. sqlite3VdbeMemSetNull(pOut);
  66172. break;
  66173. }
  66174. /* Opcode: CollSeq P1 * * P4
  66175. **
  66176. ** P4 is a pointer to a CollSeq struct. If the next call to a user function
  66177. ** or aggregate calls sqlite3GetFuncCollSeq(), this collation sequence will
  66178. ** be returned. This is used by the built-in min(), max() and nullif()
  66179. ** functions.
  66180. **
  66181. ** If P1 is not zero, then it is a register that a subsequent min() or
  66182. ** max() aggregate will set to 1 if the current row is not the minimum or
  66183. ** maximum. The P1 register is initialized to 0 by this instruction.
  66184. **
  66185. ** The interface used by the implementation of the aforementioned functions
  66186. ** to retrieve the collation sequence set by this opcode is not available
  66187. ** publicly, only to user functions defined in func.c.
  66188. */
  66189. case OP_CollSeq: {
  66190. assert( pOp->p4type==P4_COLLSEQ );
  66191. if( pOp->p1 ){
  66192. sqlite3VdbeMemSetInt64(&aMem[pOp->p1], 0);
  66193. }
  66194. break;
  66195. }
  66196. /* Opcode: Function P1 P2 P3 P4 P5
  66197. ** Synopsis: r[P3]=func(r[P2@P5])
  66198. **
  66199. ** Invoke a user function (P4 is a pointer to a Function structure that
  66200. ** defines the function) with P5 arguments taken from register P2 and
  66201. ** successors. The result of the function is stored in register P3.
  66202. ** Register P3 must not be one of the function inputs.
  66203. **
  66204. ** P1 is a 32-bit bitmask indicating whether or not each argument to the
  66205. ** function was determined to be constant at compile time. If the first
  66206. ** argument was constant then bit 0 of P1 is set. This is used to determine
  66207. ** whether meta data associated with a user function argument using the
  66208. ** sqlite3_set_auxdata() API may be safely retained until the next
  66209. ** invocation of this opcode.
  66210. **
  66211. ** See also: AggStep and AggFinal
  66212. */
  66213. case OP_Function: {
  66214. int i;
  66215. Mem *pArg;
  66216. sqlite3_context ctx;
  66217. sqlite3_value **apVal;
  66218. int n;
  66219. n = pOp->p5;
  66220. apVal = p->apArg;
  66221. assert( apVal || n==0 );
  66222. assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
  66223. ctx.pOut = &aMem[pOp->p3];
  66224. memAboutToChange(p, ctx.pOut);
  66225. assert( n==0 || (pOp->p2>0 && pOp->p2+n<=(p->nMem-p->nCursor)+1) );
  66226. assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+n );
  66227. pArg = &aMem[pOp->p2];
  66228. for(i=0; i<n; i++, pArg++){
  66229. assert( memIsValid(pArg) );
  66230. apVal[i] = pArg;
  66231. Deephemeralize(pArg);
  66232. REGISTER_TRACE(pOp->p2+i, pArg);
  66233. }
  66234. assert( pOp->p4type==P4_FUNCDEF );
  66235. ctx.pFunc = pOp->p4.pFunc;
  66236. ctx.iOp = pc;
  66237. ctx.pVdbe = p;
  66238. MemSetTypeFlag(ctx.pOut, MEM_Null);
  66239. ctx.fErrorOrAux = 0;
  66240. db->lastRowid = lastRowid;
  66241. (*ctx.pFunc->xFunc)(&ctx, n, apVal); /* IMP: R-24505-23230 */
  66242. lastRowid = db->lastRowid; /* Remember rowid changes made by xFunc */
  66243. /* If the function returned an error, throw an exception */
  66244. if( ctx.fErrorOrAux ){
  66245. if( ctx.isError ){
  66246. sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(ctx.pOut));
  66247. rc = ctx.isError;
  66248. }
  66249. sqlite3VdbeDeleteAuxData(p, pc, pOp->p1);
  66250. }
  66251. /* Copy the result of the function into register P3 */
  66252. sqlite3VdbeChangeEncoding(ctx.pOut, encoding);
  66253. if( sqlite3VdbeMemTooBig(ctx.pOut) ){
  66254. goto too_big;
  66255. }
  66256. REGISTER_TRACE(pOp->p3, ctx.pOut);
  66257. UPDATE_MAX_BLOBSIZE(ctx.pOut);
  66258. break;
  66259. }
  66260. /* Opcode: BitAnd P1 P2 P3 * *
  66261. ** Synopsis: r[P3]=r[P1]&r[P2]
  66262. **
  66263. ** Take the bit-wise AND of the values in register P1 and P2 and
  66264. ** store the result in register P3.
  66265. ** If either input is NULL, the result is NULL.
  66266. */
  66267. /* Opcode: BitOr P1 P2 P3 * *
  66268. ** Synopsis: r[P3]=r[P1]|r[P2]
  66269. **
  66270. ** Take the bit-wise OR of the values in register P1 and P2 and
  66271. ** store the result in register P3.
  66272. ** If either input is NULL, the result is NULL.
  66273. */
  66274. /* Opcode: ShiftLeft P1 P2 P3 * *
  66275. ** Synopsis: r[P3]=r[P2]<<r[P1]
  66276. **
  66277. ** Shift the integer value in register P2 to the left by the
  66278. ** number of bits specified by the integer in register P1.
  66279. ** Store the result in register P3.
  66280. ** If either input is NULL, the result is NULL.
  66281. */
  66282. /* Opcode: ShiftRight P1 P2 P3 * *
  66283. ** Synopsis: r[P3]=r[P2]>>r[P1]
  66284. **
  66285. ** Shift the integer value in register P2 to the right by the
  66286. ** number of bits specified by the integer in register P1.
  66287. ** Store the result in register P3.
  66288. ** If either input is NULL, the result is NULL.
  66289. */
  66290. case OP_BitAnd: /* same as TK_BITAND, in1, in2, out3 */
  66291. case OP_BitOr: /* same as TK_BITOR, in1, in2, out3 */
  66292. case OP_ShiftLeft: /* same as TK_LSHIFT, in1, in2, out3 */
  66293. case OP_ShiftRight: { /* same as TK_RSHIFT, in1, in2, out3 */
  66294. i64 iA;
  66295. u64 uA;
  66296. i64 iB;
  66297. u8 op;
  66298. pIn1 = &aMem[pOp->p1];
  66299. pIn2 = &aMem[pOp->p2];
  66300. pOut = &aMem[pOp->p3];
  66301. if( (pIn1->flags | pIn2->flags) & MEM_Null ){
  66302. sqlite3VdbeMemSetNull(pOut);
  66303. break;
  66304. }
  66305. iA = sqlite3VdbeIntValue(pIn2);
  66306. iB = sqlite3VdbeIntValue(pIn1);
  66307. op = pOp->opcode;
  66308. if( op==OP_BitAnd ){
  66309. iA &= iB;
  66310. }else if( op==OP_BitOr ){
  66311. iA |= iB;
  66312. }else if( iB!=0 ){
  66313. assert( op==OP_ShiftRight || op==OP_ShiftLeft );
  66314. /* If shifting by a negative amount, shift in the other direction */
  66315. if( iB<0 ){
  66316. assert( OP_ShiftRight==OP_ShiftLeft+1 );
  66317. op = 2*OP_ShiftLeft + 1 - op;
  66318. iB = iB>(-64) ? -iB : 64;
  66319. }
  66320. if( iB>=64 ){
  66321. iA = (iA>=0 || op==OP_ShiftLeft) ? 0 : -1;
  66322. }else{
  66323. memcpy(&uA, &iA, sizeof(uA));
  66324. if( op==OP_ShiftLeft ){
  66325. uA <<= iB;
  66326. }else{
  66327. uA >>= iB;
  66328. /* Sign-extend on a right shift of a negative number */
  66329. if( iA<0 ) uA |= ((((u64)0xffffffff)<<32)|0xffffffff) << (64-iB);
  66330. }
  66331. memcpy(&iA, &uA, sizeof(iA));
  66332. }
  66333. }
  66334. pOut->u.i = iA;
  66335. MemSetTypeFlag(pOut, MEM_Int);
  66336. break;
  66337. }
  66338. /* Opcode: AddImm P1 P2 * * *
  66339. ** Synopsis: r[P1]=r[P1]+P2
  66340. **
  66341. ** Add the constant P2 to the value in register P1.
  66342. ** The result is always an integer.
  66343. **
  66344. ** To force any register to be an integer, just add 0.
  66345. */
  66346. case OP_AddImm: { /* in1 */
  66347. pIn1 = &aMem[pOp->p1];
  66348. memAboutToChange(p, pIn1);
  66349. sqlite3VdbeMemIntegerify(pIn1);
  66350. pIn1->u.i += pOp->p2;
  66351. break;
  66352. }
  66353. /* Opcode: MustBeInt P1 P2 * * *
  66354. **
  66355. ** Force the value in register P1 to be an integer. If the value
  66356. ** in P1 is not an integer and cannot be converted into an integer
  66357. ** without data loss, then jump immediately to P2, or if P2==0
  66358. ** raise an SQLITE_MISMATCH exception.
  66359. */
  66360. case OP_MustBeInt: { /* jump, in1 */
  66361. pIn1 = &aMem[pOp->p1];
  66362. if( (pIn1->flags & MEM_Int)==0 ){
  66363. applyAffinity(pIn1, SQLITE_AFF_NUMERIC, encoding);
  66364. VdbeBranchTaken((pIn1->flags&MEM_Int)==0, 2);
  66365. if( (pIn1->flags & MEM_Int)==0 ){
  66366. if( pOp->p2==0 ){
  66367. rc = SQLITE_MISMATCH;
  66368. goto abort_due_to_error;
  66369. }else{
  66370. pc = pOp->p2 - 1;
  66371. break;
  66372. }
  66373. }
  66374. }
  66375. MemSetTypeFlag(pIn1, MEM_Int);
  66376. break;
  66377. }
  66378. #ifndef SQLITE_OMIT_FLOATING_POINT
  66379. /* Opcode: RealAffinity P1 * * * *
  66380. **
  66381. ** If register P1 holds an integer convert it to a real value.
  66382. **
  66383. ** This opcode is used when extracting information from a column that
  66384. ** has REAL affinity. Such column values may still be stored as
  66385. ** integers, for space efficiency, but after extraction we want them
  66386. ** to have only a real value.
  66387. */
  66388. case OP_RealAffinity: { /* in1 */
  66389. pIn1 = &aMem[pOp->p1];
  66390. if( pIn1->flags & MEM_Int ){
  66391. sqlite3VdbeMemRealify(pIn1);
  66392. }
  66393. break;
  66394. }
  66395. #endif
  66396. #ifndef SQLITE_OMIT_CAST
  66397. /* Opcode: Cast P1 P2 * * *
  66398. ** Synopsis: affinity(r[P1])
  66399. **
  66400. ** Force the value in register P1 to be the type defined by P2.
  66401. **
  66402. ** <ul>
  66403. ** <li value="97"> TEXT
  66404. ** <li value="98"> BLOB
  66405. ** <li value="99"> NUMERIC
  66406. ** <li value="100"> INTEGER
  66407. ** <li value="101"> REAL
  66408. ** </ul>
  66409. **
  66410. ** A NULL value is not changed by this routine. It remains NULL.
  66411. */
  66412. case OP_Cast: { /* in1 */
  66413. assert( pOp->p2>=SQLITE_AFF_NONE && pOp->p2<=SQLITE_AFF_REAL );
  66414. testcase( pOp->p2==SQLITE_AFF_TEXT );
  66415. testcase( pOp->p2==SQLITE_AFF_NONE );
  66416. testcase( pOp->p2==SQLITE_AFF_NUMERIC );
  66417. testcase( pOp->p2==SQLITE_AFF_INTEGER );
  66418. testcase( pOp->p2==SQLITE_AFF_REAL );
  66419. pIn1 = &aMem[pOp->p1];
  66420. memAboutToChange(p, pIn1);
  66421. rc = ExpandBlob(pIn1);
  66422. sqlite3VdbeMemCast(pIn1, pOp->p2, encoding);
  66423. UPDATE_MAX_BLOBSIZE(pIn1);
  66424. break;
  66425. }
  66426. #endif /* SQLITE_OMIT_CAST */
  66427. /* Opcode: Lt P1 P2 P3 P4 P5
  66428. ** Synopsis: if r[P1]<r[P3] goto P2
  66429. **
  66430. ** Compare the values in register P1 and P3. If reg(P3)<reg(P1) then
  66431. ** jump to address P2.
  66432. **
  66433. ** If the SQLITE_JUMPIFNULL bit of P5 is set and either reg(P1) or
  66434. ** reg(P3) is NULL then take the jump. If the SQLITE_JUMPIFNULL
  66435. ** bit is clear then fall through if either operand is NULL.
  66436. **
  66437. ** The SQLITE_AFF_MASK portion of P5 must be an affinity character -
  66438. ** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made
  66439. ** to coerce both inputs according to this affinity before the
  66440. ** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric
  66441. ** affinity is used. Note that the affinity conversions are stored
  66442. ** back into the input registers P1 and P3. So this opcode can cause
  66443. ** persistent changes to registers P1 and P3.
  66444. **
  66445. ** Once any conversions have taken place, and neither value is NULL,
  66446. ** the values are compared. If both values are blobs then memcmp() is
  66447. ** used to determine the results of the comparison. If both values
  66448. ** are text, then the appropriate collating function specified in
  66449. ** P4 is used to do the comparison. If P4 is not specified then
  66450. ** memcmp() is used to compare text string. If both values are
  66451. ** numeric, then a numeric comparison is used. If the two values
  66452. ** are of different types, then numbers are considered less than
  66453. ** strings and strings are considered less than blobs.
  66454. **
  66455. ** If the SQLITE_STOREP2 bit of P5 is set, then do not jump. Instead,
  66456. ** store a boolean result (either 0, or 1, or NULL) in register P2.
  66457. **
  66458. ** If the SQLITE_NULLEQ bit is set in P5, then NULL values are considered
  66459. ** equal to one another, provided that they do not have their MEM_Cleared
  66460. ** bit set.
  66461. */
  66462. /* Opcode: Ne P1 P2 P3 P4 P5
  66463. ** Synopsis: if r[P1]!=r[P3] goto P2
  66464. **
  66465. ** This works just like the Lt opcode except that the jump is taken if
  66466. ** the operands in registers P1 and P3 are not equal. See the Lt opcode for
  66467. ** additional information.
  66468. **
  66469. ** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
  66470. ** true or false and is never NULL. If both operands are NULL then the result
  66471. ** of comparison is false. If either operand is NULL then the result is true.
  66472. ** If neither operand is NULL the result is the same as it would be if
  66473. ** the SQLITE_NULLEQ flag were omitted from P5.
  66474. */
  66475. /* Opcode: Eq P1 P2 P3 P4 P5
  66476. ** Synopsis: if r[P1]==r[P3] goto P2
  66477. **
  66478. ** This works just like the Lt opcode except that the jump is taken if
  66479. ** the operands in registers P1 and P3 are equal.
  66480. ** See the Lt opcode for additional information.
  66481. **
  66482. ** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
  66483. ** true or false and is never NULL. If both operands are NULL then the result
  66484. ** of comparison is true. If either operand is NULL then the result is false.
  66485. ** If neither operand is NULL the result is the same as it would be if
  66486. ** the SQLITE_NULLEQ flag were omitted from P5.
  66487. */
  66488. /* Opcode: Le P1 P2 P3 P4 P5
  66489. ** Synopsis: if r[P1]<=r[P3] goto P2
  66490. **
  66491. ** This works just like the Lt opcode except that the jump is taken if
  66492. ** the content of register P3 is less than or equal to the content of
  66493. ** register P1. See the Lt opcode for additional information.
  66494. */
  66495. /* Opcode: Gt P1 P2 P3 P4 P5
  66496. ** Synopsis: if r[P1]>r[P3] goto P2
  66497. **
  66498. ** This works just like the Lt opcode except that the jump is taken if
  66499. ** the content of register P3 is greater than the content of
  66500. ** register P1. See the Lt opcode for additional information.
  66501. */
  66502. /* Opcode: Ge P1 P2 P3 P4 P5
  66503. ** Synopsis: if r[P1]>=r[P3] goto P2
  66504. **
  66505. ** This works just like the Lt opcode except that the jump is taken if
  66506. ** the content of register P3 is greater than or equal to the content of
  66507. ** register P1. See the Lt opcode for additional information.
  66508. */
  66509. case OP_Eq: /* same as TK_EQ, jump, in1, in3 */
  66510. case OP_Ne: /* same as TK_NE, jump, in1, in3 */
  66511. case OP_Lt: /* same as TK_LT, jump, in1, in3 */
  66512. case OP_Le: /* same as TK_LE, jump, in1, in3 */
  66513. case OP_Gt: /* same as TK_GT, jump, in1, in3 */
  66514. case OP_Ge: { /* same as TK_GE, jump, in1, in3 */
  66515. int res; /* Result of the comparison of pIn1 against pIn3 */
  66516. char affinity; /* Affinity to use for comparison */
  66517. u16 flags1; /* Copy of initial value of pIn1->flags */
  66518. u16 flags3; /* Copy of initial value of pIn3->flags */
  66519. pIn1 = &aMem[pOp->p1];
  66520. pIn3 = &aMem[pOp->p3];
  66521. flags1 = pIn1->flags;
  66522. flags3 = pIn3->flags;
  66523. if( (flags1 | flags3)&MEM_Null ){
  66524. /* One or both operands are NULL */
  66525. if( pOp->p5 & SQLITE_NULLEQ ){
  66526. /* If SQLITE_NULLEQ is set (which will only happen if the operator is
  66527. ** OP_Eq or OP_Ne) then take the jump or not depending on whether
  66528. ** or not both operands are null.
  66529. */
  66530. assert( pOp->opcode==OP_Eq || pOp->opcode==OP_Ne );
  66531. assert( (flags1 & MEM_Cleared)==0 );
  66532. assert( (pOp->p5 & SQLITE_JUMPIFNULL)==0 );
  66533. if( (flags1&MEM_Null)!=0
  66534. && (flags3&MEM_Null)!=0
  66535. && (flags3&MEM_Cleared)==0
  66536. ){
  66537. res = 0; /* Results are equal */
  66538. }else{
  66539. res = 1; /* Results are not equal */
  66540. }
  66541. }else{
  66542. /* SQLITE_NULLEQ is clear and at least one operand is NULL,
  66543. ** then the result is always NULL.
  66544. ** The jump is taken if the SQLITE_JUMPIFNULL bit is set.
  66545. */
  66546. if( pOp->p5 & SQLITE_STOREP2 ){
  66547. pOut = &aMem[pOp->p2];
  66548. MemSetTypeFlag(pOut, MEM_Null);
  66549. REGISTER_TRACE(pOp->p2, pOut);
  66550. }else{
  66551. VdbeBranchTaken(2,3);
  66552. if( pOp->p5 & SQLITE_JUMPIFNULL ){
  66553. pc = pOp->p2-1;
  66554. }
  66555. }
  66556. break;
  66557. }
  66558. }else{
  66559. /* Neither operand is NULL. Do a comparison. */
  66560. affinity = pOp->p5 & SQLITE_AFF_MASK;
  66561. if( affinity>=SQLITE_AFF_NUMERIC ){
  66562. if( (pIn1->flags & (MEM_Int|MEM_Real|MEM_Str))==MEM_Str ){
  66563. applyNumericAffinity(pIn1,0);
  66564. }
  66565. if( (pIn3->flags & (MEM_Int|MEM_Real|MEM_Str))==MEM_Str ){
  66566. applyNumericAffinity(pIn3,0);
  66567. }
  66568. }else if( affinity==SQLITE_AFF_TEXT ){
  66569. if( (pIn1->flags & MEM_Str)==0 && (pIn1->flags & (MEM_Int|MEM_Real))!=0 ){
  66570. testcase( pIn1->flags & MEM_Int );
  66571. testcase( pIn1->flags & MEM_Real );
  66572. sqlite3VdbeMemStringify(pIn1, encoding, 1);
  66573. }
  66574. if( (pIn3->flags & MEM_Str)==0 && (pIn3->flags & (MEM_Int|MEM_Real))!=0 ){
  66575. testcase( pIn3->flags & MEM_Int );
  66576. testcase( pIn3->flags & MEM_Real );
  66577. sqlite3VdbeMemStringify(pIn3, encoding, 1);
  66578. }
  66579. }
  66580. assert( pOp->p4type==P4_COLLSEQ || pOp->p4.pColl==0 );
  66581. if( pIn1->flags & MEM_Zero ){
  66582. sqlite3VdbeMemExpandBlob(pIn1);
  66583. flags1 &= ~MEM_Zero;
  66584. }
  66585. if( pIn3->flags & MEM_Zero ){
  66586. sqlite3VdbeMemExpandBlob(pIn3);
  66587. flags3 &= ~MEM_Zero;
  66588. }
  66589. if( db->mallocFailed ) goto no_mem;
  66590. res = sqlite3MemCompare(pIn3, pIn1, pOp->p4.pColl);
  66591. }
  66592. switch( pOp->opcode ){
  66593. case OP_Eq: res = res==0; break;
  66594. case OP_Ne: res = res!=0; break;
  66595. case OP_Lt: res = res<0; break;
  66596. case OP_Le: res = res<=0; break;
  66597. case OP_Gt: res = res>0; break;
  66598. default: res = res>=0; break;
  66599. }
  66600. if( pOp->p5 & SQLITE_STOREP2 ){
  66601. pOut = &aMem[pOp->p2];
  66602. memAboutToChange(p, pOut);
  66603. MemSetTypeFlag(pOut, MEM_Int);
  66604. pOut->u.i = res;
  66605. REGISTER_TRACE(pOp->p2, pOut);
  66606. }else{
  66607. VdbeBranchTaken(res!=0, (pOp->p5 & SQLITE_NULLEQ)?2:3);
  66608. if( res ){
  66609. pc = pOp->p2-1;
  66610. }
  66611. }
  66612. /* Undo any changes made by applyAffinity() to the input registers. */
  66613. pIn1->flags = flags1;
  66614. pIn3->flags = flags3;
  66615. break;
  66616. }
  66617. /* Opcode: Permutation * * * P4 *
  66618. **
  66619. ** Set the permutation used by the OP_Compare operator to be the array
  66620. ** of integers in P4.
  66621. **
  66622. ** The permutation is only valid until the next OP_Compare that has
  66623. ** the OPFLAG_PERMUTE bit set in P5. Typically the OP_Permutation should
  66624. ** occur immediately prior to the OP_Compare.
  66625. */
  66626. case OP_Permutation: {
  66627. assert( pOp->p4type==P4_INTARRAY );
  66628. assert( pOp->p4.ai );
  66629. aPermute = pOp->p4.ai;
  66630. break;
  66631. }
  66632. /* Opcode: Compare P1 P2 P3 P4 P5
  66633. ** Synopsis: r[P1@P3] <-> r[P2@P3]
  66634. **
  66635. ** Compare two vectors of registers in reg(P1)..reg(P1+P3-1) (call this
  66636. ** vector "A") and in reg(P2)..reg(P2+P3-1) ("B"). Save the result of
  66637. ** the comparison for use by the next OP_Jump instruct.
  66638. **
  66639. ** If P5 has the OPFLAG_PERMUTE bit set, then the order of comparison is
  66640. ** determined by the most recent OP_Permutation operator. If the
  66641. ** OPFLAG_PERMUTE bit is clear, then register are compared in sequential
  66642. ** order.
  66643. **
  66644. ** P4 is a KeyInfo structure that defines collating sequences and sort
  66645. ** orders for the comparison. The permutation applies to registers
  66646. ** only. The KeyInfo elements are used sequentially.
  66647. **
  66648. ** The comparison is a sort comparison, so NULLs compare equal,
  66649. ** NULLs are less than numbers, numbers are less than strings,
  66650. ** and strings are less than blobs.
  66651. */
  66652. case OP_Compare: {
  66653. int n;
  66654. int i;
  66655. int p1;
  66656. int p2;
  66657. const KeyInfo *pKeyInfo;
  66658. int idx;
  66659. CollSeq *pColl; /* Collating sequence to use on this term */
  66660. int bRev; /* True for DESCENDING sort order */
  66661. if( (pOp->p5 & OPFLAG_PERMUTE)==0 ) aPermute = 0;
  66662. n = pOp->p3;
  66663. pKeyInfo = pOp->p4.pKeyInfo;
  66664. assert( n>0 );
  66665. assert( pKeyInfo!=0 );
  66666. p1 = pOp->p1;
  66667. p2 = pOp->p2;
  66668. #if SQLITE_DEBUG
  66669. if( aPermute ){
  66670. int k, mx = 0;
  66671. for(k=0; k<n; k++) if( aPermute[k]>mx ) mx = aPermute[k];
  66672. assert( p1>0 && p1+mx<=(p->nMem-p->nCursor)+1 );
  66673. assert( p2>0 && p2+mx<=(p->nMem-p->nCursor)+1 );
  66674. }else{
  66675. assert( p1>0 && p1+n<=(p->nMem-p->nCursor)+1 );
  66676. assert( p2>0 && p2+n<=(p->nMem-p->nCursor)+1 );
  66677. }
  66678. #endif /* SQLITE_DEBUG */
  66679. for(i=0; i<n; i++){
  66680. idx = aPermute ? aPermute[i] : i;
  66681. assert( memIsValid(&aMem[p1+idx]) );
  66682. assert( memIsValid(&aMem[p2+idx]) );
  66683. REGISTER_TRACE(p1+idx, &aMem[p1+idx]);
  66684. REGISTER_TRACE(p2+idx, &aMem[p2+idx]);
  66685. assert( i<pKeyInfo->nField );
  66686. pColl = pKeyInfo->aColl[i];
  66687. bRev = pKeyInfo->aSortOrder[i];
  66688. iCompare = sqlite3MemCompare(&aMem[p1+idx], &aMem[p2+idx], pColl);
  66689. if( iCompare ){
  66690. if( bRev ) iCompare = -iCompare;
  66691. break;
  66692. }
  66693. }
  66694. aPermute = 0;
  66695. break;
  66696. }
  66697. /* Opcode: Jump P1 P2 P3 * *
  66698. **
  66699. ** Jump to the instruction at address P1, P2, or P3 depending on whether
  66700. ** in the most recent OP_Compare instruction the P1 vector was less than
  66701. ** equal to, or greater than the P2 vector, respectively.
  66702. */
  66703. case OP_Jump: { /* jump */
  66704. if( iCompare<0 ){
  66705. pc = pOp->p1 - 1; VdbeBranchTaken(0,3);
  66706. }else if( iCompare==0 ){
  66707. pc = pOp->p2 - 1; VdbeBranchTaken(1,3);
  66708. }else{
  66709. pc = pOp->p3 - 1; VdbeBranchTaken(2,3);
  66710. }
  66711. break;
  66712. }
  66713. /* Opcode: And P1 P2 P3 * *
  66714. ** Synopsis: r[P3]=(r[P1] && r[P2])
  66715. **
  66716. ** Take the logical AND of the values in registers P1 and P2 and
  66717. ** write the result into register P3.
  66718. **
  66719. ** If either P1 or P2 is 0 (false) then the result is 0 even if
  66720. ** the other input is NULL. A NULL and true or two NULLs give
  66721. ** a NULL output.
  66722. */
  66723. /* Opcode: Or P1 P2 P3 * *
  66724. ** Synopsis: r[P3]=(r[P1] || r[P2])
  66725. **
  66726. ** Take the logical OR of the values in register P1 and P2 and
  66727. ** store the answer in register P3.
  66728. **
  66729. ** If either P1 or P2 is nonzero (true) then the result is 1 (true)
  66730. ** even if the other input is NULL. A NULL and false or two NULLs
  66731. ** give a NULL output.
  66732. */
  66733. case OP_And: /* same as TK_AND, in1, in2, out3 */
  66734. case OP_Or: { /* same as TK_OR, in1, in2, out3 */
  66735. int v1; /* Left operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
  66736. int v2; /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
  66737. pIn1 = &aMem[pOp->p1];
  66738. if( pIn1->flags & MEM_Null ){
  66739. v1 = 2;
  66740. }else{
  66741. v1 = sqlite3VdbeIntValue(pIn1)!=0;
  66742. }
  66743. pIn2 = &aMem[pOp->p2];
  66744. if( pIn2->flags & MEM_Null ){
  66745. v2 = 2;
  66746. }else{
  66747. v2 = sqlite3VdbeIntValue(pIn2)!=0;
  66748. }
  66749. if( pOp->opcode==OP_And ){
  66750. static const unsigned char and_logic[] = { 0, 0, 0, 0, 1, 2, 0, 2, 2 };
  66751. v1 = and_logic[v1*3+v2];
  66752. }else{
  66753. static const unsigned char or_logic[] = { 0, 1, 2, 1, 1, 1, 2, 1, 2 };
  66754. v1 = or_logic[v1*3+v2];
  66755. }
  66756. pOut = &aMem[pOp->p3];
  66757. if( v1==2 ){
  66758. MemSetTypeFlag(pOut, MEM_Null);
  66759. }else{
  66760. pOut->u.i = v1;
  66761. MemSetTypeFlag(pOut, MEM_Int);
  66762. }
  66763. break;
  66764. }
  66765. /* Opcode: Not P1 P2 * * *
  66766. ** Synopsis: r[P2]= !r[P1]
  66767. **
  66768. ** Interpret the value in register P1 as a boolean value. Store the
  66769. ** boolean complement in register P2. If the value in register P1 is
  66770. ** NULL, then a NULL is stored in P2.
  66771. */
  66772. case OP_Not: { /* same as TK_NOT, in1, out2 */
  66773. pIn1 = &aMem[pOp->p1];
  66774. pOut = &aMem[pOp->p2];
  66775. sqlite3VdbeMemSetNull(pOut);
  66776. if( (pIn1->flags & MEM_Null)==0 ){
  66777. pOut->flags = MEM_Int;
  66778. pOut->u.i = !sqlite3VdbeIntValue(pIn1);
  66779. }
  66780. break;
  66781. }
  66782. /* Opcode: BitNot P1 P2 * * *
  66783. ** Synopsis: r[P1]= ~r[P1]
  66784. **
  66785. ** Interpret the content of register P1 as an integer. Store the
  66786. ** ones-complement of the P1 value into register P2. If P1 holds
  66787. ** a NULL then store a NULL in P2.
  66788. */
  66789. case OP_BitNot: { /* same as TK_BITNOT, in1, out2 */
  66790. pIn1 = &aMem[pOp->p1];
  66791. pOut = &aMem[pOp->p2];
  66792. sqlite3VdbeMemSetNull(pOut);
  66793. if( (pIn1->flags & MEM_Null)==0 ){
  66794. pOut->flags = MEM_Int;
  66795. pOut->u.i = ~sqlite3VdbeIntValue(pIn1);
  66796. }
  66797. break;
  66798. }
  66799. /* Opcode: Once P1 P2 * * *
  66800. **
  66801. ** Check the "once" flag number P1. If it is set, jump to instruction P2.
  66802. ** Otherwise, set the flag and fall through to the next instruction.
  66803. ** In other words, this opcode causes all following opcodes up through P2
  66804. ** (but not including P2) to run just once and to be skipped on subsequent
  66805. ** times through the loop.
  66806. **
  66807. ** All "once" flags are initially cleared whenever a prepared statement
  66808. ** first begins to run.
  66809. */
  66810. case OP_Once: { /* jump */
  66811. assert( pOp->p1<p->nOnceFlag );
  66812. VdbeBranchTaken(p->aOnceFlag[pOp->p1]!=0, 2);
  66813. if( p->aOnceFlag[pOp->p1] ){
  66814. pc = pOp->p2-1;
  66815. }else{
  66816. p->aOnceFlag[pOp->p1] = 1;
  66817. }
  66818. break;
  66819. }
  66820. /* Opcode: If P1 P2 P3 * *
  66821. **
  66822. ** Jump to P2 if the value in register P1 is true. The value
  66823. ** is considered true if it is numeric and non-zero. If the value
  66824. ** in P1 is NULL then take the jump if and only if P3 is non-zero.
  66825. */
  66826. /* Opcode: IfNot P1 P2 P3 * *
  66827. **
  66828. ** Jump to P2 if the value in register P1 is False. The value
  66829. ** is considered false if it has a numeric value of zero. If the value
  66830. ** in P1 is NULL then take the jump if and only if P3 is non-zero.
  66831. */
  66832. case OP_If: /* jump, in1 */
  66833. case OP_IfNot: { /* jump, in1 */
  66834. int c;
  66835. pIn1 = &aMem[pOp->p1];
  66836. if( pIn1->flags & MEM_Null ){
  66837. c = pOp->p3;
  66838. }else{
  66839. #ifdef SQLITE_OMIT_FLOATING_POINT
  66840. c = sqlite3VdbeIntValue(pIn1)!=0;
  66841. #else
  66842. c = sqlite3VdbeRealValue(pIn1)!=0.0;
  66843. #endif
  66844. if( pOp->opcode==OP_IfNot ) c = !c;
  66845. }
  66846. VdbeBranchTaken(c!=0, 2);
  66847. if( c ){
  66848. pc = pOp->p2-1;
  66849. }
  66850. break;
  66851. }
  66852. /* Opcode: IsNull P1 P2 * * *
  66853. ** Synopsis: if r[P1]==NULL goto P2
  66854. **
  66855. ** Jump to P2 if the value in register P1 is NULL.
  66856. */
  66857. case OP_IsNull: { /* same as TK_ISNULL, jump, in1 */
  66858. pIn1 = &aMem[pOp->p1];
  66859. VdbeBranchTaken( (pIn1->flags & MEM_Null)!=0, 2);
  66860. if( (pIn1->flags & MEM_Null)!=0 ){
  66861. pc = pOp->p2 - 1;
  66862. }
  66863. break;
  66864. }
  66865. /* Opcode: NotNull P1 P2 * * *
  66866. ** Synopsis: if r[P1]!=NULL goto P2
  66867. **
  66868. ** Jump to P2 if the value in register P1 is not NULL.
  66869. */
  66870. case OP_NotNull: { /* same as TK_NOTNULL, jump, in1 */
  66871. pIn1 = &aMem[pOp->p1];
  66872. VdbeBranchTaken( (pIn1->flags & MEM_Null)==0, 2);
  66873. if( (pIn1->flags & MEM_Null)==0 ){
  66874. pc = pOp->p2 - 1;
  66875. }
  66876. break;
  66877. }
  66878. /* Opcode: Column P1 P2 P3 P4 P5
  66879. ** Synopsis: r[P3]=PX
  66880. **
  66881. ** Interpret the data that cursor P1 points to as a structure built using
  66882. ** the MakeRecord instruction. (See the MakeRecord opcode for additional
  66883. ** information about the format of the data.) Extract the P2-th column
  66884. ** from this record. If there are less that (P2+1)
  66885. ** values in the record, extract a NULL.
  66886. **
  66887. ** The value extracted is stored in register P3.
  66888. **
  66889. ** If the column contains fewer than P2 fields, then extract a NULL. Or,
  66890. ** if the P4 argument is a P4_MEM use the value of the P4 argument as
  66891. ** the result.
  66892. **
  66893. ** If the OPFLAG_CLEARCACHE bit is set on P5 and P1 is a pseudo-table cursor,
  66894. ** then the cache of the cursor is reset prior to extracting the column.
  66895. ** The first OP_Column against a pseudo-table after the value of the content
  66896. ** register has changed should have this bit set.
  66897. **
  66898. ** If the OPFLAG_LENGTHARG and OPFLAG_TYPEOFARG bits are set on P5 when
  66899. ** the result is guaranteed to only be used as the argument of a length()
  66900. ** or typeof() function, respectively. The loading of large blobs can be
  66901. ** skipped for length() and all content loading can be skipped for typeof().
  66902. */
  66903. case OP_Column: {
  66904. i64 payloadSize64; /* Number of bytes in the record */
  66905. int p2; /* column number to retrieve */
  66906. VdbeCursor *pC; /* The VDBE cursor */
  66907. BtCursor *pCrsr; /* The BTree cursor */
  66908. u32 *aOffset; /* aOffset[i] is offset to start of data for i-th column */
  66909. int len; /* The length of the serialized data for the column */
  66910. int i; /* Loop counter */
  66911. Mem *pDest; /* Where to write the extracted value */
  66912. Mem sMem; /* For storing the record being decoded */
  66913. const u8 *zData; /* Part of the record being decoded */
  66914. const u8 *zHdr; /* Next unparsed byte of the header */
  66915. const u8 *zEndHdr; /* Pointer to first byte after the header */
  66916. u32 offset; /* Offset into the data */
  66917. u32 szField; /* Number of bytes in the content of a field */
  66918. u32 avail; /* Number of bytes of available data */
  66919. u32 t; /* A type code from the record header */
  66920. u16 fx; /* pDest->flags value */
  66921. Mem *pReg; /* PseudoTable input register */
  66922. p2 = pOp->p2;
  66923. assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
  66924. pDest = &aMem[pOp->p3];
  66925. memAboutToChange(p, pDest);
  66926. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  66927. pC = p->apCsr[pOp->p1];
  66928. assert( pC!=0 );
  66929. assert( p2<pC->nField );
  66930. aOffset = pC->aOffset;
  66931. #ifndef SQLITE_OMIT_VIRTUALTABLE
  66932. assert( pC->pVtabCursor==0 ); /* OP_Column never called on virtual table */
  66933. #endif
  66934. pCrsr = pC->pCursor;
  66935. assert( pCrsr!=0 || pC->pseudoTableReg>0 ); /* pCrsr NULL on PseudoTables */
  66936. assert( pCrsr!=0 || pC->nullRow ); /* pC->nullRow on PseudoTables */
  66937. /* If the cursor cache is stale, bring it up-to-date */
  66938. rc = sqlite3VdbeCursorMoveto(pC);
  66939. if( rc ) goto abort_due_to_error;
  66940. if( pC->cacheStatus!=p->cacheCtr ){
  66941. if( pC->nullRow ){
  66942. if( pCrsr==0 ){
  66943. assert( pC->pseudoTableReg>0 );
  66944. pReg = &aMem[pC->pseudoTableReg];
  66945. assert( pReg->flags & MEM_Blob );
  66946. assert( memIsValid(pReg) );
  66947. pC->payloadSize = pC->szRow = avail = pReg->n;
  66948. pC->aRow = (u8*)pReg->z;
  66949. }else{
  66950. MemSetTypeFlag(pDest, MEM_Null);
  66951. goto op_column_out;
  66952. }
  66953. }else{
  66954. assert( pCrsr );
  66955. if( pC->isTable==0 ){
  66956. assert( sqlite3BtreeCursorIsValid(pCrsr) );
  66957. VVA_ONLY(rc =) sqlite3BtreeKeySize(pCrsr, &payloadSize64);
  66958. assert( rc==SQLITE_OK ); /* True because of CursorMoveto() call above */
  66959. /* sqlite3BtreeParseCellPtr() uses getVarint32() to extract the
  66960. ** payload size, so it is impossible for payloadSize64 to be
  66961. ** larger than 32 bits. */
  66962. assert( (payloadSize64 & SQLITE_MAX_U32)==(u64)payloadSize64 );
  66963. pC->aRow = sqlite3BtreeKeyFetch(pCrsr, &avail);
  66964. pC->payloadSize = (u32)payloadSize64;
  66965. }else{
  66966. assert( sqlite3BtreeCursorIsValid(pCrsr) );
  66967. VVA_ONLY(rc =) sqlite3BtreeDataSize(pCrsr, &pC->payloadSize);
  66968. assert( rc==SQLITE_OK ); /* DataSize() cannot fail */
  66969. pC->aRow = sqlite3BtreeDataFetch(pCrsr, &avail);
  66970. }
  66971. assert( avail<=65536 ); /* Maximum page size is 64KiB */
  66972. if( pC->payloadSize <= (u32)avail ){
  66973. pC->szRow = pC->payloadSize;
  66974. }else{
  66975. pC->szRow = avail;
  66976. }
  66977. if( pC->payloadSize > (u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
  66978. goto too_big;
  66979. }
  66980. }
  66981. pC->cacheStatus = p->cacheCtr;
  66982. pC->iHdrOffset = getVarint32(pC->aRow, offset);
  66983. pC->nHdrParsed = 0;
  66984. aOffset[0] = offset;
  66985. /* Make sure a corrupt database has not given us an oversize header.
  66986. ** Do this now to avoid an oversize memory allocation.
  66987. **
  66988. ** Type entries can be between 1 and 5 bytes each. But 4 and 5 byte
  66989. ** types use so much data space that there can only be 4096 and 32 of
  66990. ** them, respectively. So the maximum header length results from a
  66991. ** 3-byte type for each of the maximum of 32768 columns plus three
  66992. ** extra bytes for the header length itself. 32768*3 + 3 = 98307.
  66993. */
  66994. if( offset > 98307 || offset > pC->payloadSize ){
  66995. rc = SQLITE_CORRUPT_BKPT;
  66996. goto op_column_error;
  66997. }
  66998. if( avail<offset ){
  66999. /* pC->aRow does not have to hold the entire row, but it does at least
  67000. ** need to cover the header of the record. If pC->aRow does not contain
  67001. ** the complete header, then set it to zero, forcing the header to be
  67002. ** dynamically allocated. */
  67003. pC->aRow = 0;
  67004. pC->szRow = 0;
  67005. }
  67006. /* The following goto is an optimization. It can be omitted and
  67007. ** everything will still work. But OP_Column is measurably faster
  67008. ** by skipping the subsequent conditional, which is always true.
  67009. */
  67010. assert( pC->nHdrParsed<=p2 ); /* Conditional skipped */
  67011. goto op_column_read_header;
  67012. }
  67013. /* Make sure at least the first p2+1 entries of the header have been
  67014. ** parsed and valid information is in aOffset[] and pC->aType[].
  67015. */
  67016. if( pC->nHdrParsed<=p2 ){
  67017. /* If there is more header available for parsing in the record, try
  67018. ** to extract additional fields up through the p2+1-th field
  67019. */
  67020. op_column_read_header:
  67021. if( pC->iHdrOffset<aOffset[0] ){
  67022. /* Make sure zData points to enough of the record to cover the header. */
  67023. if( pC->aRow==0 ){
  67024. memset(&sMem, 0, sizeof(sMem));
  67025. rc = sqlite3VdbeMemFromBtree(pCrsr, 0, aOffset[0],
  67026. !pC->isTable, &sMem);
  67027. if( rc!=SQLITE_OK ){
  67028. goto op_column_error;
  67029. }
  67030. zData = (u8*)sMem.z;
  67031. }else{
  67032. zData = pC->aRow;
  67033. }
  67034. /* Fill in pC->aType[i] and aOffset[i] values through the p2-th field. */
  67035. i = pC->nHdrParsed;
  67036. offset = aOffset[i];
  67037. zHdr = zData + pC->iHdrOffset;
  67038. zEndHdr = zData + aOffset[0];
  67039. assert( i<=p2 && zHdr<zEndHdr );
  67040. do{
  67041. if( zHdr[0]<0x80 ){
  67042. t = zHdr[0];
  67043. zHdr++;
  67044. }else{
  67045. zHdr += sqlite3GetVarint32(zHdr, &t);
  67046. }
  67047. pC->aType[i] = t;
  67048. szField = sqlite3VdbeSerialTypeLen(t);
  67049. offset += szField;
  67050. if( offset<szField ){ /* True if offset overflows */
  67051. zHdr = &zEndHdr[1]; /* Forces SQLITE_CORRUPT return below */
  67052. break;
  67053. }
  67054. i++;
  67055. aOffset[i] = offset;
  67056. }while( i<=p2 && zHdr<zEndHdr );
  67057. pC->nHdrParsed = i;
  67058. pC->iHdrOffset = (u32)(zHdr - zData);
  67059. if( pC->aRow==0 ){
  67060. sqlite3VdbeMemRelease(&sMem);
  67061. sMem.flags = MEM_Null;
  67062. }
  67063. /* The record is corrupt if any of the following are true:
  67064. ** (1) the bytes of the header extend past the declared header size
  67065. ** (zHdr>zEndHdr)
  67066. ** (2) the entire header was used but not all data was used
  67067. ** (zHdr==zEndHdr && offset!=pC->payloadSize)
  67068. ** (3) the end of the data extends beyond the end of the record.
  67069. ** (offset > pC->payloadSize)
  67070. */
  67071. if( (zHdr>=zEndHdr && (zHdr>zEndHdr || offset!=pC->payloadSize))
  67072. || (offset > pC->payloadSize)
  67073. ){
  67074. rc = SQLITE_CORRUPT_BKPT;
  67075. goto op_column_error;
  67076. }
  67077. }
  67078. /* If after trying to extra new entries from the header, nHdrParsed is
  67079. ** still not up to p2, that means that the record has fewer than p2
  67080. ** columns. So the result will be either the default value or a NULL.
  67081. */
  67082. if( pC->nHdrParsed<=p2 ){
  67083. if( pOp->p4type==P4_MEM ){
  67084. sqlite3VdbeMemShallowCopy(pDest, pOp->p4.pMem, MEM_Static);
  67085. }else{
  67086. MemSetTypeFlag(pDest, MEM_Null);
  67087. }
  67088. goto op_column_out;
  67089. }
  67090. }
  67091. /* Extract the content for the p2+1-th column. Control can only
  67092. ** reach this point if aOffset[p2], aOffset[p2+1], and pC->aType[p2] are
  67093. ** all valid.
  67094. */
  67095. assert( p2<pC->nHdrParsed );
  67096. assert( rc==SQLITE_OK );
  67097. assert( sqlite3VdbeCheckMemInvariants(pDest) );
  67098. if( VdbeMemDynamic(pDest) ) sqlite3VdbeMemSetNull(pDest);
  67099. t = pC->aType[p2];
  67100. if( pC->szRow>=aOffset[p2+1] ){
  67101. /* This is the common case where the desired content fits on the original
  67102. ** page - where the content is not on an overflow page */
  67103. sqlite3VdbeSerialGet(pC->aRow+aOffset[p2], t, pDest);
  67104. }else{
  67105. /* This branch happens only when content is on overflow pages */
  67106. if( ((pOp->p5 & (OPFLAG_LENGTHARG|OPFLAG_TYPEOFARG))!=0
  67107. && ((t>=12 && (t&1)==0) || (pOp->p5 & OPFLAG_TYPEOFARG)!=0))
  67108. || (len = sqlite3VdbeSerialTypeLen(t))==0
  67109. ){
  67110. /* Content is irrelevant for
  67111. ** 1. the typeof() function,
  67112. ** 2. the length(X) function if X is a blob, and
  67113. ** 3. if the content length is zero.
  67114. ** So we might as well use bogus content rather than reading
  67115. ** content from disk. NULL will work for the value for strings
  67116. ** and blobs and whatever is in the payloadSize64 variable
  67117. ** will work for everything else. */
  67118. sqlite3VdbeSerialGet(t<=13 ? (u8*)&payloadSize64 : 0, t, pDest);
  67119. }else{
  67120. rc = sqlite3VdbeMemFromBtree(pCrsr, aOffset[p2], len, !pC->isTable,
  67121. pDest);
  67122. if( rc!=SQLITE_OK ){
  67123. goto op_column_error;
  67124. }
  67125. sqlite3VdbeSerialGet((const u8*)pDest->z, t, pDest);
  67126. pDest->flags &= ~MEM_Ephem;
  67127. }
  67128. }
  67129. pDest->enc = encoding;
  67130. op_column_out:
  67131. /* If the column value is an ephemeral string, go ahead and persist
  67132. ** that string in case the cursor moves before the column value is
  67133. ** used. The following code does the equivalent of Deephemeralize()
  67134. ** but does it faster. */
  67135. if( (pDest->flags & MEM_Ephem)!=0 && pDest->z ){
  67136. fx = pDest->flags & (MEM_Str|MEM_Blob);
  67137. assert( fx!=0 );
  67138. zData = (const u8*)pDest->z;
  67139. len = pDest->n;
  67140. if( sqlite3VdbeMemClearAndResize(pDest, len+2) ) goto no_mem;
  67141. memcpy(pDest->z, zData, len);
  67142. pDest->z[len] = 0;
  67143. pDest->z[len+1] = 0;
  67144. pDest->flags = fx|MEM_Term;
  67145. }
  67146. op_column_error:
  67147. UPDATE_MAX_BLOBSIZE(pDest);
  67148. REGISTER_TRACE(pOp->p3, pDest);
  67149. break;
  67150. }
  67151. /* Opcode: Affinity P1 P2 * P4 *
  67152. ** Synopsis: affinity(r[P1@P2])
  67153. **
  67154. ** Apply affinities to a range of P2 registers starting with P1.
  67155. **
  67156. ** P4 is a string that is P2 characters long. The nth character of the
  67157. ** string indicates the column affinity that should be used for the nth
  67158. ** memory cell in the range.
  67159. */
  67160. case OP_Affinity: {
  67161. const char *zAffinity; /* The affinity to be applied */
  67162. char cAff; /* A single character of affinity */
  67163. zAffinity = pOp->p4.z;
  67164. assert( zAffinity!=0 );
  67165. assert( zAffinity[pOp->p2]==0 );
  67166. pIn1 = &aMem[pOp->p1];
  67167. while( (cAff = *(zAffinity++))!=0 ){
  67168. assert( pIn1 <= &p->aMem[(p->nMem-p->nCursor)] );
  67169. assert( memIsValid(pIn1) );
  67170. applyAffinity(pIn1, cAff, encoding);
  67171. pIn1++;
  67172. }
  67173. break;
  67174. }
  67175. /* Opcode: MakeRecord P1 P2 P3 P4 *
  67176. ** Synopsis: r[P3]=mkrec(r[P1@P2])
  67177. **
  67178. ** Convert P2 registers beginning with P1 into the [record format]
  67179. ** use as a data record in a database table or as a key
  67180. ** in an index. The OP_Column opcode can decode the record later.
  67181. **
  67182. ** P4 may be a string that is P2 characters long. The nth character of the
  67183. ** string indicates the column affinity that should be used for the nth
  67184. ** field of the index key.
  67185. **
  67186. ** The mapping from character to affinity is given by the SQLITE_AFF_
  67187. ** macros defined in sqliteInt.h.
  67188. **
  67189. ** If P4 is NULL then all index fields have the affinity NONE.
  67190. */
  67191. case OP_MakeRecord: {
  67192. u8 *zNewRecord; /* A buffer to hold the data for the new record */
  67193. Mem *pRec; /* The new record */
  67194. u64 nData; /* Number of bytes of data space */
  67195. int nHdr; /* Number of bytes of header space */
  67196. i64 nByte; /* Data space required for this record */
  67197. int nZero; /* Number of zero bytes at the end of the record */
  67198. int nVarint; /* Number of bytes in a varint */
  67199. u32 serial_type; /* Type field */
  67200. Mem *pData0; /* First field to be combined into the record */
  67201. Mem *pLast; /* Last field of the record */
  67202. int nField; /* Number of fields in the record */
  67203. char *zAffinity; /* The affinity string for the record */
  67204. int file_format; /* File format to use for encoding */
  67205. int i; /* Space used in zNewRecord[] header */
  67206. int j; /* Space used in zNewRecord[] content */
  67207. int len; /* Length of a field */
  67208. /* Assuming the record contains N fields, the record format looks
  67209. ** like this:
  67210. **
  67211. ** ------------------------------------------------------------------------
  67212. ** | hdr-size | type 0 | type 1 | ... | type N-1 | data0 | ... | data N-1 |
  67213. ** ------------------------------------------------------------------------
  67214. **
  67215. ** Data(0) is taken from register P1. Data(1) comes from register P1+1
  67216. ** and so forth.
  67217. **
  67218. ** Each type field is a varint representing the serial type of the
  67219. ** corresponding data element (see sqlite3VdbeSerialType()). The
  67220. ** hdr-size field is also a varint which is the offset from the beginning
  67221. ** of the record to data0.
  67222. */
  67223. nData = 0; /* Number of bytes of data space */
  67224. nHdr = 0; /* Number of bytes of header space */
  67225. nZero = 0; /* Number of zero bytes at the end of the record */
  67226. nField = pOp->p1;
  67227. zAffinity = pOp->p4.z;
  67228. assert( nField>0 && pOp->p2>0 && pOp->p2+nField<=(p->nMem-p->nCursor)+1 );
  67229. pData0 = &aMem[nField];
  67230. nField = pOp->p2;
  67231. pLast = &pData0[nField-1];
  67232. file_format = p->minWriteFileFormat;
  67233. /* Identify the output register */
  67234. assert( pOp->p3<pOp->p1 || pOp->p3>=pOp->p1+pOp->p2 );
  67235. pOut = &aMem[pOp->p3];
  67236. memAboutToChange(p, pOut);
  67237. /* Apply the requested affinity to all inputs
  67238. */
  67239. assert( pData0<=pLast );
  67240. if( zAffinity ){
  67241. pRec = pData0;
  67242. do{
  67243. applyAffinity(pRec++, *(zAffinity++), encoding);
  67244. assert( zAffinity[0]==0 || pRec<=pLast );
  67245. }while( zAffinity[0] );
  67246. }
  67247. /* Loop through the elements that will make up the record to figure
  67248. ** out how much space is required for the new record.
  67249. */
  67250. pRec = pLast;
  67251. do{
  67252. assert( memIsValid(pRec) );
  67253. pRec->uTemp = serial_type = sqlite3VdbeSerialType(pRec, file_format);
  67254. len = sqlite3VdbeSerialTypeLen(serial_type);
  67255. if( pRec->flags & MEM_Zero ){
  67256. if( nData ){
  67257. sqlite3VdbeMemExpandBlob(pRec);
  67258. }else{
  67259. nZero += pRec->u.nZero;
  67260. len -= pRec->u.nZero;
  67261. }
  67262. }
  67263. nData += len;
  67264. testcase( serial_type==127 );
  67265. testcase( serial_type==128 );
  67266. nHdr += serial_type<=127 ? 1 : sqlite3VarintLen(serial_type);
  67267. }while( (--pRec)>=pData0 );
  67268. /* Add the initial header varint and total the size */
  67269. testcase( nHdr==126 );
  67270. testcase( nHdr==127 );
  67271. if( nHdr<=126 ){
  67272. /* The common case */
  67273. nHdr += 1;
  67274. }else{
  67275. /* Rare case of a really large header */
  67276. nVarint = sqlite3VarintLen(nHdr);
  67277. nHdr += nVarint;
  67278. if( nVarint<sqlite3VarintLen(nHdr) ) nHdr++;
  67279. }
  67280. nByte = nHdr+nData;
  67281. if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  67282. goto too_big;
  67283. }
  67284. /* Make sure the output register has a buffer large enough to store
  67285. ** the new record. The output register (pOp->p3) is not allowed to
  67286. ** be one of the input registers (because the following call to
  67287. ** sqlite3VdbeMemClearAndResize() could clobber the value before it is used).
  67288. */
  67289. if( sqlite3VdbeMemClearAndResize(pOut, (int)nByte) ){
  67290. goto no_mem;
  67291. }
  67292. zNewRecord = (u8 *)pOut->z;
  67293. /* Write the record */
  67294. i = putVarint32(zNewRecord, nHdr);
  67295. j = nHdr;
  67296. assert( pData0<=pLast );
  67297. pRec = pData0;
  67298. do{
  67299. serial_type = pRec->uTemp;
  67300. i += putVarint32(&zNewRecord[i], serial_type); /* serial type */
  67301. j += sqlite3VdbeSerialPut(&zNewRecord[j], pRec, serial_type); /* content */
  67302. }while( (++pRec)<=pLast );
  67303. assert( i==nHdr );
  67304. assert( j==nByte );
  67305. assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
  67306. pOut->n = (int)nByte;
  67307. pOut->flags = MEM_Blob;
  67308. if( nZero ){
  67309. pOut->u.nZero = nZero;
  67310. pOut->flags |= MEM_Zero;
  67311. }
  67312. pOut->enc = SQLITE_UTF8; /* In case the blob is ever converted to text */
  67313. REGISTER_TRACE(pOp->p3, pOut);
  67314. UPDATE_MAX_BLOBSIZE(pOut);
  67315. break;
  67316. }
  67317. /* Opcode: Count P1 P2 * * *
  67318. ** Synopsis: r[P2]=count()
  67319. **
  67320. ** Store the number of entries (an integer value) in the table or index
  67321. ** opened by cursor P1 in register P2
  67322. */
  67323. #ifndef SQLITE_OMIT_BTREECOUNT
  67324. case OP_Count: { /* out2-prerelease */
  67325. i64 nEntry;
  67326. BtCursor *pCrsr;
  67327. pCrsr = p->apCsr[pOp->p1]->pCursor;
  67328. assert( pCrsr );
  67329. nEntry = 0; /* Not needed. Only used to silence a warning. */
  67330. rc = sqlite3BtreeCount(pCrsr, &nEntry);
  67331. pOut->u.i = nEntry;
  67332. break;
  67333. }
  67334. #endif
  67335. /* Opcode: Savepoint P1 * * P4 *
  67336. **
  67337. ** Open, release or rollback the savepoint named by parameter P4, depending
  67338. ** on the value of P1. To open a new savepoint, P1==0. To release (commit) an
  67339. ** existing savepoint, P1==1, or to rollback an existing savepoint P1==2.
  67340. */
  67341. case OP_Savepoint: {
  67342. int p1; /* Value of P1 operand */
  67343. char *zName; /* Name of savepoint */
  67344. int nName;
  67345. Savepoint *pNew;
  67346. Savepoint *pSavepoint;
  67347. Savepoint *pTmp;
  67348. int iSavepoint;
  67349. int ii;
  67350. p1 = pOp->p1;
  67351. zName = pOp->p4.z;
  67352. /* Assert that the p1 parameter is valid. Also that if there is no open
  67353. ** transaction, then there cannot be any savepoints.
  67354. */
  67355. assert( db->pSavepoint==0 || db->autoCommit==0 );
  67356. assert( p1==SAVEPOINT_BEGIN||p1==SAVEPOINT_RELEASE||p1==SAVEPOINT_ROLLBACK );
  67357. assert( db->pSavepoint || db->isTransactionSavepoint==0 );
  67358. assert( checkSavepointCount(db) );
  67359. assert( p->bIsReader );
  67360. if( p1==SAVEPOINT_BEGIN ){
  67361. if( db->nVdbeWrite>0 ){
  67362. /* A new savepoint cannot be created if there are active write
  67363. ** statements (i.e. open read/write incremental blob handles).
  67364. */
  67365. sqlite3SetString(&p->zErrMsg, db, "cannot open savepoint - "
  67366. "SQL statements in progress");
  67367. rc = SQLITE_BUSY;
  67368. }else{
  67369. nName = sqlite3Strlen30(zName);
  67370. #ifndef SQLITE_OMIT_VIRTUALTABLE
  67371. /* This call is Ok even if this savepoint is actually a transaction
  67372. ** savepoint (and therefore should not prompt xSavepoint()) callbacks.
  67373. ** If this is a transaction savepoint being opened, it is guaranteed
  67374. ** that the db->aVTrans[] array is empty. */
  67375. assert( db->autoCommit==0 || db->nVTrans==0 );
  67376. rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN,
  67377. db->nStatement+db->nSavepoint);
  67378. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  67379. #endif
  67380. /* Create a new savepoint structure. */
  67381. pNew = sqlite3DbMallocRaw(db, sizeof(Savepoint)+nName+1);
  67382. if( pNew ){
  67383. pNew->zName = (char *)&pNew[1];
  67384. memcpy(pNew->zName, zName, nName+1);
  67385. /* If there is no open transaction, then mark this as a special
  67386. ** "transaction savepoint". */
  67387. if( db->autoCommit ){
  67388. db->autoCommit = 0;
  67389. db->isTransactionSavepoint = 1;
  67390. }else{
  67391. db->nSavepoint++;
  67392. }
  67393. /* Link the new savepoint into the database handle's list. */
  67394. pNew->pNext = db->pSavepoint;
  67395. db->pSavepoint = pNew;
  67396. pNew->nDeferredCons = db->nDeferredCons;
  67397. pNew->nDeferredImmCons = db->nDeferredImmCons;
  67398. }
  67399. }
  67400. }else{
  67401. iSavepoint = 0;
  67402. /* Find the named savepoint. If there is no such savepoint, then an
  67403. ** an error is returned to the user. */
  67404. for(
  67405. pSavepoint = db->pSavepoint;
  67406. pSavepoint && sqlite3StrICmp(pSavepoint->zName, zName);
  67407. pSavepoint = pSavepoint->pNext
  67408. ){
  67409. iSavepoint++;
  67410. }
  67411. if( !pSavepoint ){
  67412. sqlite3SetString(&p->zErrMsg, db, "no such savepoint: %s", zName);
  67413. rc = SQLITE_ERROR;
  67414. }else if( db->nVdbeWrite>0 && p1==SAVEPOINT_RELEASE ){
  67415. /* It is not possible to release (commit) a savepoint if there are
  67416. ** active write statements.
  67417. */
  67418. sqlite3SetString(&p->zErrMsg, db,
  67419. "cannot release savepoint - SQL statements in progress"
  67420. );
  67421. rc = SQLITE_BUSY;
  67422. }else{
  67423. /* Determine whether or not this is a transaction savepoint. If so,
  67424. ** and this is a RELEASE command, then the current transaction
  67425. ** is committed.
  67426. */
  67427. int isTransaction = pSavepoint->pNext==0 && db->isTransactionSavepoint;
  67428. if( isTransaction && p1==SAVEPOINT_RELEASE ){
  67429. if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
  67430. goto vdbe_return;
  67431. }
  67432. db->autoCommit = 1;
  67433. if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
  67434. p->pc = pc;
  67435. db->autoCommit = 0;
  67436. p->rc = rc = SQLITE_BUSY;
  67437. goto vdbe_return;
  67438. }
  67439. db->isTransactionSavepoint = 0;
  67440. rc = p->rc;
  67441. }else{
  67442. iSavepoint = db->nSavepoint - iSavepoint - 1;
  67443. if( p1==SAVEPOINT_ROLLBACK ){
  67444. for(ii=0; ii<db->nDb; ii++){
  67445. sqlite3BtreeTripAllCursors(db->aDb[ii].pBt, SQLITE_ABORT);
  67446. }
  67447. }
  67448. for(ii=0; ii<db->nDb; ii++){
  67449. rc = sqlite3BtreeSavepoint(db->aDb[ii].pBt, p1, iSavepoint);
  67450. if( rc!=SQLITE_OK ){
  67451. goto abort_due_to_error;
  67452. }
  67453. }
  67454. if( p1==SAVEPOINT_ROLLBACK && (db->flags&SQLITE_InternChanges)!=0 ){
  67455. sqlite3ExpirePreparedStatements(db);
  67456. sqlite3ResetAllSchemasOfConnection(db);
  67457. db->flags = (db->flags | SQLITE_InternChanges);
  67458. }
  67459. }
  67460. /* Regardless of whether this is a RELEASE or ROLLBACK, destroy all
  67461. ** savepoints nested inside of the savepoint being operated on. */
  67462. while( db->pSavepoint!=pSavepoint ){
  67463. pTmp = db->pSavepoint;
  67464. db->pSavepoint = pTmp->pNext;
  67465. sqlite3DbFree(db, pTmp);
  67466. db->nSavepoint--;
  67467. }
  67468. /* If it is a RELEASE, then destroy the savepoint being operated on
  67469. ** too. If it is a ROLLBACK TO, then set the number of deferred
  67470. ** constraint violations present in the database to the value stored
  67471. ** when the savepoint was created. */
  67472. if( p1==SAVEPOINT_RELEASE ){
  67473. assert( pSavepoint==db->pSavepoint );
  67474. db->pSavepoint = pSavepoint->pNext;
  67475. sqlite3DbFree(db, pSavepoint);
  67476. if( !isTransaction ){
  67477. db->nSavepoint--;
  67478. }
  67479. }else{
  67480. db->nDeferredCons = pSavepoint->nDeferredCons;
  67481. db->nDeferredImmCons = pSavepoint->nDeferredImmCons;
  67482. }
  67483. if( !isTransaction ){
  67484. rc = sqlite3VtabSavepoint(db, p1, iSavepoint);
  67485. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  67486. }
  67487. }
  67488. }
  67489. break;
  67490. }
  67491. /* Opcode: AutoCommit P1 P2 * * *
  67492. **
  67493. ** Set the database auto-commit flag to P1 (1 or 0). If P2 is true, roll
  67494. ** back any currently active btree transactions. If there are any active
  67495. ** VMs (apart from this one), then a ROLLBACK fails. A COMMIT fails if
  67496. ** there are active writing VMs or active VMs that use shared cache.
  67497. **
  67498. ** This instruction causes the VM to halt.
  67499. */
  67500. case OP_AutoCommit: {
  67501. int desiredAutoCommit;
  67502. int iRollback;
  67503. int turnOnAC;
  67504. desiredAutoCommit = pOp->p1;
  67505. iRollback = pOp->p2;
  67506. turnOnAC = desiredAutoCommit && !db->autoCommit;
  67507. assert( desiredAutoCommit==1 || desiredAutoCommit==0 );
  67508. assert( desiredAutoCommit==1 || iRollback==0 );
  67509. assert( db->nVdbeActive>0 ); /* At least this one VM is active */
  67510. assert( p->bIsReader );
  67511. #if 0
  67512. if( turnOnAC && iRollback && db->nVdbeActive>1 ){
  67513. /* If this instruction implements a ROLLBACK and other VMs are
  67514. ** still running, and a transaction is active, return an error indicating
  67515. ** that the other VMs must complete first.
  67516. */
  67517. sqlite3SetString(&p->zErrMsg, db, "cannot rollback transaction - "
  67518. "SQL statements in progress");
  67519. rc = SQLITE_BUSY;
  67520. }else
  67521. #endif
  67522. if( turnOnAC && !iRollback && db->nVdbeWrite>0 ){
  67523. /* If this instruction implements a COMMIT and other VMs are writing
  67524. ** return an error indicating that the other VMs must complete first.
  67525. */
  67526. sqlite3SetString(&p->zErrMsg, db, "cannot commit transaction - "
  67527. "SQL statements in progress");
  67528. rc = SQLITE_BUSY;
  67529. }else if( desiredAutoCommit!=db->autoCommit ){
  67530. if( iRollback ){
  67531. assert( desiredAutoCommit==1 );
  67532. sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
  67533. db->autoCommit = 1;
  67534. }else if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
  67535. goto vdbe_return;
  67536. }else{
  67537. db->autoCommit = (u8)desiredAutoCommit;
  67538. if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
  67539. p->pc = pc;
  67540. db->autoCommit = (u8)(1-desiredAutoCommit);
  67541. p->rc = rc = SQLITE_BUSY;
  67542. goto vdbe_return;
  67543. }
  67544. }
  67545. assert( db->nStatement==0 );
  67546. sqlite3CloseSavepoints(db);
  67547. if( p->rc==SQLITE_OK ){
  67548. rc = SQLITE_DONE;
  67549. }else{
  67550. rc = SQLITE_ERROR;
  67551. }
  67552. goto vdbe_return;
  67553. }else{
  67554. sqlite3SetString(&p->zErrMsg, db,
  67555. (!desiredAutoCommit)?"cannot start a transaction within a transaction":(
  67556. (iRollback)?"cannot rollback - no transaction is active":
  67557. "cannot commit - no transaction is active"));
  67558. rc = SQLITE_ERROR;
  67559. }
  67560. break;
  67561. }
  67562. /* Opcode: Transaction P1 P2 P3 P4 P5
  67563. **
  67564. ** Begin a transaction on database P1 if a transaction is not already
  67565. ** active.
  67566. ** If P2 is non-zero, then a write-transaction is started, or if a
  67567. ** read-transaction is already active, it is upgraded to a write-transaction.
  67568. ** If P2 is zero, then a read-transaction is started.
  67569. **
  67570. ** P1 is the index of the database file on which the transaction is
  67571. ** started. Index 0 is the main database file and index 1 is the
  67572. ** file used for temporary tables. Indices of 2 or more are used for
  67573. ** attached databases.
  67574. **
  67575. ** If a write-transaction is started and the Vdbe.usesStmtJournal flag is
  67576. ** true (this flag is set if the Vdbe may modify more than one row and may
  67577. ** throw an ABORT exception), a statement transaction may also be opened.
  67578. ** More specifically, a statement transaction is opened iff the database
  67579. ** connection is currently not in autocommit mode, or if there are other
  67580. ** active statements. A statement transaction allows the changes made by this
  67581. ** VDBE to be rolled back after an error without having to roll back the
  67582. ** entire transaction. If no error is encountered, the statement transaction
  67583. ** will automatically commit when the VDBE halts.
  67584. **
  67585. ** If P5!=0 then this opcode also checks the schema cookie against P3
  67586. ** and the schema generation counter against P4.
  67587. ** The cookie changes its value whenever the database schema changes.
  67588. ** This operation is used to detect when that the cookie has changed
  67589. ** and that the current process needs to reread the schema. If the schema
  67590. ** cookie in P3 differs from the schema cookie in the database header or
  67591. ** if the schema generation counter in P4 differs from the current
  67592. ** generation counter, then an SQLITE_SCHEMA error is raised and execution
  67593. ** halts. The sqlite3_step() wrapper function might then reprepare the
  67594. ** statement and rerun it from the beginning.
  67595. */
  67596. case OP_Transaction: {
  67597. Btree *pBt;
  67598. int iMeta;
  67599. int iGen;
  67600. assert( p->bIsReader );
  67601. assert( p->readOnly==0 || pOp->p2==0 );
  67602. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  67603. assert( DbMaskTest(p->btreeMask, pOp->p1) );
  67604. if( pOp->p2 && (db->flags & SQLITE_QueryOnly)!=0 ){
  67605. rc = SQLITE_READONLY;
  67606. goto abort_due_to_error;
  67607. }
  67608. pBt = db->aDb[pOp->p1].pBt;
  67609. if( pBt ){
  67610. rc = sqlite3BtreeBeginTrans(pBt, pOp->p2);
  67611. if( rc==SQLITE_BUSY ){
  67612. p->pc = pc;
  67613. p->rc = rc = SQLITE_BUSY;
  67614. goto vdbe_return;
  67615. }
  67616. if( rc!=SQLITE_OK ){
  67617. goto abort_due_to_error;
  67618. }
  67619. if( pOp->p2 && p->usesStmtJournal
  67620. && (db->autoCommit==0 || db->nVdbeRead>1)
  67621. ){
  67622. assert( sqlite3BtreeIsInTrans(pBt) );
  67623. if( p->iStatement==0 ){
  67624. assert( db->nStatement>=0 && db->nSavepoint>=0 );
  67625. db->nStatement++;
  67626. p->iStatement = db->nSavepoint + db->nStatement;
  67627. }
  67628. rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN, p->iStatement-1);
  67629. if( rc==SQLITE_OK ){
  67630. rc = sqlite3BtreeBeginStmt(pBt, p->iStatement);
  67631. }
  67632. /* Store the current value of the database handles deferred constraint
  67633. ** counter. If the statement transaction needs to be rolled back,
  67634. ** the value of this counter needs to be restored too. */
  67635. p->nStmtDefCons = db->nDeferredCons;
  67636. p->nStmtDefImmCons = db->nDeferredImmCons;
  67637. }
  67638. /* Gather the schema version number for checking */
  67639. sqlite3BtreeGetMeta(pBt, BTREE_SCHEMA_VERSION, (u32 *)&iMeta);
  67640. iGen = db->aDb[pOp->p1].pSchema->iGeneration;
  67641. }else{
  67642. iGen = iMeta = 0;
  67643. }
  67644. assert( pOp->p5==0 || pOp->p4type==P4_INT32 );
  67645. if( pOp->p5 && (iMeta!=pOp->p3 || iGen!=pOp->p4.i) ){
  67646. sqlite3DbFree(db, p->zErrMsg);
  67647. p->zErrMsg = sqlite3DbStrDup(db, "database schema has changed");
  67648. /* If the schema-cookie from the database file matches the cookie
  67649. ** stored with the in-memory representation of the schema, do
  67650. ** not reload the schema from the database file.
  67651. **
  67652. ** If virtual-tables are in use, this is not just an optimization.
  67653. ** Often, v-tables store their data in other SQLite tables, which
  67654. ** are queried from within xNext() and other v-table methods using
  67655. ** prepared queries. If such a query is out-of-date, we do not want to
  67656. ** discard the database schema, as the user code implementing the
  67657. ** v-table would have to be ready for the sqlite3_vtab structure itself
  67658. ** to be invalidated whenever sqlite3_step() is called from within
  67659. ** a v-table method.
  67660. */
  67661. if( db->aDb[pOp->p1].pSchema->schema_cookie!=iMeta ){
  67662. sqlite3ResetOneSchema(db, pOp->p1);
  67663. }
  67664. p->expired = 1;
  67665. rc = SQLITE_SCHEMA;
  67666. }
  67667. break;
  67668. }
  67669. /* Opcode: ReadCookie P1 P2 P3 * *
  67670. **
  67671. ** Read cookie number P3 from database P1 and write it into register P2.
  67672. ** P3==1 is the schema version. P3==2 is the database format.
  67673. ** P3==3 is the recommended pager cache size, and so forth. P1==0 is
  67674. ** the main database file and P1==1 is the database file used to store
  67675. ** temporary tables.
  67676. **
  67677. ** There must be a read-lock on the database (either a transaction
  67678. ** must be started or there must be an open cursor) before
  67679. ** executing this instruction.
  67680. */
  67681. case OP_ReadCookie: { /* out2-prerelease */
  67682. int iMeta;
  67683. int iDb;
  67684. int iCookie;
  67685. assert( p->bIsReader );
  67686. iDb = pOp->p1;
  67687. iCookie = pOp->p3;
  67688. assert( pOp->p3<SQLITE_N_BTREE_META );
  67689. assert( iDb>=0 && iDb<db->nDb );
  67690. assert( db->aDb[iDb].pBt!=0 );
  67691. assert( DbMaskTest(p->btreeMask, iDb) );
  67692. sqlite3BtreeGetMeta(db->aDb[iDb].pBt, iCookie, (u32 *)&iMeta);
  67693. pOut->u.i = iMeta;
  67694. break;
  67695. }
  67696. /* Opcode: SetCookie P1 P2 P3 * *
  67697. **
  67698. ** Write the content of register P3 (interpreted as an integer)
  67699. ** into cookie number P2 of database P1. P2==1 is the schema version.
  67700. ** P2==2 is the database format. P2==3 is the recommended pager cache
  67701. ** size, and so forth. P1==0 is the main database file and P1==1 is the
  67702. ** database file used to store temporary tables.
  67703. **
  67704. ** A transaction must be started before executing this opcode.
  67705. */
  67706. case OP_SetCookie: { /* in3 */
  67707. Db *pDb;
  67708. assert( pOp->p2<SQLITE_N_BTREE_META );
  67709. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  67710. assert( DbMaskTest(p->btreeMask, pOp->p1) );
  67711. assert( p->readOnly==0 );
  67712. pDb = &db->aDb[pOp->p1];
  67713. assert( pDb->pBt!=0 );
  67714. assert( sqlite3SchemaMutexHeld(db, pOp->p1, 0) );
  67715. pIn3 = &aMem[pOp->p3];
  67716. sqlite3VdbeMemIntegerify(pIn3);
  67717. /* See note about index shifting on OP_ReadCookie */
  67718. rc = sqlite3BtreeUpdateMeta(pDb->pBt, pOp->p2, (int)pIn3->u.i);
  67719. if( pOp->p2==BTREE_SCHEMA_VERSION ){
  67720. /* When the schema cookie changes, record the new cookie internally */
  67721. pDb->pSchema->schema_cookie = (int)pIn3->u.i;
  67722. db->flags |= SQLITE_InternChanges;
  67723. }else if( pOp->p2==BTREE_FILE_FORMAT ){
  67724. /* Record changes in the file format */
  67725. pDb->pSchema->file_format = (u8)pIn3->u.i;
  67726. }
  67727. if( pOp->p1==1 ){
  67728. /* Invalidate all prepared statements whenever the TEMP database
  67729. ** schema is changed. Ticket #1644 */
  67730. sqlite3ExpirePreparedStatements(db);
  67731. p->expired = 0;
  67732. }
  67733. break;
  67734. }
  67735. /* Opcode: OpenRead P1 P2 P3 P4 P5
  67736. ** Synopsis: root=P2 iDb=P3
  67737. **
  67738. ** Open a read-only cursor for the database table whose root page is
  67739. ** P2 in a database file. The database file is determined by P3.
  67740. ** P3==0 means the main database, P3==1 means the database used for
  67741. ** temporary tables, and P3>1 means used the corresponding attached
  67742. ** database. Give the new cursor an identifier of P1. The P1
  67743. ** values need not be contiguous but all P1 values should be small integers.
  67744. ** It is an error for P1 to be negative.
  67745. **
  67746. ** If P5!=0 then use the content of register P2 as the root page, not
  67747. ** the value of P2 itself.
  67748. **
  67749. ** There will be a read lock on the database whenever there is an
  67750. ** open cursor. If the database was unlocked prior to this instruction
  67751. ** then a read lock is acquired as part of this instruction. A read
  67752. ** lock allows other processes to read the database but prohibits
  67753. ** any other process from modifying the database. The read lock is
  67754. ** released when all cursors are closed. If this instruction attempts
  67755. ** to get a read lock but fails, the script terminates with an
  67756. ** SQLITE_BUSY error code.
  67757. **
  67758. ** The P4 value may be either an integer (P4_INT32) or a pointer to
  67759. ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
  67760. ** structure, then said structure defines the content and collating
  67761. ** sequence of the index being opened. Otherwise, if P4 is an integer
  67762. ** value, it is set to the number of columns in the table.
  67763. **
  67764. ** See also: OpenWrite, ReopenIdx
  67765. */
  67766. /* Opcode: ReopenIdx P1 P2 P3 P4 P5
  67767. ** Synopsis: root=P2 iDb=P3
  67768. **
  67769. ** The ReopenIdx opcode works exactly like ReadOpen except that it first
  67770. ** checks to see if the cursor on P1 is already open with a root page
  67771. ** number of P2 and if it is this opcode becomes a no-op. In other words,
  67772. ** if the cursor is already open, do not reopen it.
  67773. **
  67774. ** The ReopenIdx opcode may only be used with P5==0 and with P4 being
  67775. ** a P4_KEYINFO object. Furthermore, the P3 value must be the same as
  67776. ** every other ReopenIdx or OpenRead for the same cursor number.
  67777. **
  67778. ** See the OpenRead opcode documentation for additional information.
  67779. */
  67780. /* Opcode: OpenWrite P1 P2 P3 P4 P5
  67781. ** Synopsis: root=P2 iDb=P3
  67782. **
  67783. ** Open a read/write cursor named P1 on the table or index whose root
  67784. ** page is P2. Or if P5!=0 use the content of register P2 to find the
  67785. ** root page.
  67786. **
  67787. ** The P4 value may be either an integer (P4_INT32) or a pointer to
  67788. ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
  67789. ** structure, then said structure defines the content and collating
  67790. ** sequence of the index being opened. Otherwise, if P4 is an integer
  67791. ** value, it is set to the number of columns in the table, or to the
  67792. ** largest index of any column of the table that is actually used.
  67793. **
  67794. ** This instruction works just like OpenRead except that it opens the cursor
  67795. ** in read/write mode. For a given table, there can be one or more read-only
  67796. ** cursors or a single read/write cursor but not both.
  67797. **
  67798. ** See also OpenRead.
  67799. */
  67800. case OP_ReopenIdx: {
  67801. VdbeCursor *pCur;
  67802. assert( pOp->p5==0 );
  67803. assert( pOp->p4type==P4_KEYINFO );
  67804. pCur = p->apCsr[pOp->p1];
  67805. if( pCur && pCur->pgnoRoot==(u32)pOp->p2 ){
  67806. assert( pCur->iDb==pOp->p3 ); /* Guaranteed by the code generator */
  67807. break;
  67808. }
  67809. /* If the cursor is not currently open or is open on a different
  67810. ** index, then fall through into OP_OpenRead to force a reopen */
  67811. }
  67812. case OP_OpenRead:
  67813. case OP_OpenWrite: {
  67814. int nField;
  67815. KeyInfo *pKeyInfo;
  67816. int p2;
  67817. int iDb;
  67818. int wrFlag;
  67819. Btree *pX;
  67820. VdbeCursor *pCur;
  67821. Db *pDb;
  67822. assert( (pOp->p5&(OPFLAG_P2ISREG|OPFLAG_BULKCSR))==pOp->p5 );
  67823. assert( pOp->opcode==OP_OpenWrite || pOp->p5==0 );
  67824. assert( p->bIsReader );
  67825. assert( pOp->opcode==OP_OpenRead || pOp->opcode==OP_ReopenIdx
  67826. || p->readOnly==0 );
  67827. if( p->expired ){
  67828. rc = SQLITE_ABORT;
  67829. break;
  67830. }
  67831. nField = 0;
  67832. pKeyInfo = 0;
  67833. p2 = pOp->p2;
  67834. iDb = pOp->p3;
  67835. assert( iDb>=0 && iDb<db->nDb );
  67836. assert( DbMaskTest(p->btreeMask, iDb) );
  67837. pDb = &db->aDb[iDb];
  67838. pX = pDb->pBt;
  67839. assert( pX!=0 );
  67840. if( pOp->opcode==OP_OpenWrite ){
  67841. wrFlag = 1;
  67842. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  67843. if( pDb->pSchema->file_format < p->minWriteFileFormat ){
  67844. p->minWriteFileFormat = pDb->pSchema->file_format;
  67845. }
  67846. }else{
  67847. wrFlag = 0;
  67848. }
  67849. if( pOp->p5 & OPFLAG_P2ISREG ){
  67850. assert( p2>0 );
  67851. assert( p2<=(p->nMem-p->nCursor) );
  67852. pIn2 = &aMem[p2];
  67853. assert( memIsValid(pIn2) );
  67854. assert( (pIn2->flags & MEM_Int)!=0 );
  67855. sqlite3VdbeMemIntegerify(pIn2);
  67856. p2 = (int)pIn2->u.i;
  67857. /* The p2 value always comes from a prior OP_CreateTable opcode and
  67858. ** that opcode will always set the p2 value to 2 or more or else fail.
  67859. ** If there were a failure, the prepared statement would have halted
  67860. ** before reaching this instruction. */
  67861. if( NEVER(p2<2) ) {
  67862. rc = SQLITE_CORRUPT_BKPT;
  67863. goto abort_due_to_error;
  67864. }
  67865. }
  67866. if( pOp->p4type==P4_KEYINFO ){
  67867. pKeyInfo = pOp->p4.pKeyInfo;
  67868. assert( pKeyInfo->enc==ENC(db) );
  67869. assert( pKeyInfo->db==db );
  67870. nField = pKeyInfo->nField+pKeyInfo->nXField;
  67871. }else if( pOp->p4type==P4_INT32 ){
  67872. nField = pOp->p4.i;
  67873. }
  67874. assert( pOp->p1>=0 );
  67875. assert( nField>=0 );
  67876. testcase( nField==0 ); /* Table with INTEGER PRIMARY KEY and nothing else */
  67877. pCur = allocateCursor(p, pOp->p1, nField, iDb, 1);
  67878. if( pCur==0 ) goto no_mem;
  67879. pCur->nullRow = 1;
  67880. pCur->isOrdered = 1;
  67881. pCur->pgnoRoot = p2;
  67882. rc = sqlite3BtreeCursor(pX, p2, wrFlag, pKeyInfo, pCur->pCursor);
  67883. pCur->pKeyInfo = pKeyInfo;
  67884. assert( OPFLAG_BULKCSR==BTREE_BULKLOAD );
  67885. sqlite3BtreeCursorHints(pCur->pCursor, (pOp->p5 & OPFLAG_BULKCSR));
  67886. /* Set the VdbeCursor.isTable variable. Previous versions of
  67887. ** SQLite used to check if the root-page flags were sane at this point
  67888. ** and report database corruption if they were not, but this check has
  67889. ** since moved into the btree layer. */
  67890. pCur->isTable = pOp->p4type!=P4_KEYINFO;
  67891. break;
  67892. }
  67893. /* Opcode: OpenEphemeral P1 P2 * P4 P5
  67894. ** Synopsis: nColumn=P2
  67895. **
  67896. ** Open a new cursor P1 to a transient table.
  67897. ** The cursor is always opened read/write even if
  67898. ** the main database is read-only. The ephemeral
  67899. ** table is deleted automatically when the cursor is closed.
  67900. **
  67901. ** P2 is the number of columns in the ephemeral table.
  67902. ** The cursor points to a BTree table if P4==0 and to a BTree index
  67903. ** if P4 is not 0. If P4 is not NULL, it points to a KeyInfo structure
  67904. ** that defines the format of keys in the index.
  67905. **
  67906. ** The P5 parameter can be a mask of the BTREE_* flags defined
  67907. ** in btree.h. These flags control aspects of the operation of
  67908. ** the btree. The BTREE_OMIT_JOURNAL and BTREE_SINGLE flags are
  67909. ** added automatically.
  67910. */
  67911. /* Opcode: OpenAutoindex P1 P2 * P4 *
  67912. ** Synopsis: nColumn=P2
  67913. **
  67914. ** This opcode works the same as OP_OpenEphemeral. It has a
  67915. ** different name to distinguish its use. Tables created using
  67916. ** by this opcode will be used for automatically created transient
  67917. ** indices in joins.
  67918. */
  67919. case OP_OpenAutoindex:
  67920. case OP_OpenEphemeral: {
  67921. VdbeCursor *pCx;
  67922. KeyInfo *pKeyInfo;
  67923. static const int vfsFlags =
  67924. SQLITE_OPEN_READWRITE |
  67925. SQLITE_OPEN_CREATE |
  67926. SQLITE_OPEN_EXCLUSIVE |
  67927. SQLITE_OPEN_DELETEONCLOSE |
  67928. SQLITE_OPEN_TRANSIENT_DB;
  67929. assert( pOp->p1>=0 );
  67930. assert( pOp->p2>=0 );
  67931. pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, 1);
  67932. if( pCx==0 ) goto no_mem;
  67933. pCx->nullRow = 1;
  67934. pCx->isEphemeral = 1;
  67935. rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pCx->pBt,
  67936. BTREE_OMIT_JOURNAL | BTREE_SINGLE | pOp->p5, vfsFlags);
  67937. if( rc==SQLITE_OK ){
  67938. rc = sqlite3BtreeBeginTrans(pCx->pBt, 1);
  67939. }
  67940. if( rc==SQLITE_OK ){
  67941. /* If a transient index is required, create it by calling
  67942. ** sqlite3BtreeCreateTable() with the BTREE_BLOBKEY flag before
  67943. ** opening it. If a transient table is required, just use the
  67944. ** automatically created table with root-page 1 (an BLOB_INTKEY table).
  67945. */
  67946. if( (pKeyInfo = pOp->p4.pKeyInfo)!=0 ){
  67947. int pgno;
  67948. assert( pOp->p4type==P4_KEYINFO );
  67949. rc = sqlite3BtreeCreateTable(pCx->pBt, &pgno, BTREE_BLOBKEY | pOp->p5);
  67950. if( rc==SQLITE_OK ){
  67951. assert( pgno==MASTER_ROOT+1 );
  67952. assert( pKeyInfo->db==db );
  67953. assert( pKeyInfo->enc==ENC(db) );
  67954. pCx->pKeyInfo = pKeyInfo;
  67955. rc = sqlite3BtreeCursor(pCx->pBt, pgno, 1, pKeyInfo, pCx->pCursor);
  67956. }
  67957. pCx->isTable = 0;
  67958. }else{
  67959. rc = sqlite3BtreeCursor(pCx->pBt, MASTER_ROOT, 1, 0, pCx->pCursor);
  67960. pCx->isTable = 1;
  67961. }
  67962. }
  67963. pCx->isOrdered = (pOp->p5!=BTREE_UNORDERED);
  67964. break;
  67965. }
  67966. /* Opcode: SorterOpen P1 P2 P3 P4 *
  67967. **
  67968. ** This opcode works like OP_OpenEphemeral except that it opens
  67969. ** a transient index that is specifically designed to sort large
  67970. ** tables using an external merge-sort algorithm.
  67971. **
  67972. ** If argument P3 is non-zero, then it indicates that the sorter may
  67973. ** assume that a stable sort considering the first P3 fields of each
  67974. ** key is sufficient to produce the required results.
  67975. */
  67976. case OP_SorterOpen: {
  67977. VdbeCursor *pCx;
  67978. assert( pOp->p1>=0 );
  67979. assert( pOp->p2>=0 );
  67980. pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, 1);
  67981. if( pCx==0 ) goto no_mem;
  67982. pCx->pKeyInfo = pOp->p4.pKeyInfo;
  67983. assert( pCx->pKeyInfo->db==db );
  67984. assert( pCx->pKeyInfo->enc==ENC(db) );
  67985. rc = sqlite3VdbeSorterInit(db, pOp->p3, pCx);
  67986. break;
  67987. }
  67988. /* Opcode: SequenceTest P1 P2 * * *
  67989. ** Synopsis: if( cursor[P1].ctr++ ) pc = P2
  67990. **
  67991. ** P1 is a sorter cursor. If the sequence counter is currently zero, jump
  67992. ** to P2. Regardless of whether or not the jump is taken, increment the
  67993. ** the sequence value.
  67994. */
  67995. case OP_SequenceTest: {
  67996. VdbeCursor *pC;
  67997. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  67998. pC = p->apCsr[pOp->p1];
  67999. assert( pC->pSorter );
  68000. if( (pC->seqCount++)==0 ){
  68001. pc = pOp->p2 - 1;
  68002. }
  68003. break;
  68004. }
  68005. /* Opcode: OpenPseudo P1 P2 P3 * *
  68006. ** Synopsis: P3 columns in r[P2]
  68007. **
  68008. ** Open a new cursor that points to a fake table that contains a single
  68009. ** row of data. The content of that one row is the content of memory
  68010. ** register P2. In other words, cursor P1 becomes an alias for the
  68011. ** MEM_Blob content contained in register P2.
  68012. **
  68013. ** A pseudo-table created by this opcode is used to hold a single
  68014. ** row output from the sorter so that the row can be decomposed into
  68015. ** individual columns using the OP_Column opcode. The OP_Column opcode
  68016. ** is the only cursor opcode that works with a pseudo-table.
  68017. **
  68018. ** P3 is the number of fields in the records that will be stored by
  68019. ** the pseudo-table.
  68020. */
  68021. case OP_OpenPseudo: {
  68022. VdbeCursor *pCx;
  68023. assert( pOp->p1>=0 );
  68024. assert( pOp->p3>=0 );
  68025. pCx = allocateCursor(p, pOp->p1, pOp->p3, -1, 0);
  68026. if( pCx==0 ) goto no_mem;
  68027. pCx->nullRow = 1;
  68028. pCx->pseudoTableReg = pOp->p2;
  68029. pCx->isTable = 1;
  68030. assert( pOp->p5==0 );
  68031. break;
  68032. }
  68033. /* Opcode: Close P1 * * * *
  68034. **
  68035. ** Close a cursor previously opened as P1. If P1 is not
  68036. ** currently open, this instruction is a no-op.
  68037. */
  68038. case OP_Close: {
  68039. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  68040. sqlite3VdbeFreeCursor(p, p->apCsr[pOp->p1]);
  68041. p->apCsr[pOp->p1] = 0;
  68042. break;
  68043. }
  68044. /* Opcode: SeekGE P1 P2 P3 P4 *
  68045. ** Synopsis: key=r[P3@P4]
  68046. **
  68047. ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
  68048. ** use the value in register P3 as the key. If cursor P1 refers
  68049. ** to an SQL index, then P3 is the first in an array of P4 registers
  68050. ** that are used as an unpacked index key.
  68051. **
  68052. ** Reposition cursor P1 so that it points to the smallest entry that
  68053. ** is greater than or equal to the key value. If there are no records
  68054. ** greater than or equal to the key and P2 is not zero, then jump to P2.
  68055. **
  68056. ** This opcode leaves the cursor configured to move in forward order,
  68057. ** from the beginning toward the end. In other words, the cursor is
  68058. ** configured to use Next, not Prev.
  68059. **
  68060. ** See also: Found, NotFound, SeekLt, SeekGt, SeekLe
  68061. */
  68062. /* Opcode: SeekGT P1 P2 P3 P4 *
  68063. ** Synopsis: key=r[P3@P4]
  68064. **
  68065. ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
  68066. ** use the value in register P3 as a key. If cursor P1 refers
  68067. ** to an SQL index, then P3 is the first in an array of P4 registers
  68068. ** that are used as an unpacked index key.
  68069. **
  68070. ** Reposition cursor P1 so that it points to the smallest entry that
  68071. ** is greater than the key value. If there are no records greater than
  68072. ** the key and P2 is not zero, then jump to P2.
  68073. **
  68074. ** This opcode leaves the cursor configured to move in forward order,
  68075. ** from the beginning toward the end. In other words, the cursor is
  68076. ** configured to use Next, not Prev.
  68077. **
  68078. ** See also: Found, NotFound, SeekLt, SeekGe, SeekLe
  68079. */
  68080. /* Opcode: SeekLT P1 P2 P3 P4 *
  68081. ** Synopsis: key=r[P3@P4]
  68082. **
  68083. ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
  68084. ** use the value in register P3 as a key. If cursor P1 refers
  68085. ** to an SQL index, then P3 is the first in an array of P4 registers
  68086. ** that are used as an unpacked index key.
  68087. **
  68088. ** Reposition cursor P1 so that it points to the largest entry that
  68089. ** is less than the key value. If there are no records less than
  68090. ** the key and P2 is not zero, then jump to P2.
  68091. **
  68092. ** This opcode leaves the cursor configured to move in reverse order,
  68093. ** from the end toward the beginning. In other words, the cursor is
  68094. ** configured to use Prev, not Next.
  68095. **
  68096. ** See also: Found, NotFound, SeekGt, SeekGe, SeekLe
  68097. */
  68098. /* Opcode: SeekLE P1 P2 P3 P4 *
  68099. ** Synopsis: key=r[P3@P4]
  68100. **
  68101. ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
  68102. ** use the value in register P3 as a key. If cursor P1 refers
  68103. ** to an SQL index, then P3 is the first in an array of P4 registers
  68104. ** that are used as an unpacked index key.
  68105. **
  68106. ** Reposition cursor P1 so that it points to the largest entry that
  68107. ** is less than or equal to the key value. If there are no records
  68108. ** less than or equal to the key and P2 is not zero, then jump to P2.
  68109. **
  68110. ** This opcode leaves the cursor configured to move in reverse order,
  68111. ** from the end toward the beginning. In other words, the cursor is
  68112. ** configured to use Prev, not Next.
  68113. **
  68114. ** See also: Found, NotFound, SeekGt, SeekGe, SeekLt
  68115. */
  68116. case OP_SeekLT: /* jump, in3 */
  68117. case OP_SeekLE: /* jump, in3 */
  68118. case OP_SeekGE: /* jump, in3 */
  68119. case OP_SeekGT: { /* jump, in3 */
  68120. int res;
  68121. int oc;
  68122. VdbeCursor *pC;
  68123. UnpackedRecord r;
  68124. int nField;
  68125. i64 iKey; /* The rowid we are to seek to */
  68126. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  68127. assert( pOp->p2!=0 );
  68128. pC = p->apCsr[pOp->p1];
  68129. assert( pC!=0 );
  68130. assert( pC->pseudoTableReg==0 );
  68131. assert( OP_SeekLE == OP_SeekLT+1 );
  68132. assert( OP_SeekGE == OP_SeekLT+2 );
  68133. assert( OP_SeekGT == OP_SeekLT+3 );
  68134. assert( pC->isOrdered );
  68135. assert( pC->pCursor!=0 );
  68136. oc = pOp->opcode;
  68137. pC->nullRow = 0;
  68138. #ifdef SQLITE_DEBUG
  68139. pC->seekOp = pOp->opcode;
  68140. #endif
  68141. if( pC->isTable ){
  68142. /* The input value in P3 might be of any type: integer, real, string,
  68143. ** blob, or NULL. But it needs to be an integer before we can do
  68144. ** the seek, so convert it. */
  68145. pIn3 = &aMem[pOp->p3];
  68146. if( (pIn3->flags & (MEM_Int|MEM_Real|MEM_Str))==MEM_Str ){
  68147. applyNumericAffinity(pIn3, 0);
  68148. }
  68149. iKey = sqlite3VdbeIntValue(pIn3);
  68150. /* If the P3 value could not be converted into an integer without
  68151. ** loss of information, then special processing is required... */
  68152. if( (pIn3->flags & MEM_Int)==0 ){
  68153. if( (pIn3->flags & MEM_Real)==0 ){
  68154. /* If the P3 value cannot be converted into any kind of a number,
  68155. ** then the seek is not possible, so jump to P2 */
  68156. pc = pOp->p2 - 1; VdbeBranchTaken(1,2);
  68157. break;
  68158. }
  68159. /* If the approximation iKey is larger than the actual real search
  68160. ** term, substitute >= for > and < for <=. e.g. if the search term
  68161. ** is 4.9 and the integer approximation 5:
  68162. **
  68163. ** (x > 4.9) -> (x >= 5)
  68164. ** (x <= 4.9) -> (x < 5)
  68165. */
  68166. if( pIn3->u.r<(double)iKey ){
  68167. assert( OP_SeekGE==(OP_SeekGT-1) );
  68168. assert( OP_SeekLT==(OP_SeekLE-1) );
  68169. assert( (OP_SeekLE & 0x0001)==(OP_SeekGT & 0x0001) );
  68170. if( (oc & 0x0001)==(OP_SeekGT & 0x0001) ) oc--;
  68171. }
  68172. /* If the approximation iKey is smaller than the actual real search
  68173. ** term, substitute <= for < and > for >=. */
  68174. else if( pIn3->u.r>(double)iKey ){
  68175. assert( OP_SeekLE==(OP_SeekLT+1) );
  68176. assert( OP_SeekGT==(OP_SeekGE+1) );
  68177. assert( (OP_SeekLT & 0x0001)==(OP_SeekGE & 0x0001) );
  68178. if( (oc & 0x0001)==(OP_SeekLT & 0x0001) ) oc++;
  68179. }
  68180. }
  68181. rc = sqlite3BtreeMovetoUnpacked(pC->pCursor, 0, (u64)iKey, 0, &res);
  68182. pC->movetoTarget = iKey; /* Used by OP_Delete */
  68183. if( rc!=SQLITE_OK ){
  68184. goto abort_due_to_error;
  68185. }
  68186. }else{
  68187. nField = pOp->p4.i;
  68188. assert( pOp->p4type==P4_INT32 );
  68189. assert( nField>0 );
  68190. r.pKeyInfo = pC->pKeyInfo;
  68191. r.nField = (u16)nField;
  68192. /* The next line of code computes as follows, only faster:
  68193. ** if( oc==OP_SeekGT || oc==OP_SeekLE ){
  68194. ** r.default_rc = -1;
  68195. ** }else{
  68196. ** r.default_rc = +1;
  68197. ** }
  68198. */
  68199. r.default_rc = ((1 & (oc - OP_SeekLT)) ? -1 : +1);
  68200. assert( oc!=OP_SeekGT || r.default_rc==-1 );
  68201. assert( oc!=OP_SeekLE || r.default_rc==-1 );
  68202. assert( oc!=OP_SeekGE || r.default_rc==+1 );
  68203. assert( oc!=OP_SeekLT || r.default_rc==+1 );
  68204. r.aMem = &aMem[pOp->p3];
  68205. #ifdef SQLITE_DEBUG
  68206. { int i; for(i=0; i<r.nField; i++) assert( memIsValid(&r.aMem[i]) ); }
  68207. #endif
  68208. ExpandBlob(r.aMem);
  68209. rc = sqlite3BtreeMovetoUnpacked(pC->pCursor, &r, 0, 0, &res);
  68210. if( rc!=SQLITE_OK ){
  68211. goto abort_due_to_error;
  68212. }
  68213. }
  68214. pC->deferredMoveto = 0;
  68215. pC->cacheStatus = CACHE_STALE;
  68216. #ifdef SQLITE_TEST
  68217. sqlite3_search_count++;
  68218. #endif
  68219. if( oc>=OP_SeekGE ){ assert( oc==OP_SeekGE || oc==OP_SeekGT );
  68220. if( res<0 || (res==0 && oc==OP_SeekGT) ){
  68221. res = 0;
  68222. rc = sqlite3BtreeNext(pC->pCursor, &res);
  68223. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  68224. }else{
  68225. res = 0;
  68226. }
  68227. }else{
  68228. assert( oc==OP_SeekLT || oc==OP_SeekLE );
  68229. if( res>0 || (res==0 && oc==OP_SeekLT) ){
  68230. res = 0;
  68231. rc = sqlite3BtreePrevious(pC->pCursor, &res);
  68232. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  68233. }else{
  68234. /* res might be negative because the table is empty. Check to
  68235. ** see if this is the case.
  68236. */
  68237. res = sqlite3BtreeEof(pC->pCursor);
  68238. }
  68239. }
  68240. assert( pOp->p2>0 );
  68241. VdbeBranchTaken(res!=0,2);
  68242. if( res ){
  68243. pc = pOp->p2 - 1;
  68244. }
  68245. break;
  68246. }
  68247. /* Opcode: Seek P1 P2 * * *
  68248. ** Synopsis: intkey=r[P2]
  68249. **
  68250. ** P1 is an open table cursor and P2 is a rowid integer. Arrange
  68251. ** for P1 to move so that it points to the rowid given by P2.
  68252. **
  68253. ** This is actually a deferred seek. Nothing actually happens until
  68254. ** the cursor is used to read a record. That way, if no reads
  68255. ** occur, no unnecessary I/O happens.
  68256. */
  68257. case OP_Seek: { /* in2 */
  68258. VdbeCursor *pC;
  68259. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  68260. pC = p->apCsr[pOp->p1];
  68261. assert( pC!=0 );
  68262. assert( pC->pCursor!=0 );
  68263. assert( pC->isTable );
  68264. pC->nullRow = 0;
  68265. pIn2 = &aMem[pOp->p2];
  68266. pC->movetoTarget = sqlite3VdbeIntValue(pIn2);
  68267. pC->deferredMoveto = 1;
  68268. break;
  68269. }
  68270. /* Opcode: Found P1 P2 P3 P4 *
  68271. ** Synopsis: key=r[P3@P4]
  68272. **
  68273. ** If P4==0 then register P3 holds a blob constructed by MakeRecord. If
  68274. ** P4>0 then register P3 is the first of P4 registers that form an unpacked
  68275. ** record.
  68276. **
  68277. ** Cursor P1 is on an index btree. If the record identified by P3 and P4
  68278. ** is a prefix of any entry in P1 then a jump is made to P2 and
  68279. ** P1 is left pointing at the matching entry.
  68280. **
  68281. ** This operation leaves the cursor in a state where it can be
  68282. ** advanced in the forward direction. The Next instruction will work,
  68283. ** but not the Prev instruction.
  68284. **
  68285. ** See also: NotFound, NoConflict, NotExists. SeekGe
  68286. */
  68287. /* Opcode: NotFound P1 P2 P3 P4 *
  68288. ** Synopsis: key=r[P3@P4]
  68289. **
  68290. ** If P4==0 then register P3 holds a blob constructed by MakeRecord. If
  68291. ** P4>0 then register P3 is the first of P4 registers that form an unpacked
  68292. ** record.
  68293. **
  68294. ** Cursor P1 is on an index btree. If the record identified by P3 and P4
  68295. ** is not the prefix of any entry in P1 then a jump is made to P2. If P1
  68296. ** does contain an entry whose prefix matches the P3/P4 record then control
  68297. ** falls through to the next instruction and P1 is left pointing at the
  68298. ** matching entry.
  68299. **
  68300. ** This operation leaves the cursor in a state where it cannot be
  68301. ** advanced in either direction. In other words, the Next and Prev
  68302. ** opcodes do not work after this operation.
  68303. **
  68304. ** See also: Found, NotExists, NoConflict
  68305. */
  68306. /* Opcode: NoConflict P1 P2 P3 P4 *
  68307. ** Synopsis: key=r[P3@P4]
  68308. **
  68309. ** If P4==0 then register P3 holds a blob constructed by MakeRecord. If
  68310. ** P4>0 then register P3 is the first of P4 registers that form an unpacked
  68311. ** record.
  68312. **
  68313. ** Cursor P1 is on an index btree. If the record identified by P3 and P4
  68314. ** contains any NULL value, jump immediately to P2. If all terms of the
  68315. ** record are not-NULL then a check is done to determine if any row in the
  68316. ** P1 index btree has a matching key prefix. If there are no matches, jump
  68317. ** immediately to P2. If there is a match, fall through and leave the P1
  68318. ** cursor pointing to the matching row.
  68319. **
  68320. ** This opcode is similar to OP_NotFound with the exceptions that the
  68321. ** branch is always taken if any part of the search key input is NULL.
  68322. **
  68323. ** This operation leaves the cursor in a state where it cannot be
  68324. ** advanced in either direction. In other words, the Next and Prev
  68325. ** opcodes do not work after this operation.
  68326. **
  68327. ** See also: NotFound, Found, NotExists
  68328. */
  68329. case OP_NoConflict: /* jump, in3 */
  68330. case OP_NotFound: /* jump, in3 */
  68331. case OP_Found: { /* jump, in3 */
  68332. int alreadyExists;
  68333. int ii;
  68334. VdbeCursor *pC;
  68335. int res;
  68336. char *pFree;
  68337. UnpackedRecord *pIdxKey;
  68338. UnpackedRecord r;
  68339. char aTempRec[ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*4 + 7];
  68340. #ifdef SQLITE_TEST
  68341. if( pOp->opcode!=OP_NoConflict ) sqlite3_found_count++;
  68342. #endif
  68343. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  68344. assert( pOp->p4type==P4_INT32 );
  68345. pC = p->apCsr[pOp->p1];
  68346. assert( pC!=0 );
  68347. #ifdef SQLITE_DEBUG
  68348. pC->seekOp = pOp->opcode;
  68349. #endif
  68350. pIn3 = &aMem[pOp->p3];
  68351. assert( pC->pCursor!=0 );
  68352. assert( pC->isTable==0 );
  68353. pFree = 0; /* Not needed. Only used to suppress a compiler warning. */
  68354. if( pOp->p4.i>0 ){
  68355. r.pKeyInfo = pC->pKeyInfo;
  68356. r.nField = (u16)pOp->p4.i;
  68357. r.aMem = pIn3;
  68358. for(ii=0; ii<r.nField; ii++){
  68359. assert( memIsValid(&r.aMem[ii]) );
  68360. ExpandBlob(&r.aMem[ii]);
  68361. #ifdef SQLITE_DEBUG
  68362. if( ii ) REGISTER_TRACE(pOp->p3+ii, &r.aMem[ii]);
  68363. #endif
  68364. }
  68365. pIdxKey = &r;
  68366. }else{
  68367. pIdxKey = sqlite3VdbeAllocUnpackedRecord(
  68368. pC->pKeyInfo, aTempRec, sizeof(aTempRec), &pFree
  68369. );
  68370. if( pIdxKey==0 ) goto no_mem;
  68371. assert( pIn3->flags & MEM_Blob );
  68372. assert( (pIn3->flags & MEM_Zero)==0 ); /* zeroblobs already expanded */
  68373. sqlite3VdbeRecordUnpack(pC->pKeyInfo, pIn3->n, pIn3->z, pIdxKey);
  68374. }
  68375. pIdxKey->default_rc = 0;
  68376. if( pOp->opcode==OP_NoConflict ){
  68377. /* For the OP_NoConflict opcode, take the jump if any of the
  68378. ** input fields are NULL, since any key with a NULL will not
  68379. ** conflict */
  68380. for(ii=0; ii<r.nField; ii++){
  68381. if( r.aMem[ii].flags & MEM_Null ){
  68382. pc = pOp->p2 - 1; VdbeBranchTaken(1,2);
  68383. break;
  68384. }
  68385. }
  68386. }
  68387. rc = sqlite3BtreeMovetoUnpacked(pC->pCursor, pIdxKey, 0, 0, &res);
  68388. if( pOp->p4.i==0 ){
  68389. sqlite3DbFree(db, pFree);
  68390. }
  68391. if( rc!=SQLITE_OK ){
  68392. break;
  68393. }
  68394. pC->seekResult = res;
  68395. alreadyExists = (res==0);
  68396. pC->nullRow = 1-alreadyExists;
  68397. pC->deferredMoveto = 0;
  68398. pC->cacheStatus = CACHE_STALE;
  68399. if( pOp->opcode==OP_Found ){
  68400. VdbeBranchTaken(alreadyExists!=0,2);
  68401. if( alreadyExists ) pc = pOp->p2 - 1;
  68402. }else{
  68403. VdbeBranchTaken(alreadyExists==0,2);
  68404. if( !alreadyExists ) pc = pOp->p2 - 1;
  68405. }
  68406. break;
  68407. }
  68408. /* Opcode: NotExists P1 P2 P3 * *
  68409. ** Synopsis: intkey=r[P3]
  68410. **
  68411. ** P1 is the index of a cursor open on an SQL table btree (with integer
  68412. ** keys). P3 is an integer rowid. If P1 does not contain a record with
  68413. ** rowid P3 then jump immediately to P2. If P1 does contain a record
  68414. ** with rowid P3 then leave the cursor pointing at that record and fall
  68415. ** through to the next instruction.
  68416. **
  68417. ** The OP_NotFound opcode performs the same operation on index btrees
  68418. ** (with arbitrary multi-value keys).
  68419. **
  68420. ** This opcode leaves the cursor in a state where it cannot be advanced
  68421. ** in either direction. In other words, the Next and Prev opcodes will
  68422. ** not work following this opcode.
  68423. **
  68424. ** See also: Found, NotFound, NoConflict
  68425. */
  68426. case OP_NotExists: { /* jump, in3 */
  68427. VdbeCursor *pC;
  68428. BtCursor *pCrsr;
  68429. int res;
  68430. u64 iKey;
  68431. pIn3 = &aMem[pOp->p3];
  68432. assert( pIn3->flags & MEM_Int );
  68433. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  68434. pC = p->apCsr[pOp->p1];
  68435. assert( pC!=0 );
  68436. #ifdef SQLITE_DEBUG
  68437. pC->seekOp = 0;
  68438. #endif
  68439. assert( pC->isTable );
  68440. assert( pC->pseudoTableReg==0 );
  68441. pCrsr = pC->pCursor;
  68442. assert( pCrsr!=0 );
  68443. res = 0;
  68444. iKey = pIn3->u.i;
  68445. rc = sqlite3BtreeMovetoUnpacked(pCrsr, 0, iKey, 0, &res);
  68446. pC->movetoTarget = iKey; /* Used by OP_Delete */
  68447. pC->nullRow = 0;
  68448. pC->cacheStatus = CACHE_STALE;
  68449. pC->deferredMoveto = 0;
  68450. VdbeBranchTaken(res!=0,2);
  68451. if( res!=0 ){
  68452. pc = pOp->p2 - 1;
  68453. }
  68454. pC->seekResult = res;
  68455. break;
  68456. }
  68457. /* Opcode: Sequence P1 P2 * * *
  68458. ** Synopsis: r[P2]=cursor[P1].ctr++
  68459. **
  68460. ** Find the next available sequence number for cursor P1.
  68461. ** Write the sequence number into register P2.
  68462. ** The sequence number on the cursor is incremented after this
  68463. ** instruction.
  68464. */
  68465. case OP_Sequence: { /* out2-prerelease */
  68466. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  68467. assert( p->apCsr[pOp->p1]!=0 );
  68468. pOut->u.i = p->apCsr[pOp->p1]->seqCount++;
  68469. break;
  68470. }
  68471. /* Opcode: NewRowid P1 P2 P3 * *
  68472. ** Synopsis: r[P2]=rowid
  68473. **
  68474. ** Get a new integer record number (a.k.a "rowid") used as the key to a table.
  68475. ** The record number is not previously used as a key in the database
  68476. ** table that cursor P1 points to. The new record number is written
  68477. ** written to register P2.
  68478. **
  68479. ** If P3>0 then P3 is a register in the root frame of this VDBE that holds
  68480. ** the largest previously generated record number. No new record numbers are
  68481. ** allowed to be less than this value. When this value reaches its maximum,
  68482. ** an SQLITE_FULL error is generated. The P3 register is updated with the '
  68483. ** generated record number. This P3 mechanism is used to help implement the
  68484. ** AUTOINCREMENT feature.
  68485. */
  68486. case OP_NewRowid: { /* out2-prerelease */
  68487. i64 v; /* The new rowid */
  68488. VdbeCursor *pC; /* Cursor of table to get the new rowid */
  68489. int res; /* Result of an sqlite3BtreeLast() */
  68490. int cnt; /* Counter to limit the number of searches */
  68491. Mem *pMem; /* Register holding largest rowid for AUTOINCREMENT */
  68492. VdbeFrame *pFrame; /* Root frame of VDBE */
  68493. v = 0;
  68494. res = 0;
  68495. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  68496. pC = p->apCsr[pOp->p1];
  68497. assert( pC!=0 );
  68498. if( NEVER(pC->pCursor==0) ){
  68499. /* The zero initialization above is all that is needed */
  68500. }else{
  68501. /* The next rowid or record number (different terms for the same
  68502. ** thing) is obtained in a two-step algorithm.
  68503. **
  68504. ** First we attempt to find the largest existing rowid and add one
  68505. ** to that. But if the largest existing rowid is already the maximum
  68506. ** positive integer, we have to fall through to the second
  68507. ** probabilistic algorithm
  68508. **
  68509. ** The second algorithm is to select a rowid at random and see if
  68510. ** it already exists in the table. If it does not exist, we have
  68511. ** succeeded. If the random rowid does exist, we select a new one
  68512. ** and try again, up to 100 times.
  68513. */
  68514. assert( pC->isTable );
  68515. #ifdef SQLITE_32BIT_ROWID
  68516. # define MAX_ROWID 0x7fffffff
  68517. #else
  68518. /* Some compilers complain about constants of the form 0x7fffffffffffffff.
  68519. ** Others complain about 0x7ffffffffffffffffLL. The following macro seems
  68520. ** to provide the constant while making all compilers happy.
  68521. */
  68522. # define MAX_ROWID (i64)( (((u64)0x7fffffff)<<32) | (u64)0xffffffff )
  68523. #endif
  68524. if( !pC->useRandomRowid ){
  68525. rc = sqlite3BtreeLast(pC->pCursor, &res);
  68526. if( rc!=SQLITE_OK ){
  68527. goto abort_due_to_error;
  68528. }
  68529. if( res ){
  68530. v = 1; /* IMP: R-61914-48074 */
  68531. }else{
  68532. assert( sqlite3BtreeCursorIsValid(pC->pCursor) );
  68533. rc = sqlite3BtreeKeySize(pC->pCursor, &v);
  68534. assert( rc==SQLITE_OK ); /* Cannot fail following BtreeLast() */
  68535. if( v>=MAX_ROWID ){
  68536. pC->useRandomRowid = 1;
  68537. }else{
  68538. v++; /* IMP: R-29538-34987 */
  68539. }
  68540. }
  68541. }
  68542. #ifndef SQLITE_OMIT_AUTOINCREMENT
  68543. if( pOp->p3 ){
  68544. /* Assert that P3 is a valid memory cell. */
  68545. assert( pOp->p3>0 );
  68546. if( p->pFrame ){
  68547. for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
  68548. /* Assert that P3 is a valid memory cell. */
  68549. assert( pOp->p3<=pFrame->nMem );
  68550. pMem = &pFrame->aMem[pOp->p3];
  68551. }else{
  68552. /* Assert that P3 is a valid memory cell. */
  68553. assert( pOp->p3<=(p->nMem-p->nCursor) );
  68554. pMem = &aMem[pOp->p3];
  68555. memAboutToChange(p, pMem);
  68556. }
  68557. assert( memIsValid(pMem) );
  68558. REGISTER_TRACE(pOp->p3, pMem);
  68559. sqlite3VdbeMemIntegerify(pMem);
  68560. assert( (pMem->flags & MEM_Int)!=0 ); /* mem(P3) holds an integer */
  68561. if( pMem->u.i==MAX_ROWID || pC->useRandomRowid ){
  68562. rc = SQLITE_FULL; /* IMP: R-12275-61338 */
  68563. goto abort_due_to_error;
  68564. }
  68565. if( v<pMem->u.i+1 ){
  68566. v = pMem->u.i + 1;
  68567. }
  68568. pMem->u.i = v;
  68569. }
  68570. #endif
  68571. if( pC->useRandomRowid ){
  68572. /* IMPLEMENTATION-OF: R-07677-41881 If the largest ROWID is equal to the
  68573. ** largest possible integer (9223372036854775807) then the database
  68574. ** engine starts picking positive candidate ROWIDs at random until
  68575. ** it finds one that is not previously used. */
  68576. assert( pOp->p3==0 ); /* We cannot be in random rowid mode if this is
  68577. ** an AUTOINCREMENT table. */
  68578. cnt = 0;
  68579. do{
  68580. sqlite3_randomness(sizeof(v), &v);
  68581. v &= (MAX_ROWID>>1); v++; /* Ensure that v is greater than zero */
  68582. }while( ((rc = sqlite3BtreeMovetoUnpacked(pC->pCursor, 0, (u64)v,
  68583. 0, &res))==SQLITE_OK)
  68584. && (res==0)
  68585. && (++cnt<100));
  68586. if( rc==SQLITE_OK && res==0 ){
  68587. rc = SQLITE_FULL; /* IMP: R-38219-53002 */
  68588. goto abort_due_to_error;
  68589. }
  68590. assert( v>0 ); /* EV: R-40812-03570 */
  68591. }
  68592. pC->deferredMoveto = 0;
  68593. pC->cacheStatus = CACHE_STALE;
  68594. }
  68595. pOut->u.i = v;
  68596. break;
  68597. }
  68598. /* Opcode: Insert P1 P2 P3 P4 P5
  68599. ** Synopsis: intkey=r[P3] data=r[P2]
  68600. **
  68601. ** Write an entry into the table of cursor P1. A new entry is
  68602. ** created if it doesn't already exist or the data for an existing
  68603. ** entry is overwritten. The data is the value MEM_Blob stored in register
  68604. ** number P2. The key is stored in register P3. The key must
  68605. ** be a MEM_Int.
  68606. **
  68607. ** If the OPFLAG_NCHANGE flag of P5 is set, then the row change count is
  68608. ** incremented (otherwise not). If the OPFLAG_LASTROWID flag of P5 is set,
  68609. ** then rowid is stored for subsequent return by the
  68610. ** sqlite3_last_insert_rowid() function (otherwise it is unmodified).
  68611. **
  68612. ** If the OPFLAG_USESEEKRESULT flag of P5 is set and if the result of
  68613. ** the last seek operation (OP_NotExists) was a success, then this
  68614. ** operation will not attempt to find the appropriate row before doing
  68615. ** the insert but will instead overwrite the row that the cursor is
  68616. ** currently pointing to. Presumably, the prior OP_NotExists opcode
  68617. ** has already positioned the cursor correctly. This is an optimization
  68618. ** that boosts performance by avoiding redundant seeks.
  68619. **
  68620. ** If the OPFLAG_ISUPDATE flag is set, then this opcode is part of an
  68621. ** UPDATE operation. Otherwise (if the flag is clear) then this opcode
  68622. ** is part of an INSERT operation. The difference is only important to
  68623. ** the update hook.
  68624. **
  68625. ** Parameter P4 may point to a string containing the table-name, or
  68626. ** may be NULL. If it is not NULL, then the update-hook
  68627. ** (sqlite3.xUpdateCallback) is invoked following a successful insert.
  68628. **
  68629. ** (WARNING/TODO: If P1 is a pseudo-cursor and P2 is dynamically
  68630. ** allocated, then ownership of P2 is transferred to the pseudo-cursor
  68631. ** and register P2 becomes ephemeral. If the cursor is changed, the
  68632. ** value of register P2 will then change. Make sure this does not
  68633. ** cause any problems.)
  68634. **
  68635. ** This instruction only works on tables. The equivalent instruction
  68636. ** for indices is OP_IdxInsert.
  68637. */
  68638. /* Opcode: InsertInt P1 P2 P3 P4 P5
  68639. ** Synopsis: intkey=P3 data=r[P2]
  68640. **
  68641. ** This works exactly like OP_Insert except that the key is the
  68642. ** integer value P3, not the value of the integer stored in register P3.
  68643. */
  68644. case OP_Insert:
  68645. case OP_InsertInt: {
  68646. Mem *pData; /* MEM cell holding data for the record to be inserted */
  68647. Mem *pKey; /* MEM cell holding key for the record */
  68648. i64 iKey; /* The integer ROWID or key for the record to be inserted */
  68649. VdbeCursor *pC; /* Cursor to table into which insert is written */
  68650. int nZero; /* Number of zero-bytes to append */
  68651. int seekResult; /* Result of prior seek or 0 if no USESEEKRESULT flag */
  68652. const char *zDb; /* database name - used by the update hook */
  68653. const char *zTbl; /* Table name - used by the opdate hook */
  68654. int op; /* Opcode for update hook: SQLITE_UPDATE or SQLITE_INSERT */
  68655. pData = &aMem[pOp->p2];
  68656. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  68657. assert( memIsValid(pData) );
  68658. pC = p->apCsr[pOp->p1];
  68659. assert( pC!=0 );
  68660. assert( pC->pCursor!=0 );
  68661. assert( pC->pseudoTableReg==0 );
  68662. assert( pC->isTable );
  68663. REGISTER_TRACE(pOp->p2, pData);
  68664. if( pOp->opcode==OP_Insert ){
  68665. pKey = &aMem[pOp->p3];
  68666. assert( pKey->flags & MEM_Int );
  68667. assert( memIsValid(pKey) );
  68668. REGISTER_TRACE(pOp->p3, pKey);
  68669. iKey = pKey->u.i;
  68670. }else{
  68671. assert( pOp->opcode==OP_InsertInt );
  68672. iKey = pOp->p3;
  68673. }
  68674. if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
  68675. if( pOp->p5 & OPFLAG_LASTROWID ) db->lastRowid = lastRowid = iKey;
  68676. if( pData->flags & MEM_Null ){
  68677. pData->z = 0;
  68678. pData->n = 0;
  68679. }else{
  68680. assert( pData->flags & (MEM_Blob|MEM_Str) );
  68681. }
  68682. seekResult = ((pOp->p5 & OPFLAG_USESEEKRESULT) ? pC->seekResult : 0);
  68683. if( pData->flags & MEM_Zero ){
  68684. nZero = pData->u.nZero;
  68685. }else{
  68686. nZero = 0;
  68687. }
  68688. rc = sqlite3BtreeInsert(pC->pCursor, 0, iKey,
  68689. pData->z, pData->n, nZero,
  68690. (pOp->p5 & OPFLAG_APPEND)!=0, seekResult
  68691. );
  68692. pC->deferredMoveto = 0;
  68693. pC->cacheStatus = CACHE_STALE;
  68694. /* Invoke the update-hook if required. */
  68695. if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p4.z ){
  68696. zDb = db->aDb[pC->iDb].zName;
  68697. zTbl = pOp->p4.z;
  68698. op = ((pOp->p5 & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_INSERT);
  68699. assert( pC->isTable );
  68700. db->xUpdateCallback(db->pUpdateArg, op, zDb, zTbl, iKey);
  68701. assert( pC->iDb>=0 );
  68702. }
  68703. break;
  68704. }
  68705. /* Opcode: Delete P1 P2 * P4 *
  68706. **
  68707. ** Delete the record at which the P1 cursor is currently pointing.
  68708. **
  68709. ** The cursor will be left pointing at either the next or the previous
  68710. ** record in the table. If it is left pointing at the next record, then
  68711. ** the next Next instruction will be a no-op. Hence it is OK to delete
  68712. ** a record from within a Next loop.
  68713. **
  68714. ** If the OPFLAG_NCHANGE flag of P2 is set, then the row change count is
  68715. ** incremented (otherwise not).
  68716. **
  68717. ** P1 must not be pseudo-table. It has to be a real table with
  68718. ** multiple rows.
  68719. **
  68720. ** If P4 is not NULL, then it is the name of the table that P1 is
  68721. ** pointing to. The update hook will be invoked, if it exists.
  68722. ** If P4 is not NULL then the P1 cursor must have been positioned
  68723. ** using OP_NotFound prior to invoking this opcode.
  68724. */
  68725. case OP_Delete: {
  68726. VdbeCursor *pC;
  68727. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  68728. pC = p->apCsr[pOp->p1];
  68729. assert( pC!=0 );
  68730. assert( pC->pCursor!=0 ); /* Only valid for real tables, no pseudotables */
  68731. assert( pC->deferredMoveto==0 );
  68732. #ifdef SQLITE_DEBUG
  68733. /* The seek operation that positioned the cursor prior to OP_Delete will
  68734. ** have also set the pC->movetoTarget field to the rowid of the row that
  68735. ** is being deleted */
  68736. if( pOp->p4.z && pC->isTable ){
  68737. i64 iKey = 0;
  68738. sqlite3BtreeKeySize(pC->pCursor, &iKey);
  68739. assert( pC->movetoTarget==iKey );
  68740. }
  68741. #endif
  68742. rc = sqlite3BtreeDelete(pC->pCursor);
  68743. pC->cacheStatus = CACHE_STALE;
  68744. /* Invoke the update-hook if required. */
  68745. if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p4.z && pC->isTable ){
  68746. db->xUpdateCallback(db->pUpdateArg, SQLITE_DELETE,
  68747. db->aDb[pC->iDb].zName, pOp->p4.z, pC->movetoTarget);
  68748. assert( pC->iDb>=0 );
  68749. }
  68750. if( pOp->p2 & OPFLAG_NCHANGE ) p->nChange++;
  68751. break;
  68752. }
  68753. /* Opcode: ResetCount * * * * *
  68754. **
  68755. ** The value of the change counter is copied to the database handle
  68756. ** change counter (returned by subsequent calls to sqlite3_changes()).
  68757. ** Then the VMs internal change counter resets to 0.
  68758. ** This is used by trigger programs.
  68759. */
  68760. case OP_ResetCount: {
  68761. sqlite3VdbeSetChanges(db, p->nChange);
  68762. p->nChange = 0;
  68763. break;
  68764. }
  68765. /* Opcode: SorterCompare P1 P2 P3 P4
  68766. ** Synopsis: if key(P1)!=trim(r[P3],P4) goto P2
  68767. **
  68768. ** P1 is a sorter cursor. This instruction compares a prefix of the
  68769. ** record blob in register P3 against a prefix of the entry that
  68770. ** the sorter cursor currently points to. Only the first P4 fields
  68771. ** of r[P3] and the sorter record are compared.
  68772. **
  68773. ** If either P3 or the sorter contains a NULL in one of their significant
  68774. ** fields (not counting the P4 fields at the end which are ignored) then
  68775. ** the comparison is assumed to be equal.
  68776. **
  68777. ** Fall through to next instruction if the two records compare equal to
  68778. ** each other. Jump to P2 if they are different.
  68779. */
  68780. case OP_SorterCompare: {
  68781. VdbeCursor *pC;
  68782. int res;
  68783. int nKeyCol;
  68784. pC = p->apCsr[pOp->p1];
  68785. assert( isSorter(pC) );
  68786. assert( pOp->p4type==P4_INT32 );
  68787. pIn3 = &aMem[pOp->p3];
  68788. nKeyCol = pOp->p4.i;
  68789. res = 0;
  68790. rc = sqlite3VdbeSorterCompare(pC, pIn3, nKeyCol, &res);
  68791. VdbeBranchTaken(res!=0,2);
  68792. if( res ){
  68793. pc = pOp->p2-1;
  68794. }
  68795. break;
  68796. };
  68797. /* Opcode: SorterData P1 P2 P3 * *
  68798. ** Synopsis: r[P2]=data
  68799. **
  68800. ** Write into register P2 the current sorter data for sorter cursor P1.
  68801. ** Then clear the column header cache on cursor P3.
  68802. **
  68803. ** This opcode is normally use to move a record out of the sorter and into
  68804. ** a register that is the source for a pseudo-table cursor created using
  68805. ** OpenPseudo. That pseudo-table cursor is the one that is identified by
  68806. ** parameter P3. Clearing the P3 column cache as part of this opcode saves
  68807. ** us from having to issue a separate NullRow instruction to clear that cache.
  68808. */
  68809. case OP_SorterData: {
  68810. VdbeCursor *pC;
  68811. pOut = &aMem[pOp->p2];
  68812. pC = p->apCsr[pOp->p1];
  68813. assert( isSorter(pC) );
  68814. rc = sqlite3VdbeSorterRowkey(pC, pOut);
  68815. assert( rc!=SQLITE_OK || (pOut->flags & MEM_Blob) );
  68816. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  68817. p->apCsr[pOp->p3]->cacheStatus = CACHE_STALE;
  68818. break;
  68819. }
  68820. /* Opcode: RowData P1 P2 * * *
  68821. ** Synopsis: r[P2]=data
  68822. **
  68823. ** Write into register P2 the complete row data for cursor P1.
  68824. ** There is no interpretation of the data.
  68825. ** It is just copied onto the P2 register exactly as
  68826. ** it is found in the database file.
  68827. **
  68828. ** If the P1 cursor must be pointing to a valid row (not a NULL row)
  68829. ** of a real table, not a pseudo-table.
  68830. */
  68831. /* Opcode: RowKey P1 P2 * * *
  68832. ** Synopsis: r[P2]=key
  68833. **
  68834. ** Write into register P2 the complete row key for cursor P1.
  68835. ** There is no interpretation of the data.
  68836. ** The key is copied onto the P2 register exactly as
  68837. ** it is found in the database file.
  68838. **
  68839. ** If the P1 cursor must be pointing to a valid row (not a NULL row)
  68840. ** of a real table, not a pseudo-table.
  68841. */
  68842. case OP_RowKey:
  68843. case OP_RowData: {
  68844. VdbeCursor *pC;
  68845. BtCursor *pCrsr;
  68846. u32 n;
  68847. i64 n64;
  68848. pOut = &aMem[pOp->p2];
  68849. memAboutToChange(p, pOut);
  68850. /* Note that RowKey and RowData are really exactly the same instruction */
  68851. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  68852. pC = p->apCsr[pOp->p1];
  68853. assert( isSorter(pC)==0 );
  68854. assert( pC->isTable || pOp->opcode!=OP_RowData );
  68855. assert( pC->isTable==0 || pOp->opcode==OP_RowData );
  68856. assert( pC!=0 );
  68857. assert( pC->nullRow==0 );
  68858. assert( pC->pseudoTableReg==0 );
  68859. assert( pC->pCursor!=0 );
  68860. pCrsr = pC->pCursor;
  68861. /* The OP_RowKey and OP_RowData opcodes always follow OP_NotExists or
  68862. ** OP_Rewind/Op_Next with no intervening instructions that might invalidate
  68863. ** the cursor. If this where not the case, on of the following assert()s
  68864. ** would fail. Should this ever change (because of changes in the code
  68865. ** generator) then the fix would be to insert a call to
  68866. ** sqlite3VdbeCursorMoveto().
  68867. */
  68868. assert( pC->deferredMoveto==0 );
  68869. assert( sqlite3BtreeCursorIsValid(pCrsr) );
  68870. #if 0 /* Not required due to the previous to assert() statements */
  68871. rc = sqlite3VdbeCursorMoveto(pC);
  68872. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  68873. #endif
  68874. if( pC->isTable==0 ){
  68875. assert( !pC->isTable );
  68876. VVA_ONLY(rc =) sqlite3BtreeKeySize(pCrsr, &n64);
  68877. assert( rc==SQLITE_OK ); /* True because of CursorMoveto() call above */
  68878. if( n64>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  68879. goto too_big;
  68880. }
  68881. n = (u32)n64;
  68882. }else{
  68883. VVA_ONLY(rc =) sqlite3BtreeDataSize(pCrsr, &n);
  68884. assert( rc==SQLITE_OK ); /* DataSize() cannot fail */
  68885. if( n>(u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
  68886. goto too_big;
  68887. }
  68888. }
  68889. testcase( n==0 );
  68890. if( sqlite3VdbeMemClearAndResize(pOut, MAX(n,32)) ){
  68891. goto no_mem;
  68892. }
  68893. pOut->n = n;
  68894. MemSetTypeFlag(pOut, MEM_Blob);
  68895. if( pC->isTable==0 ){
  68896. rc = sqlite3BtreeKey(pCrsr, 0, n, pOut->z);
  68897. }else{
  68898. rc = sqlite3BtreeData(pCrsr, 0, n, pOut->z);
  68899. }
  68900. pOut->enc = SQLITE_UTF8; /* In case the blob is ever cast to text */
  68901. UPDATE_MAX_BLOBSIZE(pOut);
  68902. REGISTER_TRACE(pOp->p2, pOut);
  68903. break;
  68904. }
  68905. /* Opcode: Rowid P1 P2 * * *
  68906. ** Synopsis: r[P2]=rowid
  68907. **
  68908. ** Store in register P2 an integer which is the key of the table entry that
  68909. ** P1 is currently point to.
  68910. **
  68911. ** P1 can be either an ordinary table or a virtual table. There used to
  68912. ** be a separate OP_VRowid opcode for use with virtual tables, but this
  68913. ** one opcode now works for both table types.
  68914. */
  68915. case OP_Rowid: { /* out2-prerelease */
  68916. VdbeCursor *pC;
  68917. i64 v;
  68918. sqlite3_vtab *pVtab;
  68919. const sqlite3_module *pModule;
  68920. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  68921. pC = p->apCsr[pOp->p1];
  68922. assert( pC!=0 );
  68923. assert( pC->pseudoTableReg==0 || pC->nullRow );
  68924. if( pC->nullRow ){
  68925. pOut->flags = MEM_Null;
  68926. break;
  68927. }else if( pC->deferredMoveto ){
  68928. v = pC->movetoTarget;
  68929. #ifndef SQLITE_OMIT_VIRTUALTABLE
  68930. }else if( pC->pVtabCursor ){
  68931. pVtab = pC->pVtabCursor->pVtab;
  68932. pModule = pVtab->pModule;
  68933. assert( pModule->xRowid );
  68934. rc = pModule->xRowid(pC->pVtabCursor, &v);
  68935. sqlite3VtabImportErrmsg(p, pVtab);
  68936. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  68937. }else{
  68938. assert( pC->pCursor!=0 );
  68939. rc = sqlite3VdbeCursorRestore(pC);
  68940. if( rc ) goto abort_due_to_error;
  68941. rc = sqlite3BtreeKeySize(pC->pCursor, &v);
  68942. assert( rc==SQLITE_OK ); /* Always so because of CursorRestore() above */
  68943. }
  68944. pOut->u.i = v;
  68945. break;
  68946. }
  68947. /* Opcode: NullRow P1 * * * *
  68948. **
  68949. ** Move the cursor P1 to a null row. Any OP_Column operations
  68950. ** that occur while the cursor is on the null row will always
  68951. ** write a NULL.
  68952. */
  68953. case OP_NullRow: {
  68954. VdbeCursor *pC;
  68955. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  68956. pC = p->apCsr[pOp->p1];
  68957. assert( pC!=0 );
  68958. pC->nullRow = 1;
  68959. pC->cacheStatus = CACHE_STALE;
  68960. if( pC->pCursor ){
  68961. sqlite3BtreeClearCursor(pC->pCursor);
  68962. }
  68963. break;
  68964. }
  68965. /* Opcode: Last P1 P2 * * *
  68966. **
  68967. ** The next use of the Rowid or Column or Prev instruction for P1
  68968. ** will refer to the last entry in the database table or index.
  68969. ** If the table or index is empty and P2>0, then jump immediately to P2.
  68970. ** If P2 is 0 or if the table or index is not empty, fall through
  68971. ** to the following instruction.
  68972. **
  68973. ** This opcode leaves the cursor configured to move in reverse order,
  68974. ** from the end toward the beginning. In other words, the cursor is
  68975. ** configured to use Prev, not Next.
  68976. */
  68977. case OP_Last: { /* jump */
  68978. VdbeCursor *pC;
  68979. BtCursor *pCrsr;
  68980. int res;
  68981. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  68982. pC = p->apCsr[pOp->p1];
  68983. assert( pC!=0 );
  68984. pCrsr = pC->pCursor;
  68985. res = 0;
  68986. assert( pCrsr!=0 );
  68987. rc = sqlite3BtreeLast(pCrsr, &res);
  68988. pC->nullRow = (u8)res;
  68989. pC->deferredMoveto = 0;
  68990. pC->cacheStatus = CACHE_STALE;
  68991. #ifdef SQLITE_DEBUG
  68992. pC->seekOp = OP_Last;
  68993. #endif
  68994. if( pOp->p2>0 ){
  68995. VdbeBranchTaken(res!=0,2);
  68996. if( res ) pc = pOp->p2 - 1;
  68997. }
  68998. break;
  68999. }
  69000. /* Opcode: Sort P1 P2 * * *
  69001. **
  69002. ** This opcode does exactly the same thing as OP_Rewind except that
  69003. ** it increments an undocumented global variable used for testing.
  69004. **
  69005. ** Sorting is accomplished by writing records into a sorting index,
  69006. ** then rewinding that index and playing it back from beginning to
  69007. ** end. We use the OP_Sort opcode instead of OP_Rewind to do the
  69008. ** rewinding so that the global variable will be incremented and
  69009. ** regression tests can determine whether or not the optimizer is
  69010. ** correctly optimizing out sorts.
  69011. */
  69012. case OP_SorterSort: /* jump */
  69013. case OP_Sort: { /* jump */
  69014. #ifdef SQLITE_TEST
  69015. sqlite3_sort_count++;
  69016. sqlite3_search_count--;
  69017. #endif
  69018. p->aCounter[SQLITE_STMTSTATUS_SORT]++;
  69019. /* Fall through into OP_Rewind */
  69020. }
  69021. /* Opcode: Rewind P1 P2 * * *
  69022. **
  69023. ** The next use of the Rowid or Column or Next instruction for P1
  69024. ** will refer to the first entry in the database table or index.
  69025. ** If the table or index is empty and P2>0, then jump immediately to P2.
  69026. ** If P2 is 0 or if the table or index is not empty, fall through
  69027. ** to the following instruction.
  69028. **
  69029. ** This opcode leaves the cursor configured to move in forward order,
  69030. ** from the beginning toward the end. In other words, the cursor is
  69031. ** configured to use Next, not Prev.
  69032. */
  69033. case OP_Rewind: { /* jump */
  69034. VdbeCursor *pC;
  69035. BtCursor *pCrsr;
  69036. int res;
  69037. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  69038. pC = p->apCsr[pOp->p1];
  69039. assert( pC!=0 );
  69040. assert( isSorter(pC)==(pOp->opcode==OP_SorterSort) );
  69041. res = 1;
  69042. #ifdef SQLITE_DEBUG
  69043. pC->seekOp = OP_Rewind;
  69044. #endif
  69045. if( isSorter(pC) ){
  69046. rc = sqlite3VdbeSorterRewind(pC, &res);
  69047. }else{
  69048. pCrsr = pC->pCursor;
  69049. assert( pCrsr );
  69050. rc = sqlite3BtreeFirst(pCrsr, &res);
  69051. pC->deferredMoveto = 0;
  69052. pC->cacheStatus = CACHE_STALE;
  69053. }
  69054. pC->nullRow = (u8)res;
  69055. assert( pOp->p2>0 && pOp->p2<p->nOp );
  69056. VdbeBranchTaken(res!=0,2);
  69057. if( res ){
  69058. pc = pOp->p2 - 1;
  69059. }
  69060. break;
  69061. }
  69062. /* Opcode: Next P1 P2 P3 P4 P5
  69063. **
  69064. ** Advance cursor P1 so that it points to the next key/data pair in its
  69065. ** table or index. If there are no more key/value pairs then fall through
  69066. ** to the following instruction. But if the cursor advance was successful,
  69067. ** jump immediately to P2.
  69068. **
  69069. ** The Next opcode is only valid following an SeekGT, SeekGE, or
  69070. ** OP_Rewind opcode used to position the cursor. Next is not allowed
  69071. ** to follow SeekLT, SeekLE, or OP_Last.
  69072. **
  69073. ** The P1 cursor must be for a real table, not a pseudo-table. P1 must have
  69074. ** been opened prior to this opcode or the program will segfault.
  69075. **
  69076. ** The P3 value is a hint to the btree implementation. If P3==1, that
  69077. ** means P1 is an SQL index and that this instruction could have been
  69078. ** omitted if that index had been unique. P3 is usually 0. P3 is
  69079. ** always either 0 or 1.
  69080. **
  69081. ** P4 is always of type P4_ADVANCE. The function pointer points to
  69082. ** sqlite3BtreeNext().
  69083. **
  69084. ** If P5 is positive and the jump is taken, then event counter
  69085. ** number P5-1 in the prepared statement is incremented.
  69086. **
  69087. ** See also: Prev, NextIfOpen
  69088. */
  69089. /* Opcode: NextIfOpen P1 P2 P3 P4 P5
  69090. **
  69091. ** This opcode works just like Next except that if cursor P1 is not
  69092. ** open it behaves a no-op.
  69093. */
  69094. /* Opcode: Prev P1 P2 P3 P4 P5
  69095. **
  69096. ** Back up cursor P1 so that it points to the previous key/data pair in its
  69097. ** table or index. If there is no previous key/value pairs then fall through
  69098. ** to the following instruction. But if the cursor backup was successful,
  69099. ** jump immediately to P2.
  69100. **
  69101. **
  69102. ** The Prev opcode is only valid following an SeekLT, SeekLE, or
  69103. ** OP_Last opcode used to position the cursor. Prev is not allowed
  69104. ** to follow SeekGT, SeekGE, or OP_Rewind.
  69105. **
  69106. ** The P1 cursor must be for a real table, not a pseudo-table. If P1 is
  69107. ** not open then the behavior is undefined.
  69108. **
  69109. ** The P3 value is a hint to the btree implementation. If P3==1, that
  69110. ** means P1 is an SQL index and that this instruction could have been
  69111. ** omitted if that index had been unique. P3 is usually 0. P3 is
  69112. ** always either 0 or 1.
  69113. **
  69114. ** P4 is always of type P4_ADVANCE. The function pointer points to
  69115. ** sqlite3BtreePrevious().
  69116. **
  69117. ** If P5 is positive and the jump is taken, then event counter
  69118. ** number P5-1 in the prepared statement is incremented.
  69119. */
  69120. /* Opcode: PrevIfOpen P1 P2 P3 P4 P5
  69121. **
  69122. ** This opcode works just like Prev except that if cursor P1 is not
  69123. ** open it behaves a no-op.
  69124. */
  69125. case OP_SorterNext: { /* jump */
  69126. VdbeCursor *pC;
  69127. int res;
  69128. pC = p->apCsr[pOp->p1];
  69129. assert( isSorter(pC) );
  69130. res = 0;
  69131. rc = sqlite3VdbeSorterNext(db, pC, &res);
  69132. goto next_tail;
  69133. case OP_PrevIfOpen: /* jump */
  69134. case OP_NextIfOpen: /* jump */
  69135. if( p->apCsr[pOp->p1]==0 ) break;
  69136. /* Fall through */
  69137. case OP_Prev: /* jump */
  69138. case OP_Next: /* jump */
  69139. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  69140. assert( pOp->p5<ArraySize(p->aCounter) );
  69141. pC = p->apCsr[pOp->p1];
  69142. res = pOp->p3;
  69143. assert( pC!=0 );
  69144. assert( pC->deferredMoveto==0 );
  69145. assert( pC->pCursor );
  69146. assert( res==0 || (res==1 && pC->isTable==0) );
  69147. testcase( res==1 );
  69148. assert( pOp->opcode!=OP_Next || pOp->p4.xAdvance==sqlite3BtreeNext );
  69149. assert( pOp->opcode!=OP_Prev || pOp->p4.xAdvance==sqlite3BtreePrevious );
  69150. assert( pOp->opcode!=OP_NextIfOpen || pOp->p4.xAdvance==sqlite3BtreeNext );
  69151. assert( pOp->opcode!=OP_PrevIfOpen || pOp->p4.xAdvance==sqlite3BtreePrevious);
  69152. /* The Next opcode is only used after SeekGT, SeekGE, and Rewind.
  69153. ** The Prev opcode is only used after SeekLT, SeekLE, and Last. */
  69154. assert( pOp->opcode!=OP_Next || pOp->opcode!=OP_NextIfOpen
  69155. || pC->seekOp==OP_SeekGT || pC->seekOp==OP_SeekGE
  69156. || pC->seekOp==OP_Rewind || pC->seekOp==OP_Found);
  69157. assert( pOp->opcode!=OP_Prev || pOp->opcode!=OP_PrevIfOpen
  69158. || pC->seekOp==OP_SeekLT || pC->seekOp==OP_SeekLE
  69159. || pC->seekOp==OP_Last );
  69160. rc = pOp->p4.xAdvance(pC->pCursor, &res);
  69161. next_tail:
  69162. pC->cacheStatus = CACHE_STALE;
  69163. VdbeBranchTaken(res==0,2);
  69164. if( res==0 ){
  69165. pC->nullRow = 0;
  69166. pc = pOp->p2 - 1;
  69167. p->aCounter[pOp->p5]++;
  69168. #ifdef SQLITE_TEST
  69169. sqlite3_search_count++;
  69170. #endif
  69171. }else{
  69172. pC->nullRow = 1;
  69173. }
  69174. goto check_for_interrupt;
  69175. }
  69176. /* Opcode: IdxInsert P1 P2 P3 * P5
  69177. ** Synopsis: key=r[P2]
  69178. **
  69179. ** Register P2 holds an SQL index key made using the
  69180. ** MakeRecord instructions. This opcode writes that key
  69181. ** into the index P1. Data for the entry is nil.
  69182. **
  69183. ** P3 is a flag that provides a hint to the b-tree layer that this
  69184. ** insert is likely to be an append.
  69185. **
  69186. ** If P5 has the OPFLAG_NCHANGE bit set, then the change counter is
  69187. ** incremented by this instruction. If the OPFLAG_NCHANGE bit is clear,
  69188. ** then the change counter is unchanged.
  69189. **
  69190. ** If P5 has the OPFLAG_USESEEKRESULT bit set, then the cursor must have
  69191. ** just done a seek to the spot where the new entry is to be inserted.
  69192. ** This flag avoids doing an extra seek.
  69193. **
  69194. ** This instruction only works for indices. The equivalent instruction
  69195. ** for tables is OP_Insert.
  69196. */
  69197. case OP_SorterInsert: /* in2 */
  69198. case OP_IdxInsert: { /* in2 */
  69199. VdbeCursor *pC;
  69200. BtCursor *pCrsr;
  69201. int nKey;
  69202. const char *zKey;
  69203. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  69204. pC = p->apCsr[pOp->p1];
  69205. assert( pC!=0 );
  69206. assert( isSorter(pC)==(pOp->opcode==OP_SorterInsert) );
  69207. pIn2 = &aMem[pOp->p2];
  69208. assert( pIn2->flags & MEM_Blob );
  69209. pCrsr = pC->pCursor;
  69210. if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
  69211. assert( pCrsr!=0 );
  69212. assert( pC->isTable==0 );
  69213. rc = ExpandBlob(pIn2);
  69214. if( rc==SQLITE_OK ){
  69215. if( isSorter(pC) ){
  69216. rc = sqlite3VdbeSorterWrite(pC, pIn2);
  69217. }else{
  69218. nKey = pIn2->n;
  69219. zKey = pIn2->z;
  69220. rc = sqlite3BtreeInsert(pCrsr, zKey, nKey, "", 0, 0, pOp->p3,
  69221. ((pOp->p5 & OPFLAG_USESEEKRESULT) ? pC->seekResult : 0)
  69222. );
  69223. assert( pC->deferredMoveto==0 );
  69224. pC->cacheStatus = CACHE_STALE;
  69225. }
  69226. }
  69227. break;
  69228. }
  69229. /* Opcode: IdxDelete P1 P2 P3 * *
  69230. ** Synopsis: key=r[P2@P3]
  69231. **
  69232. ** The content of P3 registers starting at register P2 form
  69233. ** an unpacked index key. This opcode removes that entry from the
  69234. ** index opened by cursor P1.
  69235. */
  69236. case OP_IdxDelete: {
  69237. VdbeCursor *pC;
  69238. BtCursor *pCrsr;
  69239. int res;
  69240. UnpackedRecord r;
  69241. assert( pOp->p3>0 );
  69242. assert( pOp->p2>0 && pOp->p2+pOp->p3<=(p->nMem-p->nCursor)+1 );
  69243. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  69244. pC = p->apCsr[pOp->p1];
  69245. assert( pC!=0 );
  69246. pCrsr = pC->pCursor;
  69247. assert( pCrsr!=0 );
  69248. assert( pOp->p5==0 );
  69249. r.pKeyInfo = pC->pKeyInfo;
  69250. r.nField = (u16)pOp->p3;
  69251. r.default_rc = 0;
  69252. r.aMem = &aMem[pOp->p2];
  69253. #ifdef SQLITE_DEBUG
  69254. { int i; for(i=0; i<r.nField; i++) assert( memIsValid(&r.aMem[i]) ); }
  69255. #endif
  69256. rc = sqlite3BtreeMovetoUnpacked(pCrsr, &r, 0, 0, &res);
  69257. if( rc==SQLITE_OK && res==0 ){
  69258. rc = sqlite3BtreeDelete(pCrsr);
  69259. }
  69260. assert( pC->deferredMoveto==0 );
  69261. pC->cacheStatus = CACHE_STALE;
  69262. break;
  69263. }
  69264. /* Opcode: IdxRowid P1 P2 * * *
  69265. ** Synopsis: r[P2]=rowid
  69266. **
  69267. ** Write into register P2 an integer which is the last entry in the record at
  69268. ** the end of the index key pointed to by cursor P1. This integer should be
  69269. ** the rowid of the table entry to which this index entry points.
  69270. **
  69271. ** See also: Rowid, MakeRecord.
  69272. */
  69273. case OP_IdxRowid: { /* out2-prerelease */
  69274. BtCursor *pCrsr;
  69275. VdbeCursor *pC;
  69276. i64 rowid;
  69277. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  69278. pC = p->apCsr[pOp->p1];
  69279. assert( pC!=0 );
  69280. pCrsr = pC->pCursor;
  69281. assert( pCrsr!=0 );
  69282. pOut->flags = MEM_Null;
  69283. assert( pC->isTable==0 );
  69284. assert( pC->deferredMoveto==0 );
  69285. /* sqlite3VbeCursorRestore() can only fail if the record has been deleted
  69286. ** out from under the cursor. That will never happend for an IdxRowid
  69287. ** opcode, hence the NEVER() arround the check of the return value.
  69288. */
  69289. rc = sqlite3VdbeCursorRestore(pC);
  69290. if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error;
  69291. if( !pC->nullRow ){
  69292. rowid = 0; /* Not needed. Only used to silence a warning. */
  69293. rc = sqlite3VdbeIdxRowid(db, pCrsr, &rowid);
  69294. if( rc!=SQLITE_OK ){
  69295. goto abort_due_to_error;
  69296. }
  69297. pOut->u.i = rowid;
  69298. pOut->flags = MEM_Int;
  69299. }
  69300. break;
  69301. }
  69302. /* Opcode: IdxGE P1 P2 P3 P4 P5
  69303. ** Synopsis: key=r[P3@P4]
  69304. **
  69305. ** The P4 register values beginning with P3 form an unpacked index
  69306. ** key that omits the PRIMARY KEY. Compare this key value against the index
  69307. ** that P1 is currently pointing to, ignoring the PRIMARY KEY or ROWID
  69308. ** fields at the end.
  69309. **
  69310. ** If the P1 index entry is greater than or equal to the key value
  69311. ** then jump to P2. Otherwise fall through to the next instruction.
  69312. */
  69313. /* Opcode: IdxGT P1 P2 P3 P4 P5
  69314. ** Synopsis: key=r[P3@P4]
  69315. **
  69316. ** The P4 register values beginning with P3 form an unpacked index
  69317. ** key that omits the PRIMARY KEY. Compare this key value against the index
  69318. ** that P1 is currently pointing to, ignoring the PRIMARY KEY or ROWID
  69319. ** fields at the end.
  69320. **
  69321. ** If the P1 index entry is greater than the key value
  69322. ** then jump to P2. Otherwise fall through to the next instruction.
  69323. */
  69324. /* Opcode: IdxLT P1 P2 P3 P4 P5
  69325. ** Synopsis: key=r[P3@P4]
  69326. **
  69327. ** The P4 register values beginning with P3 form an unpacked index
  69328. ** key that omits the PRIMARY KEY or ROWID. Compare this key value against
  69329. ** the index that P1 is currently pointing to, ignoring the PRIMARY KEY or
  69330. ** ROWID on the P1 index.
  69331. **
  69332. ** If the P1 index entry is less than the key value then jump to P2.
  69333. ** Otherwise fall through to the next instruction.
  69334. */
  69335. /* Opcode: IdxLE P1 P2 P3 P4 P5
  69336. ** Synopsis: key=r[P3@P4]
  69337. **
  69338. ** The P4 register values beginning with P3 form an unpacked index
  69339. ** key that omits the PRIMARY KEY or ROWID. Compare this key value against
  69340. ** the index that P1 is currently pointing to, ignoring the PRIMARY KEY or
  69341. ** ROWID on the P1 index.
  69342. **
  69343. ** If the P1 index entry is less than or equal to the key value then jump
  69344. ** to P2. Otherwise fall through to the next instruction.
  69345. */
  69346. case OP_IdxLE: /* jump */
  69347. case OP_IdxGT: /* jump */
  69348. case OP_IdxLT: /* jump */
  69349. case OP_IdxGE: { /* jump */
  69350. VdbeCursor *pC;
  69351. int res;
  69352. UnpackedRecord r;
  69353. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  69354. pC = p->apCsr[pOp->p1];
  69355. assert( pC!=0 );
  69356. assert( pC->isOrdered );
  69357. assert( pC->pCursor!=0);
  69358. assert( pC->deferredMoveto==0 );
  69359. assert( pOp->p5==0 || pOp->p5==1 );
  69360. assert( pOp->p4type==P4_INT32 );
  69361. r.pKeyInfo = pC->pKeyInfo;
  69362. r.nField = (u16)pOp->p4.i;
  69363. if( pOp->opcode<OP_IdxLT ){
  69364. assert( pOp->opcode==OP_IdxLE || pOp->opcode==OP_IdxGT );
  69365. r.default_rc = -1;
  69366. }else{
  69367. assert( pOp->opcode==OP_IdxGE || pOp->opcode==OP_IdxLT );
  69368. r.default_rc = 0;
  69369. }
  69370. r.aMem = &aMem[pOp->p3];
  69371. #ifdef SQLITE_DEBUG
  69372. { int i; for(i=0; i<r.nField; i++) assert( memIsValid(&r.aMem[i]) ); }
  69373. #endif
  69374. res = 0; /* Not needed. Only used to silence a warning. */
  69375. rc = sqlite3VdbeIdxKeyCompare(db, pC, &r, &res);
  69376. assert( (OP_IdxLE&1)==(OP_IdxLT&1) && (OP_IdxGE&1)==(OP_IdxGT&1) );
  69377. if( (pOp->opcode&1)==(OP_IdxLT&1) ){
  69378. assert( pOp->opcode==OP_IdxLE || pOp->opcode==OP_IdxLT );
  69379. res = -res;
  69380. }else{
  69381. assert( pOp->opcode==OP_IdxGE || pOp->opcode==OP_IdxGT );
  69382. res++;
  69383. }
  69384. VdbeBranchTaken(res>0,2);
  69385. if( res>0 ){
  69386. pc = pOp->p2 - 1 ;
  69387. }
  69388. break;
  69389. }
  69390. /* Opcode: Destroy P1 P2 P3 * *
  69391. **
  69392. ** Delete an entire database table or index whose root page in the database
  69393. ** file is given by P1.
  69394. **
  69395. ** The table being destroyed is in the main database file if P3==0. If
  69396. ** P3==1 then the table to be clear is in the auxiliary database file
  69397. ** that is used to store tables create using CREATE TEMPORARY TABLE.
  69398. **
  69399. ** If AUTOVACUUM is enabled then it is possible that another root page
  69400. ** might be moved into the newly deleted root page in order to keep all
  69401. ** root pages contiguous at the beginning of the database. The former
  69402. ** value of the root page that moved - its value before the move occurred -
  69403. ** is stored in register P2. If no page
  69404. ** movement was required (because the table being dropped was already
  69405. ** the last one in the database) then a zero is stored in register P2.
  69406. ** If AUTOVACUUM is disabled then a zero is stored in register P2.
  69407. **
  69408. ** See also: Clear
  69409. */
  69410. case OP_Destroy: { /* out2-prerelease */
  69411. int iMoved;
  69412. int iCnt;
  69413. Vdbe *pVdbe;
  69414. int iDb;
  69415. assert( p->readOnly==0 );
  69416. #ifndef SQLITE_OMIT_VIRTUALTABLE
  69417. iCnt = 0;
  69418. for(pVdbe=db->pVdbe; pVdbe; pVdbe = pVdbe->pNext){
  69419. if( pVdbe->magic==VDBE_MAGIC_RUN && pVdbe->bIsReader
  69420. && pVdbe->inVtabMethod<2 && pVdbe->pc>=0
  69421. ){
  69422. iCnt++;
  69423. }
  69424. }
  69425. #else
  69426. iCnt = db->nVdbeRead;
  69427. #endif
  69428. pOut->flags = MEM_Null;
  69429. if( iCnt>1 ){
  69430. rc = SQLITE_LOCKED;
  69431. p->errorAction = OE_Abort;
  69432. }else{
  69433. iDb = pOp->p3;
  69434. assert( iCnt==1 );
  69435. assert( DbMaskTest(p->btreeMask, iDb) );
  69436. iMoved = 0; /* Not needed. Only to silence a warning. */
  69437. rc = sqlite3BtreeDropTable(db->aDb[iDb].pBt, pOp->p1, &iMoved);
  69438. pOut->flags = MEM_Int;
  69439. pOut->u.i = iMoved;
  69440. #ifndef SQLITE_OMIT_AUTOVACUUM
  69441. if( rc==SQLITE_OK && iMoved!=0 ){
  69442. sqlite3RootPageMoved(db, iDb, iMoved, pOp->p1);
  69443. /* All OP_Destroy operations occur on the same btree */
  69444. assert( resetSchemaOnFault==0 || resetSchemaOnFault==iDb+1 );
  69445. resetSchemaOnFault = iDb+1;
  69446. }
  69447. #endif
  69448. }
  69449. break;
  69450. }
  69451. /* Opcode: Clear P1 P2 P3
  69452. **
  69453. ** Delete all contents of the database table or index whose root page
  69454. ** in the database file is given by P1. But, unlike Destroy, do not
  69455. ** remove the table or index from the database file.
  69456. **
  69457. ** The table being clear is in the main database file if P2==0. If
  69458. ** P2==1 then the table to be clear is in the auxiliary database file
  69459. ** that is used to store tables create using CREATE TEMPORARY TABLE.
  69460. **
  69461. ** If the P3 value is non-zero, then the table referred to must be an
  69462. ** intkey table (an SQL table, not an index). In this case the row change
  69463. ** count is incremented by the number of rows in the table being cleared.
  69464. ** If P3 is greater than zero, then the value stored in register P3 is
  69465. ** also incremented by the number of rows in the table being cleared.
  69466. **
  69467. ** See also: Destroy
  69468. */
  69469. case OP_Clear: {
  69470. int nChange;
  69471. nChange = 0;
  69472. assert( p->readOnly==0 );
  69473. assert( DbMaskTest(p->btreeMask, pOp->p2) );
  69474. rc = sqlite3BtreeClearTable(
  69475. db->aDb[pOp->p2].pBt, pOp->p1, (pOp->p3 ? &nChange : 0)
  69476. );
  69477. if( pOp->p3 ){
  69478. p->nChange += nChange;
  69479. if( pOp->p3>0 ){
  69480. assert( memIsValid(&aMem[pOp->p3]) );
  69481. memAboutToChange(p, &aMem[pOp->p3]);
  69482. aMem[pOp->p3].u.i += nChange;
  69483. }
  69484. }
  69485. break;
  69486. }
  69487. /* Opcode: ResetSorter P1 * * * *
  69488. **
  69489. ** Delete all contents from the ephemeral table or sorter
  69490. ** that is open on cursor P1.
  69491. **
  69492. ** This opcode only works for cursors used for sorting and
  69493. ** opened with OP_OpenEphemeral or OP_SorterOpen.
  69494. */
  69495. case OP_ResetSorter: {
  69496. VdbeCursor *pC;
  69497. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  69498. pC = p->apCsr[pOp->p1];
  69499. assert( pC!=0 );
  69500. if( pC->pSorter ){
  69501. sqlite3VdbeSorterReset(db, pC->pSorter);
  69502. }else{
  69503. assert( pC->isEphemeral );
  69504. rc = sqlite3BtreeClearTableOfCursor(pC->pCursor);
  69505. }
  69506. break;
  69507. }
  69508. /* Opcode: CreateTable P1 P2 * * *
  69509. ** Synopsis: r[P2]=root iDb=P1
  69510. **
  69511. ** Allocate a new table in the main database file if P1==0 or in the
  69512. ** auxiliary database file if P1==1 or in an attached database if
  69513. ** P1>1. Write the root page number of the new table into
  69514. ** register P2
  69515. **
  69516. ** The difference between a table and an index is this: A table must
  69517. ** have a 4-byte integer key and can have arbitrary data. An index
  69518. ** has an arbitrary key but no data.
  69519. **
  69520. ** See also: CreateIndex
  69521. */
  69522. /* Opcode: CreateIndex P1 P2 * * *
  69523. ** Synopsis: r[P2]=root iDb=P1
  69524. **
  69525. ** Allocate a new index in the main database file if P1==0 or in the
  69526. ** auxiliary database file if P1==1 or in an attached database if
  69527. ** P1>1. Write the root page number of the new table into
  69528. ** register P2.
  69529. **
  69530. ** See documentation on OP_CreateTable for additional information.
  69531. */
  69532. case OP_CreateIndex: /* out2-prerelease */
  69533. case OP_CreateTable: { /* out2-prerelease */
  69534. int pgno;
  69535. int flags;
  69536. Db *pDb;
  69537. pgno = 0;
  69538. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  69539. assert( DbMaskTest(p->btreeMask, pOp->p1) );
  69540. assert( p->readOnly==0 );
  69541. pDb = &db->aDb[pOp->p1];
  69542. assert( pDb->pBt!=0 );
  69543. if( pOp->opcode==OP_CreateTable ){
  69544. /* flags = BTREE_INTKEY; */
  69545. flags = BTREE_INTKEY;
  69546. }else{
  69547. flags = BTREE_BLOBKEY;
  69548. }
  69549. rc = sqlite3BtreeCreateTable(pDb->pBt, &pgno, flags);
  69550. pOut->u.i = pgno;
  69551. break;
  69552. }
  69553. /* Opcode: ParseSchema P1 * * P4 *
  69554. **
  69555. ** Read and parse all entries from the SQLITE_MASTER table of database P1
  69556. ** that match the WHERE clause P4.
  69557. **
  69558. ** This opcode invokes the parser to create a new virtual machine,
  69559. ** then runs the new virtual machine. It is thus a re-entrant opcode.
  69560. */
  69561. case OP_ParseSchema: {
  69562. int iDb;
  69563. const char *zMaster;
  69564. char *zSql;
  69565. InitData initData;
  69566. /* Any prepared statement that invokes this opcode will hold mutexes
  69567. ** on every btree. This is a prerequisite for invoking
  69568. ** sqlite3InitCallback().
  69569. */
  69570. #ifdef SQLITE_DEBUG
  69571. for(iDb=0; iDb<db->nDb; iDb++){
  69572. assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
  69573. }
  69574. #endif
  69575. iDb = pOp->p1;
  69576. assert( iDb>=0 && iDb<db->nDb );
  69577. assert( DbHasProperty(db, iDb, DB_SchemaLoaded) );
  69578. /* Used to be a conditional */ {
  69579. zMaster = SCHEMA_TABLE(iDb);
  69580. initData.db = db;
  69581. initData.iDb = pOp->p1;
  69582. initData.pzErrMsg = &p->zErrMsg;
  69583. zSql = sqlite3MPrintf(db,
  69584. "SELECT name, rootpage, sql FROM '%q'.%s WHERE %s ORDER BY rowid",
  69585. db->aDb[iDb].zName, zMaster, pOp->p4.z);
  69586. if( zSql==0 ){
  69587. rc = SQLITE_NOMEM;
  69588. }else{
  69589. assert( db->init.busy==0 );
  69590. db->init.busy = 1;
  69591. initData.rc = SQLITE_OK;
  69592. assert( !db->mallocFailed );
  69593. rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
  69594. if( rc==SQLITE_OK ) rc = initData.rc;
  69595. sqlite3DbFree(db, zSql);
  69596. db->init.busy = 0;
  69597. }
  69598. }
  69599. if( rc ) sqlite3ResetAllSchemasOfConnection(db);
  69600. if( rc==SQLITE_NOMEM ){
  69601. goto no_mem;
  69602. }
  69603. break;
  69604. }
  69605. #if !defined(SQLITE_OMIT_ANALYZE)
  69606. /* Opcode: LoadAnalysis P1 * * * *
  69607. **
  69608. ** Read the sqlite_stat1 table for database P1 and load the content
  69609. ** of that table into the internal index hash table. This will cause
  69610. ** the analysis to be used when preparing all subsequent queries.
  69611. */
  69612. case OP_LoadAnalysis: {
  69613. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  69614. rc = sqlite3AnalysisLoad(db, pOp->p1);
  69615. break;
  69616. }
  69617. #endif /* !defined(SQLITE_OMIT_ANALYZE) */
  69618. /* Opcode: DropTable P1 * * P4 *
  69619. **
  69620. ** Remove the internal (in-memory) data structures that describe
  69621. ** the table named P4 in database P1. This is called after a table
  69622. ** is dropped from disk (using the Destroy opcode) in order to keep
  69623. ** the internal representation of the
  69624. ** schema consistent with what is on disk.
  69625. */
  69626. case OP_DropTable: {
  69627. sqlite3UnlinkAndDeleteTable(db, pOp->p1, pOp->p4.z);
  69628. break;
  69629. }
  69630. /* Opcode: DropIndex P1 * * P4 *
  69631. **
  69632. ** Remove the internal (in-memory) data structures that describe
  69633. ** the index named P4 in database P1. This is called after an index
  69634. ** is dropped from disk (using the Destroy opcode)
  69635. ** in order to keep the internal representation of the
  69636. ** schema consistent with what is on disk.
  69637. */
  69638. case OP_DropIndex: {
  69639. sqlite3UnlinkAndDeleteIndex(db, pOp->p1, pOp->p4.z);
  69640. break;
  69641. }
  69642. /* Opcode: DropTrigger P1 * * P4 *
  69643. **
  69644. ** Remove the internal (in-memory) data structures that describe
  69645. ** the trigger named P4 in database P1. This is called after a trigger
  69646. ** is dropped from disk (using the Destroy opcode) in order to keep
  69647. ** the internal representation of the
  69648. ** schema consistent with what is on disk.
  69649. */
  69650. case OP_DropTrigger: {
  69651. sqlite3UnlinkAndDeleteTrigger(db, pOp->p1, pOp->p4.z);
  69652. break;
  69653. }
  69654. #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  69655. /* Opcode: IntegrityCk P1 P2 P3 * P5
  69656. **
  69657. ** Do an analysis of the currently open database. Store in
  69658. ** register P1 the text of an error message describing any problems.
  69659. ** If no problems are found, store a NULL in register P1.
  69660. **
  69661. ** The register P3 contains the maximum number of allowed errors.
  69662. ** At most reg(P3) errors will be reported.
  69663. ** In other words, the analysis stops as soon as reg(P1) errors are
  69664. ** seen. Reg(P1) is updated with the number of errors remaining.
  69665. **
  69666. ** The root page numbers of all tables in the database are integer
  69667. ** stored in reg(P1), reg(P1+1), reg(P1+2), .... There are P2 tables
  69668. ** total.
  69669. **
  69670. ** If P5 is not zero, the check is done on the auxiliary database
  69671. ** file, not the main database file.
  69672. **
  69673. ** This opcode is used to implement the integrity_check pragma.
  69674. */
  69675. case OP_IntegrityCk: {
  69676. int nRoot; /* Number of tables to check. (Number of root pages.) */
  69677. int *aRoot; /* Array of rootpage numbers for tables to be checked */
  69678. int j; /* Loop counter */
  69679. int nErr; /* Number of errors reported */
  69680. char *z; /* Text of the error report */
  69681. Mem *pnErr; /* Register keeping track of errors remaining */
  69682. assert( p->bIsReader );
  69683. nRoot = pOp->p2;
  69684. assert( nRoot>0 );
  69685. aRoot = sqlite3DbMallocRaw(db, sizeof(int)*(nRoot+1) );
  69686. if( aRoot==0 ) goto no_mem;
  69687. assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
  69688. pnErr = &aMem[pOp->p3];
  69689. assert( (pnErr->flags & MEM_Int)!=0 );
  69690. assert( (pnErr->flags & (MEM_Str|MEM_Blob))==0 );
  69691. pIn1 = &aMem[pOp->p1];
  69692. for(j=0; j<nRoot; j++){
  69693. aRoot[j] = (int)sqlite3VdbeIntValue(&pIn1[j]);
  69694. }
  69695. aRoot[j] = 0;
  69696. assert( pOp->p5<db->nDb );
  69697. assert( DbMaskTest(p->btreeMask, pOp->p5) );
  69698. z = sqlite3BtreeIntegrityCheck(db->aDb[pOp->p5].pBt, aRoot, nRoot,
  69699. (int)pnErr->u.i, &nErr);
  69700. sqlite3DbFree(db, aRoot);
  69701. pnErr->u.i -= nErr;
  69702. sqlite3VdbeMemSetNull(pIn1);
  69703. if( nErr==0 ){
  69704. assert( z==0 );
  69705. }else if( z==0 ){
  69706. goto no_mem;
  69707. }else{
  69708. sqlite3VdbeMemSetStr(pIn1, z, -1, SQLITE_UTF8, sqlite3_free);
  69709. }
  69710. UPDATE_MAX_BLOBSIZE(pIn1);
  69711. sqlite3VdbeChangeEncoding(pIn1, encoding);
  69712. break;
  69713. }
  69714. #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  69715. /* Opcode: RowSetAdd P1 P2 * * *
  69716. ** Synopsis: rowset(P1)=r[P2]
  69717. **
  69718. ** Insert the integer value held by register P2 into a boolean index
  69719. ** held in register P1.
  69720. **
  69721. ** An assertion fails if P2 is not an integer.
  69722. */
  69723. case OP_RowSetAdd: { /* in1, in2 */
  69724. pIn1 = &aMem[pOp->p1];
  69725. pIn2 = &aMem[pOp->p2];
  69726. assert( (pIn2->flags & MEM_Int)!=0 );
  69727. if( (pIn1->flags & MEM_RowSet)==0 ){
  69728. sqlite3VdbeMemSetRowSet(pIn1);
  69729. if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
  69730. }
  69731. sqlite3RowSetInsert(pIn1->u.pRowSet, pIn2->u.i);
  69732. break;
  69733. }
  69734. /* Opcode: RowSetRead P1 P2 P3 * *
  69735. ** Synopsis: r[P3]=rowset(P1)
  69736. **
  69737. ** Extract the smallest value from boolean index P1 and put that value into
  69738. ** register P3. Or, if boolean index P1 is initially empty, leave P3
  69739. ** unchanged and jump to instruction P2.
  69740. */
  69741. case OP_RowSetRead: { /* jump, in1, out3 */
  69742. i64 val;
  69743. pIn1 = &aMem[pOp->p1];
  69744. if( (pIn1->flags & MEM_RowSet)==0
  69745. || sqlite3RowSetNext(pIn1->u.pRowSet, &val)==0
  69746. ){
  69747. /* The boolean index is empty */
  69748. sqlite3VdbeMemSetNull(pIn1);
  69749. pc = pOp->p2 - 1;
  69750. VdbeBranchTaken(1,2);
  69751. }else{
  69752. /* A value was pulled from the index */
  69753. sqlite3VdbeMemSetInt64(&aMem[pOp->p3], val);
  69754. VdbeBranchTaken(0,2);
  69755. }
  69756. goto check_for_interrupt;
  69757. }
  69758. /* Opcode: RowSetTest P1 P2 P3 P4
  69759. ** Synopsis: if r[P3] in rowset(P1) goto P2
  69760. **
  69761. ** Register P3 is assumed to hold a 64-bit integer value. If register P1
  69762. ** contains a RowSet object and that RowSet object contains
  69763. ** the value held in P3, jump to register P2. Otherwise, insert the
  69764. ** integer in P3 into the RowSet and continue on to the
  69765. ** next opcode.
  69766. **
  69767. ** The RowSet object is optimized for the case where successive sets
  69768. ** of integers, where each set contains no duplicates. Each set
  69769. ** of values is identified by a unique P4 value. The first set
  69770. ** must have P4==0, the final set P4=-1. P4 must be either -1 or
  69771. ** non-negative. For non-negative values of P4 only the lower 4
  69772. ** bits are significant.
  69773. **
  69774. ** This allows optimizations: (a) when P4==0 there is no need to test
  69775. ** the rowset object for P3, as it is guaranteed not to contain it,
  69776. ** (b) when P4==-1 there is no need to insert the value, as it will
  69777. ** never be tested for, and (c) when a value that is part of set X is
  69778. ** inserted, there is no need to search to see if the same value was
  69779. ** previously inserted as part of set X (only if it was previously
  69780. ** inserted as part of some other set).
  69781. */
  69782. case OP_RowSetTest: { /* jump, in1, in3 */
  69783. int iSet;
  69784. int exists;
  69785. pIn1 = &aMem[pOp->p1];
  69786. pIn3 = &aMem[pOp->p3];
  69787. iSet = pOp->p4.i;
  69788. assert( pIn3->flags&MEM_Int );
  69789. /* If there is anything other than a rowset object in memory cell P1,
  69790. ** delete it now and initialize P1 with an empty rowset
  69791. */
  69792. if( (pIn1->flags & MEM_RowSet)==0 ){
  69793. sqlite3VdbeMemSetRowSet(pIn1);
  69794. if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
  69795. }
  69796. assert( pOp->p4type==P4_INT32 );
  69797. assert( iSet==-1 || iSet>=0 );
  69798. if( iSet ){
  69799. exists = sqlite3RowSetTest(pIn1->u.pRowSet, iSet, pIn3->u.i);
  69800. VdbeBranchTaken(exists!=0,2);
  69801. if( exists ){
  69802. pc = pOp->p2 - 1;
  69803. break;
  69804. }
  69805. }
  69806. if( iSet>=0 ){
  69807. sqlite3RowSetInsert(pIn1->u.pRowSet, pIn3->u.i);
  69808. }
  69809. break;
  69810. }
  69811. #ifndef SQLITE_OMIT_TRIGGER
  69812. /* Opcode: Program P1 P2 P3 P4 P5
  69813. **
  69814. ** Execute the trigger program passed as P4 (type P4_SUBPROGRAM).
  69815. **
  69816. ** P1 contains the address of the memory cell that contains the first memory
  69817. ** cell in an array of values used as arguments to the sub-program. P2
  69818. ** contains the address to jump to if the sub-program throws an IGNORE
  69819. ** exception using the RAISE() function. Register P3 contains the address
  69820. ** of a memory cell in this (the parent) VM that is used to allocate the
  69821. ** memory required by the sub-vdbe at runtime.
  69822. **
  69823. ** P4 is a pointer to the VM containing the trigger program.
  69824. **
  69825. ** If P5 is non-zero, then recursive program invocation is enabled.
  69826. */
  69827. case OP_Program: { /* jump */
  69828. int nMem; /* Number of memory registers for sub-program */
  69829. int nByte; /* Bytes of runtime space required for sub-program */
  69830. Mem *pRt; /* Register to allocate runtime space */
  69831. Mem *pMem; /* Used to iterate through memory cells */
  69832. Mem *pEnd; /* Last memory cell in new array */
  69833. VdbeFrame *pFrame; /* New vdbe frame to execute in */
  69834. SubProgram *pProgram; /* Sub-program to execute */
  69835. void *t; /* Token identifying trigger */
  69836. pProgram = pOp->p4.pProgram;
  69837. pRt = &aMem[pOp->p3];
  69838. assert( pProgram->nOp>0 );
  69839. /* If the p5 flag is clear, then recursive invocation of triggers is
  69840. ** disabled for backwards compatibility (p5 is set if this sub-program
  69841. ** is really a trigger, not a foreign key action, and the flag set
  69842. ** and cleared by the "PRAGMA recursive_triggers" command is clear).
  69843. **
  69844. ** It is recursive invocation of triggers, at the SQL level, that is
  69845. ** disabled. In some cases a single trigger may generate more than one
  69846. ** SubProgram (if the trigger may be executed with more than one different
  69847. ** ON CONFLICT algorithm). SubProgram structures associated with a
  69848. ** single trigger all have the same value for the SubProgram.token
  69849. ** variable. */
  69850. if( pOp->p5 ){
  69851. t = pProgram->token;
  69852. for(pFrame=p->pFrame; pFrame && pFrame->token!=t; pFrame=pFrame->pParent);
  69853. if( pFrame ) break;
  69854. }
  69855. if( p->nFrame>=db->aLimit[SQLITE_LIMIT_TRIGGER_DEPTH] ){
  69856. rc = SQLITE_ERROR;
  69857. sqlite3SetString(&p->zErrMsg, db, "too many levels of trigger recursion");
  69858. break;
  69859. }
  69860. /* Register pRt is used to store the memory required to save the state
  69861. ** of the current program, and the memory required at runtime to execute
  69862. ** the trigger program. If this trigger has been fired before, then pRt
  69863. ** is already allocated. Otherwise, it must be initialized. */
  69864. if( (pRt->flags&MEM_Frame)==0 ){
  69865. /* SubProgram.nMem is set to the number of memory cells used by the
  69866. ** program stored in SubProgram.aOp. As well as these, one memory
  69867. ** cell is required for each cursor used by the program. Set local
  69868. ** variable nMem (and later, VdbeFrame.nChildMem) to this value.
  69869. */
  69870. nMem = pProgram->nMem + pProgram->nCsr;
  69871. nByte = ROUND8(sizeof(VdbeFrame))
  69872. + nMem * sizeof(Mem)
  69873. + pProgram->nCsr * sizeof(VdbeCursor *)
  69874. + pProgram->nOnce * sizeof(u8);
  69875. pFrame = sqlite3DbMallocZero(db, nByte);
  69876. if( !pFrame ){
  69877. goto no_mem;
  69878. }
  69879. sqlite3VdbeMemRelease(pRt);
  69880. pRt->flags = MEM_Frame;
  69881. pRt->u.pFrame = pFrame;
  69882. pFrame->v = p;
  69883. pFrame->nChildMem = nMem;
  69884. pFrame->nChildCsr = pProgram->nCsr;
  69885. pFrame->pc = pc;
  69886. pFrame->aMem = p->aMem;
  69887. pFrame->nMem = p->nMem;
  69888. pFrame->apCsr = p->apCsr;
  69889. pFrame->nCursor = p->nCursor;
  69890. pFrame->aOp = p->aOp;
  69891. pFrame->nOp = p->nOp;
  69892. pFrame->token = pProgram->token;
  69893. pFrame->aOnceFlag = p->aOnceFlag;
  69894. pFrame->nOnceFlag = p->nOnceFlag;
  69895. pEnd = &VdbeFrameMem(pFrame)[pFrame->nChildMem];
  69896. for(pMem=VdbeFrameMem(pFrame); pMem!=pEnd; pMem++){
  69897. pMem->flags = MEM_Undefined;
  69898. pMem->db = db;
  69899. }
  69900. }else{
  69901. pFrame = pRt->u.pFrame;
  69902. assert( pProgram->nMem+pProgram->nCsr==pFrame->nChildMem );
  69903. assert( pProgram->nCsr==pFrame->nChildCsr );
  69904. assert( pc==pFrame->pc );
  69905. }
  69906. p->nFrame++;
  69907. pFrame->pParent = p->pFrame;
  69908. pFrame->lastRowid = lastRowid;
  69909. pFrame->nChange = p->nChange;
  69910. p->nChange = 0;
  69911. p->pFrame = pFrame;
  69912. p->aMem = aMem = &VdbeFrameMem(pFrame)[-1];
  69913. p->nMem = pFrame->nChildMem;
  69914. p->nCursor = (u16)pFrame->nChildCsr;
  69915. p->apCsr = (VdbeCursor **)&aMem[p->nMem+1];
  69916. p->aOp = aOp = pProgram->aOp;
  69917. p->nOp = pProgram->nOp;
  69918. p->aOnceFlag = (u8 *)&p->apCsr[p->nCursor];
  69919. p->nOnceFlag = pProgram->nOnce;
  69920. pc = -1;
  69921. memset(p->aOnceFlag, 0, p->nOnceFlag);
  69922. break;
  69923. }
  69924. /* Opcode: Param P1 P2 * * *
  69925. **
  69926. ** This opcode is only ever present in sub-programs called via the
  69927. ** OP_Program instruction. Copy a value currently stored in a memory
  69928. ** cell of the calling (parent) frame to cell P2 in the current frames
  69929. ** address space. This is used by trigger programs to access the new.*
  69930. ** and old.* values.
  69931. **
  69932. ** The address of the cell in the parent frame is determined by adding
  69933. ** the value of the P1 argument to the value of the P1 argument to the
  69934. ** calling OP_Program instruction.
  69935. */
  69936. case OP_Param: { /* out2-prerelease */
  69937. VdbeFrame *pFrame;
  69938. Mem *pIn;
  69939. pFrame = p->pFrame;
  69940. pIn = &pFrame->aMem[pOp->p1 + pFrame->aOp[pFrame->pc].p1];
  69941. sqlite3VdbeMemShallowCopy(pOut, pIn, MEM_Ephem);
  69942. break;
  69943. }
  69944. #endif /* #ifndef SQLITE_OMIT_TRIGGER */
  69945. #ifndef SQLITE_OMIT_FOREIGN_KEY
  69946. /* Opcode: FkCounter P1 P2 * * *
  69947. ** Synopsis: fkctr[P1]+=P2
  69948. **
  69949. ** Increment a "constraint counter" by P2 (P2 may be negative or positive).
  69950. ** If P1 is non-zero, the database constraint counter is incremented
  69951. ** (deferred foreign key constraints). Otherwise, if P1 is zero, the
  69952. ** statement counter is incremented (immediate foreign key constraints).
  69953. */
  69954. case OP_FkCounter: {
  69955. if( db->flags & SQLITE_DeferFKs ){
  69956. db->nDeferredImmCons += pOp->p2;
  69957. }else if( pOp->p1 ){
  69958. db->nDeferredCons += pOp->p2;
  69959. }else{
  69960. p->nFkConstraint += pOp->p2;
  69961. }
  69962. break;
  69963. }
  69964. /* Opcode: FkIfZero P1 P2 * * *
  69965. ** Synopsis: if fkctr[P1]==0 goto P2
  69966. **
  69967. ** This opcode tests if a foreign key constraint-counter is currently zero.
  69968. ** If so, jump to instruction P2. Otherwise, fall through to the next
  69969. ** instruction.
  69970. **
  69971. ** If P1 is non-zero, then the jump is taken if the database constraint-counter
  69972. ** is zero (the one that counts deferred constraint violations). If P1 is
  69973. ** zero, the jump is taken if the statement constraint-counter is zero
  69974. ** (immediate foreign key constraint violations).
  69975. */
  69976. case OP_FkIfZero: { /* jump */
  69977. if( pOp->p1 ){
  69978. VdbeBranchTaken(db->nDeferredCons==0 && db->nDeferredImmCons==0, 2);
  69979. if( db->nDeferredCons==0 && db->nDeferredImmCons==0 ) pc = pOp->p2-1;
  69980. }else{
  69981. VdbeBranchTaken(p->nFkConstraint==0 && db->nDeferredImmCons==0, 2);
  69982. if( p->nFkConstraint==0 && db->nDeferredImmCons==0 ) pc = pOp->p2-1;
  69983. }
  69984. break;
  69985. }
  69986. #endif /* #ifndef SQLITE_OMIT_FOREIGN_KEY */
  69987. #ifndef SQLITE_OMIT_AUTOINCREMENT
  69988. /* Opcode: MemMax P1 P2 * * *
  69989. ** Synopsis: r[P1]=max(r[P1],r[P2])
  69990. **
  69991. ** P1 is a register in the root frame of this VM (the root frame is
  69992. ** different from the current frame if this instruction is being executed
  69993. ** within a sub-program). Set the value of register P1 to the maximum of
  69994. ** its current value and the value in register P2.
  69995. **
  69996. ** This instruction throws an error if the memory cell is not initially
  69997. ** an integer.
  69998. */
  69999. case OP_MemMax: { /* in2 */
  70000. VdbeFrame *pFrame;
  70001. if( p->pFrame ){
  70002. for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
  70003. pIn1 = &pFrame->aMem[pOp->p1];
  70004. }else{
  70005. pIn1 = &aMem[pOp->p1];
  70006. }
  70007. assert( memIsValid(pIn1) );
  70008. sqlite3VdbeMemIntegerify(pIn1);
  70009. pIn2 = &aMem[pOp->p2];
  70010. sqlite3VdbeMemIntegerify(pIn2);
  70011. if( pIn1->u.i<pIn2->u.i){
  70012. pIn1->u.i = pIn2->u.i;
  70013. }
  70014. break;
  70015. }
  70016. #endif /* SQLITE_OMIT_AUTOINCREMENT */
  70017. /* Opcode: IfPos P1 P2 * * *
  70018. ** Synopsis: if r[P1]>0 goto P2
  70019. **
  70020. ** If the value of register P1 is 1 or greater, jump to P2.
  70021. **
  70022. ** It is illegal to use this instruction on a register that does
  70023. ** not contain an integer. An assertion fault will result if you try.
  70024. */
  70025. case OP_IfPos: { /* jump, in1 */
  70026. pIn1 = &aMem[pOp->p1];
  70027. assert( pIn1->flags&MEM_Int );
  70028. VdbeBranchTaken( pIn1->u.i>0, 2);
  70029. if( pIn1->u.i>0 ){
  70030. pc = pOp->p2 - 1;
  70031. }
  70032. break;
  70033. }
  70034. /* Opcode: IfNeg P1 P2 P3 * *
  70035. ** Synopsis: r[P1]+=P3, if r[P1]<0 goto P2
  70036. **
  70037. ** Register P1 must contain an integer. Add literal P3 to the value in
  70038. ** register P1 then if the value of register P1 is less than zero, jump to P2.
  70039. */
  70040. case OP_IfNeg: { /* jump, in1 */
  70041. pIn1 = &aMem[pOp->p1];
  70042. assert( pIn1->flags&MEM_Int );
  70043. pIn1->u.i += pOp->p3;
  70044. VdbeBranchTaken(pIn1->u.i<0, 2);
  70045. if( pIn1->u.i<0 ){
  70046. pc = pOp->p2 - 1;
  70047. }
  70048. break;
  70049. }
  70050. /* Opcode: IfZero P1 P2 P3 * *
  70051. ** Synopsis: r[P1]+=P3, if r[P1]==0 goto P2
  70052. **
  70053. ** The register P1 must contain an integer. Add literal P3 to the
  70054. ** value in register P1. If the result is exactly 0, jump to P2.
  70055. */
  70056. case OP_IfZero: { /* jump, in1 */
  70057. pIn1 = &aMem[pOp->p1];
  70058. assert( pIn1->flags&MEM_Int );
  70059. pIn1->u.i += pOp->p3;
  70060. VdbeBranchTaken(pIn1->u.i==0, 2);
  70061. if( pIn1->u.i==0 ){
  70062. pc = pOp->p2 - 1;
  70063. }
  70064. break;
  70065. }
  70066. /* Opcode: AggStep * P2 P3 P4 P5
  70067. ** Synopsis: accum=r[P3] step(r[P2@P5])
  70068. **
  70069. ** Execute the step function for an aggregate. The
  70070. ** function has P5 arguments. P4 is a pointer to the FuncDef
  70071. ** structure that specifies the function. Use register
  70072. ** P3 as the accumulator.
  70073. **
  70074. ** The P5 arguments are taken from register P2 and its
  70075. ** successors.
  70076. */
  70077. case OP_AggStep: {
  70078. int n;
  70079. int i;
  70080. Mem *pMem;
  70081. Mem *pRec;
  70082. Mem t;
  70083. sqlite3_context ctx;
  70084. sqlite3_value **apVal;
  70085. n = pOp->p5;
  70086. assert( n>=0 );
  70087. pRec = &aMem[pOp->p2];
  70088. apVal = p->apArg;
  70089. assert( apVal || n==0 );
  70090. for(i=0; i<n; i++, pRec++){
  70091. assert( memIsValid(pRec) );
  70092. apVal[i] = pRec;
  70093. memAboutToChange(p, pRec);
  70094. }
  70095. ctx.pFunc = pOp->p4.pFunc;
  70096. assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
  70097. ctx.pMem = pMem = &aMem[pOp->p3];
  70098. pMem->n++;
  70099. sqlite3VdbeMemInit(&t, db, MEM_Null);
  70100. ctx.pOut = &t;
  70101. ctx.isError = 0;
  70102. ctx.pVdbe = p;
  70103. ctx.iOp = pc;
  70104. ctx.skipFlag = 0;
  70105. (ctx.pFunc->xStep)(&ctx, n, apVal); /* IMP: R-24505-23230 */
  70106. if( ctx.isError ){
  70107. sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(&t));
  70108. rc = ctx.isError;
  70109. }
  70110. if( ctx.skipFlag ){
  70111. assert( pOp[-1].opcode==OP_CollSeq );
  70112. i = pOp[-1].p1;
  70113. if( i ) sqlite3VdbeMemSetInt64(&aMem[i], 1);
  70114. }
  70115. sqlite3VdbeMemRelease(&t);
  70116. break;
  70117. }
  70118. /* Opcode: AggFinal P1 P2 * P4 *
  70119. ** Synopsis: accum=r[P1] N=P2
  70120. **
  70121. ** Execute the finalizer function for an aggregate. P1 is
  70122. ** the memory location that is the accumulator for the aggregate.
  70123. **
  70124. ** P2 is the number of arguments that the step function takes and
  70125. ** P4 is a pointer to the FuncDef for this function. The P2
  70126. ** argument is not used by this opcode. It is only there to disambiguate
  70127. ** functions that can take varying numbers of arguments. The
  70128. ** P4 argument is only needed for the degenerate case where
  70129. ** the step function was not previously called.
  70130. */
  70131. case OP_AggFinal: {
  70132. Mem *pMem;
  70133. assert( pOp->p1>0 && pOp->p1<=(p->nMem-p->nCursor) );
  70134. pMem = &aMem[pOp->p1];
  70135. assert( (pMem->flags & ~(MEM_Null|MEM_Agg))==0 );
  70136. rc = sqlite3VdbeMemFinalize(pMem, pOp->p4.pFunc);
  70137. if( rc ){
  70138. sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(pMem));
  70139. }
  70140. sqlite3VdbeChangeEncoding(pMem, encoding);
  70141. UPDATE_MAX_BLOBSIZE(pMem);
  70142. if( sqlite3VdbeMemTooBig(pMem) ){
  70143. goto too_big;
  70144. }
  70145. break;
  70146. }
  70147. #ifndef SQLITE_OMIT_WAL
  70148. /* Opcode: Checkpoint P1 P2 P3 * *
  70149. **
  70150. ** Checkpoint database P1. This is a no-op if P1 is not currently in
  70151. ** WAL mode. Parameter P2 is one of SQLITE_CHECKPOINT_PASSIVE, FULL
  70152. ** or RESTART. Write 1 or 0 into mem[P3] if the checkpoint returns
  70153. ** SQLITE_BUSY or not, respectively. Write the number of pages in the
  70154. ** WAL after the checkpoint into mem[P3+1] and the number of pages
  70155. ** in the WAL that have been checkpointed after the checkpoint
  70156. ** completes into mem[P3+2]. However on an error, mem[P3+1] and
  70157. ** mem[P3+2] are initialized to -1.
  70158. */
  70159. case OP_Checkpoint: {
  70160. int i; /* Loop counter */
  70161. int aRes[3]; /* Results */
  70162. Mem *pMem; /* Write results here */
  70163. assert( p->readOnly==0 );
  70164. aRes[0] = 0;
  70165. aRes[1] = aRes[2] = -1;
  70166. assert( pOp->p2==SQLITE_CHECKPOINT_PASSIVE
  70167. || pOp->p2==SQLITE_CHECKPOINT_FULL
  70168. || pOp->p2==SQLITE_CHECKPOINT_RESTART
  70169. );
  70170. rc = sqlite3Checkpoint(db, pOp->p1, pOp->p2, &aRes[1], &aRes[2]);
  70171. if( rc==SQLITE_BUSY ){
  70172. rc = SQLITE_OK;
  70173. aRes[0] = 1;
  70174. }
  70175. for(i=0, pMem = &aMem[pOp->p3]; i<3; i++, pMem++){
  70176. sqlite3VdbeMemSetInt64(pMem, (i64)aRes[i]);
  70177. }
  70178. break;
  70179. };
  70180. #endif
  70181. #ifndef SQLITE_OMIT_PRAGMA
  70182. /* Opcode: JournalMode P1 P2 P3 * *
  70183. **
  70184. ** Change the journal mode of database P1 to P3. P3 must be one of the
  70185. ** PAGER_JOURNALMODE_XXX values. If changing between the various rollback
  70186. ** modes (delete, truncate, persist, off and memory), this is a simple
  70187. ** operation. No IO is required.
  70188. **
  70189. ** If changing into or out of WAL mode the procedure is more complicated.
  70190. **
  70191. ** Write a string containing the final journal-mode to register P2.
  70192. */
  70193. case OP_JournalMode: { /* out2-prerelease */
  70194. Btree *pBt; /* Btree to change journal mode of */
  70195. Pager *pPager; /* Pager associated with pBt */
  70196. int eNew; /* New journal mode */
  70197. int eOld; /* The old journal mode */
  70198. #ifndef SQLITE_OMIT_WAL
  70199. const char *zFilename; /* Name of database file for pPager */
  70200. #endif
  70201. eNew = pOp->p3;
  70202. assert( eNew==PAGER_JOURNALMODE_DELETE
  70203. || eNew==PAGER_JOURNALMODE_TRUNCATE
  70204. || eNew==PAGER_JOURNALMODE_PERSIST
  70205. || eNew==PAGER_JOURNALMODE_OFF
  70206. || eNew==PAGER_JOURNALMODE_MEMORY
  70207. || eNew==PAGER_JOURNALMODE_WAL
  70208. || eNew==PAGER_JOURNALMODE_QUERY
  70209. );
  70210. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  70211. assert( p->readOnly==0 );
  70212. pBt = db->aDb[pOp->p1].pBt;
  70213. pPager = sqlite3BtreePager(pBt);
  70214. eOld = sqlite3PagerGetJournalMode(pPager);
  70215. if( eNew==PAGER_JOURNALMODE_QUERY ) eNew = eOld;
  70216. if( !sqlite3PagerOkToChangeJournalMode(pPager) ) eNew = eOld;
  70217. #ifndef SQLITE_OMIT_WAL
  70218. zFilename = sqlite3PagerFilename(pPager, 1);
  70219. /* Do not allow a transition to journal_mode=WAL for a database
  70220. ** in temporary storage or if the VFS does not support shared memory
  70221. */
  70222. if( eNew==PAGER_JOURNALMODE_WAL
  70223. && (sqlite3Strlen30(zFilename)==0 /* Temp file */
  70224. || !sqlite3PagerWalSupported(pPager)) /* No shared-memory support */
  70225. ){
  70226. eNew = eOld;
  70227. }
  70228. if( (eNew!=eOld)
  70229. && (eOld==PAGER_JOURNALMODE_WAL || eNew==PAGER_JOURNALMODE_WAL)
  70230. ){
  70231. if( !db->autoCommit || db->nVdbeRead>1 ){
  70232. rc = SQLITE_ERROR;
  70233. sqlite3SetString(&p->zErrMsg, db,
  70234. "cannot change %s wal mode from within a transaction",
  70235. (eNew==PAGER_JOURNALMODE_WAL ? "into" : "out of")
  70236. );
  70237. break;
  70238. }else{
  70239. if( eOld==PAGER_JOURNALMODE_WAL ){
  70240. /* If leaving WAL mode, close the log file. If successful, the call
  70241. ** to PagerCloseWal() checkpoints and deletes the write-ahead-log
  70242. ** file. An EXCLUSIVE lock may still be held on the database file
  70243. ** after a successful return.
  70244. */
  70245. rc = sqlite3PagerCloseWal(pPager);
  70246. if( rc==SQLITE_OK ){
  70247. sqlite3PagerSetJournalMode(pPager, eNew);
  70248. }
  70249. }else if( eOld==PAGER_JOURNALMODE_MEMORY ){
  70250. /* Cannot transition directly from MEMORY to WAL. Use mode OFF
  70251. ** as an intermediate */
  70252. sqlite3PagerSetJournalMode(pPager, PAGER_JOURNALMODE_OFF);
  70253. }
  70254. /* Open a transaction on the database file. Regardless of the journal
  70255. ** mode, this transaction always uses a rollback journal.
  70256. */
  70257. assert( sqlite3BtreeIsInTrans(pBt)==0 );
  70258. if( rc==SQLITE_OK ){
  70259. rc = sqlite3BtreeSetVersion(pBt, (eNew==PAGER_JOURNALMODE_WAL ? 2 : 1));
  70260. }
  70261. }
  70262. }
  70263. #endif /* ifndef SQLITE_OMIT_WAL */
  70264. if( rc ){
  70265. eNew = eOld;
  70266. }
  70267. eNew = sqlite3PagerSetJournalMode(pPager, eNew);
  70268. pOut = &aMem[pOp->p2];
  70269. pOut->flags = MEM_Str|MEM_Static|MEM_Term;
  70270. pOut->z = (char *)sqlite3JournalModename(eNew);
  70271. pOut->n = sqlite3Strlen30(pOut->z);
  70272. pOut->enc = SQLITE_UTF8;
  70273. sqlite3VdbeChangeEncoding(pOut, encoding);
  70274. break;
  70275. };
  70276. #endif /* SQLITE_OMIT_PRAGMA */
  70277. #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
  70278. /* Opcode: Vacuum * * * * *
  70279. **
  70280. ** Vacuum the entire database. This opcode will cause other virtual
  70281. ** machines to be created and run. It may not be called from within
  70282. ** a transaction.
  70283. */
  70284. case OP_Vacuum: {
  70285. assert( p->readOnly==0 );
  70286. rc = sqlite3RunVacuum(&p->zErrMsg, db);
  70287. break;
  70288. }
  70289. #endif
  70290. #if !defined(SQLITE_OMIT_AUTOVACUUM)
  70291. /* Opcode: IncrVacuum P1 P2 * * *
  70292. **
  70293. ** Perform a single step of the incremental vacuum procedure on
  70294. ** the P1 database. If the vacuum has finished, jump to instruction
  70295. ** P2. Otherwise, fall through to the next instruction.
  70296. */
  70297. case OP_IncrVacuum: { /* jump */
  70298. Btree *pBt;
  70299. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  70300. assert( DbMaskTest(p->btreeMask, pOp->p1) );
  70301. assert( p->readOnly==0 );
  70302. pBt = db->aDb[pOp->p1].pBt;
  70303. rc = sqlite3BtreeIncrVacuum(pBt);
  70304. VdbeBranchTaken(rc==SQLITE_DONE,2);
  70305. if( rc==SQLITE_DONE ){
  70306. pc = pOp->p2 - 1;
  70307. rc = SQLITE_OK;
  70308. }
  70309. break;
  70310. }
  70311. #endif
  70312. /* Opcode: Expire P1 * * * *
  70313. **
  70314. ** Cause precompiled statements to expire. When an expired statement
  70315. ** is executed using sqlite3_step() it will either automatically
  70316. ** reprepare itself (if it was originally created using sqlite3_prepare_v2())
  70317. ** or it will fail with SQLITE_SCHEMA.
  70318. **
  70319. ** If P1 is 0, then all SQL statements become expired. If P1 is non-zero,
  70320. ** then only the currently executing statement is expired.
  70321. */
  70322. case OP_Expire: {
  70323. if( !pOp->p1 ){
  70324. sqlite3ExpirePreparedStatements(db);
  70325. }else{
  70326. p->expired = 1;
  70327. }
  70328. break;
  70329. }
  70330. #ifndef SQLITE_OMIT_SHARED_CACHE
  70331. /* Opcode: TableLock P1 P2 P3 P4 *
  70332. ** Synopsis: iDb=P1 root=P2 write=P3
  70333. **
  70334. ** Obtain a lock on a particular table. This instruction is only used when
  70335. ** the shared-cache feature is enabled.
  70336. **
  70337. ** P1 is the index of the database in sqlite3.aDb[] of the database
  70338. ** on which the lock is acquired. A readlock is obtained if P3==0 or
  70339. ** a write lock if P3==1.
  70340. **
  70341. ** P2 contains the root-page of the table to lock.
  70342. **
  70343. ** P4 contains a pointer to the name of the table being locked. This is only
  70344. ** used to generate an error message if the lock cannot be obtained.
  70345. */
  70346. case OP_TableLock: {
  70347. u8 isWriteLock = (u8)pOp->p3;
  70348. if( isWriteLock || 0==(db->flags&SQLITE_ReadUncommitted) ){
  70349. int p1 = pOp->p1;
  70350. assert( p1>=0 && p1<db->nDb );
  70351. assert( DbMaskTest(p->btreeMask, p1) );
  70352. assert( isWriteLock==0 || isWriteLock==1 );
  70353. rc = sqlite3BtreeLockTable(db->aDb[p1].pBt, pOp->p2, isWriteLock);
  70354. if( (rc&0xFF)==SQLITE_LOCKED ){
  70355. const char *z = pOp->p4.z;
  70356. sqlite3SetString(&p->zErrMsg, db, "database table is locked: %s", z);
  70357. }
  70358. }
  70359. break;
  70360. }
  70361. #endif /* SQLITE_OMIT_SHARED_CACHE */
  70362. #ifndef SQLITE_OMIT_VIRTUALTABLE
  70363. /* Opcode: VBegin * * * P4 *
  70364. **
  70365. ** P4 may be a pointer to an sqlite3_vtab structure. If so, call the
  70366. ** xBegin method for that table.
  70367. **
  70368. ** Also, whether or not P4 is set, check that this is not being called from
  70369. ** within a callback to a virtual table xSync() method. If it is, the error
  70370. ** code will be set to SQLITE_LOCKED.
  70371. */
  70372. case OP_VBegin: {
  70373. VTable *pVTab;
  70374. pVTab = pOp->p4.pVtab;
  70375. rc = sqlite3VtabBegin(db, pVTab);
  70376. if( pVTab ) sqlite3VtabImportErrmsg(p, pVTab->pVtab);
  70377. break;
  70378. }
  70379. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  70380. #ifndef SQLITE_OMIT_VIRTUALTABLE
  70381. /* Opcode: VCreate P1 * * P4 *
  70382. **
  70383. ** P4 is the name of a virtual table in database P1. Call the xCreate method
  70384. ** for that table.
  70385. */
  70386. case OP_VCreate: {
  70387. rc = sqlite3VtabCallCreate(db, pOp->p1, pOp->p4.z, &p->zErrMsg);
  70388. break;
  70389. }
  70390. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  70391. #ifndef SQLITE_OMIT_VIRTUALTABLE
  70392. /* Opcode: VDestroy P1 * * P4 *
  70393. **
  70394. ** P4 is the name of a virtual table in database P1. Call the xDestroy method
  70395. ** of that table.
  70396. */
  70397. case OP_VDestroy: {
  70398. p->inVtabMethod = 2;
  70399. rc = sqlite3VtabCallDestroy(db, pOp->p1, pOp->p4.z);
  70400. p->inVtabMethod = 0;
  70401. break;
  70402. }
  70403. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  70404. #ifndef SQLITE_OMIT_VIRTUALTABLE
  70405. /* Opcode: VOpen P1 * * P4 *
  70406. **
  70407. ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
  70408. ** P1 is a cursor number. This opcode opens a cursor to the virtual
  70409. ** table and stores that cursor in P1.
  70410. */
  70411. case OP_VOpen: {
  70412. VdbeCursor *pCur;
  70413. sqlite3_vtab_cursor *pVtabCursor;
  70414. sqlite3_vtab *pVtab;
  70415. sqlite3_module *pModule;
  70416. assert( p->bIsReader );
  70417. pCur = 0;
  70418. pVtabCursor = 0;
  70419. pVtab = pOp->p4.pVtab->pVtab;
  70420. pModule = (sqlite3_module *)pVtab->pModule;
  70421. assert(pVtab && pModule);
  70422. rc = pModule->xOpen(pVtab, &pVtabCursor);
  70423. sqlite3VtabImportErrmsg(p, pVtab);
  70424. if( SQLITE_OK==rc ){
  70425. /* Initialize sqlite3_vtab_cursor base class */
  70426. pVtabCursor->pVtab = pVtab;
  70427. /* Initialize vdbe cursor object */
  70428. pCur = allocateCursor(p, pOp->p1, 0, -1, 0);
  70429. if( pCur ){
  70430. pCur->pVtabCursor = pVtabCursor;
  70431. }else{
  70432. db->mallocFailed = 1;
  70433. pModule->xClose(pVtabCursor);
  70434. }
  70435. }
  70436. break;
  70437. }
  70438. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  70439. #ifndef SQLITE_OMIT_VIRTUALTABLE
  70440. /* Opcode: VFilter P1 P2 P3 P4 *
  70441. ** Synopsis: iplan=r[P3] zplan='P4'
  70442. **
  70443. ** P1 is a cursor opened using VOpen. P2 is an address to jump to if
  70444. ** the filtered result set is empty.
  70445. **
  70446. ** P4 is either NULL or a string that was generated by the xBestIndex
  70447. ** method of the module. The interpretation of the P4 string is left
  70448. ** to the module implementation.
  70449. **
  70450. ** This opcode invokes the xFilter method on the virtual table specified
  70451. ** by P1. The integer query plan parameter to xFilter is stored in register
  70452. ** P3. Register P3+1 stores the argc parameter to be passed to the
  70453. ** xFilter method. Registers P3+2..P3+1+argc are the argc
  70454. ** additional parameters which are passed to
  70455. ** xFilter as argv. Register P3+2 becomes argv[0] when passed to xFilter.
  70456. **
  70457. ** A jump is made to P2 if the result set after filtering would be empty.
  70458. */
  70459. case OP_VFilter: { /* jump */
  70460. int nArg;
  70461. int iQuery;
  70462. const sqlite3_module *pModule;
  70463. Mem *pQuery;
  70464. Mem *pArgc;
  70465. sqlite3_vtab_cursor *pVtabCursor;
  70466. sqlite3_vtab *pVtab;
  70467. VdbeCursor *pCur;
  70468. int res;
  70469. int i;
  70470. Mem **apArg;
  70471. pQuery = &aMem[pOp->p3];
  70472. pArgc = &pQuery[1];
  70473. pCur = p->apCsr[pOp->p1];
  70474. assert( memIsValid(pQuery) );
  70475. REGISTER_TRACE(pOp->p3, pQuery);
  70476. assert( pCur->pVtabCursor );
  70477. pVtabCursor = pCur->pVtabCursor;
  70478. pVtab = pVtabCursor->pVtab;
  70479. pModule = pVtab->pModule;
  70480. /* Grab the index number and argc parameters */
  70481. assert( (pQuery->flags&MEM_Int)!=0 && pArgc->flags==MEM_Int );
  70482. nArg = (int)pArgc->u.i;
  70483. iQuery = (int)pQuery->u.i;
  70484. /* Invoke the xFilter method */
  70485. {
  70486. res = 0;
  70487. apArg = p->apArg;
  70488. for(i = 0; i<nArg; i++){
  70489. apArg[i] = &pArgc[i+1];
  70490. }
  70491. p->inVtabMethod = 1;
  70492. rc = pModule->xFilter(pVtabCursor, iQuery, pOp->p4.z, nArg, apArg);
  70493. p->inVtabMethod = 0;
  70494. sqlite3VtabImportErrmsg(p, pVtab);
  70495. if( rc==SQLITE_OK ){
  70496. res = pModule->xEof(pVtabCursor);
  70497. }
  70498. VdbeBranchTaken(res!=0,2);
  70499. if( res ){
  70500. pc = pOp->p2 - 1;
  70501. }
  70502. }
  70503. pCur->nullRow = 0;
  70504. break;
  70505. }
  70506. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  70507. #ifndef SQLITE_OMIT_VIRTUALTABLE
  70508. /* Opcode: VColumn P1 P2 P3 * *
  70509. ** Synopsis: r[P3]=vcolumn(P2)
  70510. **
  70511. ** Store the value of the P2-th column of
  70512. ** the row of the virtual-table that the
  70513. ** P1 cursor is pointing to into register P3.
  70514. */
  70515. case OP_VColumn: {
  70516. sqlite3_vtab *pVtab;
  70517. const sqlite3_module *pModule;
  70518. Mem *pDest;
  70519. sqlite3_context sContext;
  70520. VdbeCursor *pCur = p->apCsr[pOp->p1];
  70521. assert( pCur->pVtabCursor );
  70522. assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
  70523. pDest = &aMem[pOp->p3];
  70524. memAboutToChange(p, pDest);
  70525. if( pCur->nullRow ){
  70526. sqlite3VdbeMemSetNull(pDest);
  70527. break;
  70528. }
  70529. pVtab = pCur->pVtabCursor->pVtab;
  70530. pModule = pVtab->pModule;
  70531. assert( pModule->xColumn );
  70532. memset(&sContext, 0, sizeof(sContext));
  70533. sContext.pOut = pDest;
  70534. MemSetTypeFlag(pDest, MEM_Null);
  70535. rc = pModule->xColumn(pCur->pVtabCursor, &sContext, pOp->p2);
  70536. sqlite3VtabImportErrmsg(p, pVtab);
  70537. if( sContext.isError ){
  70538. rc = sContext.isError;
  70539. }
  70540. sqlite3VdbeChangeEncoding(pDest, encoding);
  70541. REGISTER_TRACE(pOp->p3, pDest);
  70542. UPDATE_MAX_BLOBSIZE(pDest);
  70543. if( sqlite3VdbeMemTooBig(pDest) ){
  70544. goto too_big;
  70545. }
  70546. break;
  70547. }
  70548. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  70549. #ifndef SQLITE_OMIT_VIRTUALTABLE
  70550. /* Opcode: VNext P1 P2 * * *
  70551. **
  70552. ** Advance virtual table P1 to the next row in its result set and
  70553. ** jump to instruction P2. Or, if the virtual table has reached
  70554. ** the end of its result set, then fall through to the next instruction.
  70555. */
  70556. case OP_VNext: { /* jump */
  70557. sqlite3_vtab *pVtab;
  70558. const sqlite3_module *pModule;
  70559. int res;
  70560. VdbeCursor *pCur;
  70561. res = 0;
  70562. pCur = p->apCsr[pOp->p1];
  70563. assert( pCur->pVtabCursor );
  70564. if( pCur->nullRow ){
  70565. break;
  70566. }
  70567. pVtab = pCur->pVtabCursor->pVtab;
  70568. pModule = pVtab->pModule;
  70569. assert( pModule->xNext );
  70570. /* Invoke the xNext() method of the module. There is no way for the
  70571. ** underlying implementation to return an error if one occurs during
  70572. ** xNext(). Instead, if an error occurs, true is returned (indicating that
  70573. ** data is available) and the error code returned when xColumn or
  70574. ** some other method is next invoked on the save virtual table cursor.
  70575. */
  70576. p->inVtabMethod = 1;
  70577. rc = pModule->xNext(pCur->pVtabCursor);
  70578. p->inVtabMethod = 0;
  70579. sqlite3VtabImportErrmsg(p, pVtab);
  70580. if( rc==SQLITE_OK ){
  70581. res = pModule->xEof(pCur->pVtabCursor);
  70582. }
  70583. VdbeBranchTaken(!res,2);
  70584. if( !res ){
  70585. /* If there is data, jump to P2 */
  70586. pc = pOp->p2 - 1;
  70587. }
  70588. goto check_for_interrupt;
  70589. }
  70590. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  70591. #ifndef SQLITE_OMIT_VIRTUALTABLE
  70592. /* Opcode: VRename P1 * * P4 *
  70593. **
  70594. ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
  70595. ** This opcode invokes the corresponding xRename method. The value
  70596. ** in register P1 is passed as the zName argument to the xRename method.
  70597. */
  70598. case OP_VRename: {
  70599. sqlite3_vtab *pVtab;
  70600. Mem *pName;
  70601. pVtab = pOp->p4.pVtab->pVtab;
  70602. pName = &aMem[pOp->p1];
  70603. assert( pVtab->pModule->xRename );
  70604. assert( memIsValid(pName) );
  70605. assert( p->readOnly==0 );
  70606. REGISTER_TRACE(pOp->p1, pName);
  70607. assert( pName->flags & MEM_Str );
  70608. testcase( pName->enc==SQLITE_UTF8 );
  70609. testcase( pName->enc==SQLITE_UTF16BE );
  70610. testcase( pName->enc==SQLITE_UTF16LE );
  70611. rc = sqlite3VdbeChangeEncoding(pName, SQLITE_UTF8);
  70612. if( rc==SQLITE_OK ){
  70613. rc = pVtab->pModule->xRename(pVtab, pName->z);
  70614. sqlite3VtabImportErrmsg(p, pVtab);
  70615. p->expired = 0;
  70616. }
  70617. break;
  70618. }
  70619. #endif
  70620. #ifndef SQLITE_OMIT_VIRTUALTABLE
  70621. /* Opcode: VUpdate P1 P2 P3 P4 P5
  70622. ** Synopsis: data=r[P3@P2]
  70623. **
  70624. ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
  70625. ** This opcode invokes the corresponding xUpdate method. P2 values
  70626. ** are contiguous memory cells starting at P3 to pass to the xUpdate
  70627. ** invocation. The value in register (P3+P2-1) corresponds to the
  70628. ** p2th element of the argv array passed to xUpdate.
  70629. **
  70630. ** The xUpdate method will do a DELETE or an INSERT or both.
  70631. ** The argv[0] element (which corresponds to memory cell P3)
  70632. ** is the rowid of a row to delete. If argv[0] is NULL then no
  70633. ** deletion occurs. The argv[1] element is the rowid of the new
  70634. ** row. This can be NULL to have the virtual table select the new
  70635. ** rowid for itself. The subsequent elements in the array are
  70636. ** the values of columns in the new row.
  70637. **
  70638. ** If P2==1 then no insert is performed. argv[0] is the rowid of
  70639. ** a row to delete.
  70640. **
  70641. ** P1 is a boolean flag. If it is set to true and the xUpdate call
  70642. ** is successful, then the value returned by sqlite3_last_insert_rowid()
  70643. ** is set to the value of the rowid for the row just inserted.
  70644. **
  70645. ** P5 is the error actions (OE_Replace, OE_Fail, OE_Ignore, etc) to
  70646. ** apply in the case of a constraint failure on an insert or update.
  70647. */
  70648. case OP_VUpdate: {
  70649. sqlite3_vtab *pVtab;
  70650. sqlite3_module *pModule;
  70651. int nArg;
  70652. int i;
  70653. sqlite_int64 rowid;
  70654. Mem **apArg;
  70655. Mem *pX;
  70656. assert( pOp->p2==1 || pOp->p5==OE_Fail || pOp->p5==OE_Rollback
  70657. || pOp->p5==OE_Abort || pOp->p5==OE_Ignore || pOp->p5==OE_Replace
  70658. );
  70659. assert( p->readOnly==0 );
  70660. pVtab = pOp->p4.pVtab->pVtab;
  70661. pModule = (sqlite3_module *)pVtab->pModule;
  70662. nArg = pOp->p2;
  70663. assert( pOp->p4type==P4_VTAB );
  70664. if( ALWAYS(pModule->xUpdate) ){
  70665. u8 vtabOnConflict = db->vtabOnConflict;
  70666. apArg = p->apArg;
  70667. pX = &aMem[pOp->p3];
  70668. for(i=0; i<nArg; i++){
  70669. assert( memIsValid(pX) );
  70670. memAboutToChange(p, pX);
  70671. apArg[i] = pX;
  70672. pX++;
  70673. }
  70674. db->vtabOnConflict = pOp->p5;
  70675. rc = pModule->xUpdate(pVtab, nArg, apArg, &rowid);
  70676. db->vtabOnConflict = vtabOnConflict;
  70677. sqlite3VtabImportErrmsg(p, pVtab);
  70678. if( rc==SQLITE_OK && pOp->p1 ){
  70679. assert( nArg>1 && apArg[0] && (apArg[0]->flags&MEM_Null) );
  70680. db->lastRowid = lastRowid = rowid;
  70681. }
  70682. if( (rc&0xff)==SQLITE_CONSTRAINT && pOp->p4.pVtab->bConstraint ){
  70683. if( pOp->p5==OE_Ignore ){
  70684. rc = SQLITE_OK;
  70685. }else{
  70686. p->errorAction = ((pOp->p5==OE_Replace) ? OE_Abort : pOp->p5);
  70687. }
  70688. }else{
  70689. p->nChange++;
  70690. }
  70691. }
  70692. break;
  70693. }
  70694. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  70695. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  70696. /* Opcode: Pagecount P1 P2 * * *
  70697. **
  70698. ** Write the current number of pages in database P1 to memory cell P2.
  70699. */
  70700. case OP_Pagecount: { /* out2-prerelease */
  70701. pOut->u.i = sqlite3BtreeLastPage(db->aDb[pOp->p1].pBt);
  70702. break;
  70703. }
  70704. #endif
  70705. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  70706. /* Opcode: MaxPgcnt P1 P2 P3 * *
  70707. **
  70708. ** Try to set the maximum page count for database P1 to the value in P3.
  70709. ** Do not let the maximum page count fall below the current page count and
  70710. ** do not change the maximum page count value if P3==0.
  70711. **
  70712. ** Store the maximum page count after the change in register P2.
  70713. */
  70714. case OP_MaxPgcnt: { /* out2-prerelease */
  70715. unsigned int newMax;
  70716. Btree *pBt;
  70717. pBt = db->aDb[pOp->p1].pBt;
  70718. newMax = 0;
  70719. if( pOp->p3 ){
  70720. newMax = sqlite3BtreeLastPage(pBt);
  70721. if( newMax < (unsigned)pOp->p3 ) newMax = (unsigned)pOp->p3;
  70722. }
  70723. pOut->u.i = sqlite3BtreeMaxPageCount(pBt, newMax);
  70724. break;
  70725. }
  70726. #endif
  70727. /* Opcode: Init * P2 * P4 *
  70728. ** Synopsis: Start at P2
  70729. **
  70730. ** Programs contain a single instance of this opcode as the very first
  70731. ** opcode.
  70732. **
  70733. ** If tracing is enabled (by the sqlite3_trace()) interface, then
  70734. ** the UTF-8 string contained in P4 is emitted on the trace callback.
  70735. ** Or if P4 is blank, use the string returned by sqlite3_sql().
  70736. **
  70737. ** If P2 is not zero, jump to instruction P2.
  70738. */
  70739. case OP_Init: { /* jump */
  70740. char *zTrace;
  70741. char *z;
  70742. if( pOp->p2 ){
  70743. pc = pOp->p2 - 1;
  70744. }
  70745. #ifndef SQLITE_OMIT_TRACE
  70746. if( db->xTrace
  70747. && !p->doingRerun
  70748. && (zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
  70749. ){
  70750. z = sqlite3VdbeExpandSql(p, zTrace);
  70751. db->xTrace(db->pTraceArg, z);
  70752. sqlite3DbFree(db, z);
  70753. }
  70754. #ifdef SQLITE_USE_FCNTL_TRACE
  70755. zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql);
  70756. if( zTrace ){
  70757. int i;
  70758. for(i=0; i<db->nDb; i++){
  70759. if( DbMaskTest(p->btreeMask, i)==0 ) continue;
  70760. sqlite3_file_control(db, db->aDb[i].zName, SQLITE_FCNTL_TRACE, zTrace);
  70761. }
  70762. }
  70763. #endif /* SQLITE_USE_FCNTL_TRACE */
  70764. #ifdef SQLITE_DEBUG
  70765. if( (db->flags & SQLITE_SqlTrace)!=0
  70766. && (zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
  70767. ){
  70768. sqlite3DebugPrintf("SQL-trace: %s\n", zTrace);
  70769. }
  70770. #endif /* SQLITE_DEBUG */
  70771. #endif /* SQLITE_OMIT_TRACE */
  70772. break;
  70773. }
  70774. /* Opcode: Noop * * * * *
  70775. **
  70776. ** Do nothing. This instruction is often useful as a jump
  70777. ** destination.
  70778. */
  70779. /*
  70780. ** The magic Explain opcode are only inserted when explain==2 (which
  70781. ** is to say when the EXPLAIN QUERY PLAN syntax is used.)
  70782. ** This opcode records information from the optimizer. It is the
  70783. ** the same as a no-op. This opcodesnever appears in a real VM program.
  70784. */
  70785. default: { /* This is really OP_Noop and OP_Explain */
  70786. assert( pOp->opcode==OP_Noop || pOp->opcode==OP_Explain );
  70787. break;
  70788. }
  70789. /*****************************************************************************
  70790. ** The cases of the switch statement above this line should all be indented
  70791. ** by 6 spaces. But the left-most 6 spaces have been removed to improve the
  70792. ** readability. From this point on down, the normal indentation rules are
  70793. ** restored.
  70794. *****************************************************************************/
  70795. }
  70796. #ifdef VDBE_PROFILE
  70797. {
  70798. u64 endTime = sqlite3Hwtime();
  70799. if( endTime>start ) pOp->cycles += endTime - start;
  70800. pOp->cnt++;
  70801. }
  70802. #endif
  70803. /* The following code adds nothing to the actual functionality
  70804. ** of the program. It is only here for testing and debugging.
  70805. ** On the other hand, it does burn CPU cycles every time through
  70806. ** the evaluator loop. So we can leave it out when NDEBUG is defined.
  70807. */
  70808. #ifndef NDEBUG
  70809. assert( pc>=-1 && pc<p->nOp );
  70810. #ifdef SQLITE_DEBUG
  70811. if( db->flags & SQLITE_VdbeTrace ){
  70812. if( rc!=0 ) printf("rc=%d\n",rc);
  70813. if( pOp->opflags & (OPFLG_OUT2_PRERELEASE|OPFLG_OUT2) ){
  70814. registerTrace(pOp->p2, &aMem[pOp->p2]);
  70815. }
  70816. if( pOp->opflags & OPFLG_OUT3 ){
  70817. registerTrace(pOp->p3, &aMem[pOp->p3]);
  70818. }
  70819. }
  70820. #endif /* SQLITE_DEBUG */
  70821. #endif /* NDEBUG */
  70822. } /* The end of the for(;;) loop the loops through opcodes */
  70823. /* If we reach this point, it means that execution is finished with
  70824. ** an error of some kind.
  70825. */
  70826. vdbe_error_halt:
  70827. assert( rc );
  70828. p->rc = rc;
  70829. testcase( sqlite3GlobalConfig.xLog!=0 );
  70830. sqlite3_log(rc, "statement aborts at %d: [%s] %s",
  70831. pc, p->zSql, p->zErrMsg);
  70832. sqlite3VdbeHalt(p);
  70833. if( rc==SQLITE_IOERR_NOMEM ) db->mallocFailed = 1;
  70834. rc = SQLITE_ERROR;
  70835. if( resetSchemaOnFault>0 ){
  70836. sqlite3ResetOneSchema(db, resetSchemaOnFault-1);
  70837. }
  70838. /* This is the only way out of this procedure. We have to
  70839. ** release the mutexes on btrees that were acquired at the
  70840. ** top. */
  70841. vdbe_return:
  70842. db->lastRowid = lastRowid;
  70843. testcase( nVmStep>0 );
  70844. p->aCounter[SQLITE_STMTSTATUS_VM_STEP] += (int)nVmStep;
  70845. sqlite3VdbeLeave(p);
  70846. return rc;
  70847. /* Jump to here if a string or blob larger than SQLITE_MAX_LENGTH
  70848. ** is encountered.
  70849. */
  70850. too_big:
  70851. sqlite3SetString(&p->zErrMsg, db, "string or blob too big");
  70852. rc = SQLITE_TOOBIG;
  70853. goto vdbe_error_halt;
  70854. /* Jump to here if a malloc() fails.
  70855. */
  70856. no_mem:
  70857. db->mallocFailed = 1;
  70858. sqlite3SetString(&p->zErrMsg, db, "out of memory");
  70859. rc = SQLITE_NOMEM;
  70860. goto vdbe_error_halt;
  70861. /* Jump to here for any other kind of fatal error. The "rc" variable
  70862. ** should hold the error number.
  70863. */
  70864. abort_due_to_error:
  70865. assert( p->zErrMsg==0 );
  70866. if( db->mallocFailed ) rc = SQLITE_NOMEM;
  70867. if( rc!=SQLITE_IOERR_NOMEM ){
  70868. sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(rc));
  70869. }
  70870. goto vdbe_error_halt;
  70871. /* Jump to here if the sqlite3_interrupt() API sets the interrupt
  70872. ** flag.
  70873. */
  70874. abort_due_to_interrupt:
  70875. assert( db->u1.isInterrupted );
  70876. rc = SQLITE_INTERRUPT;
  70877. p->rc = rc;
  70878. sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(rc));
  70879. goto vdbe_error_halt;
  70880. }
  70881. /************** End of vdbe.c ************************************************/
  70882. /************** Begin file vdbeblob.c ****************************************/
  70883. /*
  70884. ** 2007 May 1
  70885. **
  70886. ** The author disclaims copyright to this source code. In place of
  70887. ** a legal notice, here is a blessing:
  70888. **
  70889. ** May you do good and not evil.
  70890. ** May you find forgiveness for yourself and forgive others.
  70891. ** May you share freely, never taking more than you give.
  70892. **
  70893. *************************************************************************
  70894. **
  70895. ** This file contains code used to implement incremental BLOB I/O.
  70896. */
  70897. #ifndef SQLITE_OMIT_INCRBLOB
  70898. /*
  70899. ** Valid sqlite3_blob* handles point to Incrblob structures.
  70900. */
  70901. typedef struct Incrblob Incrblob;
  70902. struct Incrblob {
  70903. int flags; /* Copy of "flags" passed to sqlite3_blob_open() */
  70904. int nByte; /* Size of open blob, in bytes */
  70905. int iOffset; /* Byte offset of blob in cursor data */
  70906. int iCol; /* Table column this handle is open on */
  70907. BtCursor *pCsr; /* Cursor pointing at blob row */
  70908. sqlite3_stmt *pStmt; /* Statement holding cursor open */
  70909. sqlite3 *db; /* The associated database */
  70910. };
  70911. /*
  70912. ** This function is used by both blob_open() and blob_reopen(). It seeks
  70913. ** the b-tree cursor associated with blob handle p to point to row iRow.
  70914. ** If successful, SQLITE_OK is returned and subsequent calls to
  70915. ** sqlite3_blob_read() or sqlite3_blob_write() access the specified row.
  70916. **
  70917. ** If an error occurs, or if the specified row does not exist or does not
  70918. ** contain a value of type TEXT or BLOB in the column nominated when the
  70919. ** blob handle was opened, then an error code is returned and *pzErr may
  70920. ** be set to point to a buffer containing an error message. It is the
  70921. ** responsibility of the caller to free the error message buffer using
  70922. ** sqlite3DbFree().
  70923. **
  70924. ** If an error does occur, then the b-tree cursor is closed. All subsequent
  70925. ** calls to sqlite3_blob_read(), blob_write() or blob_reopen() will
  70926. ** immediately return SQLITE_ABORT.
  70927. */
  70928. static int blobSeekToRow(Incrblob *p, sqlite3_int64 iRow, char **pzErr){
  70929. int rc; /* Error code */
  70930. char *zErr = 0; /* Error message */
  70931. Vdbe *v = (Vdbe *)p->pStmt;
  70932. /* Set the value of the SQL statements only variable to integer iRow.
  70933. ** This is done directly instead of using sqlite3_bind_int64() to avoid
  70934. ** triggering asserts related to mutexes.
  70935. */
  70936. assert( v->aVar[0].flags&MEM_Int );
  70937. v->aVar[0].u.i = iRow;
  70938. rc = sqlite3_step(p->pStmt);
  70939. if( rc==SQLITE_ROW ){
  70940. VdbeCursor *pC = v->apCsr[0];
  70941. u32 type = pC->aType[p->iCol];
  70942. if( type<12 ){
  70943. zErr = sqlite3MPrintf(p->db, "cannot open value of type %s",
  70944. type==0?"null": type==7?"real": "integer"
  70945. );
  70946. rc = SQLITE_ERROR;
  70947. sqlite3_finalize(p->pStmt);
  70948. p->pStmt = 0;
  70949. }else{
  70950. p->iOffset = pC->aType[p->iCol + pC->nField];
  70951. p->nByte = sqlite3VdbeSerialTypeLen(type);
  70952. p->pCsr = pC->pCursor;
  70953. sqlite3BtreeIncrblobCursor(p->pCsr);
  70954. }
  70955. }
  70956. if( rc==SQLITE_ROW ){
  70957. rc = SQLITE_OK;
  70958. }else if( p->pStmt ){
  70959. rc = sqlite3_finalize(p->pStmt);
  70960. p->pStmt = 0;
  70961. if( rc==SQLITE_OK ){
  70962. zErr = sqlite3MPrintf(p->db, "no such rowid: %lld", iRow);
  70963. rc = SQLITE_ERROR;
  70964. }else{
  70965. zErr = sqlite3MPrintf(p->db, "%s", sqlite3_errmsg(p->db));
  70966. }
  70967. }
  70968. assert( rc!=SQLITE_OK || zErr==0 );
  70969. assert( rc!=SQLITE_ROW && rc!=SQLITE_DONE );
  70970. *pzErr = zErr;
  70971. return rc;
  70972. }
  70973. /*
  70974. ** Open a blob handle.
  70975. */
  70976. SQLITE_API int sqlite3_blob_open(
  70977. sqlite3* db, /* The database connection */
  70978. const char *zDb, /* The attached database containing the blob */
  70979. const char *zTable, /* The table containing the blob */
  70980. const char *zColumn, /* The column containing the blob */
  70981. sqlite_int64 iRow, /* The row containing the glob */
  70982. int flags, /* True -> read/write access, false -> read-only */
  70983. sqlite3_blob **ppBlob /* Handle for accessing the blob returned here */
  70984. ){
  70985. int nAttempt = 0;
  70986. int iCol; /* Index of zColumn in row-record */
  70987. /* This VDBE program seeks a btree cursor to the identified
  70988. ** db/table/row entry. The reason for using a vdbe program instead
  70989. ** of writing code to use the b-tree layer directly is that the
  70990. ** vdbe program will take advantage of the various transaction,
  70991. ** locking and error handling infrastructure built into the vdbe.
  70992. **
  70993. ** After seeking the cursor, the vdbe executes an OP_ResultRow.
  70994. ** Code external to the Vdbe then "borrows" the b-tree cursor and
  70995. ** uses it to implement the blob_read(), blob_write() and
  70996. ** blob_bytes() functions.
  70997. **
  70998. ** The sqlite3_blob_close() function finalizes the vdbe program,
  70999. ** which closes the b-tree cursor and (possibly) commits the
  71000. ** transaction.
  71001. */
  71002. static const int iLn = VDBE_OFFSET_LINENO(4);
  71003. static const VdbeOpList openBlob[] = {
  71004. /* {OP_Transaction, 0, 0, 0}, // 0: Inserted separately */
  71005. {OP_TableLock, 0, 0, 0}, /* 1: Acquire a read or write lock */
  71006. /* One of the following two instructions is replaced by an OP_Noop. */
  71007. {OP_OpenRead, 0, 0, 0}, /* 2: Open cursor 0 for reading */
  71008. {OP_OpenWrite, 0, 0, 0}, /* 3: Open cursor 0 for read/write */
  71009. {OP_Variable, 1, 1, 1}, /* 4: Push the rowid to the stack */
  71010. {OP_NotExists, 0, 10, 1}, /* 5: Seek the cursor */
  71011. {OP_Column, 0, 0, 1}, /* 6 */
  71012. {OP_ResultRow, 1, 0, 0}, /* 7 */
  71013. {OP_Goto, 0, 4, 0}, /* 8 */
  71014. {OP_Close, 0, 0, 0}, /* 9 */
  71015. {OP_Halt, 0, 0, 0}, /* 10 */
  71016. };
  71017. int rc = SQLITE_OK;
  71018. char *zErr = 0;
  71019. Table *pTab;
  71020. Parse *pParse = 0;
  71021. Incrblob *pBlob = 0;
  71022. #ifdef SQLITE_ENABLE_API_ARMOR
  71023. if( !sqlite3SafetyCheckOk(db) || ppBlob==0 || zTable==0 ){
  71024. return SQLITE_MISUSE_BKPT;
  71025. }
  71026. #endif
  71027. flags = !!flags; /* flags = (flags ? 1 : 0); */
  71028. *ppBlob = 0;
  71029. sqlite3_mutex_enter(db->mutex);
  71030. pBlob = (Incrblob *)sqlite3DbMallocZero(db, sizeof(Incrblob));
  71031. if( !pBlob ) goto blob_open_out;
  71032. pParse = sqlite3StackAllocRaw(db, sizeof(*pParse));
  71033. if( !pParse ) goto blob_open_out;
  71034. do {
  71035. memset(pParse, 0, sizeof(Parse));
  71036. pParse->db = db;
  71037. sqlite3DbFree(db, zErr);
  71038. zErr = 0;
  71039. sqlite3BtreeEnterAll(db);
  71040. pTab = sqlite3LocateTable(pParse, 0, zTable, zDb);
  71041. if( pTab && IsVirtual(pTab) ){
  71042. pTab = 0;
  71043. sqlite3ErrorMsg(pParse, "cannot open virtual table: %s", zTable);
  71044. }
  71045. if( pTab && !HasRowid(pTab) ){
  71046. pTab = 0;
  71047. sqlite3ErrorMsg(pParse, "cannot open table without rowid: %s", zTable);
  71048. }
  71049. #ifndef SQLITE_OMIT_VIEW
  71050. if( pTab && pTab->pSelect ){
  71051. pTab = 0;
  71052. sqlite3ErrorMsg(pParse, "cannot open view: %s", zTable);
  71053. }
  71054. #endif
  71055. if( !pTab ){
  71056. if( pParse->zErrMsg ){
  71057. sqlite3DbFree(db, zErr);
  71058. zErr = pParse->zErrMsg;
  71059. pParse->zErrMsg = 0;
  71060. }
  71061. rc = SQLITE_ERROR;
  71062. sqlite3BtreeLeaveAll(db);
  71063. goto blob_open_out;
  71064. }
  71065. /* Now search pTab for the exact column. */
  71066. for(iCol=0; iCol<pTab->nCol; iCol++) {
  71067. if( sqlite3StrICmp(pTab->aCol[iCol].zName, zColumn)==0 ){
  71068. break;
  71069. }
  71070. }
  71071. if( iCol==pTab->nCol ){
  71072. sqlite3DbFree(db, zErr);
  71073. zErr = sqlite3MPrintf(db, "no such column: \"%s\"", zColumn);
  71074. rc = SQLITE_ERROR;
  71075. sqlite3BtreeLeaveAll(db);
  71076. goto blob_open_out;
  71077. }
  71078. /* If the value is being opened for writing, check that the
  71079. ** column is not indexed, and that it is not part of a foreign key.
  71080. ** It is against the rules to open a column to which either of these
  71081. ** descriptions applies for writing. */
  71082. if( flags ){
  71083. const char *zFault = 0;
  71084. Index *pIdx;
  71085. #ifndef SQLITE_OMIT_FOREIGN_KEY
  71086. if( db->flags&SQLITE_ForeignKeys ){
  71087. /* Check that the column is not part of an FK child key definition. It
  71088. ** is not necessary to check if it is part of a parent key, as parent
  71089. ** key columns must be indexed. The check below will pick up this
  71090. ** case. */
  71091. FKey *pFKey;
  71092. for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
  71093. int j;
  71094. for(j=0; j<pFKey->nCol; j++){
  71095. if( pFKey->aCol[j].iFrom==iCol ){
  71096. zFault = "foreign key";
  71097. }
  71098. }
  71099. }
  71100. }
  71101. #endif
  71102. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  71103. int j;
  71104. for(j=0; j<pIdx->nKeyCol; j++){
  71105. if( pIdx->aiColumn[j]==iCol ){
  71106. zFault = "indexed";
  71107. }
  71108. }
  71109. }
  71110. if( zFault ){
  71111. sqlite3DbFree(db, zErr);
  71112. zErr = sqlite3MPrintf(db, "cannot open %s column for writing", zFault);
  71113. rc = SQLITE_ERROR;
  71114. sqlite3BtreeLeaveAll(db);
  71115. goto blob_open_out;
  71116. }
  71117. }
  71118. pBlob->pStmt = (sqlite3_stmt *)sqlite3VdbeCreate(pParse);
  71119. assert( pBlob->pStmt || db->mallocFailed );
  71120. if( pBlob->pStmt ){
  71121. Vdbe *v = (Vdbe *)pBlob->pStmt;
  71122. int iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  71123. sqlite3VdbeAddOp4Int(v, OP_Transaction, iDb, flags,
  71124. pTab->pSchema->schema_cookie,
  71125. pTab->pSchema->iGeneration);
  71126. sqlite3VdbeChangeP5(v, 1);
  71127. sqlite3VdbeAddOpList(v, ArraySize(openBlob), openBlob, iLn);
  71128. /* Make sure a mutex is held on the table to be accessed */
  71129. sqlite3VdbeUsesBtree(v, iDb);
  71130. /* Configure the OP_TableLock instruction */
  71131. #ifdef SQLITE_OMIT_SHARED_CACHE
  71132. sqlite3VdbeChangeToNoop(v, 1);
  71133. #else
  71134. sqlite3VdbeChangeP1(v, 1, iDb);
  71135. sqlite3VdbeChangeP2(v, 1, pTab->tnum);
  71136. sqlite3VdbeChangeP3(v, 1, flags);
  71137. sqlite3VdbeChangeP4(v, 1, pTab->zName, P4_TRANSIENT);
  71138. #endif
  71139. /* Remove either the OP_OpenWrite or OpenRead. Set the P2
  71140. ** parameter of the other to pTab->tnum. */
  71141. sqlite3VdbeChangeToNoop(v, 3 - flags);
  71142. sqlite3VdbeChangeP2(v, 2 + flags, pTab->tnum);
  71143. sqlite3VdbeChangeP3(v, 2 + flags, iDb);
  71144. /* Configure the number of columns. Configure the cursor to
  71145. ** think that the table has one more column than it really
  71146. ** does. An OP_Column to retrieve this imaginary column will
  71147. ** always return an SQL NULL. This is useful because it means
  71148. ** we can invoke OP_Column to fill in the vdbe cursors type
  71149. ** and offset cache without causing any IO.
  71150. */
  71151. sqlite3VdbeChangeP4(v, 2+flags, SQLITE_INT_TO_PTR(pTab->nCol+1),P4_INT32);
  71152. sqlite3VdbeChangeP2(v, 6, pTab->nCol);
  71153. if( !db->mallocFailed ){
  71154. pParse->nVar = 1;
  71155. pParse->nMem = 1;
  71156. pParse->nTab = 1;
  71157. sqlite3VdbeMakeReady(v, pParse);
  71158. }
  71159. }
  71160. pBlob->flags = flags;
  71161. pBlob->iCol = iCol;
  71162. pBlob->db = db;
  71163. sqlite3BtreeLeaveAll(db);
  71164. if( db->mallocFailed ){
  71165. goto blob_open_out;
  71166. }
  71167. sqlite3_bind_int64(pBlob->pStmt, 1, iRow);
  71168. rc = blobSeekToRow(pBlob, iRow, &zErr);
  71169. } while( (++nAttempt)<SQLITE_MAX_SCHEMA_RETRY && rc==SQLITE_SCHEMA );
  71170. blob_open_out:
  71171. if( rc==SQLITE_OK && db->mallocFailed==0 ){
  71172. *ppBlob = (sqlite3_blob *)pBlob;
  71173. }else{
  71174. if( pBlob && pBlob->pStmt ) sqlite3VdbeFinalize((Vdbe *)pBlob->pStmt);
  71175. sqlite3DbFree(db, pBlob);
  71176. }
  71177. sqlite3ErrorWithMsg(db, rc, (zErr ? "%s" : 0), zErr);
  71178. sqlite3DbFree(db, zErr);
  71179. sqlite3ParserReset(pParse);
  71180. sqlite3StackFree(db, pParse);
  71181. rc = sqlite3ApiExit(db, rc);
  71182. sqlite3_mutex_leave(db->mutex);
  71183. return rc;
  71184. }
  71185. /*
  71186. ** Close a blob handle that was previously created using
  71187. ** sqlite3_blob_open().
  71188. */
  71189. SQLITE_API int sqlite3_blob_close(sqlite3_blob *pBlob){
  71190. Incrblob *p = (Incrblob *)pBlob;
  71191. int rc;
  71192. sqlite3 *db;
  71193. if( p ){
  71194. db = p->db;
  71195. sqlite3_mutex_enter(db->mutex);
  71196. rc = sqlite3_finalize(p->pStmt);
  71197. sqlite3DbFree(db, p);
  71198. sqlite3_mutex_leave(db->mutex);
  71199. }else{
  71200. rc = SQLITE_OK;
  71201. }
  71202. return rc;
  71203. }
  71204. /*
  71205. ** Perform a read or write operation on a blob
  71206. */
  71207. static int blobReadWrite(
  71208. sqlite3_blob *pBlob,
  71209. void *z,
  71210. int n,
  71211. int iOffset,
  71212. int (*xCall)(BtCursor*, u32, u32, void*)
  71213. ){
  71214. int rc;
  71215. Incrblob *p = (Incrblob *)pBlob;
  71216. Vdbe *v;
  71217. sqlite3 *db;
  71218. if( p==0 ) return SQLITE_MISUSE_BKPT;
  71219. db = p->db;
  71220. sqlite3_mutex_enter(db->mutex);
  71221. v = (Vdbe*)p->pStmt;
  71222. if( n<0 || iOffset<0 || (iOffset+n)>p->nByte ){
  71223. /* Request is out of range. Return a transient error. */
  71224. rc = SQLITE_ERROR;
  71225. sqlite3Error(db, SQLITE_ERROR);
  71226. }else if( v==0 ){
  71227. /* If there is no statement handle, then the blob-handle has
  71228. ** already been invalidated. Return SQLITE_ABORT in this case.
  71229. */
  71230. rc = SQLITE_ABORT;
  71231. }else{
  71232. /* Call either BtreeData() or BtreePutData(). If SQLITE_ABORT is
  71233. ** returned, clean-up the statement handle.
  71234. */
  71235. assert( db == v->db );
  71236. sqlite3BtreeEnterCursor(p->pCsr);
  71237. rc = xCall(p->pCsr, iOffset+p->iOffset, n, z);
  71238. sqlite3BtreeLeaveCursor(p->pCsr);
  71239. if( rc==SQLITE_ABORT ){
  71240. sqlite3VdbeFinalize(v);
  71241. p->pStmt = 0;
  71242. }else{
  71243. db->errCode = rc;
  71244. v->rc = rc;
  71245. }
  71246. }
  71247. rc = sqlite3ApiExit(db, rc);
  71248. sqlite3_mutex_leave(db->mutex);
  71249. return rc;
  71250. }
  71251. /*
  71252. ** Read data from a blob handle.
  71253. */
  71254. SQLITE_API int sqlite3_blob_read(sqlite3_blob *pBlob, void *z, int n, int iOffset){
  71255. return blobReadWrite(pBlob, z, n, iOffset, sqlite3BtreeData);
  71256. }
  71257. /*
  71258. ** Write data to a blob handle.
  71259. */
  71260. SQLITE_API int sqlite3_blob_write(sqlite3_blob *pBlob, const void *z, int n, int iOffset){
  71261. return blobReadWrite(pBlob, (void *)z, n, iOffset, sqlite3BtreePutData);
  71262. }
  71263. /*
  71264. ** Query a blob handle for the size of the data.
  71265. **
  71266. ** The Incrblob.nByte field is fixed for the lifetime of the Incrblob
  71267. ** so no mutex is required for access.
  71268. */
  71269. SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *pBlob){
  71270. Incrblob *p = (Incrblob *)pBlob;
  71271. return (p && p->pStmt) ? p->nByte : 0;
  71272. }
  71273. /*
  71274. ** Move an existing blob handle to point to a different row of the same
  71275. ** database table.
  71276. **
  71277. ** If an error occurs, or if the specified row does not exist or does not
  71278. ** contain a blob or text value, then an error code is returned and the
  71279. ** database handle error code and message set. If this happens, then all
  71280. ** subsequent calls to sqlite3_blob_xxx() functions (except blob_close())
  71281. ** immediately return SQLITE_ABORT.
  71282. */
  71283. SQLITE_API int sqlite3_blob_reopen(sqlite3_blob *pBlob, sqlite3_int64 iRow){
  71284. int rc;
  71285. Incrblob *p = (Incrblob *)pBlob;
  71286. sqlite3 *db;
  71287. if( p==0 ) return SQLITE_MISUSE_BKPT;
  71288. db = p->db;
  71289. sqlite3_mutex_enter(db->mutex);
  71290. if( p->pStmt==0 ){
  71291. /* If there is no statement handle, then the blob-handle has
  71292. ** already been invalidated. Return SQLITE_ABORT in this case.
  71293. */
  71294. rc = SQLITE_ABORT;
  71295. }else{
  71296. char *zErr;
  71297. rc = blobSeekToRow(p, iRow, &zErr);
  71298. if( rc!=SQLITE_OK ){
  71299. sqlite3ErrorWithMsg(db, rc, (zErr ? "%s" : 0), zErr);
  71300. sqlite3DbFree(db, zErr);
  71301. }
  71302. assert( rc!=SQLITE_SCHEMA );
  71303. }
  71304. rc = sqlite3ApiExit(db, rc);
  71305. assert( rc==SQLITE_OK || p->pStmt==0 );
  71306. sqlite3_mutex_leave(db->mutex);
  71307. return rc;
  71308. }
  71309. #endif /* #ifndef SQLITE_OMIT_INCRBLOB */
  71310. /************** End of vdbeblob.c ********************************************/
  71311. /************** Begin file vdbesort.c ****************************************/
  71312. /*
  71313. ** 2011-07-09
  71314. **
  71315. ** The author disclaims copyright to this source code. In place of
  71316. ** a legal notice, here is a blessing:
  71317. **
  71318. ** May you do good and not evil.
  71319. ** May you find forgiveness for yourself and forgive others.
  71320. ** May you share freely, never taking more than you give.
  71321. **
  71322. *************************************************************************
  71323. ** This file contains code for the VdbeSorter object, used in concert with
  71324. ** a VdbeCursor to sort large numbers of keys for CREATE INDEX statements
  71325. ** or by SELECT statements with ORDER BY clauses that cannot be satisfied
  71326. ** using indexes and without LIMIT clauses.
  71327. **
  71328. ** The VdbeSorter object implements a multi-threaded external merge sort
  71329. ** algorithm that is efficient even if the number of elements being sorted
  71330. ** exceeds the available memory.
  71331. **
  71332. ** Here is the (internal, non-API) interface between this module and the
  71333. ** rest of the SQLite system:
  71334. **
  71335. ** sqlite3VdbeSorterInit() Create a new VdbeSorter object.
  71336. **
  71337. ** sqlite3VdbeSorterWrite() Add a single new row to the VdbeSorter
  71338. ** object. The row is a binary blob in the
  71339. ** OP_MakeRecord format that contains both
  71340. ** the ORDER BY key columns and result columns
  71341. ** in the case of a SELECT w/ ORDER BY, or
  71342. ** the complete record for an index entry
  71343. ** in the case of a CREATE INDEX.
  71344. **
  71345. ** sqlite3VdbeSorterRewind() Sort all content previously added.
  71346. ** Position the read cursor on the
  71347. ** first sorted element.
  71348. **
  71349. ** sqlite3VdbeSorterNext() Advance the read cursor to the next sorted
  71350. ** element.
  71351. **
  71352. ** sqlite3VdbeSorterRowkey() Return the complete binary blob for the
  71353. ** row currently under the read cursor.
  71354. **
  71355. ** sqlite3VdbeSorterCompare() Compare the binary blob for the row
  71356. ** currently under the read cursor against
  71357. ** another binary blob X and report if
  71358. ** X is strictly less than the read cursor.
  71359. ** Used to enforce uniqueness in a
  71360. ** CREATE UNIQUE INDEX statement.
  71361. **
  71362. ** sqlite3VdbeSorterClose() Close the VdbeSorter object and reclaim
  71363. ** all resources.
  71364. **
  71365. ** sqlite3VdbeSorterReset() Refurbish the VdbeSorter for reuse. This
  71366. ** is like Close() followed by Init() only
  71367. ** much faster.
  71368. **
  71369. ** The interfaces above must be called in a particular order. Write() can
  71370. ** only occur in between Init()/Reset() and Rewind(). Next(), Rowkey(), and
  71371. ** Compare() can only occur in between Rewind() and Close()/Reset(). i.e.
  71372. **
  71373. ** Init()
  71374. ** for each record: Write()
  71375. ** Rewind()
  71376. ** Rowkey()/Compare()
  71377. ** Next()
  71378. ** Close()
  71379. **
  71380. ** Algorithm:
  71381. **
  71382. ** Records passed to the sorter via calls to Write() are initially held
  71383. ** unsorted in main memory. Assuming the amount of memory used never exceeds
  71384. ** a threshold, when Rewind() is called the set of records is sorted using
  71385. ** an in-memory merge sort. In this case, no temporary files are required
  71386. ** and subsequent calls to Rowkey(), Next() and Compare() read records
  71387. ** directly from main memory.
  71388. **
  71389. ** If the amount of space used to store records in main memory exceeds the
  71390. ** threshold, then the set of records currently in memory are sorted and
  71391. ** written to a temporary file in "Packed Memory Array" (PMA) format.
  71392. ** A PMA created at this point is known as a "level-0 PMA". Higher levels
  71393. ** of PMAs may be created by merging existing PMAs together - for example
  71394. ** merging two or more level-0 PMAs together creates a level-1 PMA.
  71395. **
  71396. ** The threshold for the amount of main memory to use before flushing
  71397. ** records to a PMA is roughly the same as the limit configured for the
  71398. ** page-cache of the main database. Specifically, the threshold is set to
  71399. ** the value returned by "PRAGMA main.page_size" multipled by
  71400. ** that returned by "PRAGMA main.cache_size", in bytes.
  71401. **
  71402. ** If the sorter is running in single-threaded mode, then all PMAs generated
  71403. ** are appended to a single temporary file. Or, if the sorter is running in
  71404. ** multi-threaded mode then up to (N+1) temporary files may be opened, where
  71405. ** N is the configured number of worker threads. In this case, instead of
  71406. ** sorting the records and writing the PMA to a temporary file itself, the
  71407. ** calling thread usually launches a worker thread to do so. Except, if
  71408. ** there are already N worker threads running, the main thread does the work
  71409. ** itself.
  71410. **
  71411. ** The sorter is running in multi-threaded mode if (a) the library was built
  71412. ** with pre-processor symbol SQLITE_MAX_WORKER_THREADS set to a value greater
  71413. ** than zero, and (b) worker threads have been enabled at runtime by calling
  71414. ** sqlite3_config(SQLITE_CONFIG_WORKER_THREADS, ...).
  71415. **
  71416. ** When Rewind() is called, any data remaining in memory is flushed to a
  71417. ** final PMA. So at this point the data is stored in some number of sorted
  71418. ** PMAs within temporary files on disk.
  71419. **
  71420. ** If there are fewer than SORTER_MAX_MERGE_COUNT PMAs in total and the
  71421. ** sorter is running in single-threaded mode, then these PMAs are merged
  71422. ** incrementally as keys are retreived from the sorter by the VDBE. The
  71423. ** MergeEngine object, described in further detail below, performs this
  71424. ** merge.
  71425. **
  71426. ** Or, if running in multi-threaded mode, then a background thread is
  71427. ** launched to merge the existing PMAs. Once the background thread has
  71428. ** merged T bytes of data into a single sorted PMA, the main thread
  71429. ** begins reading keys from that PMA while the background thread proceeds
  71430. ** with merging the next T bytes of data. And so on.
  71431. **
  71432. ** Parameter T is set to half the value of the memory threshold used
  71433. ** by Write() above to determine when to create a new PMA.
  71434. **
  71435. ** If there are more than SORTER_MAX_MERGE_COUNT PMAs in total when
  71436. ** Rewind() is called, then a hierarchy of incremental-merges is used.
  71437. ** First, T bytes of data from the first SORTER_MAX_MERGE_COUNT PMAs on
  71438. ** disk are merged together. Then T bytes of data from the second set, and
  71439. ** so on, such that no operation ever merges more than SORTER_MAX_MERGE_COUNT
  71440. ** PMAs at a time. This done is to improve locality.
  71441. **
  71442. ** If running in multi-threaded mode and there are more than
  71443. ** SORTER_MAX_MERGE_COUNT PMAs on disk when Rewind() is called, then more
  71444. ** than one background thread may be created. Specifically, there may be
  71445. ** one background thread for each temporary file on disk, and one background
  71446. ** thread to merge the output of each of the others to a single PMA for
  71447. ** the main thread to read from.
  71448. */
  71449. /*
  71450. ** If SQLITE_DEBUG_SORTER_THREADS is defined, this module outputs various
  71451. ** messages to stderr that may be helpful in understanding the performance
  71452. ** characteristics of the sorter in multi-threaded mode.
  71453. */
  71454. #if 0
  71455. # define SQLITE_DEBUG_SORTER_THREADS 1
  71456. #endif
  71457. /*
  71458. ** Private objects used by the sorter
  71459. */
  71460. typedef struct MergeEngine MergeEngine; /* Merge PMAs together */
  71461. typedef struct PmaReader PmaReader; /* Incrementally read one PMA */
  71462. typedef struct PmaWriter PmaWriter; /* Incrementally write one PMA */
  71463. typedef struct SorterRecord SorterRecord; /* A record being sorted */
  71464. typedef struct SortSubtask SortSubtask; /* A sub-task in the sort process */
  71465. typedef struct SorterFile SorterFile; /* Temporary file object wrapper */
  71466. typedef struct SorterList SorterList; /* In-memory list of records */
  71467. typedef struct IncrMerger IncrMerger; /* Read & merge multiple PMAs */
  71468. /*
  71469. ** A container for a temp file handle and the current amount of data
  71470. ** stored in the file.
  71471. */
  71472. struct SorterFile {
  71473. sqlite3_file *pFd; /* File handle */
  71474. i64 iEof; /* Bytes of data stored in pFd */
  71475. };
  71476. /*
  71477. ** An in-memory list of objects to be sorted.
  71478. **
  71479. ** If aMemory==0 then each object is allocated separately and the objects
  71480. ** are connected using SorterRecord.u.pNext. If aMemory!=0 then all objects
  71481. ** are stored in the aMemory[] bulk memory, one right after the other, and
  71482. ** are connected using SorterRecord.u.iNext.
  71483. */
  71484. struct SorterList {
  71485. SorterRecord *pList; /* Linked list of records */
  71486. u8 *aMemory; /* If non-NULL, bulk memory to hold pList */
  71487. int szPMA; /* Size of pList as PMA in bytes */
  71488. };
  71489. /*
  71490. ** The MergeEngine object is used to combine two or more smaller PMAs into
  71491. ** one big PMA using a merge operation. Separate PMAs all need to be
  71492. ** combined into one big PMA in order to be able to step through the sorted
  71493. ** records in order.
  71494. **
  71495. ** The aReadr[] array contains a PmaReader object for each of the PMAs being
  71496. ** merged. An aReadr[] object either points to a valid key or else is at EOF.
  71497. ** ("EOF" means "End Of File". When aReadr[] is at EOF there is no more data.)
  71498. ** For the purposes of the paragraphs below, we assume that the array is
  71499. ** actually N elements in size, where N is the smallest power of 2 greater
  71500. ** to or equal to the number of PMAs being merged. The extra aReadr[] elements
  71501. ** are treated as if they are empty (always at EOF).
  71502. **
  71503. ** The aTree[] array is also N elements in size. The value of N is stored in
  71504. ** the MergeEngine.nTree variable.
  71505. **
  71506. ** The final (N/2) elements of aTree[] contain the results of comparing
  71507. ** pairs of PMA keys together. Element i contains the result of
  71508. ** comparing aReadr[2*i-N] and aReadr[2*i-N+1]. Whichever key is smaller, the
  71509. ** aTree element is set to the index of it.
  71510. **
  71511. ** For the purposes of this comparison, EOF is considered greater than any
  71512. ** other key value. If the keys are equal (only possible with two EOF
  71513. ** values), it doesn't matter which index is stored.
  71514. **
  71515. ** The (N/4) elements of aTree[] that precede the final (N/2) described
  71516. ** above contains the index of the smallest of each block of 4 PmaReaders
  71517. ** And so on. So that aTree[1] contains the index of the PmaReader that
  71518. ** currently points to the smallest key value. aTree[0] is unused.
  71519. **
  71520. ** Example:
  71521. **
  71522. ** aReadr[0] -> Banana
  71523. ** aReadr[1] -> Feijoa
  71524. ** aReadr[2] -> Elderberry
  71525. ** aReadr[3] -> Currant
  71526. ** aReadr[4] -> Grapefruit
  71527. ** aReadr[5] -> Apple
  71528. ** aReadr[6] -> Durian
  71529. ** aReadr[7] -> EOF
  71530. **
  71531. ** aTree[] = { X, 5 0, 5 0, 3, 5, 6 }
  71532. **
  71533. ** The current element is "Apple" (the value of the key indicated by
  71534. ** PmaReader 5). When the Next() operation is invoked, PmaReader 5 will
  71535. ** be advanced to the next key in its segment. Say the next key is
  71536. ** "Eggplant":
  71537. **
  71538. ** aReadr[5] -> Eggplant
  71539. **
  71540. ** The contents of aTree[] are updated first by comparing the new PmaReader
  71541. ** 5 key to the current key of PmaReader 4 (still "Grapefruit"). The PmaReader
  71542. ** 5 value is still smaller, so aTree[6] is set to 5. And so on up the tree.
  71543. ** The value of PmaReader 6 - "Durian" - is now smaller than that of PmaReader
  71544. ** 5, so aTree[3] is set to 6. Key 0 is smaller than key 6 (Banana<Durian),
  71545. ** so the value written into element 1 of the array is 0. As follows:
  71546. **
  71547. ** aTree[] = { X, 0 0, 6 0, 3, 5, 6 }
  71548. **
  71549. ** In other words, each time we advance to the next sorter element, log2(N)
  71550. ** key comparison operations are required, where N is the number of segments
  71551. ** being merged (rounded up to the next power of 2).
  71552. */
  71553. struct MergeEngine {
  71554. int nTree; /* Used size of aTree/aReadr (power of 2) */
  71555. SortSubtask *pTask; /* Used by this thread only */
  71556. int *aTree; /* Current state of incremental merge */
  71557. PmaReader *aReadr; /* Array of PmaReaders to merge data from */
  71558. };
  71559. /*
  71560. ** This object represents a single thread of control in a sort operation.
  71561. ** Exactly VdbeSorter.nTask instances of this object are allocated
  71562. ** as part of each VdbeSorter object. Instances are never allocated any
  71563. ** other way. VdbeSorter.nTask is set to the number of worker threads allowed
  71564. ** (see SQLITE_CONFIG_WORKER_THREADS) plus one (the main thread). Thus for
  71565. ** single-threaded operation, there is exactly one instance of this object
  71566. ** and for multi-threaded operation there are two or more instances.
  71567. **
  71568. ** Essentially, this structure contains all those fields of the VdbeSorter
  71569. ** structure for which each thread requires a separate instance. For example,
  71570. ** each thread requries its own UnpackedRecord object to unpack records in
  71571. ** as part of comparison operations.
  71572. **
  71573. ** Before a background thread is launched, variable bDone is set to 0. Then,
  71574. ** right before it exits, the thread itself sets bDone to 1. This is used for
  71575. ** two purposes:
  71576. **
  71577. ** 1. When flushing the contents of memory to a level-0 PMA on disk, to
  71578. ** attempt to select a SortSubtask for which there is not already an
  71579. ** active background thread (since doing so causes the main thread
  71580. ** to block until it finishes).
  71581. **
  71582. ** 2. If SQLITE_DEBUG_SORTER_THREADS is defined, to determine if a call
  71583. ** to sqlite3ThreadJoin() is likely to block. Cases that are likely to
  71584. ** block provoke debugging output.
  71585. **
  71586. ** In both cases, the effects of the main thread seeing (bDone==0) even
  71587. ** after the thread has finished are not dire. So we don't worry about
  71588. ** memory barriers and such here.
  71589. */
  71590. struct SortSubtask {
  71591. SQLiteThread *pThread; /* Background thread, if any */
  71592. int bDone; /* Set if thread is finished but not joined */
  71593. VdbeSorter *pSorter; /* Sorter that owns this sub-task */
  71594. UnpackedRecord *pUnpacked; /* Space to unpack a record */
  71595. SorterList list; /* List for thread to write to a PMA */
  71596. int nPMA; /* Number of PMAs currently in file */
  71597. SorterFile file; /* Temp file for level-0 PMAs */
  71598. SorterFile file2; /* Space for other PMAs */
  71599. };
  71600. /*
  71601. ** Main sorter structure. A single instance of this is allocated for each
  71602. ** sorter cursor created by the VDBE.
  71603. **
  71604. ** mxKeysize:
  71605. ** As records are added to the sorter by calls to sqlite3VdbeSorterWrite(),
  71606. ** this variable is updated so as to be set to the size on disk of the
  71607. ** largest record in the sorter.
  71608. */
  71609. struct VdbeSorter {
  71610. int mnPmaSize; /* Minimum PMA size, in bytes */
  71611. int mxPmaSize; /* Maximum PMA size, in bytes. 0==no limit */
  71612. int mxKeysize; /* Largest serialized key seen so far */
  71613. int pgsz; /* Main database page size */
  71614. PmaReader *pReader; /* Readr data from here after Rewind() */
  71615. MergeEngine *pMerger; /* Or here, if bUseThreads==0 */
  71616. sqlite3 *db; /* Database connection */
  71617. KeyInfo *pKeyInfo; /* How to compare records */
  71618. UnpackedRecord *pUnpacked; /* Used by VdbeSorterCompare() */
  71619. SorterList list; /* List of in-memory records */
  71620. int iMemory; /* Offset of free space in list.aMemory */
  71621. int nMemory; /* Size of list.aMemory allocation in bytes */
  71622. u8 bUsePMA; /* True if one or more PMAs created */
  71623. u8 bUseThreads; /* True to use background threads */
  71624. u8 iPrev; /* Previous thread used to flush PMA */
  71625. u8 nTask; /* Size of aTask[] array */
  71626. SortSubtask aTask[1]; /* One or more subtasks */
  71627. };
  71628. /*
  71629. ** An instance of the following object is used to read records out of a
  71630. ** PMA, in sorted order. The next key to be read is cached in nKey/aKey.
  71631. ** aKey might point into aMap or into aBuffer. If neither of those locations
  71632. ** contain a contiguous representation of the key, then aAlloc is allocated
  71633. ** and the key is copied into aAlloc and aKey is made to poitn to aAlloc.
  71634. **
  71635. ** pFd==0 at EOF.
  71636. */
  71637. struct PmaReader {
  71638. i64 iReadOff; /* Current read offset */
  71639. i64 iEof; /* 1 byte past EOF for this PmaReader */
  71640. int nAlloc; /* Bytes of space at aAlloc */
  71641. int nKey; /* Number of bytes in key */
  71642. sqlite3_file *pFd; /* File handle we are reading from */
  71643. u8 *aAlloc; /* Space for aKey if aBuffer and pMap wont work */
  71644. u8 *aKey; /* Pointer to current key */
  71645. u8 *aBuffer; /* Current read buffer */
  71646. int nBuffer; /* Size of read buffer in bytes */
  71647. u8 *aMap; /* Pointer to mapping of entire file */
  71648. IncrMerger *pIncr; /* Incremental merger */
  71649. };
  71650. /*
  71651. ** Normally, a PmaReader object iterates through an existing PMA stored
  71652. ** within a temp file. However, if the PmaReader.pIncr variable points to
  71653. ** an object of the following type, it may be used to iterate/merge through
  71654. ** multiple PMAs simultaneously.
  71655. **
  71656. ** There are two types of IncrMerger object - single (bUseThread==0) and
  71657. ** multi-threaded (bUseThread==1).
  71658. **
  71659. ** A multi-threaded IncrMerger object uses two temporary files - aFile[0]
  71660. ** and aFile[1]. Neither file is allowed to grow to more than mxSz bytes in
  71661. ** size. When the IncrMerger is initialized, it reads enough data from
  71662. ** pMerger to populate aFile[0]. It then sets variables within the
  71663. ** corresponding PmaReader object to read from that file and kicks off
  71664. ** a background thread to populate aFile[1] with the next mxSz bytes of
  71665. ** sorted record data from pMerger.
  71666. **
  71667. ** When the PmaReader reaches the end of aFile[0], it blocks until the
  71668. ** background thread has finished populating aFile[1]. It then exchanges
  71669. ** the contents of the aFile[0] and aFile[1] variables within this structure,
  71670. ** sets the PmaReader fields to read from the new aFile[0] and kicks off
  71671. ** another background thread to populate the new aFile[1]. And so on, until
  71672. ** the contents of pMerger are exhausted.
  71673. **
  71674. ** A single-threaded IncrMerger does not open any temporary files of its
  71675. ** own. Instead, it has exclusive access to mxSz bytes of space beginning
  71676. ** at offset iStartOff of file pTask->file2. And instead of using a
  71677. ** background thread to prepare data for the PmaReader, with a single
  71678. ** threaded IncrMerger the allocate part of pTask->file2 is "refilled" with
  71679. ** keys from pMerger by the calling thread whenever the PmaReader runs out
  71680. ** of data.
  71681. */
  71682. struct IncrMerger {
  71683. SortSubtask *pTask; /* Task that owns this merger */
  71684. MergeEngine *pMerger; /* Merge engine thread reads data from */
  71685. i64 iStartOff; /* Offset to start writing file at */
  71686. int mxSz; /* Maximum bytes of data to store */
  71687. int bEof; /* Set to true when merge is finished */
  71688. int bUseThread; /* True to use a bg thread for this object */
  71689. SorterFile aFile[2]; /* aFile[0] for reading, [1] for writing */
  71690. };
  71691. /*
  71692. ** An instance of this object is used for writing a PMA.
  71693. **
  71694. ** The PMA is written one record at a time. Each record is of an arbitrary
  71695. ** size. But I/O is more efficient if it occurs in page-sized blocks where
  71696. ** each block is aligned on a page boundary. This object caches writes to
  71697. ** the PMA so that aligned, page-size blocks are written.
  71698. */
  71699. struct PmaWriter {
  71700. int eFWErr; /* Non-zero if in an error state */
  71701. u8 *aBuffer; /* Pointer to write buffer */
  71702. int nBuffer; /* Size of write buffer in bytes */
  71703. int iBufStart; /* First byte of buffer to write */
  71704. int iBufEnd; /* Last byte of buffer to write */
  71705. i64 iWriteOff; /* Offset of start of buffer in file */
  71706. sqlite3_file *pFd; /* File handle to write to */
  71707. };
  71708. /*
  71709. ** This object is the header on a single record while that record is being
  71710. ** held in memory and prior to being written out as part of a PMA.
  71711. **
  71712. ** How the linked list is connected depends on how memory is being managed
  71713. ** by this module. If using a separate allocation for each in-memory record
  71714. ** (VdbeSorter.list.aMemory==0), then the list is always connected using the
  71715. ** SorterRecord.u.pNext pointers.
  71716. **
  71717. ** Or, if using the single large allocation method (VdbeSorter.list.aMemory!=0),
  71718. ** then while records are being accumulated the list is linked using the
  71719. ** SorterRecord.u.iNext offset. This is because the aMemory[] array may
  71720. ** be sqlite3Realloc()ed while records are being accumulated. Once the VM
  71721. ** has finished passing records to the sorter, or when the in-memory buffer
  71722. ** is full, the list is sorted. As part of the sorting process, it is
  71723. ** converted to use the SorterRecord.u.pNext pointers. See function
  71724. ** vdbeSorterSort() for details.
  71725. */
  71726. struct SorterRecord {
  71727. int nVal; /* Size of the record in bytes */
  71728. union {
  71729. SorterRecord *pNext; /* Pointer to next record in list */
  71730. int iNext; /* Offset within aMemory of next record */
  71731. } u;
  71732. /* The data for the record immediately follows this header */
  71733. };
  71734. /* Return a pointer to the buffer containing the record data for SorterRecord
  71735. ** object p. Should be used as if:
  71736. **
  71737. ** void *SRVAL(SorterRecord *p) { return (void*)&p[1]; }
  71738. */
  71739. #define SRVAL(p) ((void*)((SorterRecord*)(p) + 1))
  71740. /* The minimum PMA size is set to this value multiplied by the database
  71741. ** page size in bytes. */
  71742. #define SORTER_MIN_WORKING 10
  71743. /* Maximum number of PMAs that a single MergeEngine can merge */
  71744. #define SORTER_MAX_MERGE_COUNT 16
  71745. static int vdbeIncrSwap(IncrMerger*);
  71746. static void vdbeIncrFree(IncrMerger *);
  71747. /*
  71748. ** Free all memory belonging to the PmaReader object passed as the
  71749. ** argument. All structure fields are set to zero before returning.
  71750. */
  71751. static void vdbePmaReaderClear(PmaReader *pReadr){
  71752. sqlite3_free(pReadr->aAlloc);
  71753. sqlite3_free(pReadr->aBuffer);
  71754. if( pReadr->aMap ) sqlite3OsUnfetch(pReadr->pFd, 0, pReadr->aMap);
  71755. vdbeIncrFree(pReadr->pIncr);
  71756. memset(pReadr, 0, sizeof(PmaReader));
  71757. }
  71758. /*
  71759. ** Read the next nByte bytes of data from the PMA p.
  71760. ** If successful, set *ppOut to point to a buffer containing the data
  71761. ** and return SQLITE_OK. Otherwise, if an error occurs, return an SQLite
  71762. ** error code.
  71763. **
  71764. ** The buffer returned in *ppOut is only valid until the
  71765. ** next call to this function.
  71766. */
  71767. static int vdbePmaReadBlob(
  71768. PmaReader *p, /* PmaReader from which to take the blob */
  71769. int nByte, /* Bytes of data to read */
  71770. u8 **ppOut /* OUT: Pointer to buffer containing data */
  71771. ){
  71772. int iBuf; /* Offset within buffer to read from */
  71773. int nAvail; /* Bytes of data available in buffer */
  71774. if( p->aMap ){
  71775. *ppOut = &p->aMap[p->iReadOff];
  71776. p->iReadOff += nByte;
  71777. return SQLITE_OK;
  71778. }
  71779. assert( p->aBuffer );
  71780. /* If there is no more data to be read from the buffer, read the next
  71781. ** p->nBuffer bytes of data from the file into it. Or, if there are less
  71782. ** than p->nBuffer bytes remaining in the PMA, read all remaining data. */
  71783. iBuf = p->iReadOff % p->nBuffer;
  71784. if( iBuf==0 ){
  71785. int nRead; /* Bytes to read from disk */
  71786. int rc; /* sqlite3OsRead() return code */
  71787. /* Determine how many bytes of data to read. */
  71788. if( (p->iEof - p->iReadOff) > (i64)p->nBuffer ){
  71789. nRead = p->nBuffer;
  71790. }else{
  71791. nRead = (int)(p->iEof - p->iReadOff);
  71792. }
  71793. assert( nRead>0 );
  71794. /* Readr data from the file. Return early if an error occurs. */
  71795. rc = sqlite3OsRead(p->pFd, p->aBuffer, nRead, p->iReadOff);
  71796. assert( rc!=SQLITE_IOERR_SHORT_READ );
  71797. if( rc!=SQLITE_OK ) return rc;
  71798. }
  71799. nAvail = p->nBuffer - iBuf;
  71800. if( nByte<=nAvail ){
  71801. /* The requested data is available in the in-memory buffer. In this
  71802. ** case there is no need to make a copy of the data, just return a
  71803. ** pointer into the buffer to the caller. */
  71804. *ppOut = &p->aBuffer[iBuf];
  71805. p->iReadOff += nByte;
  71806. }else{
  71807. /* The requested data is not all available in the in-memory buffer.
  71808. ** In this case, allocate space at p->aAlloc[] to copy the requested
  71809. ** range into. Then return a copy of pointer p->aAlloc to the caller. */
  71810. int nRem; /* Bytes remaining to copy */
  71811. /* Extend the p->aAlloc[] allocation if required. */
  71812. if( p->nAlloc<nByte ){
  71813. u8 *aNew;
  71814. int nNew = MAX(128, p->nAlloc*2);
  71815. while( nByte>nNew ) nNew = nNew*2;
  71816. aNew = sqlite3Realloc(p->aAlloc, nNew);
  71817. if( !aNew ) return SQLITE_NOMEM;
  71818. p->nAlloc = nNew;
  71819. p->aAlloc = aNew;
  71820. }
  71821. /* Copy as much data as is available in the buffer into the start of
  71822. ** p->aAlloc[]. */
  71823. memcpy(p->aAlloc, &p->aBuffer[iBuf], nAvail);
  71824. p->iReadOff += nAvail;
  71825. nRem = nByte - nAvail;
  71826. /* The following loop copies up to p->nBuffer bytes per iteration into
  71827. ** the p->aAlloc[] buffer. */
  71828. while( nRem>0 ){
  71829. int rc; /* vdbePmaReadBlob() return code */
  71830. int nCopy; /* Number of bytes to copy */
  71831. u8 *aNext; /* Pointer to buffer to copy data from */
  71832. nCopy = nRem;
  71833. if( nRem>p->nBuffer ) nCopy = p->nBuffer;
  71834. rc = vdbePmaReadBlob(p, nCopy, &aNext);
  71835. if( rc!=SQLITE_OK ) return rc;
  71836. assert( aNext!=p->aAlloc );
  71837. memcpy(&p->aAlloc[nByte - nRem], aNext, nCopy);
  71838. nRem -= nCopy;
  71839. }
  71840. *ppOut = p->aAlloc;
  71841. }
  71842. return SQLITE_OK;
  71843. }
  71844. /*
  71845. ** Read a varint from the stream of data accessed by p. Set *pnOut to
  71846. ** the value read.
  71847. */
  71848. static int vdbePmaReadVarint(PmaReader *p, u64 *pnOut){
  71849. int iBuf;
  71850. if( p->aMap ){
  71851. p->iReadOff += sqlite3GetVarint(&p->aMap[p->iReadOff], pnOut);
  71852. }else{
  71853. iBuf = p->iReadOff % p->nBuffer;
  71854. if( iBuf && (p->nBuffer-iBuf)>=9 ){
  71855. p->iReadOff += sqlite3GetVarint(&p->aBuffer[iBuf], pnOut);
  71856. }else{
  71857. u8 aVarint[16], *a;
  71858. int i = 0, rc;
  71859. do{
  71860. rc = vdbePmaReadBlob(p, 1, &a);
  71861. if( rc ) return rc;
  71862. aVarint[(i++)&0xf] = a[0];
  71863. }while( (a[0]&0x80)!=0 );
  71864. sqlite3GetVarint(aVarint, pnOut);
  71865. }
  71866. }
  71867. return SQLITE_OK;
  71868. }
  71869. /*
  71870. ** Attempt to memory map file pFile. If successful, set *pp to point to the
  71871. ** new mapping and return SQLITE_OK. If the mapping is not attempted
  71872. ** (because the file is too large or the VFS layer is configured not to use
  71873. ** mmap), return SQLITE_OK and set *pp to NULL.
  71874. **
  71875. ** Or, if an error occurs, return an SQLite error code. The final value of
  71876. ** *pp is undefined in this case.
  71877. */
  71878. static int vdbeSorterMapFile(SortSubtask *pTask, SorterFile *pFile, u8 **pp){
  71879. int rc = SQLITE_OK;
  71880. if( pFile->iEof<=(i64)(pTask->pSorter->db->nMaxSorterMmap) ){
  71881. sqlite3_file *pFd = pFile->pFd;
  71882. if( pFd->pMethods->iVersion>=3 ){
  71883. rc = sqlite3OsFetch(pFd, 0, (int)pFile->iEof, (void**)pp);
  71884. testcase( rc!=SQLITE_OK );
  71885. }
  71886. }
  71887. return rc;
  71888. }
  71889. /*
  71890. ** Attach PmaReader pReadr to file pFile (if it is not already attached to
  71891. ** that file) and seek it to offset iOff within the file. Return SQLITE_OK
  71892. ** if successful, or an SQLite error code if an error occurs.
  71893. */
  71894. static int vdbePmaReaderSeek(
  71895. SortSubtask *pTask, /* Task context */
  71896. PmaReader *pReadr, /* Reader whose cursor is to be moved */
  71897. SorterFile *pFile, /* Sorter file to read from */
  71898. i64 iOff /* Offset in pFile */
  71899. ){
  71900. int rc = SQLITE_OK;
  71901. assert( pReadr->pIncr==0 || pReadr->pIncr->bEof==0 );
  71902. if( sqlite3FaultSim(201) ) return SQLITE_IOERR_READ;
  71903. if( pReadr->aMap ){
  71904. sqlite3OsUnfetch(pReadr->pFd, 0, pReadr->aMap);
  71905. pReadr->aMap = 0;
  71906. }
  71907. pReadr->iReadOff = iOff;
  71908. pReadr->iEof = pFile->iEof;
  71909. pReadr->pFd = pFile->pFd;
  71910. rc = vdbeSorterMapFile(pTask, pFile, &pReadr->aMap);
  71911. if( rc==SQLITE_OK && pReadr->aMap==0 ){
  71912. int pgsz = pTask->pSorter->pgsz;
  71913. int iBuf = pReadr->iReadOff % pgsz;
  71914. if( pReadr->aBuffer==0 ){
  71915. pReadr->aBuffer = (u8*)sqlite3Malloc(pgsz);
  71916. if( pReadr->aBuffer==0 ) rc = SQLITE_NOMEM;
  71917. pReadr->nBuffer = pgsz;
  71918. }
  71919. if( rc==SQLITE_OK && iBuf ){
  71920. int nRead = pgsz - iBuf;
  71921. if( (pReadr->iReadOff + nRead) > pReadr->iEof ){
  71922. nRead = (int)(pReadr->iEof - pReadr->iReadOff);
  71923. }
  71924. rc = sqlite3OsRead(
  71925. pReadr->pFd, &pReadr->aBuffer[iBuf], nRead, pReadr->iReadOff
  71926. );
  71927. testcase( rc!=SQLITE_OK );
  71928. }
  71929. }
  71930. return rc;
  71931. }
  71932. /*
  71933. ** Advance PmaReader pReadr to the next key in its PMA. Return SQLITE_OK if
  71934. ** no error occurs, or an SQLite error code if one does.
  71935. */
  71936. static int vdbePmaReaderNext(PmaReader *pReadr){
  71937. int rc = SQLITE_OK; /* Return Code */
  71938. u64 nRec = 0; /* Size of record in bytes */
  71939. if( pReadr->iReadOff>=pReadr->iEof ){
  71940. IncrMerger *pIncr = pReadr->pIncr;
  71941. int bEof = 1;
  71942. if( pIncr ){
  71943. rc = vdbeIncrSwap(pIncr);
  71944. if( rc==SQLITE_OK && pIncr->bEof==0 ){
  71945. rc = vdbePmaReaderSeek(
  71946. pIncr->pTask, pReadr, &pIncr->aFile[0], pIncr->iStartOff
  71947. );
  71948. bEof = 0;
  71949. }
  71950. }
  71951. if( bEof ){
  71952. /* This is an EOF condition */
  71953. vdbePmaReaderClear(pReadr);
  71954. testcase( rc!=SQLITE_OK );
  71955. return rc;
  71956. }
  71957. }
  71958. if( rc==SQLITE_OK ){
  71959. rc = vdbePmaReadVarint(pReadr, &nRec);
  71960. }
  71961. if( rc==SQLITE_OK ){
  71962. pReadr->nKey = (int)nRec;
  71963. rc = vdbePmaReadBlob(pReadr, (int)nRec, &pReadr->aKey);
  71964. testcase( rc!=SQLITE_OK );
  71965. }
  71966. return rc;
  71967. }
  71968. /*
  71969. ** Initialize PmaReader pReadr to scan through the PMA stored in file pFile
  71970. ** starting at offset iStart and ending at offset iEof-1. This function
  71971. ** leaves the PmaReader pointing to the first key in the PMA (or EOF if the
  71972. ** PMA is empty).
  71973. **
  71974. ** If the pnByte parameter is NULL, then it is assumed that the file
  71975. ** contains a single PMA, and that that PMA omits the initial length varint.
  71976. */
  71977. static int vdbePmaReaderInit(
  71978. SortSubtask *pTask, /* Task context */
  71979. SorterFile *pFile, /* Sorter file to read from */
  71980. i64 iStart, /* Start offset in pFile */
  71981. PmaReader *pReadr, /* PmaReader to populate */
  71982. i64 *pnByte /* IN/OUT: Increment this value by PMA size */
  71983. ){
  71984. int rc;
  71985. assert( pFile->iEof>iStart );
  71986. assert( pReadr->aAlloc==0 && pReadr->nAlloc==0 );
  71987. assert( pReadr->aBuffer==0 );
  71988. assert( pReadr->aMap==0 );
  71989. rc = vdbePmaReaderSeek(pTask, pReadr, pFile, iStart);
  71990. if( rc==SQLITE_OK ){
  71991. u64 nByte; /* Size of PMA in bytes */
  71992. rc = vdbePmaReadVarint(pReadr, &nByte);
  71993. pReadr->iEof = pReadr->iReadOff + nByte;
  71994. *pnByte += nByte;
  71995. }
  71996. if( rc==SQLITE_OK ){
  71997. rc = vdbePmaReaderNext(pReadr);
  71998. }
  71999. return rc;
  72000. }
  72001. /*
  72002. ** Compare key1 (buffer pKey1, size nKey1 bytes) with key2 (buffer pKey2,
  72003. ** size nKey2 bytes). Use (pTask->pKeyInfo) for the collation sequences
  72004. ** used by the comparison. Return the result of the comparison.
  72005. **
  72006. ** Before returning, object (pTask->pUnpacked) is populated with the
  72007. ** unpacked version of key2. Or, if pKey2 is passed a NULL pointer, then it
  72008. ** is assumed that the (pTask->pUnpacked) structure already contains the
  72009. ** unpacked key to use as key2.
  72010. **
  72011. ** If an OOM error is encountered, (pTask->pUnpacked->error_rc) is set
  72012. ** to SQLITE_NOMEM.
  72013. */
  72014. static int vdbeSorterCompare(
  72015. SortSubtask *pTask, /* Subtask context (for pKeyInfo) */
  72016. const void *pKey1, int nKey1, /* Left side of comparison */
  72017. const void *pKey2, int nKey2 /* Right side of comparison */
  72018. ){
  72019. UnpackedRecord *r2 = pTask->pUnpacked;
  72020. if( pKey2 ){
  72021. sqlite3VdbeRecordUnpack(pTask->pSorter->pKeyInfo, nKey2, pKey2, r2);
  72022. }
  72023. return sqlite3VdbeRecordCompare(nKey1, pKey1, r2);
  72024. }
  72025. /*
  72026. ** Initialize the temporary index cursor just opened as a sorter cursor.
  72027. **
  72028. ** Usually, the sorter module uses the value of (pCsr->pKeyInfo->nField)
  72029. ** to determine the number of fields that should be compared from the
  72030. ** records being sorted. However, if the value passed as argument nField
  72031. ** is non-zero and the sorter is able to guarantee a stable sort, nField
  72032. ** is used instead. This is used when sorting records for a CREATE INDEX
  72033. ** statement. In this case, keys are always delivered to the sorter in
  72034. ** order of the primary key, which happens to be make up the final part
  72035. ** of the records being sorted. So if the sort is stable, there is never
  72036. ** any reason to compare PK fields and they can be ignored for a small
  72037. ** performance boost.
  72038. **
  72039. ** The sorter can guarantee a stable sort when running in single-threaded
  72040. ** mode, but not in multi-threaded mode.
  72041. **
  72042. ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
  72043. */
  72044. SQLITE_PRIVATE int sqlite3VdbeSorterInit(
  72045. sqlite3 *db, /* Database connection (for malloc()) */
  72046. int nField, /* Number of key fields in each record */
  72047. VdbeCursor *pCsr /* Cursor that holds the new sorter */
  72048. ){
  72049. int pgsz; /* Page size of main database */
  72050. int i; /* Used to iterate through aTask[] */
  72051. int mxCache; /* Cache size */
  72052. VdbeSorter *pSorter; /* The new sorter */
  72053. KeyInfo *pKeyInfo; /* Copy of pCsr->pKeyInfo with db==0 */
  72054. int szKeyInfo; /* Size of pCsr->pKeyInfo in bytes */
  72055. int sz; /* Size of pSorter in bytes */
  72056. int rc = SQLITE_OK;
  72057. #if SQLITE_MAX_WORKER_THREADS==0
  72058. # define nWorker 0
  72059. #else
  72060. int nWorker;
  72061. #endif
  72062. /* Initialize the upper limit on the number of worker threads */
  72063. #if SQLITE_MAX_WORKER_THREADS>0
  72064. if( sqlite3TempInMemory(db) || sqlite3GlobalConfig.bCoreMutex==0 ){
  72065. nWorker = 0;
  72066. }else{
  72067. nWorker = db->aLimit[SQLITE_LIMIT_WORKER_THREADS];
  72068. }
  72069. #endif
  72070. /* Do not allow the total number of threads (main thread + all workers)
  72071. ** to exceed the maximum merge count */
  72072. #if SQLITE_MAX_WORKER_THREADS>=SORTER_MAX_MERGE_COUNT
  72073. if( nWorker>=SORTER_MAX_MERGE_COUNT ){
  72074. nWorker = SORTER_MAX_MERGE_COUNT-1;
  72075. }
  72076. #endif
  72077. assert( pCsr->pKeyInfo && pCsr->pBt==0 );
  72078. szKeyInfo = sizeof(KeyInfo) + (pCsr->pKeyInfo->nField-1)*sizeof(CollSeq*);
  72079. sz = sizeof(VdbeSorter) + nWorker * sizeof(SortSubtask);
  72080. pSorter = (VdbeSorter*)sqlite3DbMallocZero(db, sz + szKeyInfo);
  72081. pCsr->pSorter = pSorter;
  72082. if( pSorter==0 ){
  72083. rc = SQLITE_NOMEM;
  72084. }else{
  72085. pSorter->pKeyInfo = pKeyInfo = (KeyInfo*)((u8*)pSorter + sz);
  72086. memcpy(pKeyInfo, pCsr->pKeyInfo, szKeyInfo);
  72087. pKeyInfo->db = 0;
  72088. if( nField && nWorker==0 ) pKeyInfo->nField = nField;
  72089. pSorter->pgsz = pgsz = sqlite3BtreeGetPageSize(db->aDb[0].pBt);
  72090. pSorter->nTask = nWorker + 1;
  72091. pSorter->bUseThreads = (pSorter->nTask>1);
  72092. pSorter->db = db;
  72093. for(i=0; i<pSorter->nTask; i++){
  72094. SortSubtask *pTask = &pSorter->aTask[i];
  72095. pTask->pSorter = pSorter;
  72096. }
  72097. if( !sqlite3TempInMemory(db) ){
  72098. pSorter->mnPmaSize = SORTER_MIN_WORKING * pgsz;
  72099. mxCache = db->aDb[0].pSchema->cache_size;
  72100. if( mxCache<SORTER_MIN_WORKING ) mxCache = SORTER_MIN_WORKING;
  72101. pSorter->mxPmaSize = mxCache * pgsz;
  72102. /* If the application has not configure scratch memory using
  72103. ** SQLITE_CONFIG_SCRATCH then we assume it is OK to do large memory
  72104. ** allocations. If scratch memory has been configured, then assume
  72105. ** large memory allocations should be avoided to prevent heap
  72106. ** fragmentation.
  72107. */
  72108. if( sqlite3GlobalConfig.pScratch==0 ){
  72109. assert( pSorter->iMemory==0 );
  72110. pSorter->nMemory = pgsz;
  72111. pSorter->list.aMemory = (u8*)sqlite3Malloc(pgsz);
  72112. if( !pSorter->list.aMemory ) rc = SQLITE_NOMEM;
  72113. }
  72114. }
  72115. }
  72116. return rc;
  72117. }
  72118. #undef nWorker /* Defined at the top of this function */
  72119. /*
  72120. ** Free the list of sorted records starting at pRecord.
  72121. */
  72122. static void vdbeSorterRecordFree(sqlite3 *db, SorterRecord *pRecord){
  72123. SorterRecord *p;
  72124. SorterRecord *pNext;
  72125. for(p=pRecord; p; p=pNext){
  72126. pNext = p->u.pNext;
  72127. sqlite3DbFree(db, p);
  72128. }
  72129. }
  72130. /*
  72131. ** Free all resources owned by the object indicated by argument pTask. All
  72132. ** fields of *pTask are zeroed before returning.
  72133. */
  72134. static void vdbeSortSubtaskCleanup(sqlite3 *db, SortSubtask *pTask){
  72135. sqlite3DbFree(db, pTask->pUnpacked);
  72136. pTask->pUnpacked = 0;
  72137. #if SQLITE_MAX_WORKER_THREADS>0
  72138. /* pTask->list.aMemory can only be non-zero if it was handed memory
  72139. ** from the main thread. That only occurs SQLITE_MAX_WORKER_THREADS>0 */
  72140. if( pTask->list.aMemory ){
  72141. sqlite3_free(pTask->list.aMemory);
  72142. pTask->list.aMemory = 0;
  72143. }else
  72144. #endif
  72145. {
  72146. assert( pTask->list.aMemory==0 );
  72147. vdbeSorterRecordFree(0, pTask->list.pList);
  72148. }
  72149. pTask->list.pList = 0;
  72150. if( pTask->file.pFd ){
  72151. sqlite3OsCloseFree(pTask->file.pFd);
  72152. pTask->file.pFd = 0;
  72153. pTask->file.iEof = 0;
  72154. }
  72155. if( pTask->file2.pFd ){
  72156. sqlite3OsCloseFree(pTask->file2.pFd);
  72157. pTask->file2.pFd = 0;
  72158. pTask->file2.iEof = 0;
  72159. }
  72160. }
  72161. #ifdef SQLITE_DEBUG_SORTER_THREADS
  72162. static void vdbeSorterWorkDebug(SortSubtask *pTask, const char *zEvent){
  72163. i64 t;
  72164. int iTask = (pTask - pTask->pSorter->aTask);
  72165. sqlite3OsCurrentTimeInt64(pTask->pSorter->db->pVfs, &t);
  72166. fprintf(stderr, "%lld:%d %s\n", t, iTask, zEvent);
  72167. }
  72168. static void vdbeSorterRewindDebug(const char *zEvent){
  72169. i64 t;
  72170. sqlite3OsCurrentTimeInt64(sqlite3_vfs_find(0), &t);
  72171. fprintf(stderr, "%lld:X %s\n", t, zEvent);
  72172. }
  72173. static void vdbeSorterPopulateDebug(
  72174. SortSubtask *pTask,
  72175. const char *zEvent
  72176. ){
  72177. i64 t;
  72178. int iTask = (pTask - pTask->pSorter->aTask);
  72179. sqlite3OsCurrentTimeInt64(pTask->pSorter->db->pVfs, &t);
  72180. fprintf(stderr, "%lld:bg%d %s\n", t, iTask, zEvent);
  72181. }
  72182. static void vdbeSorterBlockDebug(
  72183. SortSubtask *pTask,
  72184. int bBlocked,
  72185. const char *zEvent
  72186. ){
  72187. if( bBlocked ){
  72188. i64 t;
  72189. sqlite3OsCurrentTimeInt64(pTask->pSorter->db->pVfs, &t);
  72190. fprintf(stderr, "%lld:main %s\n", t, zEvent);
  72191. }
  72192. }
  72193. #else
  72194. # define vdbeSorterWorkDebug(x,y)
  72195. # define vdbeSorterRewindDebug(y)
  72196. # define vdbeSorterPopulateDebug(x,y)
  72197. # define vdbeSorterBlockDebug(x,y,z)
  72198. #endif
  72199. #if SQLITE_MAX_WORKER_THREADS>0
  72200. /*
  72201. ** Join thread pTask->thread.
  72202. */
  72203. static int vdbeSorterJoinThread(SortSubtask *pTask){
  72204. int rc = SQLITE_OK;
  72205. if( pTask->pThread ){
  72206. #ifdef SQLITE_DEBUG_SORTER_THREADS
  72207. int bDone = pTask->bDone;
  72208. #endif
  72209. void *pRet = SQLITE_INT_TO_PTR(SQLITE_ERROR);
  72210. vdbeSorterBlockDebug(pTask, !bDone, "enter");
  72211. (void)sqlite3ThreadJoin(pTask->pThread, &pRet);
  72212. vdbeSorterBlockDebug(pTask, !bDone, "exit");
  72213. rc = SQLITE_PTR_TO_INT(pRet);
  72214. assert( pTask->bDone==1 );
  72215. pTask->bDone = 0;
  72216. pTask->pThread = 0;
  72217. }
  72218. return rc;
  72219. }
  72220. /*
  72221. ** Launch a background thread to run xTask(pIn).
  72222. */
  72223. static int vdbeSorterCreateThread(
  72224. SortSubtask *pTask, /* Thread will use this task object */
  72225. void *(*xTask)(void*), /* Routine to run in a separate thread */
  72226. void *pIn /* Argument passed into xTask() */
  72227. ){
  72228. assert( pTask->pThread==0 && pTask->bDone==0 );
  72229. return sqlite3ThreadCreate(&pTask->pThread, xTask, pIn);
  72230. }
  72231. /*
  72232. ** Join all outstanding threads launched by SorterWrite() to create
  72233. ** level-0 PMAs.
  72234. */
  72235. static int vdbeSorterJoinAll(VdbeSorter *pSorter, int rcin){
  72236. int rc = rcin;
  72237. int i;
  72238. /* This function is always called by the main user thread.
  72239. **
  72240. ** If this function is being called after SorterRewind() has been called,
  72241. ** it is possible that thread pSorter->aTask[pSorter->nTask-1].pThread
  72242. ** is currently attempt to join one of the other threads. To avoid a race
  72243. ** condition where this thread also attempts to join the same object, join
  72244. ** thread pSorter->aTask[pSorter->nTask-1].pThread first. */
  72245. for(i=pSorter->nTask-1; i>=0; i--){
  72246. SortSubtask *pTask = &pSorter->aTask[i];
  72247. int rc2 = vdbeSorterJoinThread(pTask);
  72248. if( rc==SQLITE_OK ) rc = rc2;
  72249. }
  72250. return rc;
  72251. }
  72252. #else
  72253. # define vdbeSorterJoinAll(x,rcin) (rcin)
  72254. # define vdbeSorterJoinThread(pTask) SQLITE_OK
  72255. #endif
  72256. /*
  72257. ** Allocate a new MergeEngine object capable of handling up to
  72258. ** nReader PmaReader inputs.
  72259. **
  72260. ** nReader is automatically rounded up to the next power of two.
  72261. ** nReader may not exceed SORTER_MAX_MERGE_COUNT even after rounding up.
  72262. */
  72263. static MergeEngine *vdbeMergeEngineNew(int nReader){
  72264. int N = 2; /* Smallest power of two >= nReader */
  72265. int nByte; /* Total bytes of space to allocate */
  72266. MergeEngine *pNew; /* Pointer to allocated object to return */
  72267. assert( nReader<=SORTER_MAX_MERGE_COUNT );
  72268. while( N<nReader ) N += N;
  72269. nByte = sizeof(MergeEngine) + N * (sizeof(int) + sizeof(PmaReader));
  72270. pNew = sqlite3FaultSim(100) ? 0 : (MergeEngine*)sqlite3MallocZero(nByte);
  72271. if( pNew ){
  72272. pNew->nTree = N;
  72273. pNew->pTask = 0;
  72274. pNew->aReadr = (PmaReader*)&pNew[1];
  72275. pNew->aTree = (int*)&pNew->aReadr[N];
  72276. }
  72277. return pNew;
  72278. }
  72279. /*
  72280. ** Free the MergeEngine object passed as the only argument.
  72281. */
  72282. static void vdbeMergeEngineFree(MergeEngine *pMerger){
  72283. int i;
  72284. if( pMerger ){
  72285. for(i=0; i<pMerger->nTree; i++){
  72286. vdbePmaReaderClear(&pMerger->aReadr[i]);
  72287. }
  72288. }
  72289. sqlite3_free(pMerger);
  72290. }
  72291. /*
  72292. ** Free all resources associated with the IncrMerger object indicated by
  72293. ** the first argument.
  72294. */
  72295. static void vdbeIncrFree(IncrMerger *pIncr){
  72296. if( pIncr ){
  72297. #if SQLITE_MAX_WORKER_THREADS>0
  72298. if( pIncr->bUseThread ){
  72299. vdbeSorterJoinThread(pIncr->pTask);
  72300. if( pIncr->aFile[0].pFd ) sqlite3OsCloseFree(pIncr->aFile[0].pFd);
  72301. if( pIncr->aFile[1].pFd ) sqlite3OsCloseFree(pIncr->aFile[1].pFd);
  72302. }
  72303. #endif
  72304. vdbeMergeEngineFree(pIncr->pMerger);
  72305. sqlite3_free(pIncr);
  72306. }
  72307. }
  72308. /*
  72309. ** Reset a sorting cursor back to its original empty state.
  72310. */
  72311. SQLITE_PRIVATE void sqlite3VdbeSorterReset(sqlite3 *db, VdbeSorter *pSorter){
  72312. int i;
  72313. (void)vdbeSorterJoinAll(pSorter, SQLITE_OK);
  72314. assert( pSorter->bUseThreads || pSorter->pReader==0 );
  72315. #if SQLITE_MAX_WORKER_THREADS>0
  72316. if( pSorter->pReader ){
  72317. vdbePmaReaderClear(pSorter->pReader);
  72318. sqlite3DbFree(db, pSorter->pReader);
  72319. pSorter->pReader = 0;
  72320. }
  72321. #endif
  72322. vdbeMergeEngineFree(pSorter->pMerger);
  72323. pSorter->pMerger = 0;
  72324. for(i=0; i<pSorter->nTask; i++){
  72325. SortSubtask *pTask = &pSorter->aTask[i];
  72326. vdbeSortSubtaskCleanup(db, pTask);
  72327. }
  72328. if( pSorter->list.aMemory==0 ){
  72329. vdbeSorterRecordFree(0, pSorter->list.pList);
  72330. }
  72331. pSorter->list.pList = 0;
  72332. pSorter->list.szPMA = 0;
  72333. pSorter->bUsePMA = 0;
  72334. pSorter->iMemory = 0;
  72335. pSorter->mxKeysize = 0;
  72336. sqlite3DbFree(db, pSorter->pUnpacked);
  72337. pSorter->pUnpacked = 0;
  72338. }
  72339. /*
  72340. ** Free any cursor components allocated by sqlite3VdbeSorterXXX routines.
  72341. */
  72342. SQLITE_PRIVATE void sqlite3VdbeSorterClose(sqlite3 *db, VdbeCursor *pCsr){
  72343. VdbeSorter *pSorter = pCsr->pSorter;
  72344. if( pSorter ){
  72345. sqlite3VdbeSorterReset(db, pSorter);
  72346. sqlite3_free(pSorter->list.aMemory);
  72347. sqlite3DbFree(db, pSorter);
  72348. pCsr->pSorter = 0;
  72349. }
  72350. }
  72351. #if SQLITE_MAX_MMAP_SIZE>0
  72352. /*
  72353. ** The first argument is a file-handle open on a temporary file. The file
  72354. ** is guaranteed to be nByte bytes or smaller in size. This function
  72355. ** attempts to extend the file to nByte bytes in size and to ensure that
  72356. ** the VFS has memory mapped it.
  72357. **
  72358. ** Whether or not the file does end up memory mapped of course depends on
  72359. ** the specific VFS implementation.
  72360. */
  72361. static void vdbeSorterExtendFile(sqlite3 *db, sqlite3_file *pFd, i64 nByte){
  72362. if( nByte<=(i64)(db->nMaxSorterMmap) && pFd->pMethods->iVersion>=3 ){
  72363. int rc = sqlite3OsTruncate(pFd, nByte);
  72364. if( rc==SQLITE_OK ){
  72365. void *p = 0;
  72366. sqlite3OsFetch(pFd, 0, (int)nByte, &p);
  72367. sqlite3OsUnfetch(pFd, 0, p);
  72368. }
  72369. }
  72370. }
  72371. #else
  72372. # define vdbeSorterExtendFile(x,y,z)
  72373. #endif
  72374. /*
  72375. ** Allocate space for a file-handle and open a temporary file. If successful,
  72376. ** set *ppFd to point to the malloc'd file-handle and return SQLITE_OK.
  72377. ** Otherwise, set *ppFd to 0 and return an SQLite error code.
  72378. */
  72379. static int vdbeSorterOpenTempFile(
  72380. sqlite3 *db, /* Database handle doing sort */
  72381. i64 nExtend, /* Attempt to extend file to this size */
  72382. sqlite3_file **ppFd
  72383. ){
  72384. int rc;
  72385. rc = sqlite3OsOpenMalloc(db->pVfs, 0, ppFd,
  72386. SQLITE_OPEN_TEMP_JOURNAL |
  72387. SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
  72388. SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE, &rc
  72389. );
  72390. if( rc==SQLITE_OK ){
  72391. i64 max = SQLITE_MAX_MMAP_SIZE;
  72392. sqlite3OsFileControlHint(*ppFd, SQLITE_FCNTL_MMAP_SIZE, (void*)&max);
  72393. if( nExtend>0 ){
  72394. vdbeSorterExtendFile(db, *ppFd, nExtend);
  72395. }
  72396. }
  72397. return rc;
  72398. }
  72399. /*
  72400. ** If it has not already been allocated, allocate the UnpackedRecord
  72401. ** structure at pTask->pUnpacked. Return SQLITE_OK if successful (or
  72402. ** if no allocation was required), or SQLITE_NOMEM otherwise.
  72403. */
  72404. static int vdbeSortAllocUnpacked(SortSubtask *pTask){
  72405. if( pTask->pUnpacked==0 ){
  72406. char *pFree;
  72407. pTask->pUnpacked = sqlite3VdbeAllocUnpackedRecord(
  72408. pTask->pSorter->pKeyInfo, 0, 0, &pFree
  72409. );
  72410. assert( pTask->pUnpacked==(UnpackedRecord*)pFree );
  72411. if( pFree==0 ) return SQLITE_NOMEM;
  72412. pTask->pUnpacked->nField = pTask->pSorter->pKeyInfo->nField;
  72413. pTask->pUnpacked->errCode = 0;
  72414. }
  72415. return SQLITE_OK;
  72416. }
  72417. /*
  72418. ** Merge the two sorted lists p1 and p2 into a single list.
  72419. ** Set *ppOut to the head of the new list.
  72420. */
  72421. static void vdbeSorterMerge(
  72422. SortSubtask *pTask, /* Calling thread context */
  72423. SorterRecord *p1, /* First list to merge */
  72424. SorterRecord *p2, /* Second list to merge */
  72425. SorterRecord **ppOut /* OUT: Head of merged list */
  72426. ){
  72427. SorterRecord *pFinal = 0;
  72428. SorterRecord **pp = &pFinal;
  72429. void *pVal2 = p2 ? SRVAL(p2) : 0;
  72430. while( p1 && p2 ){
  72431. int res;
  72432. res = vdbeSorterCompare(pTask, SRVAL(p1), p1->nVal, pVal2, p2->nVal);
  72433. if( res<=0 ){
  72434. *pp = p1;
  72435. pp = &p1->u.pNext;
  72436. p1 = p1->u.pNext;
  72437. pVal2 = 0;
  72438. }else{
  72439. *pp = p2;
  72440. pp = &p2->u.pNext;
  72441. p2 = p2->u.pNext;
  72442. if( p2==0 ) break;
  72443. pVal2 = SRVAL(p2);
  72444. }
  72445. }
  72446. *pp = p1 ? p1 : p2;
  72447. *ppOut = pFinal;
  72448. }
  72449. /*
  72450. ** Sort the linked list of records headed at pTask->pList. Return
  72451. ** SQLITE_OK if successful, or an SQLite error code (i.e. SQLITE_NOMEM) if
  72452. ** an error occurs.
  72453. */
  72454. static int vdbeSorterSort(SortSubtask *pTask, SorterList *pList){
  72455. int i;
  72456. SorterRecord **aSlot;
  72457. SorterRecord *p;
  72458. int rc;
  72459. rc = vdbeSortAllocUnpacked(pTask);
  72460. if( rc!=SQLITE_OK ) return rc;
  72461. aSlot = (SorterRecord **)sqlite3MallocZero(64 * sizeof(SorterRecord *));
  72462. if( !aSlot ){
  72463. return SQLITE_NOMEM;
  72464. }
  72465. p = pList->pList;
  72466. while( p ){
  72467. SorterRecord *pNext;
  72468. if( pList->aMemory ){
  72469. if( (u8*)p==pList->aMemory ){
  72470. pNext = 0;
  72471. }else{
  72472. assert( p->u.iNext<sqlite3MallocSize(pList->aMemory) );
  72473. pNext = (SorterRecord*)&pList->aMemory[p->u.iNext];
  72474. }
  72475. }else{
  72476. pNext = p->u.pNext;
  72477. }
  72478. p->u.pNext = 0;
  72479. for(i=0; aSlot[i]; i++){
  72480. vdbeSorterMerge(pTask, p, aSlot[i], &p);
  72481. aSlot[i] = 0;
  72482. }
  72483. aSlot[i] = p;
  72484. p = pNext;
  72485. }
  72486. p = 0;
  72487. for(i=0; i<64; i++){
  72488. vdbeSorterMerge(pTask, p, aSlot[i], &p);
  72489. }
  72490. pList->pList = p;
  72491. sqlite3_free(aSlot);
  72492. assert( pTask->pUnpacked->errCode==SQLITE_OK
  72493. || pTask->pUnpacked->errCode==SQLITE_NOMEM
  72494. );
  72495. return pTask->pUnpacked->errCode;
  72496. }
  72497. /*
  72498. ** Initialize a PMA-writer object.
  72499. */
  72500. static void vdbePmaWriterInit(
  72501. sqlite3_file *pFd, /* File handle to write to */
  72502. PmaWriter *p, /* Object to populate */
  72503. int nBuf, /* Buffer size */
  72504. i64 iStart /* Offset of pFd to begin writing at */
  72505. ){
  72506. memset(p, 0, sizeof(PmaWriter));
  72507. p->aBuffer = (u8*)sqlite3Malloc(nBuf);
  72508. if( !p->aBuffer ){
  72509. p->eFWErr = SQLITE_NOMEM;
  72510. }else{
  72511. p->iBufEnd = p->iBufStart = (iStart % nBuf);
  72512. p->iWriteOff = iStart - p->iBufStart;
  72513. p->nBuffer = nBuf;
  72514. p->pFd = pFd;
  72515. }
  72516. }
  72517. /*
  72518. ** Write nData bytes of data to the PMA. Return SQLITE_OK
  72519. ** if successful, or an SQLite error code if an error occurs.
  72520. */
  72521. static void vdbePmaWriteBlob(PmaWriter *p, u8 *pData, int nData){
  72522. int nRem = nData;
  72523. while( nRem>0 && p->eFWErr==0 ){
  72524. int nCopy = nRem;
  72525. if( nCopy>(p->nBuffer - p->iBufEnd) ){
  72526. nCopy = p->nBuffer - p->iBufEnd;
  72527. }
  72528. memcpy(&p->aBuffer[p->iBufEnd], &pData[nData-nRem], nCopy);
  72529. p->iBufEnd += nCopy;
  72530. if( p->iBufEnd==p->nBuffer ){
  72531. p->eFWErr = sqlite3OsWrite(p->pFd,
  72532. &p->aBuffer[p->iBufStart], p->iBufEnd - p->iBufStart,
  72533. p->iWriteOff + p->iBufStart
  72534. );
  72535. p->iBufStart = p->iBufEnd = 0;
  72536. p->iWriteOff += p->nBuffer;
  72537. }
  72538. assert( p->iBufEnd<p->nBuffer );
  72539. nRem -= nCopy;
  72540. }
  72541. }
  72542. /*
  72543. ** Flush any buffered data to disk and clean up the PMA-writer object.
  72544. ** The results of using the PMA-writer after this call are undefined.
  72545. ** Return SQLITE_OK if flushing the buffered data succeeds or is not
  72546. ** required. Otherwise, return an SQLite error code.
  72547. **
  72548. ** Before returning, set *piEof to the offset immediately following the
  72549. ** last byte written to the file.
  72550. */
  72551. static int vdbePmaWriterFinish(PmaWriter *p, i64 *piEof){
  72552. int rc;
  72553. if( p->eFWErr==0 && ALWAYS(p->aBuffer) && p->iBufEnd>p->iBufStart ){
  72554. p->eFWErr = sqlite3OsWrite(p->pFd,
  72555. &p->aBuffer[p->iBufStart], p->iBufEnd - p->iBufStart,
  72556. p->iWriteOff + p->iBufStart
  72557. );
  72558. }
  72559. *piEof = (p->iWriteOff + p->iBufEnd);
  72560. sqlite3_free(p->aBuffer);
  72561. rc = p->eFWErr;
  72562. memset(p, 0, sizeof(PmaWriter));
  72563. return rc;
  72564. }
  72565. /*
  72566. ** Write value iVal encoded as a varint to the PMA. Return
  72567. ** SQLITE_OK if successful, or an SQLite error code if an error occurs.
  72568. */
  72569. static void vdbePmaWriteVarint(PmaWriter *p, u64 iVal){
  72570. int nByte;
  72571. u8 aByte[10];
  72572. nByte = sqlite3PutVarint(aByte, iVal);
  72573. vdbePmaWriteBlob(p, aByte, nByte);
  72574. }
  72575. /*
  72576. ** Write the current contents of in-memory linked-list pList to a level-0
  72577. ** PMA in the temp file belonging to sub-task pTask. Return SQLITE_OK if
  72578. ** successful, or an SQLite error code otherwise.
  72579. **
  72580. ** The format of a PMA is:
  72581. **
  72582. ** * A varint. This varint contains the total number of bytes of content
  72583. ** in the PMA (not including the varint itself).
  72584. **
  72585. ** * One or more records packed end-to-end in order of ascending keys.
  72586. ** Each record consists of a varint followed by a blob of data (the
  72587. ** key). The varint is the number of bytes in the blob of data.
  72588. */
  72589. static int vdbeSorterListToPMA(SortSubtask *pTask, SorterList *pList){
  72590. sqlite3 *db = pTask->pSorter->db;
  72591. int rc = SQLITE_OK; /* Return code */
  72592. PmaWriter writer; /* Object used to write to the file */
  72593. #ifdef SQLITE_DEBUG
  72594. /* Set iSz to the expected size of file pTask->file after writing the PMA.
  72595. ** This is used by an assert() statement at the end of this function. */
  72596. i64 iSz = pList->szPMA + sqlite3VarintLen(pList->szPMA) + pTask->file.iEof;
  72597. #endif
  72598. vdbeSorterWorkDebug(pTask, "enter");
  72599. memset(&writer, 0, sizeof(PmaWriter));
  72600. assert( pList->szPMA>0 );
  72601. /* If the first temporary PMA file has not been opened, open it now. */
  72602. if( pTask->file.pFd==0 ){
  72603. rc = vdbeSorterOpenTempFile(db, 0, &pTask->file.pFd);
  72604. assert( rc!=SQLITE_OK || pTask->file.pFd );
  72605. assert( pTask->file.iEof==0 );
  72606. assert( pTask->nPMA==0 );
  72607. }
  72608. /* Try to get the file to memory map */
  72609. if( rc==SQLITE_OK ){
  72610. vdbeSorterExtendFile(db, pTask->file.pFd, pTask->file.iEof+pList->szPMA+9);
  72611. }
  72612. /* Sort the list */
  72613. if( rc==SQLITE_OK ){
  72614. rc = vdbeSorterSort(pTask, pList);
  72615. }
  72616. if( rc==SQLITE_OK ){
  72617. SorterRecord *p;
  72618. SorterRecord *pNext = 0;
  72619. vdbePmaWriterInit(pTask->file.pFd, &writer, pTask->pSorter->pgsz,
  72620. pTask->file.iEof);
  72621. pTask->nPMA++;
  72622. vdbePmaWriteVarint(&writer, pList->szPMA);
  72623. for(p=pList->pList; p; p=pNext){
  72624. pNext = p->u.pNext;
  72625. vdbePmaWriteVarint(&writer, p->nVal);
  72626. vdbePmaWriteBlob(&writer, SRVAL(p), p->nVal);
  72627. if( pList->aMemory==0 ) sqlite3_free(p);
  72628. }
  72629. pList->pList = p;
  72630. rc = vdbePmaWriterFinish(&writer, &pTask->file.iEof);
  72631. }
  72632. vdbeSorterWorkDebug(pTask, "exit");
  72633. assert( rc!=SQLITE_OK || pList->pList==0 );
  72634. assert( rc!=SQLITE_OK || pTask->file.iEof==iSz );
  72635. return rc;
  72636. }
  72637. /*
  72638. ** Advance the MergeEngine to its next entry.
  72639. ** Set *pbEof to true there is no next entry because
  72640. ** the MergeEngine has reached the end of all its inputs.
  72641. **
  72642. ** Return SQLITE_OK if successful or an error code if an error occurs.
  72643. */
  72644. static int vdbeMergeEngineStep(
  72645. MergeEngine *pMerger, /* The merge engine to advance to the next row */
  72646. int *pbEof /* Set TRUE at EOF. Set false for more content */
  72647. ){
  72648. int rc;
  72649. int iPrev = pMerger->aTree[1];/* Index of PmaReader to advance */
  72650. SortSubtask *pTask = pMerger->pTask;
  72651. /* Advance the current PmaReader */
  72652. rc = vdbePmaReaderNext(&pMerger->aReadr[iPrev]);
  72653. /* Update contents of aTree[] */
  72654. if( rc==SQLITE_OK ){
  72655. int i; /* Index of aTree[] to recalculate */
  72656. PmaReader *pReadr1; /* First PmaReader to compare */
  72657. PmaReader *pReadr2; /* Second PmaReader to compare */
  72658. u8 *pKey2; /* To pReadr2->aKey, or 0 if record cached */
  72659. /* Find the first two PmaReaders to compare. The one that was just
  72660. ** advanced (iPrev) and the one next to it in the array. */
  72661. pReadr1 = &pMerger->aReadr[(iPrev & 0xFFFE)];
  72662. pReadr2 = &pMerger->aReadr[(iPrev | 0x0001)];
  72663. pKey2 = pReadr2->aKey;
  72664. for(i=(pMerger->nTree+iPrev)/2; i>0; i=i/2){
  72665. /* Compare pReadr1 and pReadr2. Store the result in variable iRes. */
  72666. int iRes;
  72667. if( pReadr1->pFd==0 ){
  72668. iRes = +1;
  72669. }else if( pReadr2->pFd==0 ){
  72670. iRes = -1;
  72671. }else{
  72672. iRes = vdbeSorterCompare(pTask,
  72673. pReadr1->aKey, pReadr1->nKey, pKey2, pReadr2->nKey
  72674. );
  72675. }
  72676. /* If pReadr1 contained the smaller value, set aTree[i] to its index.
  72677. ** Then set pReadr2 to the next PmaReader to compare to pReadr1. In this
  72678. ** case there is no cache of pReadr2 in pTask->pUnpacked, so set
  72679. ** pKey2 to point to the record belonging to pReadr2.
  72680. **
  72681. ** Alternatively, if pReadr2 contains the smaller of the two values,
  72682. ** set aTree[i] to its index and update pReadr1. If vdbeSorterCompare()
  72683. ** was actually called above, then pTask->pUnpacked now contains
  72684. ** a value equivalent to pReadr2. So set pKey2 to NULL to prevent
  72685. ** vdbeSorterCompare() from decoding pReadr2 again.
  72686. **
  72687. ** If the two values were equal, then the value from the oldest
  72688. ** PMA should be considered smaller. The VdbeSorter.aReadr[] array
  72689. ** is sorted from oldest to newest, so pReadr1 contains older values
  72690. ** than pReadr2 iff (pReadr1<pReadr2). */
  72691. if( iRes<0 || (iRes==0 && pReadr1<pReadr2) ){
  72692. pMerger->aTree[i] = (int)(pReadr1 - pMerger->aReadr);
  72693. pReadr2 = &pMerger->aReadr[ pMerger->aTree[i ^ 0x0001] ];
  72694. pKey2 = pReadr2->aKey;
  72695. }else{
  72696. if( pReadr1->pFd ) pKey2 = 0;
  72697. pMerger->aTree[i] = (int)(pReadr2 - pMerger->aReadr);
  72698. pReadr1 = &pMerger->aReadr[ pMerger->aTree[i ^ 0x0001] ];
  72699. }
  72700. }
  72701. *pbEof = (pMerger->aReadr[pMerger->aTree[1]].pFd==0);
  72702. }
  72703. return (rc==SQLITE_OK ? pTask->pUnpacked->errCode : rc);
  72704. }
  72705. #if SQLITE_MAX_WORKER_THREADS>0
  72706. /*
  72707. ** The main routine for background threads that write level-0 PMAs.
  72708. */
  72709. static void *vdbeSorterFlushThread(void *pCtx){
  72710. SortSubtask *pTask = (SortSubtask*)pCtx;
  72711. int rc; /* Return code */
  72712. assert( pTask->bDone==0 );
  72713. rc = vdbeSorterListToPMA(pTask, &pTask->list);
  72714. pTask->bDone = 1;
  72715. return SQLITE_INT_TO_PTR(rc);
  72716. }
  72717. #endif /* SQLITE_MAX_WORKER_THREADS>0 */
  72718. /*
  72719. ** Flush the current contents of VdbeSorter.list to a new PMA, possibly
  72720. ** using a background thread.
  72721. */
  72722. static int vdbeSorterFlushPMA(VdbeSorter *pSorter){
  72723. #if SQLITE_MAX_WORKER_THREADS==0
  72724. pSorter->bUsePMA = 1;
  72725. return vdbeSorterListToPMA(&pSorter->aTask[0], &pSorter->list);
  72726. #else
  72727. int rc = SQLITE_OK;
  72728. int i;
  72729. SortSubtask *pTask = 0; /* Thread context used to create new PMA */
  72730. int nWorker = (pSorter->nTask-1);
  72731. /* Set the flag to indicate that at least one PMA has been written.
  72732. ** Or will be, anyhow. */
  72733. pSorter->bUsePMA = 1;
  72734. /* Select a sub-task to sort and flush the current list of in-memory
  72735. ** records to disk. If the sorter is running in multi-threaded mode,
  72736. ** round-robin between the first (pSorter->nTask-1) tasks. Except, if
  72737. ** the background thread from a sub-tasks previous turn is still running,
  72738. ** skip it. If the first (pSorter->nTask-1) sub-tasks are all still busy,
  72739. ** fall back to using the final sub-task. The first (pSorter->nTask-1)
  72740. ** sub-tasks are prefered as they use background threads - the final
  72741. ** sub-task uses the main thread. */
  72742. for(i=0; i<nWorker; i++){
  72743. int iTest = (pSorter->iPrev + i + 1) % nWorker;
  72744. pTask = &pSorter->aTask[iTest];
  72745. if( pTask->bDone ){
  72746. rc = vdbeSorterJoinThread(pTask);
  72747. }
  72748. if( rc!=SQLITE_OK || pTask->pThread==0 ) break;
  72749. }
  72750. if( rc==SQLITE_OK ){
  72751. if( i==nWorker ){
  72752. /* Use the foreground thread for this operation */
  72753. rc = vdbeSorterListToPMA(&pSorter->aTask[nWorker], &pSorter->list);
  72754. }else{
  72755. /* Launch a background thread for this operation */
  72756. u8 *aMem = pTask->list.aMemory;
  72757. void *pCtx = (void*)pTask;
  72758. assert( pTask->pThread==0 && pTask->bDone==0 );
  72759. assert( pTask->list.pList==0 );
  72760. assert( pTask->list.aMemory==0 || pSorter->list.aMemory!=0 );
  72761. pSorter->iPrev = (u8)(pTask - pSorter->aTask);
  72762. pTask->list = pSorter->list;
  72763. pSorter->list.pList = 0;
  72764. pSorter->list.szPMA = 0;
  72765. if( aMem ){
  72766. pSorter->list.aMemory = aMem;
  72767. pSorter->nMemory = sqlite3MallocSize(aMem);
  72768. }else if( pSorter->list.aMemory ){
  72769. pSorter->list.aMemory = sqlite3Malloc(pSorter->nMemory);
  72770. if( !pSorter->list.aMemory ) return SQLITE_NOMEM;
  72771. }
  72772. rc = vdbeSorterCreateThread(pTask, vdbeSorterFlushThread, pCtx);
  72773. }
  72774. }
  72775. return rc;
  72776. #endif /* SQLITE_MAX_WORKER_THREADS!=0 */
  72777. }
  72778. /*
  72779. ** Add a record to the sorter.
  72780. */
  72781. SQLITE_PRIVATE int sqlite3VdbeSorterWrite(
  72782. const VdbeCursor *pCsr, /* Sorter cursor */
  72783. Mem *pVal /* Memory cell containing record */
  72784. ){
  72785. VdbeSorter *pSorter = pCsr->pSorter;
  72786. int rc = SQLITE_OK; /* Return Code */
  72787. SorterRecord *pNew; /* New list element */
  72788. int bFlush; /* True to flush contents of memory to PMA */
  72789. int nReq; /* Bytes of memory required */
  72790. int nPMA; /* Bytes of PMA space required */
  72791. assert( pSorter );
  72792. /* Figure out whether or not the current contents of memory should be
  72793. ** flushed to a PMA before continuing. If so, do so.
  72794. **
  72795. ** If using the single large allocation mode (pSorter->aMemory!=0), then
  72796. ** flush the contents of memory to a new PMA if (a) at least one value is
  72797. ** already in memory and (b) the new value will not fit in memory.
  72798. **
  72799. ** Or, if using separate allocations for each record, flush the contents
  72800. ** of memory to a PMA if either of the following are true:
  72801. **
  72802. ** * The total memory allocated for the in-memory list is greater
  72803. ** than (page-size * cache-size), or
  72804. **
  72805. ** * The total memory allocated for the in-memory list is greater
  72806. ** than (page-size * 10) and sqlite3HeapNearlyFull() returns true.
  72807. */
  72808. nReq = pVal->n + sizeof(SorterRecord);
  72809. nPMA = pVal->n + sqlite3VarintLen(pVal->n);
  72810. if( pSorter->mxPmaSize ){
  72811. if( pSorter->list.aMemory ){
  72812. bFlush = pSorter->iMemory && (pSorter->iMemory+nReq) > pSorter->mxPmaSize;
  72813. }else{
  72814. bFlush = (
  72815. (pSorter->list.szPMA > pSorter->mxPmaSize)
  72816. || (pSorter->list.szPMA > pSorter->mnPmaSize && sqlite3HeapNearlyFull())
  72817. );
  72818. }
  72819. if( bFlush ){
  72820. rc = vdbeSorterFlushPMA(pSorter);
  72821. pSorter->list.szPMA = 0;
  72822. pSorter->iMemory = 0;
  72823. assert( rc!=SQLITE_OK || pSorter->list.pList==0 );
  72824. }
  72825. }
  72826. pSorter->list.szPMA += nPMA;
  72827. if( nPMA>pSorter->mxKeysize ){
  72828. pSorter->mxKeysize = nPMA;
  72829. }
  72830. if( pSorter->list.aMemory ){
  72831. int nMin = pSorter->iMemory + nReq;
  72832. if( nMin>pSorter->nMemory ){
  72833. u8 *aNew;
  72834. int nNew = pSorter->nMemory * 2;
  72835. while( nNew < nMin ) nNew = nNew*2;
  72836. if( nNew > pSorter->mxPmaSize ) nNew = pSorter->mxPmaSize;
  72837. if( nNew < nMin ) nNew = nMin;
  72838. aNew = sqlite3Realloc(pSorter->list.aMemory, nNew);
  72839. if( !aNew ) return SQLITE_NOMEM;
  72840. pSorter->list.pList = (SorterRecord*)(
  72841. aNew + ((u8*)pSorter->list.pList - pSorter->list.aMemory)
  72842. );
  72843. pSorter->list.aMemory = aNew;
  72844. pSorter->nMemory = nNew;
  72845. }
  72846. pNew = (SorterRecord*)&pSorter->list.aMemory[pSorter->iMemory];
  72847. pSorter->iMemory += ROUND8(nReq);
  72848. pNew->u.iNext = (int)((u8*)(pSorter->list.pList) - pSorter->list.aMemory);
  72849. }else{
  72850. pNew = (SorterRecord *)sqlite3Malloc(nReq);
  72851. if( pNew==0 ){
  72852. return SQLITE_NOMEM;
  72853. }
  72854. pNew->u.pNext = pSorter->list.pList;
  72855. }
  72856. memcpy(SRVAL(pNew), pVal->z, pVal->n);
  72857. pNew->nVal = pVal->n;
  72858. pSorter->list.pList = pNew;
  72859. return rc;
  72860. }
  72861. /*
  72862. ** Read keys from pIncr->pMerger and populate pIncr->aFile[1]. The format
  72863. ** of the data stored in aFile[1] is the same as that used by regular PMAs,
  72864. ** except that the number-of-bytes varint is omitted from the start.
  72865. */
  72866. static int vdbeIncrPopulate(IncrMerger *pIncr){
  72867. int rc = SQLITE_OK;
  72868. int rc2;
  72869. i64 iStart = pIncr->iStartOff;
  72870. SorterFile *pOut = &pIncr->aFile[1];
  72871. SortSubtask *pTask = pIncr->pTask;
  72872. MergeEngine *pMerger = pIncr->pMerger;
  72873. PmaWriter writer;
  72874. assert( pIncr->bEof==0 );
  72875. vdbeSorterPopulateDebug(pTask, "enter");
  72876. vdbePmaWriterInit(pOut->pFd, &writer, pTask->pSorter->pgsz, iStart);
  72877. while( rc==SQLITE_OK ){
  72878. int dummy;
  72879. PmaReader *pReader = &pMerger->aReadr[ pMerger->aTree[1] ];
  72880. int nKey = pReader->nKey;
  72881. i64 iEof = writer.iWriteOff + writer.iBufEnd;
  72882. /* Check if the output file is full or if the input has been exhausted.
  72883. ** In either case exit the loop. */
  72884. if( pReader->pFd==0 ) break;
  72885. if( (iEof + nKey + sqlite3VarintLen(nKey))>(iStart + pIncr->mxSz) ) break;
  72886. /* Write the next key to the output. */
  72887. vdbePmaWriteVarint(&writer, nKey);
  72888. vdbePmaWriteBlob(&writer, pReader->aKey, nKey);
  72889. assert( pIncr->pMerger->pTask==pTask );
  72890. rc = vdbeMergeEngineStep(pIncr->pMerger, &dummy);
  72891. }
  72892. rc2 = vdbePmaWriterFinish(&writer, &pOut->iEof);
  72893. if( rc==SQLITE_OK ) rc = rc2;
  72894. vdbeSorterPopulateDebug(pTask, "exit");
  72895. return rc;
  72896. }
  72897. #if SQLITE_MAX_WORKER_THREADS>0
  72898. /*
  72899. ** The main routine for background threads that populate aFile[1] of
  72900. ** multi-threaded IncrMerger objects.
  72901. */
  72902. static void *vdbeIncrPopulateThread(void *pCtx){
  72903. IncrMerger *pIncr = (IncrMerger*)pCtx;
  72904. void *pRet = SQLITE_INT_TO_PTR( vdbeIncrPopulate(pIncr) );
  72905. pIncr->pTask->bDone = 1;
  72906. return pRet;
  72907. }
  72908. /*
  72909. ** Launch a background thread to populate aFile[1] of pIncr.
  72910. */
  72911. static int vdbeIncrBgPopulate(IncrMerger *pIncr){
  72912. void *p = (void*)pIncr;
  72913. assert( pIncr->bUseThread );
  72914. return vdbeSorterCreateThread(pIncr->pTask, vdbeIncrPopulateThread, p);
  72915. }
  72916. #endif
  72917. /*
  72918. ** This function is called when the PmaReader corresponding to pIncr has
  72919. ** finished reading the contents of aFile[0]. Its purpose is to "refill"
  72920. ** aFile[0] such that the PmaReader should start rereading it from the
  72921. ** beginning.
  72922. **
  72923. ** For single-threaded objects, this is accomplished by literally reading
  72924. ** keys from pIncr->pMerger and repopulating aFile[0].
  72925. **
  72926. ** For multi-threaded objects, all that is required is to wait until the
  72927. ** background thread is finished (if it is not already) and then swap
  72928. ** aFile[0] and aFile[1] in place. If the contents of pMerger have not
  72929. ** been exhausted, this function also launches a new background thread
  72930. ** to populate the new aFile[1].
  72931. **
  72932. ** SQLITE_OK is returned on success, or an SQLite error code otherwise.
  72933. */
  72934. static int vdbeIncrSwap(IncrMerger *pIncr){
  72935. int rc = SQLITE_OK;
  72936. #if SQLITE_MAX_WORKER_THREADS>0
  72937. if( pIncr->bUseThread ){
  72938. rc = vdbeSorterJoinThread(pIncr->pTask);
  72939. if( rc==SQLITE_OK ){
  72940. SorterFile f0 = pIncr->aFile[0];
  72941. pIncr->aFile[0] = pIncr->aFile[1];
  72942. pIncr->aFile[1] = f0;
  72943. }
  72944. if( rc==SQLITE_OK ){
  72945. if( pIncr->aFile[0].iEof==pIncr->iStartOff ){
  72946. pIncr->bEof = 1;
  72947. }else{
  72948. rc = vdbeIncrBgPopulate(pIncr);
  72949. }
  72950. }
  72951. }else
  72952. #endif
  72953. {
  72954. rc = vdbeIncrPopulate(pIncr);
  72955. pIncr->aFile[0] = pIncr->aFile[1];
  72956. if( pIncr->aFile[0].iEof==pIncr->iStartOff ){
  72957. pIncr->bEof = 1;
  72958. }
  72959. }
  72960. return rc;
  72961. }
  72962. /*
  72963. ** Allocate and return a new IncrMerger object to read data from pMerger.
  72964. **
  72965. ** If an OOM condition is encountered, return NULL. In this case free the
  72966. ** pMerger argument before returning.
  72967. */
  72968. static int vdbeIncrMergerNew(
  72969. SortSubtask *pTask, /* The thread that will be using the new IncrMerger */
  72970. MergeEngine *pMerger, /* The MergeEngine that the IncrMerger will control */
  72971. IncrMerger **ppOut /* Write the new IncrMerger here */
  72972. ){
  72973. int rc = SQLITE_OK;
  72974. IncrMerger *pIncr = *ppOut = (IncrMerger*)
  72975. (sqlite3FaultSim(100) ? 0 : sqlite3MallocZero(sizeof(*pIncr)));
  72976. if( pIncr ){
  72977. pIncr->pMerger = pMerger;
  72978. pIncr->pTask = pTask;
  72979. pIncr->mxSz = MAX(pTask->pSorter->mxKeysize+9,pTask->pSorter->mxPmaSize/2);
  72980. pTask->file2.iEof += pIncr->mxSz;
  72981. }else{
  72982. vdbeMergeEngineFree(pMerger);
  72983. rc = SQLITE_NOMEM;
  72984. }
  72985. return rc;
  72986. }
  72987. #if SQLITE_MAX_WORKER_THREADS>0
  72988. /*
  72989. ** Set the "use-threads" flag on object pIncr.
  72990. */
  72991. static void vdbeIncrMergerSetThreads(IncrMerger *pIncr){
  72992. pIncr->bUseThread = 1;
  72993. pIncr->pTask->file2.iEof -= pIncr->mxSz;
  72994. }
  72995. #endif /* SQLITE_MAX_WORKER_THREADS>0 */
  72996. /*
  72997. ** Recompute pMerger->aTree[iOut] by comparing the next keys on the
  72998. ** two PmaReaders that feed that entry. Neither of the PmaReaders
  72999. ** are advanced. This routine merely does the comparison.
  73000. */
  73001. static void vdbeMergeEngineCompare(
  73002. MergeEngine *pMerger, /* Merge engine containing PmaReaders to compare */
  73003. int iOut /* Store the result in pMerger->aTree[iOut] */
  73004. ){
  73005. int i1;
  73006. int i2;
  73007. int iRes;
  73008. PmaReader *p1;
  73009. PmaReader *p2;
  73010. assert( iOut<pMerger->nTree && iOut>0 );
  73011. if( iOut>=(pMerger->nTree/2) ){
  73012. i1 = (iOut - pMerger->nTree/2) * 2;
  73013. i2 = i1 + 1;
  73014. }else{
  73015. i1 = pMerger->aTree[iOut*2];
  73016. i2 = pMerger->aTree[iOut*2+1];
  73017. }
  73018. p1 = &pMerger->aReadr[i1];
  73019. p2 = &pMerger->aReadr[i2];
  73020. if( p1->pFd==0 ){
  73021. iRes = i2;
  73022. }else if( p2->pFd==0 ){
  73023. iRes = i1;
  73024. }else{
  73025. int res;
  73026. assert( pMerger->pTask->pUnpacked!=0 ); /* from vdbeSortSubtaskMain() */
  73027. res = vdbeSorterCompare(
  73028. pMerger->pTask, p1->aKey, p1->nKey, p2->aKey, p2->nKey
  73029. );
  73030. if( res<=0 ){
  73031. iRes = i1;
  73032. }else{
  73033. iRes = i2;
  73034. }
  73035. }
  73036. pMerger->aTree[iOut] = iRes;
  73037. }
  73038. /*
  73039. ** Allowed values for the eMode parameter to vdbeMergeEngineInit()
  73040. ** and vdbePmaReaderIncrMergeInit().
  73041. **
  73042. ** Only INCRINIT_NORMAL is valid in single-threaded builds (when
  73043. ** SQLITE_MAX_WORKER_THREADS==0). The other values are only used
  73044. ** when there exists one or more separate worker threads.
  73045. */
  73046. #define INCRINIT_NORMAL 0
  73047. #define INCRINIT_TASK 1
  73048. #define INCRINIT_ROOT 2
  73049. /* Forward reference.
  73050. ** The vdbeIncrMergeInit() and vdbePmaReaderIncrMergeInit() routines call each
  73051. ** other (when building a merge tree).
  73052. */
  73053. static int vdbePmaReaderIncrMergeInit(PmaReader *pReadr, int eMode);
  73054. /*
  73055. ** Initialize the MergeEngine object passed as the second argument. Once this
  73056. ** function returns, the first key of merged data may be read from the
  73057. ** MergeEngine object in the usual fashion.
  73058. **
  73059. ** If argument eMode is INCRINIT_ROOT, then it is assumed that any IncrMerge
  73060. ** objects attached to the PmaReader objects that the merger reads from have
  73061. ** already been populated, but that they have not yet populated aFile[0] and
  73062. ** set the PmaReader objects up to read from it. In this case all that is
  73063. ** required is to call vdbePmaReaderNext() on each PmaReader to point it at
  73064. ** its first key.
  73065. **
  73066. ** Otherwise, if eMode is any value other than INCRINIT_ROOT, then use
  73067. ** vdbePmaReaderIncrMergeInit() to initialize each PmaReader that feeds data
  73068. ** to pMerger.
  73069. **
  73070. ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
  73071. */
  73072. static int vdbeMergeEngineInit(
  73073. SortSubtask *pTask, /* Thread that will run pMerger */
  73074. MergeEngine *pMerger, /* MergeEngine to initialize */
  73075. int eMode /* One of the INCRINIT_XXX constants */
  73076. ){
  73077. int rc = SQLITE_OK; /* Return code */
  73078. int i; /* For looping over PmaReader objects */
  73079. int nTree = pMerger->nTree;
  73080. /* eMode is always INCRINIT_NORMAL in single-threaded mode */
  73081. assert( SQLITE_MAX_WORKER_THREADS>0 || eMode==INCRINIT_NORMAL );
  73082. /* Verify that the MergeEngine is assigned to a single thread */
  73083. assert( pMerger->pTask==0 );
  73084. pMerger->pTask = pTask;
  73085. for(i=0; i<nTree; i++){
  73086. if( SQLITE_MAX_WORKER_THREADS>0 && eMode==INCRINIT_ROOT ){
  73087. /* PmaReaders should be normally initialized in order, as if they are
  73088. ** reading from the same temp file this makes for more linear file IO.
  73089. ** However, in the INCRINIT_ROOT case, if PmaReader aReadr[nTask-1] is
  73090. ** in use it will block the vdbePmaReaderNext() call while it uses
  73091. ** the main thread to fill its buffer. So calling PmaReaderNext()
  73092. ** on this PmaReader before any of the multi-threaded PmaReaders takes
  73093. ** better advantage of multi-processor hardware. */
  73094. rc = vdbePmaReaderNext(&pMerger->aReadr[nTree-i-1]);
  73095. }else{
  73096. rc = vdbePmaReaderIncrMergeInit(&pMerger->aReadr[i], INCRINIT_NORMAL);
  73097. }
  73098. if( rc!=SQLITE_OK ) return rc;
  73099. }
  73100. for(i=pMerger->nTree-1; i>0; i--){
  73101. vdbeMergeEngineCompare(pMerger, i);
  73102. }
  73103. return pTask->pUnpacked->errCode;
  73104. }
  73105. /*
  73106. ** Initialize the IncrMerge field of a PmaReader.
  73107. **
  73108. ** If the PmaReader passed as the first argument is not an incremental-reader
  73109. ** (if pReadr->pIncr==0), then this function is a no-op. Otherwise, it serves
  73110. ** to open and/or initialize the temp file related fields of the IncrMerge
  73111. ** object at (pReadr->pIncr).
  73112. **
  73113. ** If argument eMode is set to INCRINIT_NORMAL, then all PmaReaders
  73114. ** in the sub-tree headed by pReadr are also initialized. Data is then loaded
  73115. ** into the buffers belonging to pReadr and it is set to
  73116. ** point to the first key in its range.
  73117. **
  73118. ** If argument eMode is set to INCRINIT_TASK, then pReadr is guaranteed
  73119. ** to be a multi-threaded PmaReader and this function is being called in a
  73120. ** background thread. In this case all PmaReaders in the sub-tree are
  73121. ** initialized as for INCRINIT_NORMAL and the aFile[1] buffer belonging to
  73122. ** pReadr is populated. However, pReadr itself is not set up to point
  73123. ** to its first key. A call to vdbePmaReaderNext() is still required to do
  73124. ** that.
  73125. **
  73126. ** The reason this function does not call vdbePmaReaderNext() immediately
  73127. ** in the INCRINIT_TASK case is that vdbePmaReaderNext() assumes that it has
  73128. ** to block on thread (pTask->thread) before accessing aFile[1]. But, since
  73129. ** this entire function is being run by thread (pTask->thread), that will
  73130. ** lead to the current background thread attempting to join itself.
  73131. **
  73132. ** Finally, if argument eMode is set to INCRINIT_ROOT, it may be assumed
  73133. ** that pReadr->pIncr is a multi-threaded IncrMerge objects, and that all
  73134. ** child-trees have already been initialized using IncrInit(INCRINIT_TASK).
  73135. ** In this case vdbePmaReaderNext() is called on all child PmaReaders and
  73136. ** the current PmaReader set to point to the first key in its range.
  73137. **
  73138. ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
  73139. */
  73140. static int vdbePmaReaderIncrMergeInit(PmaReader *pReadr, int eMode){
  73141. int rc = SQLITE_OK;
  73142. IncrMerger *pIncr = pReadr->pIncr;
  73143. /* eMode is always INCRINIT_NORMAL in single-threaded mode */
  73144. assert( SQLITE_MAX_WORKER_THREADS>0 || eMode==INCRINIT_NORMAL );
  73145. if( pIncr ){
  73146. SortSubtask *pTask = pIncr->pTask;
  73147. sqlite3 *db = pTask->pSorter->db;
  73148. rc = vdbeMergeEngineInit(pTask, pIncr->pMerger, eMode);
  73149. /* Set up the required files for pIncr. A multi-theaded IncrMerge object
  73150. ** requires two temp files to itself, whereas a single-threaded object
  73151. ** only requires a region of pTask->file2. */
  73152. if( rc==SQLITE_OK ){
  73153. int mxSz = pIncr->mxSz;
  73154. #if SQLITE_MAX_WORKER_THREADS>0
  73155. if( pIncr->bUseThread ){
  73156. rc = vdbeSorterOpenTempFile(db, mxSz, &pIncr->aFile[0].pFd);
  73157. if( rc==SQLITE_OK ){
  73158. rc = vdbeSorterOpenTempFile(db, mxSz, &pIncr->aFile[1].pFd);
  73159. }
  73160. }else
  73161. #endif
  73162. /*if( !pIncr->bUseThread )*/{
  73163. if( pTask->file2.pFd==0 ){
  73164. assert( pTask->file2.iEof>0 );
  73165. rc = vdbeSorterOpenTempFile(db, pTask->file2.iEof, &pTask->file2.pFd);
  73166. pTask->file2.iEof = 0;
  73167. }
  73168. if( rc==SQLITE_OK ){
  73169. pIncr->aFile[1].pFd = pTask->file2.pFd;
  73170. pIncr->iStartOff = pTask->file2.iEof;
  73171. pTask->file2.iEof += mxSz;
  73172. }
  73173. }
  73174. }
  73175. #if SQLITE_MAX_WORKER_THREADS>0
  73176. if( rc==SQLITE_OK && pIncr->bUseThread ){
  73177. /* Use the current thread to populate aFile[1], even though this
  73178. ** PmaReader is multi-threaded. The reason being that this function
  73179. ** is already running in background thread pIncr->pTask->thread. */
  73180. assert( eMode==INCRINIT_ROOT || eMode==INCRINIT_TASK );
  73181. rc = vdbeIncrPopulate(pIncr);
  73182. }
  73183. #endif
  73184. if( rc==SQLITE_OK
  73185. && (SQLITE_MAX_WORKER_THREADS==0 || eMode!=INCRINIT_TASK)
  73186. ){
  73187. rc = vdbePmaReaderNext(pReadr);
  73188. }
  73189. }
  73190. return rc;
  73191. }
  73192. #if SQLITE_MAX_WORKER_THREADS>0
  73193. /*
  73194. ** The main routine for vdbePmaReaderIncrMergeInit() operations run in
  73195. ** background threads.
  73196. */
  73197. static void *vdbePmaReaderBgInit(void *pCtx){
  73198. PmaReader *pReader = (PmaReader*)pCtx;
  73199. void *pRet = SQLITE_INT_TO_PTR(
  73200. vdbePmaReaderIncrMergeInit(pReader,INCRINIT_TASK)
  73201. );
  73202. pReader->pIncr->pTask->bDone = 1;
  73203. return pRet;
  73204. }
  73205. /*
  73206. ** Use a background thread to invoke vdbePmaReaderIncrMergeInit(INCRINIT_TASK)
  73207. ** on the PmaReader object passed as the first argument.
  73208. **
  73209. ** This call will initialize the various fields of the pReadr->pIncr
  73210. ** structure and, if it is a multi-threaded IncrMerger, launch a
  73211. ** background thread to populate aFile[1].
  73212. */
  73213. static int vdbePmaReaderBgIncrInit(PmaReader *pReadr){
  73214. void *pCtx = (void*)pReadr;
  73215. return vdbeSorterCreateThread(pReadr->pIncr->pTask, vdbePmaReaderBgInit, pCtx);
  73216. }
  73217. #endif
  73218. /*
  73219. ** Allocate a new MergeEngine object to merge the contents of nPMA level-0
  73220. ** PMAs from pTask->file. If no error occurs, set *ppOut to point to
  73221. ** the new object and return SQLITE_OK. Or, if an error does occur, set *ppOut
  73222. ** to NULL and return an SQLite error code.
  73223. **
  73224. ** When this function is called, *piOffset is set to the offset of the
  73225. ** first PMA to read from pTask->file. Assuming no error occurs, it is
  73226. ** set to the offset immediately following the last byte of the last
  73227. ** PMA before returning. If an error does occur, then the final value of
  73228. ** *piOffset is undefined.
  73229. */
  73230. static int vdbeMergeEngineLevel0(
  73231. SortSubtask *pTask, /* Sorter task to read from */
  73232. int nPMA, /* Number of PMAs to read */
  73233. i64 *piOffset, /* IN/OUT: Readr offset in pTask->file */
  73234. MergeEngine **ppOut /* OUT: New merge-engine */
  73235. ){
  73236. MergeEngine *pNew; /* Merge engine to return */
  73237. i64 iOff = *piOffset;
  73238. int i;
  73239. int rc = SQLITE_OK;
  73240. *ppOut = pNew = vdbeMergeEngineNew(nPMA);
  73241. if( pNew==0 ) rc = SQLITE_NOMEM;
  73242. for(i=0; i<nPMA && rc==SQLITE_OK; i++){
  73243. i64 nDummy;
  73244. PmaReader *pReadr = &pNew->aReadr[i];
  73245. rc = vdbePmaReaderInit(pTask, &pTask->file, iOff, pReadr, &nDummy);
  73246. iOff = pReadr->iEof;
  73247. }
  73248. if( rc!=SQLITE_OK ){
  73249. vdbeMergeEngineFree(pNew);
  73250. *ppOut = 0;
  73251. }
  73252. *piOffset = iOff;
  73253. return rc;
  73254. }
  73255. /*
  73256. ** Return the depth of a tree comprising nPMA PMAs, assuming a fanout of
  73257. ** SORTER_MAX_MERGE_COUNT. The returned value does not include leaf nodes.
  73258. **
  73259. ** i.e.
  73260. **
  73261. ** nPMA<=16 -> TreeDepth() == 0
  73262. ** nPMA<=256 -> TreeDepth() == 1
  73263. ** nPMA<=65536 -> TreeDepth() == 2
  73264. */
  73265. static int vdbeSorterTreeDepth(int nPMA){
  73266. int nDepth = 0;
  73267. i64 nDiv = SORTER_MAX_MERGE_COUNT;
  73268. while( nDiv < (i64)nPMA ){
  73269. nDiv = nDiv * SORTER_MAX_MERGE_COUNT;
  73270. nDepth++;
  73271. }
  73272. return nDepth;
  73273. }
  73274. /*
  73275. ** pRoot is the root of an incremental merge-tree with depth nDepth (according
  73276. ** to vdbeSorterTreeDepth()). pLeaf is the iSeq'th leaf to be added to the
  73277. ** tree, counting from zero. This function adds pLeaf to the tree.
  73278. **
  73279. ** If successful, SQLITE_OK is returned. If an error occurs, an SQLite error
  73280. ** code is returned and pLeaf is freed.
  73281. */
  73282. static int vdbeSorterAddToTree(
  73283. SortSubtask *pTask, /* Task context */
  73284. int nDepth, /* Depth of tree according to TreeDepth() */
  73285. int iSeq, /* Sequence number of leaf within tree */
  73286. MergeEngine *pRoot, /* Root of tree */
  73287. MergeEngine *pLeaf /* Leaf to add to tree */
  73288. ){
  73289. int rc = SQLITE_OK;
  73290. int nDiv = 1;
  73291. int i;
  73292. MergeEngine *p = pRoot;
  73293. IncrMerger *pIncr;
  73294. rc = vdbeIncrMergerNew(pTask, pLeaf, &pIncr);
  73295. for(i=1; i<nDepth; i++){
  73296. nDiv = nDiv * SORTER_MAX_MERGE_COUNT;
  73297. }
  73298. for(i=1; i<nDepth && rc==SQLITE_OK; i++){
  73299. int iIter = (iSeq / nDiv) % SORTER_MAX_MERGE_COUNT;
  73300. PmaReader *pReadr = &p->aReadr[iIter];
  73301. if( pReadr->pIncr==0 ){
  73302. MergeEngine *pNew = vdbeMergeEngineNew(SORTER_MAX_MERGE_COUNT);
  73303. if( pNew==0 ){
  73304. rc = SQLITE_NOMEM;
  73305. }else{
  73306. rc = vdbeIncrMergerNew(pTask, pNew, &pReadr->pIncr);
  73307. }
  73308. }
  73309. if( rc==SQLITE_OK ){
  73310. p = pReadr->pIncr->pMerger;
  73311. nDiv = nDiv / SORTER_MAX_MERGE_COUNT;
  73312. }
  73313. }
  73314. if( rc==SQLITE_OK ){
  73315. p->aReadr[iSeq % SORTER_MAX_MERGE_COUNT].pIncr = pIncr;
  73316. }else{
  73317. vdbeIncrFree(pIncr);
  73318. }
  73319. return rc;
  73320. }
  73321. /*
  73322. ** This function is called as part of a SorterRewind() operation on a sorter
  73323. ** that has already written two or more level-0 PMAs to one or more temp
  73324. ** files. It builds a tree of MergeEngine/IncrMerger/PmaReader objects that
  73325. ** can be used to incrementally merge all PMAs on disk.
  73326. **
  73327. ** If successful, SQLITE_OK is returned and *ppOut set to point to the
  73328. ** MergeEngine object at the root of the tree before returning. Or, if an
  73329. ** error occurs, an SQLite error code is returned and the final value
  73330. ** of *ppOut is undefined.
  73331. */
  73332. static int vdbeSorterMergeTreeBuild(
  73333. VdbeSorter *pSorter, /* The VDBE cursor that implements the sort */
  73334. MergeEngine **ppOut /* Write the MergeEngine here */
  73335. ){
  73336. MergeEngine *pMain = 0;
  73337. int rc = SQLITE_OK;
  73338. int iTask;
  73339. #if SQLITE_MAX_WORKER_THREADS>0
  73340. /* If the sorter uses more than one task, then create the top-level
  73341. ** MergeEngine here. This MergeEngine will read data from exactly
  73342. ** one PmaReader per sub-task. */
  73343. assert( pSorter->bUseThreads || pSorter->nTask==1 );
  73344. if( pSorter->nTask>1 ){
  73345. pMain = vdbeMergeEngineNew(pSorter->nTask);
  73346. if( pMain==0 ) rc = SQLITE_NOMEM;
  73347. }
  73348. #endif
  73349. for(iTask=0; rc==SQLITE_OK && iTask<pSorter->nTask; iTask++){
  73350. SortSubtask *pTask = &pSorter->aTask[iTask];
  73351. assert( pTask->nPMA>0 || SQLITE_MAX_WORKER_THREADS>0 );
  73352. if( SQLITE_MAX_WORKER_THREADS==0 || pTask->nPMA ){
  73353. MergeEngine *pRoot = 0; /* Root node of tree for this task */
  73354. int nDepth = vdbeSorterTreeDepth(pTask->nPMA);
  73355. i64 iReadOff = 0;
  73356. if( pTask->nPMA<=SORTER_MAX_MERGE_COUNT ){
  73357. rc = vdbeMergeEngineLevel0(pTask, pTask->nPMA, &iReadOff, &pRoot);
  73358. }else{
  73359. int i;
  73360. int iSeq = 0;
  73361. pRoot = vdbeMergeEngineNew(SORTER_MAX_MERGE_COUNT);
  73362. if( pRoot==0 ) rc = SQLITE_NOMEM;
  73363. for(i=0; i<pTask->nPMA && rc==SQLITE_OK; i += SORTER_MAX_MERGE_COUNT){
  73364. MergeEngine *pMerger = 0; /* New level-0 PMA merger */
  73365. int nReader; /* Number of level-0 PMAs to merge */
  73366. nReader = MIN(pTask->nPMA - i, SORTER_MAX_MERGE_COUNT);
  73367. rc = vdbeMergeEngineLevel0(pTask, nReader, &iReadOff, &pMerger);
  73368. if( rc==SQLITE_OK ){
  73369. rc = vdbeSorterAddToTree(pTask, nDepth, iSeq++, pRoot, pMerger);
  73370. }
  73371. }
  73372. }
  73373. if( rc==SQLITE_OK ){
  73374. #if SQLITE_MAX_WORKER_THREADS>0
  73375. if( pMain!=0 ){
  73376. rc = vdbeIncrMergerNew(pTask, pRoot, &pMain->aReadr[iTask].pIncr);
  73377. }else
  73378. #endif
  73379. {
  73380. assert( pMain==0 );
  73381. pMain = pRoot;
  73382. }
  73383. }else{
  73384. vdbeMergeEngineFree(pRoot);
  73385. }
  73386. }
  73387. }
  73388. if( rc!=SQLITE_OK ){
  73389. vdbeMergeEngineFree(pMain);
  73390. pMain = 0;
  73391. }
  73392. *ppOut = pMain;
  73393. return rc;
  73394. }
  73395. /*
  73396. ** This function is called as part of an sqlite3VdbeSorterRewind() operation
  73397. ** on a sorter that has written two or more PMAs to temporary files. It sets
  73398. ** up either VdbeSorter.pMerger (for single threaded sorters) or pReader
  73399. ** (for multi-threaded sorters) so that it can be used to iterate through
  73400. ** all records stored in the sorter.
  73401. **
  73402. ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
  73403. */
  73404. static int vdbeSorterSetupMerge(VdbeSorter *pSorter){
  73405. int rc; /* Return code */
  73406. SortSubtask *pTask0 = &pSorter->aTask[0];
  73407. MergeEngine *pMain = 0;
  73408. #if SQLITE_MAX_WORKER_THREADS
  73409. sqlite3 *db = pTask0->pSorter->db;
  73410. #endif
  73411. rc = vdbeSorterMergeTreeBuild(pSorter, &pMain);
  73412. if( rc==SQLITE_OK ){
  73413. #if SQLITE_MAX_WORKER_THREADS
  73414. assert( pSorter->bUseThreads==0 || pSorter->nTask>1 );
  73415. if( pSorter->bUseThreads ){
  73416. int iTask;
  73417. PmaReader *pReadr = 0;
  73418. SortSubtask *pLast = &pSorter->aTask[pSorter->nTask-1];
  73419. rc = vdbeSortAllocUnpacked(pLast);
  73420. if( rc==SQLITE_OK ){
  73421. pReadr = (PmaReader*)sqlite3DbMallocZero(db, sizeof(PmaReader));
  73422. pSorter->pReader = pReadr;
  73423. if( pReadr==0 ) rc = SQLITE_NOMEM;
  73424. }
  73425. if( rc==SQLITE_OK ){
  73426. rc = vdbeIncrMergerNew(pLast, pMain, &pReadr->pIncr);
  73427. if( rc==SQLITE_OK ){
  73428. vdbeIncrMergerSetThreads(pReadr->pIncr);
  73429. for(iTask=0; iTask<(pSorter->nTask-1); iTask++){
  73430. IncrMerger *pIncr;
  73431. if( (pIncr = pMain->aReadr[iTask].pIncr) ){
  73432. vdbeIncrMergerSetThreads(pIncr);
  73433. assert( pIncr->pTask!=pLast );
  73434. }
  73435. }
  73436. for(iTask=0; rc==SQLITE_OK && iTask<pSorter->nTask; iTask++){
  73437. PmaReader *p = &pMain->aReadr[iTask];
  73438. assert( p->pIncr==0 || p->pIncr->pTask==&pSorter->aTask[iTask] );
  73439. if( p->pIncr ){
  73440. if( iTask==pSorter->nTask-1 ){
  73441. rc = vdbePmaReaderIncrMergeInit(p, INCRINIT_TASK);
  73442. }else{
  73443. rc = vdbePmaReaderBgIncrInit(p);
  73444. }
  73445. }
  73446. }
  73447. }
  73448. pMain = 0;
  73449. }
  73450. if( rc==SQLITE_OK ){
  73451. rc = vdbePmaReaderIncrMergeInit(pReadr, INCRINIT_ROOT);
  73452. }
  73453. }else
  73454. #endif
  73455. {
  73456. rc = vdbeMergeEngineInit(pTask0, pMain, INCRINIT_NORMAL);
  73457. pSorter->pMerger = pMain;
  73458. pMain = 0;
  73459. }
  73460. }
  73461. if( rc!=SQLITE_OK ){
  73462. vdbeMergeEngineFree(pMain);
  73463. }
  73464. return rc;
  73465. }
  73466. /*
  73467. ** Once the sorter has been populated by calls to sqlite3VdbeSorterWrite,
  73468. ** this function is called to prepare for iterating through the records
  73469. ** in sorted order.
  73470. */
  73471. SQLITE_PRIVATE int sqlite3VdbeSorterRewind(const VdbeCursor *pCsr, int *pbEof){
  73472. VdbeSorter *pSorter = pCsr->pSorter;
  73473. int rc = SQLITE_OK; /* Return code */
  73474. assert( pSorter );
  73475. /* If no data has been written to disk, then do not do so now. Instead,
  73476. ** sort the VdbeSorter.pRecord list. The vdbe layer will read data directly
  73477. ** from the in-memory list. */
  73478. if( pSorter->bUsePMA==0 ){
  73479. if( pSorter->list.pList ){
  73480. *pbEof = 0;
  73481. rc = vdbeSorterSort(&pSorter->aTask[0], &pSorter->list);
  73482. }else{
  73483. *pbEof = 1;
  73484. }
  73485. return rc;
  73486. }
  73487. /* Write the current in-memory list to a PMA. When the VdbeSorterWrite()
  73488. ** function flushes the contents of memory to disk, it immediately always
  73489. ** creates a new list consisting of a single key immediately afterwards.
  73490. ** So the list is never empty at this point. */
  73491. assert( pSorter->list.pList );
  73492. rc = vdbeSorterFlushPMA(pSorter);
  73493. /* Join all threads */
  73494. rc = vdbeSorterJoinAll(pSorter, rc);
  73495. vdbeSorterRewindDebug("rewind");
  73496. /* Assuming no errors have occurred, set up a merger structure to
  73497. ** incrementally read and merge all remaining PMAs. */
  73498. assert( pSorter->pReader==0 );
  73499. if( rc==SQLITE_OK ){
  73500. rc = vdbeSorterSetupMerge(pSorter);
  73501. *pbEof = 0;
  73502. }
  73503. vdbeSorterRewindDebug("rewinddone");
  73504. return rc;
  73505. }
  73506. /*
  73507. ** Advance to the next element in the sorter.
  73508. */
  73509. SQLITE_PRIVATE int sqlite3VdbeSorterNext(sqlite3 *db, const VdbeCursor *pCsr, int *pbEof){
  73510. VdbeSorter *pSorter = pCsr->pSorter;
  73511. int rc; /* Return code */
  73512. assert( pSorter->bUsePMA || (pSorter->pReader==0 && pSorter->pMerger==0) );
  73513. if( pSorter->bUsePMA ){
  73514. assert( pSorter->pReader==0 || pSorter->pMerger==0 );
  73515. assert( pSorter->bUseThreads==0 || pSorter->pReader );
  73516. assert( pSorter->bUseThreads==1 || pSorter->pMerger );
  73517. #if SQLITE_MAX_WORKER_THREADS>0
  73518. if( pSorter->bUseThreads ){
  73519. rc = vdbePmaReaderNext(pSorter->pReader);
  73520. *pbEof = (pSorter->pReader->pFd==0);
  73521. }else
  73522. #endif
  73523. /*if( !pSorter->bUseThreads )*/ {
  73524. assert( pSorter->pMerger->pTask==(&pSorter->aTask[0]) );
  73525. rc = vdbeMergeEngineStep(pSorter->pMerger, pbEof);
  73526. }
  73527. }else{
  73528. SorterRecord *pFree = pSorter->list.pList;
  73529. pSorter->list.pList = pFree->u.pNext;
  73530. pFree->u.pNext = 0;
  73531. if( pSorter->list.aMemory==0 ) vdbeSorterRecordFree(db, pFree);
  73532. *pbEof = !pSorter->list.pList;
  73533. rc = SQLITE_OK;
  73534. }
  73535. return rc;
  73536. }
  73537. /*
  73538. ** Return a pointer to a buffer owned by the sorter that contains the
  73539. ** current key.
  73540. */
  73541. static void *vdbeSorterRowkey(
  73542. const VdbeSorter *pSorter, /* Sorter object */
  73543. int *pnKey /* OUT: Size of current key in bytes */
  73544. ){
  73545. void *pKey;
  73546. if( pSorter->bUsePMA ){
  73547. PmaReader *pReader;
  73548. #if SQLITE_MAX_WORKER_THREADS>0
  73549. if( pSorter->bUseThreads ){
  73550. pReader = pSorter->pReader;
  73551. }else
  73552. #endif
  73553. /*if( !pSorter->bUseThreads )*/{
  73554. pReader = &pSorter->pMerger->aReadr[pSorter->pMerger->aTree[1]];
  73555. }
  73556. *pnKey = pReader->nKey;
  73557. pKey = pReader->aKey;
  73558. }else{
  73559. *pnKey = pSorter->list.pList->nVal;
  73560. pKey = SRVAL(pSorter->list.pList);
  73561. }
  73562. return pKey;
  73563. }
  73564. /*
  73565. ** Copy the current sorter key into the memory cell pOut.
  73566. */
  73567. SQLITE_PRIVATE int sqlite3VdbeSorterRowkey(const VdbeCursor *pCsr, Mem *pOut){
  73568. VdbeSorter *pSorter = pCsr->pSorter;
  73569. void *pKey; int nKey; /* Sorter key to copy into pOut */
  73570. pKey = vdbeSorterRowkey(pSorter, &nKey);
  73571. if( sqlite3VdbeMemClearAndResize(pOut, nKey) ){
  73572. return SQLITE_NOMEM;
  73573. }
  73574. pOut->n = nKey;
  73575. MemSetTypeFlag(pOut, MEM_Blob);
  73576. memcpy(pOut->z, pKey, nKey);
  73577. return SQLITE_OK;
  73578. }
  73579. /*
  73580. ** Compare the key in memory cell pVal with the key that the sorter cursor
  73581. ** passed as the first argument currently points to. For the purposes of
  73582. ** the comparison, ignore the rowid field at the end of each record.
  73583. **
  73584. ** If the sorter cursor key contains any NULL values, consider it to be
  73585. ** less than pVal. Even if pVal also contains NULL values.
  73586. **
  73587. ** If an error occurs, return an SQLite error code (i.e. SQLITE_NOMEM).
  73588. ** Otherwise, set *pRes to a negative, zero or positive value if the
  73589. ** key in pVal is smaller than, equal to or larger than the current sorter
  73590. ** key.
  73591. **
  73592. ** This routine forms the core of the OP_SorterCompare opcode, which in
  73593. ** turn is used to verify uniqueness when constructing a UNIQUE INDEX.
  73594. */
  73595. SQLITE_PRIVATE int sqlite3VdbeSorterCompare(
  73596. const VdbeCursor *pCsr, /* Sorter cursor */
  73597. Mem *pVal, /* Value to compare to current sorter key */
  73598. int nKeyCol, /* Compare this many columns */
  73599. int *pRes /* OUT: Result of comparison */
  73600. ){
  73601. VdbeSorter *pSorter = pCsr->pSorter;
  73602. UnpackedRecord *r2 = pSorter->pUnpacked;
  73603. KeyInfo *pKeyInfo = pCsr->pKeyInfo;
  73604. int i;
  73605. void *pKey; int nKey; /* Sorter key to compare pVal with */
  73606. if( r2==0 ){
  73607. char *p;
  73608. r2 = pSorter->pUnpacked = sqlite3VdbeAllocUnpackedRecord(pKeyInfo,0,0,&p);
  73609. assert( pSorter->pUnpacked==(UnpackedRecord*)p );
  73610. if( r2==0 ) return SQLITE_NOMEM;
  73611. r2->nField = nKeyCol;
  73612. }
  73613. assert( r2->nField==nKeyCol );
  73614. pKey = vdbeSorterRowkey(pSorter, &nKey);
  73615. sqlite3VdbeRecordUnpack(pKeyInfo, nKey, pKey, r2);
  73616. for(i=0; i<nKeyCol; i++){
  73617. if( r2->aMem[i].flags & MEM_Null ){
  73618. *pRes = -1;
  73619. return SQLITE_OK;
  73620. }
  73621. }
  73622. *pRes = sqlite3VdbeRecordCompare(pVal->n, pVal->z, r2);
  73623. return SQLITE_OK;
  73624. }
  73625. /************** End of vdbesort.c ********************************************/
  73626. /************** Begin file journal.c *****************************************/
  73627. /*
  73628. ** 2007 August 22
  73629. **
  73630. ** The author disclaims copyright to this source code. In place of
  73631. ** a legal notice, here is a blessing:
  73632. **
  73633. ** May you do good and not evil.
  73634. ** May you find forgiveness for yourself and forgive others.
  73635. ** May you share freely, never taking more than you give.
  73636. **
  73637. *************************************************************************
  73638. **
  73639. ** This file implements a special kind of sqlite3_file object used
  73640. ** by SQLite to create journal files if the atomic-write optimization
  73641. ** is enabled.
  73642. **
  73643. ** The distinctive characteristic of this sqlite3_file is that the
  73644. ** actual on disk file is created lazily. When the file is created,
  73645. ** the caller specifies a buffer size for an in-memory buffer to
  73646. ** be used to service read() and write() requests. The actual file
  73647. ** on disk is not created or populated until either:
  73648. **
  73649. ** 1) The in-memory representation grows too large for the allocated
  73650. ** buffer, or
  73651. ** 2) The sqlite3JournalCreate() function is called.
  73652. */
  73653. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  73654. /*
  73655. ** A JournalFile object is a subclass of sqlite3_file used by
  73656. ** as an open file handle for journal files.
  73657. */
  73658. struct JournalFile {
  73659. sqlite3_io_methods *pMethod; /* I/O methods on journal files */
  73660. int nBuf; /* Size of zBuf[] in bytes */
  73661. char *zBuf; /* Space to buffer journal writes */
  73662. int iSize; /* Amount of zBuf[] currently used */
  73663. int flags; /* xOpen flags */
  73664. sqlite3_vfs *pVfs; /* The "real" underlying VFS */
  73665. sqlite3_file *pReal; /* The "real" underlying file descriptor */
  73666. const char *zJournal; /* Name of the journal file */
  73667. };
  73668. typedef struct JournalFile JournalFile;
  73669. /*
  73670. ** If it does not already exists, create and populate the on-disk file
  73671. ** for JournalFile p.
  73672. */
  73673. static int createFile(JournalFile *p){
  73674. int rc = SQLITE_OK;
  73675. if( !p->pReal ){
  73676. sqlite3_file *pReal = (sqlite3_file *)&p[1];
  73677. rc = sqlite3OsOpen(p->pVfs, p->zJournal, pReal, p->flags, 0);
  73678. if( rc==SQLITE_OK ){
  73679. p->pReal = pReal;
  73680. if( p->iSize>0 ){
  73681. assert(p->iSize<=p->nBuf);
  73682. rc = sqlite3OsWrite(p->pReal, p->zBuf, p->iSize, 0);
  73683. }
  73684. if( rc!=SQLITE_OK ){
  73685. /* If an error occurred while writing to the file, close it before
  73686. ** returning. This way, SQLite uses the in-memory journal data to
  73687. ** roll back changes made to the internal page-cache before this
  73688. ** function was called. */
  73689. sqlite3OsClose(pReal);
  73690. p->pReal = 0;
  73691. }
  73692. }
  73693. }
  73694. return rc;
  73695. }
  73696. /*
  73697. ** Close the file.
  73698. */
  73699. static int jrnlClose(sqlite3_file *pJfd){
  73700. JournalFile *p = (JournalFile *)pJfd;
  73701. if( p->pReal ){
  73702. sqlite3OsClose(p->pReal);
  73703. }
  73704. sqlite3_free(p->zBuf);
  73705. return SQLITE_OK;
  73706. }
  73707. /*
  73708. ** Read data from the file.
  73709. */
  73710. static int jrnlRead(
  73711. sqlite3_file *pJfd, /* The journal file from which to read */
  73712. void *zBuf, /* Put the results here */
  73713. int iAmt, /* Number of bytes to read */
  73714. sqlite_int64 iOfst /* Begin reading at this offset */
  73715. ){
  73716. int rc = SQLITE_OK;
  73717. JournalFile *p = (JournalFile *)pJfd;
  73718. if( p->pReal ){
  73719. rc = sqlite3OsRead(p->pReal, zBuf, iAmt, iOfst);
  73720. }else if( (iAmt+iOfst)>p->iSize ){
  73721. rc = SQLITE_IOERR_SHORT_READ;
  73722. }else{
  73723. memcpy(zBuf, &p->zBuf[iOfst], iAmt);
  73724. }
  73725. return rc;
  73726. }
  73727. /*
  73728. ** Write data to the file.
  73729. */
  73730. static int jrnlWrite(
  73731. sqlite3_file *pJfd, /* The journal file into which to write */
  73732. const void *zBuf, /* Take data to be written from here */
  73733. int iAmt, /* Number of bytes to write */
  73734. sqlite_int64 iOfst /* Begin writing at this offset into the file */
  73735. ){
  73736. int rc = SQLITE_OK;
  73737. JournalFile *p = (JournalFile *)pJfd;
  73738. if( !p->pReal && (iOfst+iAmt)>p->nBuf ){
  73739. rc = createFile(p);
  73740. }
  73741. if( rc==SQLITE_OK ){
  73742. if( p->pReal ){
  73743. rc = sqlite3OsWrite(p->pReal, zBuf, iAmt, iOfst);
  73744. }else{
  73745. memcpy(&p->zBuf[iOfst], zBuf, iAmt);
  73746. if( p->iSize<(iOfst+iAmt) ){
  73747. p->iSize = (iOfst+iAmt);
  73748. }
  73749. }
  73750. }
  73751. return rc;
  73752. }
  73753. /*
  73754. ** Truncate the file.
  73755. */
  73756. static int jrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
  73757. int rc = SQLITE_OK;
  73758. JournalFile *p = (JournalFile *)pJfd;
  73759. if( p->pReal ){
  73760. rc = sqlite3OsTruncate(p->pReal, size);
  73761. }else if( size<p->iSize ){
  73762. p->iSize = size;
  73763. }
  73764. return rc;
  73765. }
  73766. /*
  73767. ** Sync the file.
  73768. */
  73769. static int jrnlSync(sqlite3_file *pJfd, int flags){
  73770. int rc;
  73771. JournalFile *p = (JournalFile *)pJfd;
  73772. if( p->pReal ){
  73773. rc = sqlite3OsSync(p->pReal, flags);
  73774. }else{
  73775. rc = SQLITE_OK;
  73776. }
  73777. return rc;
  73778. }
  73779. /*
  73780. ** Query the size of the file in bytes.
  73781. */
  73782. static int jrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
  73783. int rc = SQLITE_OK;
  73784. JournalFile *p = (JournalFile *)pJfd;
  73785. if( p->pReal ){
  73786. rc = sqlite3OsFileSize(p->pReal, pSize);
  73787. }else{
  73788. *pSize = (sqlite_int64) p->iSize;
  73789. }
  73790. return rc;
  73791. }
  73792. /*
  73793. ** Table of methods for JournalFile sqlite3_file object.
  73794. */
  73795. static struct sqlite3_io_methods JournalFileMethods = {
  73796. 1, /* iVersion */
  73797. jrnlClose, /* xClose */
  73798. jrnlRead, /* xRead */
  73799. jrnlWrite, /* xWrite */
  73800. jrnlTruncate, /* xTruncate */
  73801. jrnlSync, /* xSync */
  73802. jrnlFileSize, /* xFileSize */
  73803. 0, /* xLock */
  73804. 0, /* xUnlock */
  73805. 0, /* xCheckReservedLock */
  73806. 0, /* xFileControl */
  73807. 0, /* xSectorSize */
  73808. 0, /* xDeviceCharacteristics */
  73809. 0, /* xShmMap */
  73810. 0, /* xShmLock */
  73811. 0, /* xShmBarrier */
  73812. 0 /* xShmUnmap */
  73813. };
  73814. /*
  73815. ** Open a journal file.
  73816. */
  73817. SQLITE_PRIVATE int sqlite3JournalOpen(
  73818. sqlite3_vfs *pVfs, /* The VFS to use for actual file I/O */
  73819. const char *zName, /* Name of the journal file */
  73820. sqlite3_file *pJfd, /* Preallocated, blank file handle */
  73821. int flags, /* Opening flags */
  73822. int nBuf /* Bytes buffered before opening the file */
  73823. ){
  73824. JournalFile *p = (JournalFile *)pJfd;
  73825. memset(p, 0, sqlite3JournalSize(pVfs));
  73826. if( nBuf>0 ){
  73827. p->zBuf = sqlite3MallocZero(nBuf);
  73828. if( !p->zBuf ){
  73829. return SQLITE_NOMEM;
  73830. }
  73831. }else{
  73832. return sqlite3OsOpen(pVfs, zName, pJfd, flags, 0);
  73833. }
  73834. p->pMethod = &JournalFileMethods;
  73835. p->nBuf = nBuf;
  73836. p->flags = flags;
  73837. p->zJournal = zName;
  73838. p->pVfs = pVfs;
  73839. return SQLITE_OK;
  73840. }
  73841. /*
  73842. ** If the argument p points to a JournalFile structure, and the underlying
  73843. ** file has not yet been created, create it now.
  73844. */
  73845. SQLITE_PRIVATE int sqlite3JournalCreate(sqlite3_file *p){
  73846. if( p->pMethods!=&JournalFileMethods ){
  73847. return SQLITE_OK;
  73848. }
  73849. return createFile((JournalFile *)p);
  73850. }
  73851. /*
  73852. ** The file-handle passed as the only argument is guaranteed to be an open
  73853. ** file. It may or may not be of class JournalFile. If the file is a
  73854. ** JournalFile, and the underlying file on disk has not yet been opened,
  73855. ** return 0. Otherwise, return 1.
  73856. */
  73857. SQLITE_PRIVATE int sqlite3JournalExists(sqlite3_file *p){
  73858. return (p->pMethods!=&JournalFileMethods || ((JournalFile *)p)->pReal!=0);
  73859. }
  73860. /*
  73861. ** Return the number of bytes required to store a JournalFile that uses vfs
  73862. ** pVfs to create the underlying on-disk files.
  73863. */
  73864. SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *pVfs){
  73865. return (pVfs->szOsFile+sizeof(JournalFile));
  73866. }
  73867. #endif
  73868. /************** End of journal.c *********************************************/
  73869. /************** Begin file memjournal.c **************************************/
  73870. /*
  73871. ** 2008 October 7
  73872. **
  73873. ** The author disclaims copyright to this source code. In place of
  73874. ** a legal notice, here is a blessing:
  73875. **
  73876. ** May you do good and not evil.
  73877. ** May you find forgiveness for yourself and forgive others.
  73878. ** May you share freely, never taking more than you give.
  73879. **
  73880. *************************************************************************
  73881. **
  73882. ** This file contains code use to implement an in-memory rollback journal.
  73883. ** The in-memory rollback journal is used to journal transactions for
  73884. ** ":memory:" databases and when the journal_mode=MEMORY pragma is used.
  73885. */
  73886. /* Forward references to internal structures */
  73887. typedef struct MemJournal MemJournal;
  73888. typedef struct FilePoint FilePoint;
  73889. typedef struct FileChunk FileChunk;
  73890. /* Space to hold the rollback journal is allocated in increments of
  73891. ** this many bytes.
  73892. **
  73893. ** The size chosen is a little less than a power of two. That way,
  73894. ** the FileChunk object will have a size that almost exactly fills
  73895. ** a power-of-two allocation. This minimizes wasted space in power-of-two
  73896. ** memory allocators.
  73897. */
  73898. #define JOURNAL_CHUNKSIZE ((int)(1024-sizeof(FileChunk*)))
  73899. /*
  73900. ** The rollback journal is composed of a linked list of these structures.
  73901. */
  73902. struct FileChunk {
  73903. FileChunk *pNext; /* Next chunk in the journal */
  73904. u8 zChunk[JOURNAL_CHUNKSIZE]; /* Content of this chunk */
  73905. };
  73906. /*
  73907. ** An instance of this object serves as a cursor into the rollback journal.
  73908. ** The cursor can be either for reading or writing.
  73909. */
  73910. struct FilePoint {
  73911. sqlite3_int64 iOffset; /* Offset from the beginning of the file */
  73912. FileChunk *pChunk; /* Specific chunk into which cursor points */
  73913. };
  73914. /*
  73915. ** This subclass is a subclass of sqlite3_file. Each open memory-journal
  73916. ** is an instance of this class.
  73917. */
  73918. struct MemJournal {
  73919. sqlite3_io_methods *pMethod; /* Parent class. MUST BE FIRST */
  73920. FileChunk *pFirst; /* Head of in-memory chunk-list */
  73921. FilePoint endpoint; /* Pointer to the end of the file */
  73922. FilePoint readpoint; /* Pointer to the end of the last xRead() */
  73923. };
  73924. /*
  73925. ** Read data from the in-memory journal file. This is the implementation
  73926. ** of the sqlite3_vfs.xRead method.
  73927. */
  73928. static int memjrnlRead(
  73929. sqlite3_file *pJfd, /* The journal file from which to read */
  73930. void *zBuf, /* Put the results here */
  73931. int iAmt, /* Number of bytes to read */
  73932. sqlite_int64 iOfst /* Begin reading at this offset */
  73933. ){
  73934. MemJournal *p = (MemJournal *)pJfd;
  73935. u8 *zOut = zBuf;
  73936. int nRead = iAmt;
  73937. int iChunkOffset;
  73938. FileChunk *pChunk;
  73939. /* SQLite never tries to read past the end of a rollback journal file */
  73940. assert( iOfst+iAmt<=p->endpoint.iOffset );
  73941. if( p->readpoint.iOffset!=iOfst || iOfst==0 ){
  73942. sqlite3_int64 iOff = 0;
  73943. for(pChunk=p->pFirst;
  73944. ALWAYS(pChunk) && (iOff+JOURNAL_CHUNKSIZE)<=iOfst;
  73945. pChunk=pChunk->pNext
  73946. ){
  73947. iOff += JOURNAL_CHUNKSIZE;
  73948. }
  73949. }else{
  73950. pChunk = p->readpoint.pChunk;
  73951. }
  73952. iChunkOffset = (int)(iOfst%JOURNAL_CHUNKSIZE);
  73953. do {
  73954. int iSpace = JOURNAL_CHUNKSIZE - iChunkOffset;
  73955. int nCopy = MIN(nRead, (JOURNAL_CHUNKSIZE - iChunkOffset));
  73956. memcpy(zOut, &pChunk->zChunk[iChunkOffset], nCopy);
  73957. zOut += nCopy;
  73958. nRead -= iSpace;
  73959. iChunkOffset = 0;
  73960. } while( nRead>=0 && (pChunk=pChunk->pNext)!=0 && nRead>0 );
  73961. p->readpoint.iOffset = iOfst+iAmt;
  73962. p->readpoint.pChunk = pChunk;
  73963. return SQLITE_OK;
  73964. }
  73965. /*
  73966. ** Write data to the file.
  73967. */
  73968. static int memjrnlWrite(
  73969. sqlite3_file *pJfd, /* The journal file into which to write */
  73970. const void *zBuf, /* Take data to be written from here */
  73971. int iAmt, /* Number of bytes to write */
  73972. sqlite_int64 iOfst /* Begin writing at this offset into the file */
  73973. ){
  73974. MemJournal *p = (MemJournal *)pJfd;
  73975. int nWrite = iAmt;
  73976. u8 *zWrite = (u8 *)zBuf;
  73977. /* An in-memory journal file should only ever be appended to. Random
  73978. ** access writes are not required by sqlite.
  73979. */
  73980. assert( iOfst==p->endpoint.iOffset );
  73981. UNUSED_PARAMETER(iOfst);
  73982. while( nWrite>0 ){
  73983. FileChunk *pChunk = p->endpoint.pChunk;
  73984. int iChunkOffset = (int)(p->endpoint.iOffset%JOURNAL_CHUNKSIZE);
  73985. int iSpace = MIN(nWrite, JOURNAL_CHUNKSIZE - iChunkOffset);
  73986. if( iChunkOffset==0 ){
  73987. /* New chunk is required to extend the file. */
  73988. FileChunk *pNew = sqlite3_malloc(sizeof(FileChunk));
  73989. if( !pNew ){
  73990. return SQLITE_IOERR_NOMEM;
  73991. }
  73992. pNew->pNext = 0;
  73993. if( pChunk ){
  73994. assert( p->pFirst );
  73995. pChunk->pNext = pNew;
  73996. }else{
  73997. assert( !p->pFirst );
  73998. p->pFirst = pNew;
  73999. }
  74000. p->endpoint.pChunk = pNew;
  74001. }
  74002. memcpy(&p->endpoint.pChunk->zChunk[iChunkOffset], zWrite, iSpace);
  74003. zWrite += iSpace;
  74004. nWrite -= iSpace;
  74005. p->endpoint.iOffset += iSpace;
  74006. }
  74007. return SQLITE_OK;
  74008. }
  74009. /*
  74010. ** Truncate the file.
  74011. */
  74012. static int memjrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
  74013. MemJournal *p = (MemJournal *)pJfd;
  74014. FileChunk *pChunk;
  74015. assert(size==0);
  74016. UNUSED_PARAMETER(size);
  74017. pChunk = p->pFirst;
  74018. while( pChunk ){
  74019. FileChunk *pTmp = pChunk;
  74020. pChunk = pChunk->pNext;
  74021. sqlite3_free(pTmp);
  74022. }
  74023. sqlite3MemJournalOpen(pJfd);
  74024. return SQLITE_OK;
  74025. }
  74026. /*
  74027. ** Close the file.
  74028. */
  74029. static int memjrnlClose(sqlite3_file *pJfd){
  74030. memjrnlTruncate(pJfd, 0);
  74031. return SQLITE_OK;
  74032. }
  74033. /*
  74034. ** Sync the file.
  74035. **
  74036. ** Syncing an in-memory journal is a no-op. And, in fact, this routine
  74037. ** is never called in a working implementation. This implementation
  74038. ** exists purely as a contingency, in case some malfunction in some other
  74039. ** part of SQLite causes Sync to be called by mistake.
  74040. */
  74041. static int memjrnlSync(sqlite3_file *NotUsed, int NotUsed2){
  74042. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  74043. return SQLITE_OK;
  74044. }
  74045. /*
  74046. ** Query the size of the file in bytes.
  74047. */
  74048. static int memjrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
  74049. MemJournal *p = (MemJournal *)pJfd;
  74050. *pSize = (sqlite_int64) p->endpoint.iOffset;
  74051. return SQLITE_OK;
  74052. }
  74053. /*
  74054. ** Table of methods for MemJournal sqlite3_file object.
  74055. */
  74056. static const struct sqlite3_io_methods MemJournalMethods = {
  74057. 1, /* iVersion */
  74058. memjrnlClose, /* xClose */
  74059. memjrnlRead, /* xRead */
  74060. memjrnlWrite, /* xWrite */
  74061. memjrnlTruncate, /* xTruncate */
  74062. memjrnlSync, /* xSync */
  74063. memjrnlFileSize, /* xFileSize */
  74064. 0, /* xLock */
  74065. 0, /* xUnlock */
  74066. 0, /* xCheckReservedLock */
  74067. 0, /* xFileControl */
  74068. 0, /* xSectorSize */
  74069. 0, /* xDeviceCharacteristics */
  74070. 0, /* xShmMap */
  74071. 0, /* xShmLock */
  74072. 0, /* xShmBarrier */
  74073. 0, /* xShmUnmap */
  74074. 0, /* xFetch */
  74075. 0 /* xUnfetch */
  74076. };
  74077. /*
  74078. ** Open a journal file.
  74079. */
  74080. SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *pJfd){
  74081. MemJournal *p = (MemJournal *)pJfd;
  74082. assert( EIGHT_BYTE_ALIGNMENT(p) );
  74083. memset(p, 0, sqlite3MemJournalSize());
  74084. p->pMethod = (sqlite3_io_methods*)&MemJournalMethods;
  74085. }
  74086. /*
  74087. ** Return true if the file-handle passed as an argument is
  74088. ** an in-memory journal
  74089. */
  74090. SQLITE_PRIVATE int sqlite3IsMemJournal(sqlite3_file *pJfd){
  74091. return pJfd->pMethods==&MemJournalMethods;
  74092. }
  74093. /*
  74094. ** Return the number of bytes required to store a MemJournal file descriptor.
  74095. */
  74096. SQLITE_PRIVATE int sqlite3MemJournalSize(void){
  74097. return sizeof(MemJournal);
  74098. }
  74099. /************** End of memjournal.c ******************************************/
  74100. /************** Begin file walker.c ******************************************/
  74101. /*
  74102. ** 2008 August 16
  74103. **
  74104. ** The author disclaims copyright to this source code. In place of
  74105. ** a legal notice, here is a blessing:
  74106. **
  74107. ** May you do good and not evil.
  74108. ** May you find forgiveness for yourself and forgive others.
  74109. ** May you share freely, never taking more than you give.
  74110. **
  74111. *************************************************************************
  74112. ** This file contains routines used for walking the parser tree for
  74113. ** an SQL statement.
  74114. */
  74115. /* #include <stdlib.h> */
  74116. /* #include <string.h> */
  74117. /*
  74118. ** Walk an expression tree. Invoke the callback once for each node
  74119. ** of the expression, while descending. (In other words, the callback
  74120. ** is invoked before visiting children.)
  74121. **
  74122. ** The return value from the callback should be one of the WRC_*
  74123. ** constants to specify how to proceed with the walk.
  74124. **
  74125. ** WRC_Continue Continue descending down the tree.
  74126. **
  74127. ** WRC_Prune Do not descend into child nodes. But allow
  74128. ** the walk to continue with sibling nodes.
  74129. **
  74130. ** WRC_Abort Do no more callbacks. Unwind the stack and
  74131. ** return the top-level walk call.
  74132. **
  74133. ** The return value from this routine is WRC_Abort to abandon the tree walk
  74134. ** and WRC_Continue to continue.
  74135. */
  74136. SQLITE_PRIVATE int sqlite3WalkExpr(Walker *pWalker, Expr *pExpr){
  74137. int rc;
  74138. if( pExpr==0 ) return WRC_Continue;
  74139. testcase( ExprHasProperty(pExpr, EP_TokenOnly) );
  74140. testcase( ExprHasProperty(pExpr, EP_Reduced) );
  74141. rc = pWalker->xExprCallback(pWalker, pExpr);
  74142. if( rc==WRC_Continue
  74143. && !ExprHasProperty(pExpr,EP_TokenOnly) ){
  74144. if( sqlite3WalkExpr(pWalker, pExpr->pLeft) ) return WRC_Abort;
  74145. if( sqlite3WalkExpr(pWalker, pExpr->pRight) ) return WRC_Abort;
  74146. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  74147. if( sqlite3WalkSelect(pWalker, pExpr->x.pSelect) ) return WRC_Abort;
  74148. }else{
  74149. if( sqlite3WalkExprList(pWalker, pExpr->x.pList) ) return WRC_Abort;
  74150. }
  74151. }
  74152. return rc & WRC_Abort;
  74153. }
  74154. /*
  74155. ** Call sqlite3WalkExpr() for every expression in list p or until
  74156. ** an abort request is seen.
  74157. */
  74158. SQLITE_PRIVATE int sqlite3WalkExprList(Walker *pWalker, ExprList *p){
  74159. int i;
  74160. struct ExprList_item *pItem;
  74161. if( p ){
  74162. for(i=p->nExpr, pItem=p->a; i>0; i--, pItem++){
  74163. if( sqlite3WalkExpr(pWalker, pItem->pExpr) ) return WRC_Abort;
  74164. }
  74165. }
  74166. return WRC_Continue;
  74167. }
  74168. /*
  74169. ** Walk all expressions associated with SELECT statement p. Do
  74170. ** not invoke the SELECT callback on p, but do (of course) invoke
  74171. ** any expr callbacks and SELECT callbacks that come from subqueries.
  74172. ** Return WRC_Abort or WRC_Continue.
  74173. */
  74174. SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker *pWalker, Select *p){
  74175. if( sqlite3WalkExprList(pWalker, p->pEList) ) return WRC_Abort;
  74176. if( sqlite3WalkExpr(pWalker, p->pWhere) ) return WRC_Abort;
  74177. if( sqlite3WalkExprList(pWalker, p->pGroupBy) ) return WRC_Abort;
  74178. if( sqlite3WalkExpr(pWalker, p->pHaving) ) return WRC_Abort;
  74179. if( sqlite3WalkExprList(pWalker, p->pOrderBy) ) return WRC_Abort;
  74180. if( sqlite3WalkExpr(pWalker, p->pLimit) ) return WRC_Abort;
  74181. if( sqlite3WalkExpr(pWalker, p->pOffset) ) return WRC_Abort;
  74182. return WRC_Continue;
  74183. }
  74184. /*
  74185. ** Walk the parse trees associated with all subqueries in the
  74186. ** FROM clause of SELECT statement p. Do not invoke the select
  74187. ** callback on p, but do invoke it on each FROM clause subquery
  74188. ** and on any subqueries further down in the tree. Return
  74189. ** WRC_Abort or WRC_Continue;
  74190. */
  74191. SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker *pWalker, Select *p){
  74192. SrcList *pSrc;
  74193. int i;
  74194. struct SrcList_item *pItem;
  74195. pSrc = p->pSrc;
  74196. if( ALWAYS(pSrc) ){
  74197. for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
  74198. if( sqlite3WalkSelect(pWalker, pItem->pSelect) ){
  74199. return WRC_Abort;
  74200. }
  74201. }
  74202. }
  74203. return WRC_Continue;
  74204. }
  74205. /*
  74206. ** Call sqlite3WalkExpr() for every expression in Select statement p.
  74207. ** Invoke sqlite3WalkSelect() for subqueries in the FROM clause and
  74208. ** on the compound select chain, p->pPrior.
  74209. **
  74210. ** If it is not NULL, the xSelectCallback() callback is invoked before
  74211. ** the walk of the expressions and FROM clause. The xSelectCallback2()
  74212. ** method, if it is not NULL, is invoked following the walk of the
  74213. ** expressions and FROM clause.
  74214. **
  74215. ** Return WRC_Continue under normal conditions. Return WRC_Abort if
  74216. ** there is an abort request.
  74217. **
  74218. ** If the Walker does not have an xSelectCallback() then this routine
  74219. ** is a no-op returning WRC_Continue.
  74220. */
  74221. SQLITE_PRIVATE int sqlite3WalkSelect(Walker *pWalker, Select *p){
  74222. int rc;
  74223. if( p==0 || (pWalker->xSelectCallback==0 && pWalker->xSelectCallback2==0) ){
  74224. return WRC_Continue;
  74225. }
  74226. rc = WRC_Continue;
  74227. pWalker->walkerDepth++;
  74228. while( p ){
  74229. if( pWalker->xSelectCallback ){
  74230. rc = pWalker->xSelectCallback(pWalker, p);
  74231. if( rc ) break;
  74232. }
  74233. if( sqlite3WalkSelectExpr(pWalker, p)
  74234. || sqlite3WalkSelectFrom(pWalker, p)
  74235. ){
  74236. pWalker->walkerDepth--;
  74237. return WRC_Abort;
  74238. }
  74239. if( pWalker->xSelectCallback2 ){
  74240. pWalker->xSelectCallback2(pWalker, p);
  74241. }
  74242. p = p->pPrior;
  74243. }
  74244. pWalker->walkerDepth--;
  74245. return rc & WRC_Abort;
  74246. }
  74247. /************** End of walker.c **********************************************/
  74248. /************** Begin file resolve.c *****************************************/
  74249. /*
  74250. ** 2008 August 18
  74251. **
  74252. ** The author disclaims copyright to this source code. In place of
  74253. ** a legal notice, here is a blessing:
  74254. **
  74255. ** May you do good and not evil.
  74256. ** May you find forgiveness for yourself and forgive others.
  74257. ** May you share freely, never taking more than you give.
  74258. **
  74259. *************************************************************************
  74260. **
  74261. ** This file contains routines used for walking the parser tree and
  74262. ** resolve all identifiers by associating them with a particular
  74263. ** table and column.
  74264. */
  74265. /* #include <stdlib.h> */
  74266. /* #include <string.h> */
  74267. /*
  74268. ** Walk the expression tree pExpr and increase the aggregate function
  74269. ** depth (the Expr.op2 field) by N on every TK_AGG_FUNCTION node.
  74270. ** This needs to occur when copying a TK_AGG_FUNCTION node from an
  74271. ** outer query into an inner subquery.
  74272. **
  74273. ** incrAggFunctionDepth(pExpr,n) is the main routine. incrAggDepth(..)
  74274. ** is a helper function - a callback for the tree walker.
  74275. */
  74276. static int incrAggDepth(Walker *pWalker, Expr *pExpr){
  74277. if( pExpr->op==TK_AGG_FUNCTION ) pExpr->op2 += pWalker->u.n;
  74278. return WRC_Continue;
  74279. }
  74280. static void incrAggFunctionDepth(Expr *pExpr, int N){
  74281. if( N>0 ){
  74282. Walker w;
  74283. memset(&w, 0, sizeof(w));
  74284. w.xExprCallback = incrAggDepth;
  74285. w.u.n = N;
  74286. sqlite3WalkExpr(&w, pExpr);
  74287. }
  74288. }
  74289. /*
  74290. ** Turn the pExpr expression into an alias for the iCol-th column of the
  74291. ** result set in pEList.
  74292. **
  74293. ** If the result set column is a simple column reference, then this routine
  74294. ** makes an exact copy. But for any other kind of expression, this
  74295. ** routine make a copy of the result set column as the argument to the
  74296. ** TK_AS operator. The TK_AS operator causes the expression to be
  74297. ** evaluated just once and then reused for each alias.
  74298. **
  74299. ** The reason for suppressing the TK_AS term when the expression is a simple
  74300. ** column reference is so that the column reference will be recognized as
  74301. ** usable by indices within the WHERE clause processing logic.
  74302. **
  74303. ** The TK_AS operator is inhibited if zType[0]=='G'. This means
  74304. ** that in a GROUP BY clause, the expression is evaluated twice. Hence:
  74305. **
  74306. ** SELECT random()%5 AS x, count(*) FROM tab GROUP BY x
  74307. **
  74308. ** Is equivalent to:
  74309. **
  74310. ** SELECT random()%5 AS x, count(*) FROM tab GROUP BY random()%5
  74311. **
  74312. ** The result of random()%5 in the GROUP BY clause is probably different
  74313. ** from the result in the result-set. On the other hand Standard SQL does
  74314. ** not allow the GROUP BY clause to contain references to result-set columns.
  74315. ** So this should never come up in well-formed queries.
  74316. **
  74317. ** If the reference is followed by a COLLATE operator, then make sure
  74318. ** the COLLATE operator is preserved. For example:
  74319. **
  74320. ** SELECT a+b, c+d FROM t1 ORDER BY 1 COLLATE nocase;
  74321. **
  74322. ** Should be transformed into:
  74323. **
  74324. ** SELECT a+b, c+d FROM t1 ORDER BY (a+b) COLLATE nocase;
  74325. **
  74326. ** The nSubquery parameter specifies how many levels of subquery the
  74327. ** alias is removed from the original expression. The usually value is
  74328. ** zero but it might be more if the alias is contained within a subquery
  74329. ** of the original expression. The Expr.op2 field of TK_AGG_FUNCTION
  74330. ** structures must be increased by the nSubquery amount.
  74331. */
  74332. static void resolveAlias(
  74333. Parse *pParse, /* Parsing context */
  74334. ExprList *pEList, /* A result set */
  74335. int iCol, /* A column in the result set. 0..pEList->nExpr-1 */
  74336. Expr *pExpr, /* Transform this into an alias to the result set */
  74337. const char *zType, /* "GROUP" or "ORDER" or "" */
  74338. int nSubquery /* Number of subqueries that the label is moving */
  74339. ){
  74340. Expr *pOrig; /* The iCol-th column of the result set */
  74341. Expr *pDup; /* Copy of pOrig */
  74342. sqlite3 *db; /* The database connection */
  74343. assert( iCol>=0 && iCol<pEList->nExpr );
  74344. pOrig = pEList->a[iCol].pExpr;
  74345. assert( pOrig!=0 );
  74346. assert( pOrig->flags & EP_Resolved );
  74347. db = pParse->db;
  74348. pDup = sqlite3ExprDup(db, pOrig, 0);
  74349. if( pDup==0 ) return;
  74350. if( pOrig->op!=TK_COLUMN && zType[0]!='G' ){
  74351. incrAggFunctionDepth(pDup, nSubquery);
  74352. pDup = sqlite3PExpr(pParse, TK_AS, pDup, 0, 0);
  74353. if( pDup==0 ) return;
  74354. ExprSetProperty(pDup, EP_Skip);
  74355. if( pEList->a[iCol].u.x.iAlias==0 ){
  74356. pEList->a[iCol].u.x.iAlias = (u16)(++pParse->nAlias);
  74357. }
  74358. pDup->iTable = pEList->a[iCol].u.x.iAlias;
  74359. }
  74360. if( pExpr->op==TK_COLLATE ){
  74361. pDup = sqlite3ExprAddCollateString(pParse, pDup, pExpr->u.zToken);
  74362. }
  74363. /* Before calling sqlite3ExprDelete(), set the EP_Static flag. This
  74364. ** prevents ExprDelete() from deleting the Expr structure itself,
  74365. ** allowing it to be repopulated by the memcpy() on the following line.
  74366. ** The pExpr->u.zToken might point into memory that will be freed by the
  74367. ** sqlite3DbFree(db, pDup) on the last line of this block, so be sure to
  74368. ** make a copy of the token before doing the sqlite3DbFree().
  74369. */
  74370. ExprSetProperty(pExpr, EP_Static);
  74371. sqlite3ExprDelete(db, pExpr);
  74372. memcpy(pExpr, pDup, sizeof(*pExpr));
  74373. if( !ExprHasProperty(pExpr, EP_IntValue) && pExpr->u.zToken!=0 ){
  74374. assert( (pExpr->flags & (EP_Reduced|EP_TokenOnly))==0 );
  74375. pExpr->u.zToken = sqlite3DbStrDup(db, pExpr->u.zToken);
  74376. pExpr->flags |= EP_MemToken;
  74377. }
  74378. sqlite3DbFree(db, pDup);
  74379. }
  74380. /*
  74381. ** Return TRUE if the name zCol occurs anywhere in the USING clause.
  74382. **
  74383. ** Return FALSE if the USING clause is NULL or if it does not contain
  74384. ** zCol.
  74385. */
  74386. static int nameInUsingClause(IdList *pUsing, const char *zCol){
  74387. if( pUsing ){
  74388. int k;
  74389. for(k=0; k<pUsing->nId; k++){
  74390. if( sqlite3StrICmp(pUsing->a[k].zName, zCol)==0 ) return 1;
  74391. }
  74392. }
  74393. return 0;
  74394. }
  74395. /*
  74396. ** Subqueries stores the original database, table and column names for their
  74397. ** result sets in ExprList.a[].zSpan, in the form "DATABASE.TABLE.COLUMN".
  74398. ** Check to see if the zSpan given to this routine matches the zDb, zTab,
  74399. ** and zCol. If any of zDb, zTab, and zCol are NULL then those fields will
  74400. ** match anything.
  74401. */
  74402. SQLITE_PRIVATE int sqlite3MatchSpanName(
  74403. const char *zSpan,
  74404. const char *zCol,
  74405. const char *zTab,
  74406. const char *zDb
  74407. ){
  74408. int n;
  74409. for(n=0; ALWAYS(zSpan[n]) && zSpan[n]!='.'; n++){}
  74410. if( zDb && (sqlite3StrNICmp(zSpan, zDb, n)!=0 || zDb[n]!=0) ){
  74411. return 0;
  74412. }
  74413. zSpan += n+1;
  74414. for(n=0; ALWAYS(zSpan[n]) && zSpan[n]!='.'; n++){}
  74415. if( zTab && (sqlite3StrNICmp(zSpan, zTab, n)!=0 || zTab[n]!=0) ){
  74416. return 0;
  74417. }
  74418. zSpan += n+1;
  74419. if( zCol && sqlite3StrICmp(zSpan, zCol)!=0 ){
  74420. return 0;
  74421. }
  74422. return 1;
  74423. }
  74424. /*
  74425. ** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up
  74426. ** that name in the set of source tables in pSrcList and make the pExpr
  74427. ** expression node refer back to that source column. The following changes
  74428. ** are made to pExpr:
  74429. **
  74430. ** pExpr->iDb Set the index in db->aDb[] of the database X
  74431. ** (even if X is implied).
  74432. ** pExpr->iTable Set to the cursor number for the table obtained
  74433. ** from pSrcList.
  74434. ** pExpr->pTab Points to the Table structure of X.Y (even if
  74435. ** X and/or Y are implied.)
  74436. ** pExpr->iColumn Set to the column number within the table.
  74437. ** pExpr->op Set to TK_COLUMN.
  74438. ** pExpr->pLeft Any expression this points to is deleted
  74439. ** pExpr->pRight Any expression this points to is deleted.
  74440. **
  74441. ** The zDb variable is the name of the database (the "X"). This value may be
  74442. ** NULL meaning that name is of the form Y.Z or Z. Any available database
  74443. ** can be used. The zTable variable is the name of the table (the "Y"). This
  74444. ** value can be NULL if zDb is also NULL. If zTable is NULL it
  74445. ** means that the form of the name is Z and that columns from any table
  74446. ** can be used.
  74447. **
  74448. ** If the name cannot be resolved unambiguously, leave an error message
  74449. ** in pParse and return WRC_Abort. Return WRC_Prune on success.
  74450. */
  74451. static int lookupName(
  74452. Parse *pParse, /* The parsing context */
  74453. const char *zDb, /* Name of the database containing table, or NULL */
  74454. const char *zTab, /* Name of table containing column, or NULL */
  74455. const char *zCol, /* Name of the column. */
  74456. NameContext *pNC, /* The name context used to resolve the name */
  74457. Expr *pExpr /* Make this EXPR node point to the selected column */
  74458. ){
  74459. int i, j; /* Loop counters */
  74460. int cnt = 0; /* Number of matching column names */
  74461. int cntTab = 0; /* Number of matching table names */
  74462. int nSubquery = 0; /* How many levels of subquery */
  74463. sqlite3 *db = pParse->db; /* The database connection */
  74464. struct SrcList_item *pItem; /* Use for looping over pSrcList items */
  74465. struct SrcList_item *pMatch = 0; /* The matching pSrcList item */
  74466. NameContext *pTopNC = pNC; /* First namecontext in the list */
  74467. Schema *pSchema = 0; /* Schema of the expression */
  74468. int isTrigger = 0; /* True if resolved to a trigger column */
  74469. Table *pTab = 0; /* Table hold the row */
  74470. Column *pCol; /* A column of pTab */
  74471. assert( pNC ); /* the name context cannot be NULL. */
  74472. assert( zCol ); /* The Z in X.Y.Z cannot be NULL */
  74473. assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
  74474. /* Initialize the node to no-match */
  74475. pExpr->iTable = -1;
  74476. pExpr->pTab = 0;
  74477. ExprSetVVAProperty(pExpr, EP_NoReduce);
  74478. /* Translate the schema name in zDb into a pointer to the corresponding
  74479. ** schema. If not found, pSchema will remain NULL and nothing will match
  74480. ** resulting in an appropriate error message toward the end of this routine
  74481. */
  74482. if( zDb ){
  74483. testcase( pNC->ncFlags & NC_PartIdx );
  74484. testcase( pNC->ncFlags & NC_IsCheck );
  74485. if( (pNC->ncFlags & (NC_PartIdx|NC_IsCheck))!=0 ){
  74486. /* Silently ignore database qualifiers inside CHECK constraints and partial
  74487. ** indices. Do not raise errors because that might break legacy and
  74488. ** because it does not hurt anything to just ignore the database name. */
  74489. zDb = 0;
  74490. }else{
  74491. for(i=0; i<db->nDb; i++){
  74492. assert( db->aDb[i].zName );
  74493. if( sqlite3StrICmp(db->aDb[i].zName,zDb)==0 ){
  74494. pSchema = db->aDb[i].pSchema;
  74495. break;
  74496. }
  74497. }
  74498. }
  74499. }
  74500. /* Start at the inner-most context and move outward until a match is found */
  74501. while( pNC && cnt==0 ){
  74502. ExprList *pEList;
  74503. SrcList *pSrcList = pNC->pSrcList;
  74504. if( pSrcList ){
  74505. for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){
  74506. pTab = pItem->pTab;
  74507. assert( pTab!=0 && pTab->zName!=0 );
  74508. assert( pTab->nCol>0 );
  74509. if( pItem->pSelect && (pItem->pSelect->selFlags & SF_NestedFrom)!=0 ){
  74510. int hit = 0;
  74511. pEList = pItem->pSelect->pEList;
  74512. for(j=0; j<pEList->nExpr; j++){
  74513. if( sqlite3MatchSpanName(pEList->a[j].zSpan, zCol, zTab, zDb) ){
  74514. cnt++;
  74515. cntTab = 2;
  74516. pMatch = pItem;
  74517. pExpr->iColumn = j;
  74518. hit = 1;
  74519. }
  74520. }
  74521. if( hit || zTab==0 ) continue;
  74522. }
  74523. if( zDb && pTab->pSchema!=pSchema ){
  74524. continue;
  74525. }
  74526. if( zTab ){
  74527. const char *zTabName = pItem->zAlias ? pItem->zAlias : pTab->zName;
  74528. assert( zTabName!=0 );
  74529. if( sqlite3StrICmp(zTabName, zTab)!=0 ){
  74530. continue;
  74531. }
  74532. }
  74533. if( 0==(cntTab++) ){
  74534. pMatch = pItem;
  74535. }
  74536. for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){
  74537. if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
  74538. /* If there has been exactly one prior match and this match
  74539. ** is for the right-hand table of a NATURAL JOIN or is in a
  74540. ** USING clause, then skip this match.
  74541. */
  74542. if( cnt==1 ){
  74543. if( pItem->jointype & JT_NATURAL ) continue;
  74544. if( nameInUsingClause(pItem->pUsing, zCol) ) continue;
  74545. }
  74546. cnt++;
  74547. pMatch = pItem;
  74548. /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */
  74549. pExpr->iColumn = j==pTab->iPKey ? -1 : (i16)j;
  74550. break;
  74551. }
  74552. }
  74553. }
  74554. if( pMatch ){
  74555. pExpr->iTable = pMatch->iCursor;
  74556. pExpr->pTab = pMatch->pTab;
  74557. pSchema = pExpr->pTab->pSchema;
  74558. }
  74559. } /* if( pSrcList ) */
  74560. #ifndef SQLITE_OMIT_TRIGGER
  74561. /* If we have not already resolved the name, then maybe
  74562. ** it is a new.* or old.* trigger argument reference
  74563. */
  74564. if( zDb==0 && zTab!=0 && cntTab==0 && pParse->pTriggerTab!=0 ){
  74565. int op = pParse->eTriggerOp;
  74566. assert( op==TK_DELETE || op==TK_UPDATE || op==TK_INSERT );
  74567. if( op!=TK_DELETE && sqlite3StrICmp("new",zTab) == 0 ){
  74568. pExpr->iTable = 1;
  74569. pTab = pParse->pTriggerTab;
  74570. }else if( op!=TK_INSERT && sqlite3StrICmp("old",zTab)==0 ){
  74571. pExpr->iTable = 0;
  74572. pTab = pParse->pTriggerTab;
  74573. }else{
  74574. pTab = 0;
  74575. }
  74576. if( pTab ){
  74577. int iCol;
  74578. pSchema = pTab->pSchema;
  74579. cntTab++;
  74580. for(iCol=0, pCol=pTab->aCol; iCol<pTab->nCol; iCol++, pCol++){
  74581. if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
  74582. if( iCol==pTab->iPKey ){
  74583. iCol = -1;
  74584. }
  74585. break;
  74586. }
  74587. }
  74588. if( iCol>=pTab->nCol && sqlite3IsRowid(zCol) && HasRowid(pTab) ){
  74589. /* IMP: R-51414-32910 */
  74590. /* IMP: R-44911-55124 */
  74591. iCol = -1;
  74592. }
  74593. if( iCol<pTab->nCol ){
  74594. cnt++;
  74595. if( iCol<0 ){
  74596. pExpr->affinity = SQLITE_AFF_INTEGER;
  74597. }else if( pExpr->iTable==0 ){
  74598. testcase( iCol==31 );
  74599. testcase( iCol==32 );
  74600. pParse->oldmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
  74601. }else{
  74602. testcase( iCol==31 );
  74603. testcase( iCol==32 );
  74604. pParse->newmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
  74605. }
  74606. pExpr->iColumn = (i16)iCol;
  74607. pExpr->pTab = pTab;
  74608. isTrigger = 1;
  74609. }
  74610. }
  74611. }
  74612. #endif /* !defined(SQLITE_OMIT_TRIGGER) */
  74613. /*
  74614. ** Perhaps the name is a reference to the ROWID
  74615. */
  74616. if( cnt==0 && cntTab==1 && pMatch && sqlite3IsRowid(zCol)
  74617. && HasRowid(pMatch->pTab) ){
  74618. cnt = 1;
  74619. pExpr->iColumn = -1; /* IMP: R-44911-55124 */
  74620. pExpr->affinity = SQLITE_AFF_INTEGER;
  74621. }
  74622. /*
  74623. ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z
  74624. ** might refer to an result-set alias. This happens, for example, when
  74625. ** we are resolving names in the WHERE clause of the following command:
  74626. **
  74627. ** SELECT a+b AS x FROM table WHERE x<10;
  74628. **
  74629. ** In cases like this, replace pExpr with a copy of the expression that
  74630. ** forms the result set entry ("a+b" in the example) and return immediately.
  74631. ** Note that the expression in the result set should have already been
  74632. ** resolved by the time the WHERE clause is resolved.
  74633. **
  74634. ** The ability to use an output result-set column in the WHERE, GROUP BY,
  74635. ** or HAVING clauses, or as part of a larger expression in the ORDRE BY
  74636. ** clause is not standard SQL. This is a (goofy) SQLite extension, that
  74637. ** is supported for backwards compatibility only. TO DO: Issue a warning
  74638. ** on sqlite3_log() whenever the capability is used.
  74639. */
  74640. if( (pEList = pNC->pEList)!=0
  74641. && zTab==0
  74642. && cnt==0
  74643. ){
  74644. for(j=0; j<pEList->nExpr; j++){
  74645. char *zAs = pEList->a[j].zName;
  74646. if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
  74647. Expr *pOrig;
  74648. assert( pExpr->pLeft==0 && pExpr->pRight==0 );
  74649. assert( pExpr->x.pList==0 );
  74650. assert( pExpr->x.pSelect==0 );
  74651. pOrig = pEList->a[j].pExpr;
  74652. if( (pNC->ncFlags&NC_AllowAgg)==0 && ExprHasProperty(pOrig, EP_Agg) ){
  74653. sqlite3ErrorMsg(pParse, "misuse of aliased aggregate %s", zAs);
  74654. return WRC_Abort;
  74655. }
  74656. resolveAlias(pParse, pEList, j, pExpr, "", nSubquery);
  74657. cnt = 1;
  74658. pMatch = 0;
  74659. assert( zTab==0 && zDb==0 );
  74660. goto lookupname_end;
  74661. }
  74662. }
  74663. }
  74664. /* Advance to the next name context. The loop will exit when either
  74665. ** we have a match (cnt>0) or when we run out of name contexts.
  74666. */
  74667. if( cnt==0 ){
  74668. pNC = pNC->pNext;
  74669. nSubquery++;
  74670. }
  74671. }
  74672. /*
  74673. ** If X and Y are NULL (in other words if only the column name Z is
  74674. ** supplied) and the value of Z is enclosed in double-quotes, then
  74675. ** Z is a string literal if it doesn't match any column names. In that
  74676. ** case, we need to return right away and not make any changes to
  74677. ** pExpr.
  74678. **
  74679. ** Because no reference was made to outer contexts, the pNC->nRef
  74680. ** fields are not changed in any context.
  74681. */
  74682. if( cnt==0 && zTab==0 && ExprHasProperty(pExpr,EP_DblQuoted) ){
  74683. pExpr->op = TK_STRING;
  74684. pExpr->pTab = 0;
  74685. return WRC_Prune;
  74686. }
  74687. /*
  74688. ** cnt==0 means there was not match. cnt>1 means there were two or
  74689. ** more matches. Either way, we have an error.
  74690. */
  74691. if( cnt!=1 ){
  74692. const char *zErr;
  74693. zErr = cnt==0 ? "no such column" : "ambiguous column name";
  74694. if( zDb ){
  74695. sqlite3ErrorMsg(pParse, "%s: %s.%s.%s", zErr, zDb, zTab, zCol);
  74696. }else if( zTab ){
  74697. sqlite3ErrorMsg(pParse, "%s: %s.%s", zErr, zTab, zCol);
  74698. }else{
  74699. sqlite3ErrorMsg(pParse, "%s: %s", zErr, zCol);
  74700. }
  74701. pParse->checkSchema = 1;
  74702. pTopNC->nErr++;
  74703. }
  74704. /* If a column from a table in pSrcList is referenced, then record
  74705. ** this fact in the pSrcList.a[].colUsed bitmask. Column 0 causes
  74706. ** bit 0 to be set. Column 1 sets bit 1. And so forth. If the
  74707. ** column number is greater than the number of bits in the bitmask
  74708. ** then set the high-order bit of the bitmask.
  74709. */
  74710. if( pExpr->iColumn>=0 && pMatch!=0 ){
  74711. int n = pExpr->iColumn;
  74712. testcase( n==BMS-1 );
  74713. if( n>=BMS ){
  74714. n = BMS-1;
  74715. }
  74716. assert( pMatch->iCursor==pExpr->iTable );
  74717. pMatch->colUsed |= ((Bitmask)1)<<n;
  74718. }
  74719. /* Clean up and return
  74720. */
  74721. sqlite3ExprDelete(db, pExpr->pLeft);
  74722. pExpr->pLeft = 0;
  74723. sqlite3ExprDelete(db, pExpr->pRight);
  74724. pExpr->pRight = 0;
  74725. pExpr->op = (isTrigger ? TK_TRIGGER : TK_COLUMN);
  74726. lookupname_end:
  74727. if( cnt==1 ){
  74728. assert( pNC!=0 );
  74729. if( pExpr->op!=TK_AS ){
  74730. sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList);
  74731. }
  74732. /* Increment the nRef value on all name contexts from TopNC up to
  74733. ** the point where the name matched. */
  74734. for(;;){
  74735. assert( pTopNC!=0 );
  74736. pTopNC->nRef++;
  74737. if( pTopNC==pNC ) break;
  74738. pTopNC = pTopNC->pNext;
  74739. }
  74740. return WRC_Prune;
  74741. } else {
  74742. return WRC_Abort;
  74743. }
  74744. }
  74745. /*
  74746. ** Allocate and return a pointer to an expression to load the column iCol
  74747. ** from datasource iSrc in SrcList pSrc.
  74748. */
  74749. SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *db, SrcList *pSrc, int iSrc, int iCol){
  74750. Expr *p = sqlite3ExprAlloc(db, TK_COLUMN, 0, 0);
  74751. if( p ){
  74752. struct SrcList_item *pItem = &pSrc->a[iSrc];
  74753. p->pTab = pItem->pTab;
  74754. p->iTable = pItem->iCursor;
  74755. if( p->pTab->iPKey==iCol ){
  74756. p->iColumn = -1;
  74757. }else{
  74758. p->iColumn = (ynVar)iCol;
  74759. testcase( iCol==BMS );
  74760. testcase( iCol==BMS-1 );
  74761. pItem->colUsed |= ((Bitmask)1)<<(iCol>=BMS ? BMS-1 : iCol);
  74762. }
  74763. ExprSetProperty(p, EP_Resolved);
  74764. }
  74765. return p;
  74766. }
  74767. /*
  74768. ** Report an error that an expression is not valid for a partial index WHERE
  74769. ** clause.
  74770. */
  74771. static void notValidPartIdxWhere(
  74772. Parse *pParse, /* Leave error message here */
  74773. NameContext *pNC, /* The name context */
  74774. const char *zMsg /* Type of error */
  74775. ){
  74776. if( (pNC->ncFlags & NC_PartIdx)!=0 ){
  74777. sqlite3ErrorMsg(pParse, "%s prohibited in partial index WHERE clauses",
  74778. zMsg);
  74779. }
  74780. }
  74781. #ifndef SQLITE_OMIT_CHECK
  74782. /*
  74783. ** Report an error that an expression is not valid for a CHECK constraint.
  74784. */
  74785. static void notValidCheckConstraint(
  74786. Parse *pParse, /* Leave error message here */
  74787. NameContext *pNC, /* The name context */
  74788. const char *zMsg /* Type of error */
  74789. ){
  74790. if( (pNC->ncFlags & NC_IsCheck)!=0 ){
  74791. sqlite3ErrorMsg(pParse,"%s prohibited in CHECK constraints", zMsg);
  74792. }
  74793. }
  74794. #else
  74795. # define notValidCheckConstraint(P,N,M)
  74796. #endif
  74797. /*
  74798. ** Expression p should encode a floating point value between 1.0 and 0.0.
  74799. ** Return 1024 times this value. Or return -1 if p is not a floating point
  74800. ** value between 1.0 and 0.0.
  74801. */
  74802. static int exprProbability(Expr *p){
  74803. double r = -1.0;
  74804. if( p->op!=TK_FLOAT ) return -1;
  74805. sqlite3AtoF(p->u.zToken, &r, sqlite3Strlen30(p->u.zToken), SQLITE_UTF8);
  74806. assert( r>=0.0 );
  74807. if( r>1.0 ) return -1;
  74808. return (int)(r*134217728.0);
  74809. }
  74810. /*
  74811. ** This routine is callback for sqlite3WalkExpr().
  74812. **
  74813. ** Resolve symbolic names into TK_COLUMN operators for the current
  74814. ** node in the expression tree. Return 0 to continue the search down
  74815. ** the tree or 2 to abort the tree walk.
  74816. **
  74817. ** This routine also does error checking and name resolution for
  74818. ** function names. The operator for aggregate functions is changed
  74819. ** to TK_AGG_FUNCTION.
  74820. */
  74821. static int resolveExprStep(Walker *pWalker, Expr *pExpr){
  74822. NameContext *pNC;
  74823. Parse *pParse;
  74824. pNC = pWalker->u.pNC;
  74825. assert( pNC!=0 );
  74826. pParse = pNC->pParse;
  74827. assert( pParse==pWalker->pParse );
  74828. if( ExprHasProperty(pExpr, EP_Resolved) ) return WRC_Prune;
  74829. ExprSetProperty(pExpr, EP_Resolved);
  74830. #ifndef NDEBUG
  74831. if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){
  74832. SrcList *pSrcList = pNC->pSrcList;
  74833. int i;
  74834. for(i=0; i<pNC->pSrcList->nSrc; i++){
  74835. assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab);
  74836. }
  74837. }
  74838. #endif
  74839. switch( pExpr->op ){
  74840. #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
  74841. /* The special operator TK_ROW means use the rowid for the first
  74842. ** column in the FROM clause. This is used by the LIMIT and ORDER BY
  74843. ** clause processing on UPDATE and DELETE statements.
  74844. */
  74845. case TK_ROW: {
  74846. SrcList *pSrcList = pNC->pSrcList;
  74847. struct SrcList_item *pItem;
  74848. assert( pSrcList && pSrcList->nSrc==1 );
  74849. pItem = pSrcList->a;
  74850. pExpr->op = TK_COLUMN;
  74851. pExpr->pTab = pItem->pTab;
  74852. pExpr->iTable = pItem->iCursor;
  74853. pExpr->iColumn = -1;
  74854. pExpr->affinity = SQLITE_AFF_INTEGER;
  74855. break;
  74856. }
  74857. #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) */
  74858. /* A lone identifier is the name of a column.
  74859. */
  74860. case TK_ID: {
  74861. return lookupName(pParse, 0, 0, pExpr->u.zToken, pNC, pExpr);
  74862. }
  74863. /* A table name and column name: ID.ID
  74864. ** Or a database, table and column: ID.ID.ID
  74865. */
  74866. case TK_DOT: {
  74867. const char *zColumn;
  74868. const char *zTable;
  74869. const char *zDb;
  74870. Expr *pRight;
  74871. /* if( pSrcList==0 ) break; */
  74872. pRight = pExpr->pRight;
  74873. if( pRight->op==TK_ID ){
  74874. zDb = 0;
  74875. zTable = pExpr->pLeft->u.zToken;
  74876. zColumn = pRight->u.zToken;
  74877. }else{
  74878. assert( pRight->op==TK_DOT );
  74879. zDb = pExpr->pLeft->u.zToken;
  74880. zTable = pRight->pLeft->u.zToken;
  74881. zColumn = pRight->pRight->u.zToken;
  74882. }
  74883. return lookupName(pParse, zDb, zTable, zColumn, pNC, pExpr);
  74884. }
  74885. /* Resolve function names
  74886. */
  74887. case TK_FUNCTION: {
  74888. ExprList *pList = pExpr->x.pList; /* The argument list */
  74889. int n = pList ? pList->nExpr : 0; /* Number of arguments */
  74890. int no_such_func = 0; /* True if no such function exists */
  74891. int wrong_num_args = 0; /* True if wrong number of arguments */
  74892. int is_agg = 0; /* True if is an aggregate function */
  74893. int auth; /* Authorization to use the function */
  74894. int nId; /* Number of characters in function name */
  74895. const char *zId; /* The function name. */
  74896. FuncDef *pDef; /* Information about the function */
  74897. u8 enc = ENC(pParse->db); /* The database encoding */
  74898. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  74899. notValidPartIdxWhere(pParse, pNC, "functions");
  74900. zId = pExpr->u.zToken;
  74901. nId = sqlite3Strlen30(zId);
  74902. pDef = sqlite3FindFunction(pParse->db, zId, nId, n, enc, 0);
  74903. if( pDef==0 ){
  74904. pDef = sqlite3FindFunction(pParse->db, zId, nId, -2, enc, 0);
  74905. if( pDef==0 ){
  74906. no_such_func = 1;
  74907. }else{
  74908. wrong_num_args = 1;
  74909. }
  74910. }else{
  74911. is_agg = pDef->xFunc==0;
  74912. if( pDef->funcFlags & SQLITE_FUNC_UNLIKELY ){
  74913. ExprSetProperty(pExpr, EP_Unlikely|EP_Skip);
  74914. if( n==2 ){
  74915. pExpr->iTable = exprProbability(pList->a[1].pExpr);
  74916. if( pExpr->iTable<0 ){
  74917. sqlite3ErrorMsg(pParse, "second argument to likelihood() must be a "
  74918. "constant between 0.0 and 1.0");
  74919. pNC->nErr++;
  74920. }
  74921. }else{
  74922. /* EVIDENCE-OF: R-61304-29449 The unlikely(X) function is equivalent to
  74923. ** likelihood(X, 0.0625).
  74924. ** EVIDENCE-OF: R-01283-11636 The unlikely(X) function is short-hand for
  74925. ** likelihood(X,0.0625).
  74926. ** EVIDENCE-OF: R-36850-34127 The likely(X) function is short-hand for
  74927. ** likelihood(X,0.9375).
  74928. ** EVIDENCE-OF: R-53436-40973 The likely(X) function is equivalent to
  74929. ** likelihood(X,0.9375). */
  74930. /* TUNING: unlikely() probability is 0.0625. likely() is 0.9375 */
  74931. pExpr->iTable = pDef->zName[0]=='u' ? 8388608 : 125829120;
  74932. }
  74933. }
  74934. #ifndef SQLITE_OMIT_AUTHORIZATION
  74935. auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0, pDef->zName, 0);
  74936. if( auth!=SQLITE_OK ){
  74937. if( auth==SQLITE_DENY ){
  74938. sqlite3ErrorMsg(pParse, "not authorized to use function: %s",
  74939. pDef->zName);
  74940. pNC->nErr++;
  74941. }
  74942. pExpr->op = TK_NULL;
  74943. return WRC_Prune;
  74944. }
  74945. #endif
  74946. if( pDef->funcFlags & SQLITE_FUNC_CONSTANT ) ExprSetProperty(pExpr,EP_Constant);
  74947. }
  74948. if( is_agg && (pNC->ncFlags & NC_AllowAgg)==0 ){
  74949. sqlite3ErrorMsg(pParse, "misuse of aggregate function %.*s()", nId,zId);
  74950. pNC->nErr++;
  74951. is_agg = 0;
  74952. }else if( no_such_func && pParse->db->init.busy==0 ){
  74953. sqlite3ErrorMsg(pParse, "no such function: %.*s", nId, zId);
  74954. pNC->nErr++;
  74955. }else if( wrong_num_args ){
  74956. sqlite3ErrorMsg(pParse,"wrong number of arguments to function %.*s()",
  74957. nId, zId);
  74958. pNC->nErr++;
  74959. }
  74960. if( is_agg ) pNC->ncFlags &= ~NC_AllowAgg;
  74961. sqlite3WalkExprList(pWalker, pList);
  74962. if( is_agg ){
  74963. NameContext *pNC2 = pNC;
  74964. pExpr->op = TK_AGG_FUNCTION;
  74965. pExpr->op2 = 0;
  74966. while( pNC2 && !sqlite3FunctionUsesThisSrc(pExpr, pNC2->pSrcList) ){
  74967. pExpr->op2++;
  74968. pNC2 = pNC2->pNext;
  74969. }
  74970. assert( pDef!=0 );
  74971. if( pNC2 ){
  74972. assert( SQLITE_FUNC_MINMAX==NC_MinMaxAgg );
  74973. testcase( (pDef->funcFlags & SQLITE_FUNC_MINMAX)!=0 );
  74974. pNC2->ncFlags |= NC_HasAgg | (pDef->funcFlags & SQLITE_FUNC_MINMAX);
  74975. }
  74976. pNC->ncFlags |= NC_AllowAgg;
  74977. }
  74978. /* FIX ME: Compute pExpr->affinity based on the expected return
  74979. ** type of the function
  74980. */
  74981. return WRC_Prune;
  74982. }
  74983. #ifndef SQLITE_OMIT_SUBQUERY
  74984. case TK_SELECT:
  74985. case TK_EXISTS: testcase( pExpr->op==TK_EXISTS );
  74986. #endif
  74987. case TK_IN: {
  74988. testcase( pExpr->op==TK_IN );
  74989. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  74990. int nRef = pNC->nRef;
  74991. notValidCheckConstraint(pParse, pNC, "subqueries");
  74992. notValidPartIdxWhere(pParse, pNC, "subqueries");
  74993. sqlite3WalkSelect(pWalker, pExpr->x.pSelect);
  74994. assert( pNC->nRef>=nRef );
  74995. if( nRef!=pNC->nRef ){
  74996. ExprSetProperty(pExpr, EP_VarSelect);
  74997. }
  74998. }
  74999. break;
  75000. }
  75001. case TK_VARIABLE: {
  75002. notValidCheckConstraint(pParse, pNC, "parameters");
  75003. notValidPartIdxWhere(pParse, pNC, "parameters");
  75004. break;
  75005. }
  75006. }
  75007. return (pParse->nErr || pParse->db->mallocFailed) ? WRC_Abort : WRC_Continue;
  75008. }
  75009. /*
  75010. ** pEList is a list of expressions which are really the result set of the
  75011. ** a SELECT statement. pE is a term in an ORDER BY or GROUP BY clause.
  75012. ** This routine checks to see if pE is a simple identifier which corresponds
  75013. ** to the AS-name of one of the terms of the expression list. If it is,
  75014. ** this routine return an integer between 1 and N where N is the number of
  75015. ** elements in pEList, corresponding to the matching entry. If there is
  75016. ** no match, or if pE is not a simple identifier, then this routine
  75017. ** return 0.
  75018. **
  75019. ** pEList has been resolved. pE has not.
  75020. */
  75021. static int resolveAsName(
  75022. Parse *pParse, /* Parsing context for error messages */
  75023. ExprList *pEList, /* List of expressions to scan */
  75024. Expr *pE /* Expression we are trying to match */
  75025. ){
  75026. int i; /* Loop counter */
  75027. UNUSED_PARAMETER(pParse);
  75028. if( pE->op==TK_ID ){
  75029. char *zCol = pE->u.zToken;
  75030. for(i=0; i<pEList->nExpr; i++){
  75031. char *zAs = pEList->a[i].zName;
  75032. if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
  75033. return i+1;
  75034. }
  75035. }
  75036. }
  75037. return 0;
  75038. }
  75039. /*
  75040. ** pE is a pointer to an expression which is a single term in the
  75041. ** ORDER BY of a compound SELECT. The expression has not been
  75042. ** name resolved.
  75043. **
  75044. ** At the point this routine is called, we already know that the
  75045. ** ORDER BY term is not an integer index into the result set. That
  75046. ** case is handled by the calling routine.
  75047. **
  75048. ** Attempt to match pE against result set columns in the left-most
  75049. ** SELECT statement. Return the index i of the matching column,
  75050. ** as an indication to the caller that it should sort by the i-th column.
  75051. ** The left-most column is 1. In other words, the value returned is the
  75052. ** same integer value that would be used in the SQL statement to indicate
  75053. ** the column.
  75054. **
  75055. ** If there is no match, return 0. Return -1 if an error occurs.
  75056. */
  75057. static int resolveOrderByTermToExprList(
  75058. Parse *pParse, /* Parsing context for error messages */
  75059. Select *pSelect, /* The SELECT statement with the ORDER BY clause */
  75060. Expr *pE /* The specific ORDER BY term */
  75061. ){
  75062. int i; /* Loop counter */
  75063. ExprList *pEList; /* The columns of the result set */
  75064. NameContext nc; /* Name context for resolving pE */
  75065. sqlite3 *db; /* Database connection */
  75066. int rc; /* Return code from subprocedures */
  75067. u8 savedSuppErr; /* Saved value of db->suppressErr */
  75068. assert( sqlite3ExprIsInteger(pE, &i)==0 );
  75069. pEList = pSelect->pEList;
  75070. /* Resolve all names in the ORDER BY term expression
  75071. */
  75072. memset(&nc, 0, sizeof(nc));
  75073. nc.pParse = pParse;
  75074. nc.pSrcList = pSelect->pSrc;
  75075. nc.pEList = pEList;
  75076. nc.ncFlags = NC_AllowAgg;
  75077. nc.nErr = 0;
  75078. db = pParse->db;
  75079. savedSuppErr = db->suppressErr;
  75080. db->suppressErr = 1;
  75081. rc = sqlite3ResolveExprNames(&nc, pE);
  75082. db->suppressErr = savedSuppErr;
  75083. if( rc ) return 0;
  75084. /* Try to match the ORDER BY expression against an expression
  75085. ** in the result set. Return an 1-based index of the matching
  75086. ** result-set entry.
  75087. */
  75088. for(i=0; i<pEList->nExpr; i++){
  75089. if( sqlite3ExprCompare(pEList->a[i].pExpr, pE, -1)<2 ){
  75090. return i+1;
  75091. }
  75092. }
  75093. /* If no match, return 0. */
  75094. return 0;
  75095. }
  75096. /*
  75097. ** Generate an ORDER BY or GROUP BY term out-of-range error.
  75098. */
  75099. static void resolveOutOfRangeError(
  75100. Parse *pParse, /* The error context into which to write the error */
  75101. const char *zType, /* "ORDER" or "GROUP" */
  75102. int i, /* The index (1-based) of the term out of range */
  75103. int mx /* Largest permissible value of i */
  75104. ){
  75105. sqlite3ErrorMsg(pParse,
  75106. "%r %s BY term out of range - should be "
  75107. "between 1 and %d", i, zType, mx);
  75108. }
  75109. /*
  75110. ** Analyze the ORDER BY clause in a compound SELECT statement. Modify
  75111. ** each term of the ORDER BY clause is a constant integer between 1
  75112. ** and N where N is the number of columns in the compound SELECT.
  75113. **
  75114. ** ORDER BY terms that are already an integer between 1 and N are
  75115. ** unmodified. ORDER BY terms that are integers outside the range of
  75116. ** 1 through N generate an error. ORDER BY terms that are expressions
  75117. ** are matched against result set expressions of compound SELECT
  75118. ** beginning with the left-most SELECT and working toward the right.
  75119. ** At the first match, the ORDER BY expression is transformed into
  75120. ** the integer column number.
  75121. **
  75122. ** Return the number of errors seen.
  75123. */
  75124. static int resolveCompoundOrderBy(
  75125. Parse *pParse, /* Parsing context. Leave error messages here */
  75126. Select *pSelect /* The SELECT statement containing the ORDER BY */
  75127. ){
  75128. int i;
  75129. ExprList *pOrderBy;
  75130. ExprList *pEList;
  75131. sqlite3 *db;
  75132. int moreToDo = 1;
  75133. pOrderBy = pSelect->pOrderBy;
  75134. if( pOrderBy==0 ) return 0;
  75135. db = pParse->db;
  75136. #if SQLITE_MAX_COLUMN
  75137. if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
  75138. sqlite3ErrorMsg(pParse, "too many terms in ORDER BY clause");
  75139. return 1;
  75140. }
  75141. #endif
  75142. for(i=0; i<pOrderBy->nExpr; i++){
  75143. pOrderBy->a[i].done = 0;
  75144. }
  75145. pSelect->pNext = 0;
  75146. while( pSelect->pPrior ){
  75147. pSelect->pPrior->pNext = pSelect;
  75148. pSelect = pSelect->pPrior;
  75149. }
  75150. while( pSelect && moreToDo ){
  75151. struct ExprList_item *pItem;
  75152. moreToDo = 0;
  75153. pEList = pSelect->pEList;
  75154. assert( pEList!=0 );
  75155. for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
  75156. int iCol = -1;
  75157. Expr *pE, *pDup;
  75158. if( pItem->done ) continue;
  75159. pE = sqlite3ExprSkipCollate(pItem->pExpr);
  75160. if( sqlite3ExprIsInteger(pE, &iCol) ){
  75161. if( iCol<=0 || iCol>pEList->nExpr ){
  75162. resolveOutOfRangeError(pParse, "ORDER", i+1, pEList->nExpr);
  75163. return 1;
  75164. }
  75165. }else{
  75166. iCol = resolveAsName(pParse, pEList, pE);
  75167. if( iCol==0 ){
  75168. pDup = sqlite3ExprDup(db, pE, 0);
  75169. if( !db->mallocFailed ){
  75170. assert(pDup);
  75171. iCol = resolveOrderByTermToExprList(pParse, pSelect, pDup);
  75172. }
  75173. sqlite3ExprDelete(db, pDup);
  75174. }
  75175. }
  75176. if( iCol>0 ){
  75177. /* Convert the ORDER BY term into an integer column number iCol,
  75178. ** taking care to preserve the COLLATE clause if it exists */
  75179. Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
  75180. if( pNew==0 ) return 1;
  75181. pNew->flags |= EP_IntValue;
  75182. pNew->u.iValue = iCol;
  75183. if( pItem->pExpr==pE ){
  75184. pItem->pExpr = pNew;
  75185. }else{
  75186. assert( pItem->pExpr->op==TK_COLLATE );
  75187. assert( pItem->pExpr->pLeft==pE );
  75188. pItem->pExpr->pLeft = pNew;
  75189. }
  75190. sqlite3ExprDelete(db, pE);
  75191. pItem->u.x.iOrderByCol = (u16)iCol;
  75192. pItem->done = 1;
  75193. }else{
  75194. moreToDo = 1;
  75195. }
  75196. }
  75197. pSelect = pSelect->pNext;
  75198. }
  75199. for(i=0; i<pOrderBy->nExpr; i++){
  75200. if( pOrderBy->a[i].done==0 ){
  75201. sqlite3ErrorMsg(pParse, "%r ORDER BY term does not match any "
  75202. "column in the result set", i+1);
  75203. return 1;
  75204. }
  75205. }
  75206. return 0;
  75207. }
  75208. /*
  75209. ** Check every term in the ORDER BY or GROUP BY clause pOrderBy of
  75210. ** the SELECT statement pSelect. If any term is reference to a
  75211. ** result set expression (as determined by the ExprList.a.u.x.iOrderByCol
  75212. ** field) then convert that term into a copy of the corresponding result set
  75213. ** column.
  75214. **
  75215. ** If any errors are detected, add an error message to pParse and
  75216. ** return non-zero. Return zero if no errors are seen.
  75217. */
  75218. SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(
  75219. Parse *pParse, /* Parsing context. Leave error messages here */
  75220. Select *pSelect, /* The SELECT statement containing the clause */
  75221. ExprList *pOrderBy, /* The ORDER BY or GROUP BY clause to be processed */
  75222. const char *zType /* "ORDER" or "GROUP" */
  75223. ){
  75224. int i;
  75225. sqlite3 *db = pParse->db;
  75226. ExprList *pEList;
  75227. struct ExprList_item *pItem;
  75228. if( pOrderBy==0 || pParse->db->mallocFailed ) return 0;
  75229. #if SQLITE_MAX_COLUMN
  75230. if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
  75231. sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType);
  75232. return 1;
  75233. }
  75234. #endif
  75235. pEList = pSelect->pEList;
  75236. assert( pEList!=0 ); /* sqlite3SelectNew() guarantees this */
  75237. for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
  75238. if( pItem->u.x.iOrderByCol ){
  75239. if( pItem->u.x.iOrderByCol>pEList->nExpr ){
  75240. resolveOutOfRangeError(pParse, zType, i+1, pEList->nExpr);
  75241. return 1;
  75242. }
  75243. resolveAlias(pParse, pEList, pItem->u.x.iOrderByCol-1, pItem->pExpr, zType,0);
  75244. }
  75245. }
  75246. return 0;
  75247. }
  75248. /*
  75249. ** pOrderBy is an ORDER BY or GROUP BY clause in SELECT statement pSelect.
  75250. ** The Name context of the SELECT statement is pNC. zType is either
  75251. ** "ORDER" or "GROUP" depending on which type of clause pOrderBy is.
  75252. **
  75253. ** This routine resolves each term of the clause into an expression.
  75254. ** If the order-by term is an integer I between 1 and N (where N is the
  75255. ** number of columns in the result set of the SELECT) then the expression
  75256. ** in the resolution is a copy of the I-th result-set expression. If
  75257. ** the order-by term is an identifier that corresponds to the AS-name of
  75258. ** a result-set expression, then the term resolves to a copy of the
  75259. ** result-set expression. Otherwise, the expression is resolved in
  75260. ** the usual way - using sqlite3ResolveExprNames().
  75261. **
  75262. ** This routine returns the number of errors. If errors occur, then
  75263. ** an appropriate error message might be left in pParse. (OOM errors
  75264. ** excepted.)
  75265. */
  75266. static int resolveOrderGroupBy(
  75267. NameContext *pNC, /* The name context of the SELECT statement */
  75268. Select *pSelect, /* The SELECT statement holding pOrderBy */
  75269. ExprList *pOrderBy, /* An ORDER BY or GROUP BY clause to resolve */
  75270. const char *zType /* Either "ORDER" or "GROUP", as appropriate */
  75271. ){
  75272. int i, j; /* Loop counters */
  75273. int iCol; /* Column number */
  75274. struct ExprList_item *pItem; /* A term of the ORDER BY clause */
  75275. Parse *pParse; /* Parsing context */
  75276. int nResult; /* Number of terms in the result set */
  75277. if( pOrderBy==0 ) return 0;
  75278. nResult = pSelect->pEList->nExpr;
  75279. pParse = pNC->pParse;
  75280. for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
  75281. Expr *pE = pItem->pExpr;
  75282. Expr *pE2 = sqlite3ExprSkipCollate(pE);
  75283. if( zType[0]!='G' ){
  75284. iCol = resolveAsName(pParse, pSelect->pEList, pE2);
  75285. if( iCol>0 ){
  75286. /* If an AS-name match is found, mark this ORDER BY column as being
  75287. ** a copy of the iCol-th result-set column. The subsequent call to
  75288. ** sqlite3ResolveOrderGroupBy() will convert the expression to a
  75289. ** copy of the iCol-th result-set expression. */
  75290. pItem->u.x.iOrderByCol = (u16)iCol;
  75291. continue;
  75292. }
  75293. }
  75294. if( sqlite3ExprIsInteger(pE2, &iCol) ){
  75295. /* The ORDER BY term is an integer constant. Again, set the column
  75296. ** number so that sqlite3ResolveOrderGroupBy() will convert the
  75297. ** order-by term to a copy of the result-set expression */
  75298. if( iCol<1 || iCol>0xffff ){
  75299. resolveOutOfRangeError(pParse, zType, i+1, nResult);
  75300. return 1;
  75301. }
  75302. pItem->u.x.iOrderByCol = (u16)iCol;
  75303. continue;
  75304. }
  75305. /* Otherwise, treat the ORDER BY term as an ordinary expression */
  75306. pItem->u.x.iOrderByCol = 0;
  75307. if( sqlite3ResolveExprNames(pNC, pE) ){
  75308. return 1;
  75309. }
  75310. for(j=0; j<pSelect->pEList->nExpr; j++){
  75311. if( sqlite3ExprCompare(pE, pSelect->pEList->a[j].pExpr, -1)==0 ){
  75312. pItem->u.x.iOrderByCol = j+1;
  75313. }
  75314. }
  75315. }
  75316. return sqlite3ResolveOrderGroupBy(pParse, pSelect, pOrderBy, zType);
  75317. }
  75318. /*
  75319. ** Resolve names in the SELECT statement p and all of its descendants.
  75320. */
  75321. static int resolveSelectStep(Walker *pWalker, Select *p){
  75322. NameContext *pOuterNC; /* Context that contains this SELECT */
  75323. NameContext sNC; /* Name context of this SELECT */
  75324. int isCompound; /* True if p is a compound select */
  75325. int nCompound; /* Number of compound terms processed so far */
  75326. Parse *pParse; /* Parsing context */
  75327. ExprList *pEList; /* Result set expression list */
  75328. int i; /* Loop counter */
  75329. ExprList *pGroupBy; /* The GROUP BY clause */
  75330. Select *pLeftmost; /* Left-most of SELECT of a compound */
  75331. sqlite3 *db; /* Database connection */
  75332. assert( p!=0 );
  75333. if( p->selFlags & SF_Resolved ){
  75334. return WRC_Prune;
  75335. }
  75336. pOuterNC = pWalker->u.pNC;
  75337. pParse = pWalker->pParse;
  75338. db = pParse->db;
  75339. /* Normally sqlite3SelectExpand() will be called first and will have
  75340. ** already expanded this SELECT. However, if this is a subquery within
  75341. ** an expression, sqlite3ResolveExprNames() will be called without a
  75342. ** prior call to sqlite3SelectExpand(). When that happens, let
  75343. ** sqlite3SelectPrep() do all of the processing for this SELECT.
  75344. ** sqlite3SelectPrep() will invoke both sqlite3SelectExpand() and
  75345. ** this routine in the correct order.
  75346. */
  75347. if( (p->selFlags & SF_Expanded)==0 ){
  75348. sqlite3SelectPrep(pParse, p, pOuterNC);
  75349. return (pParse->nErr || db->mallocFailed) ? WRC_Abort : WRC_Prune;
  75350. }
  75351. isCompound = p->pPrior!=0;
  75352. nCompound = 0;
  75353. pLeftmost = p;
  75354. while( p ){
  75355. assert( (p->selFlags & SF_Expanded)!=0 );
  75356. assert( (p->selFlags & SF_Resolved)==0 );
  75357. p->selFlags |= SF_Resolved;
  75358. /* Resolve the expressions in the LIMIT and OFFSET clauses. These
  75359. ** are not allowed to refer to any names, so pass an empty NameContext.
  75360. */
  75361. memset(&sNC, 0, sizeof(sNC));
  75362. sNC.pParse = pParse;
  75363. if( sqlite3ResolveExprNames(&sNC, p->pLimit) ||
  75364. sqlite3ResolveExprNames(&sNC, p->pOffset) ){
  75365. return WRC_Abort;
  75366. }
  75367. /* Recursively resolve names in all subqueries
  75368. */
  75369. for(i=0; i<p->pSrc->nSrc; i++){
  75370. struct SrcList_item *pItem = &p->pSrc->a[i];
  75371. if( pItem->pSelect ){
  75372. NameContext *pNC; /* Used to iterate name contexts */
  75373. int nRef = 0; /* Refcount for pOuterNC and outer contexts */
  75374. const char *zSavedContext = pParse->zAuthContext;
  75375. /* Count the total number of references to pOuterNC and all of its
  75376. ** parent contexts. After resolving references to expressions in
  75377. ** pItem->pSelect, check if this value has changed. If so, then
  75378. ** SELECT statement pItem->pSelect must be correlated. Set the
  75379. ** pItem->isCorrelated flag if this is the case. */
  75380. for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef += pNC->nRef;
  75381. if( pItem->zName ) pParse->zAuthContext = pItem->zName;
  75382. sqlite3ResolveSelectNames(pParse, pItem->pSelect, pOuterNC);
  75383. pParse->zAuthContext = zSavedContext;
  75384. if( pParse->nErr || db->mallocFailed ) return WRC_Abort;
  75385. for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef -= pNC->nRef;
  75386. assert( pItem->isCorrelated==0 && nRef<=0 );
  75387. pItem->isCorrelated = (nRef!=0);
  75388. }
  75389. }
  75390. /* Set up the local name-context to pass to sqlite3ResolveExprNames() to
  75391. ** resolve the result-set expression list.
  75392. */
  75393. sNC.ncFlags = NC_AllowAgg;
  75394. sNC.pSrcList = p->pSrc;
  75395. sNC.pNext = pOuterNC;
  75396. /* Resolve names in the result set. */
  75397. pEList = p->pEList;
  75398. assert( pEList!=0 );
  75399. for(i=0; i<pEList->nExpr; i++){
  75400. Expr *pX = pEList->a[i].pExpr;
  75401. if( sqlite3ResolveExprNames(&sNC, pX) ){
  75402. return WRC_Abort;
  75403. }
  75404. }
  75405. /* If there are no aggregate functions in the result-set, and no GROUP BY
  75406. ** expression, do not allow aggregates in any of the other expressions.
  75407. */
  75408. assert( (p->selFlags & SF_Aggregate)==0 );
  75409. pGroupBy = p->pGroupBy;
  75410. if( pGroupBy || (sNC.ncFlags & NC_HasAgg)!=0 ){
  75411. assert( NC_MinMaxAgg==SF_MinMaxAgg );
  75412. p->selFlags |= SF_Aggregate | (sNC.ncFlags&NC_MinMaxAgg);
  75413. }else{
  75414. sNC.ncFlags &= ~NC_AllowAgg;
  75415. }
  75416. /* If a HAVING clause is present, then there must be a GROUP BY clause.
  75417. */
  75418. if( p->pHaving && !pGroupBy ){
  75419. sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
  75420. return WRC_Abort;
  75421. }
  75422. /* Add the output column list to the name-context before parsing the
  75423. ** other expressions in the SELECT statement. This is so that
  75424. ** expressions in the WHERE clause (etc.) can refer to expressions by
  75425. ** aliases in the result set.
  75426. **
  75427. ** Minor point: If this is the case, then the expression will be
  75428. ** re-evaluated for each reference to it.
  75429. */
  75430. sNC.pEList = p->pEList;
  75431. if( sqlite3ResolveExprNames(&sNC, p->pHaving) ) return WRC_Abort;
  75432. if( sqlite3ResolveExprNames(&sNC, p->pWhere) ) return WRC_Abort;
  75433. /* The ORDER BY and GROUP BY clauses may not refer to terms in
  75434. ** outer queries
  75435. */
  75436. sNC.pNext = 0;
  75437. sNC.ncFlags |= NC_AllowAgg;
  75438. /* Process the ORDER BY clause for singleton SELECT statements.
  75439. ** The ORDER BY clause for compounds SELECT statements is handled
  75440. ** below, after all of the result-sets for all of the elements of
  75441. ** the compound have been resolved.
  75442. */
  75443. if( !isCompound && resolveOrderGroupBy(&sNC, p, p->pOrderBy, "ORDER") ){
  75444. return WRC_Abort;
  75445. }
  75446. if( db->mallocFailed ){
  75447. return WRC_Abort;
  75448. }
  75449. /* Resolve the GROUP BY clause. At the same time, make sure
  75450. ** the GROUP BY clause does not contain aggregate functions.
  75451. */
  75452. if( pGroupBy ){
  75453. struct ExprList_item *pItem;
  75454. if( resolveOrderGroupBy(&sNC, p, pGroupBy, "GROUP") || db->mallocFailed ){
  75455. return WRC_Abort;
  75456. }
  75457. for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){
  75458. if( ExprHasProperty(pItem->pExpr, EP_Agg) ){
  75459. sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in "
  75460. "the GROUP BY clause");
  75461. return WRC_Abort;
  75462. }
  75463. }
  75464. }
  75465. /* Advance to the next term of the compound
  75466. */
  75467. p = p->pPrior;
  75468. nCompound++;
  75469. }
  75470. /* Resolve the ORDER BY on a compound SELECT after all terms of
  75471. ** the compound have been resolved.
  75472. */
  75473. if( isCompound && resolveCompoundOrderBy(pParse, pLeftmost) ){
  75474. return WRC_Abort;
  75475. }
  75476. return WRC_Prune;
  75477. }
  75478. /*
  75479. ** This routine walks an expression tree and resolves references to
  75480. ** table columns and result-set columns. At the same time, do error
  75481. ** checking on function usage and set a flag if any aggregate functions
  75482. ** are seen.
  75483. **
  75484. ** To resolve table columns references we look for nodes (or subtrees) of the
  75485. ** form X.Y.Z or Y.Z or just Z where
  75486. **
  75487. ** X: The name of a database. Ex: "main" or "temp" or
  75488. ** the symbolic name assigned to an ATTACH-ed database.
  75489. **
  75490. ** Y: The name of a table in a FROM clause. Or in a trigger
  75491. ** one of the special names "old" or "new".
  75492. **
  75493. ** Z: The name of a column in table Y.
  75494. **
  75495. ** The node at the root of the subtree is modified as follows:
  75496. **
  75497. ** Expr.op Changed to TK_COLUMN
  75498. ** Expr.pTab Points to the Table object for X.Y
  75499. ** Expr.iColumn The column index in X.Y. -1 for the rowid.
  75500. ** Expr.iTable The VDBE cursor number for X.Y
  75501. **
  75502. **
  75503. ** To resolve result-set references, look for expression nodes of the
  75504. ** form Z (with no X and Y prefix) where the Z matches the right-hand
  75505. ** size of an AS clause in the result-set of a SELECT. The Z expression
  75506. ** is replaced by a copy of the left-hand side of the result-set expression.
  75507. ** Table-name and function resolution occurs on the substituted expression
  75508. ** tree. For example, in:
  75509. **
  75510. ** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY x;
  75511. **
  75512. ** The "x" term of the order by is replaced by "a+b" to render:
  75513. **
  75514. ** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY a+b;
  75515. **
  75516. ** Function calls are checked to make sure that the function is
  75517. ** defined and that the correct number of arguments are specified.
  75518. ** If the function is an aggregate function, then the NC_HasAgg flag is
  75519. ** set and the opcode is changed from TK_FUNCTION to TK_AGG_FUNCTION.
  75520. ** If an expression contains aggregate functions then the EP_Agg
  75521. ** property on the expression is set.
  75522. **
  75523. ** An error message is left in pParse if anything is amiss. The number
  75524. ** if errors is returned.
  75525. */
  75526. SQLITE_PRIVATE int sqlite3ResolveExprNames(
  75527. NameContext *pNC, /* Namespace to resolve expressions in. */
  75528. Expr *pExpr /* The expression to be analyzed. */
  75529. ){
  75530. u16 savedHasAgg;
  75531. Walker w;
  75532. if( pExpr==0 ) return 0;
  75533. #if SQLITE_MAX_EXPR_DEPTH>0
  75534. {
  75535. Parse *pParse = pNC->pParse;
  75536. if( sqlite3ExprCheckHeight(pParse, pExpr->nHeight+pNC->pParse->nHeight) ){
  75537. return 1;
  75538. }
  75539. pParse->nHeight += pExpr->nHeight;
  75540. }
  75541. #endif
  75542. savedHasAgg = pNC->ncFlags & (NC_HasAgg|NC_MinMaxAgg);
  75543. pNC->ncFlags &= ~(NC_HasAgg|NC_MinMaxAgg);
  75544. memset(&w, 0, sizeof(w));
  75545. w.xExprCallback = resolveExprStep;
  75546. w.xSelectCallback = resolveSelectStep;
  75547. w.pParse = pNC->pParse;
  75548. w.u.pNC = pNC;
  75549. sqlite3WalkExpr(&w, pExpr);
  75550. #if SQLITE_MAX_EXPR_DEPTH>0
  75551. pNC->pParse->nHeight -= pExpr->nHeight;
  75552. #endif
  75553. if( pNC->nErr>0 || w.pParse->nErr>0 ){
  75554. ExprSetProperty(pExpr, EP_Error);
  75555. }
  75556. if( pNC->ncFlags & NC_HasAgg ){
  75557. ExprSetProperty(pExpr, EP_Agg);
  75558. }
  75559. pNC->ncFlags |= savedHasAgg;
  75560. return ExprHasProperty(pExpr, EP_Error);
  75561. }
  75562. /*
  75563. ** Resolve all names in all expressions of a SELECT and in all
  75564. ** decendents of the SELECT, including compounds off of p->pPrior,
  75565. ** subqueries in expressions, and subqueries used as FROM clause
  75566. ** terms.
  75567. **
  75568. ** See sqlite3ResolveExprNames() for a description of the kinds of
  75569. ** transformations that occur.
  75570. **
  75571. ** All SELECT statements should have been expanded using
  75572. ** sqlite3SelectExpand() prior to invoking this routine.
  75573. */
  75574. SQLITE_PRIVATE void sqlite3ResolveSelectNames(
  75575. Parse *pParse, /* The parser context */
  75576. Select *p, /* The SELECT statement being coded. */
  75577. NameContext *pOuterNC /* Name context for parent SELECT statement */
  75578. ){
  75579. Walker w;
  75580. assert( p!=0 );
  75581. memset(&w, 0, sizeof(w));
  75582. w.xExprCallback = resolveExprStep;
  75583. w.xSelectCallback = resolveSelectStep;
  75584. w.pParse = pParse;
  75585. w.u.pNC = pOuterNC;
  75586. sqlite3WalkSelect(&w, p);
  75587. }
  75588. /*
  75589. ** Resolve names in expressions that can only reference a single table:
  75590. **
  75591. ** * CHECK constraints
  75592. ** * WHERE clauses on partial indices
  75593. **
  75594. ** The Expr.iTable value for Expr.op==TK_COLUMN nodes of the expression
  75595. ** is set to -1 and the Expr.iColumn value is set to the column number.
  75596. **
  75597. ** Any errors cause an error message to be set in pParse.
  75598. */
  75599. SQLITE_PRIVATE void sqlite3ResolveSelfReference(
  75600. Parse *pParse, /* Parsing context */
  75601. Table *pTab, /* The table being referenced */
  75602. int type, /* NC_IsCheck or NC_PartIdx */
  75603. Expr *pExpr, /* Expression to resolve. May be NULL. */
  75604. ExprList *pList /* Expression list to resolve. May be NUL. */
  75605. ){
  75606. SrcList sSrc; /* Fake SrcList for pParse->pNewTable */
  75607. NameContext sNC; /* Name context for pParse->pNewTable */
  75608. int i; /* Loop counter */
  75609. assert( type==NC_IsCheck || type==NC_PartIdx );
  75610. memset(&sNC, 0, sizeof(sNC));
  75611. memset(&sSrc, 0, sizeof(sSrc));
  75612. sSrc.nSrc = 1;
  75613. sSrc.a[0].zName = pTab->zName;
  75614. sSrc.a[0].pTab = pTab;
  75615. sSrc.a[0].iCursor = -1;
  75616. sNC.pParse = pParse;
  75617. sNC.pSrcList = &sSrc;
  75618. sNC.ncFlags = type;
  75619. if( sqlite3ResolveExprNames(&sNC, pExpr) ) return;
  75620. if( pList ){
  75621. for(i=0; i<pList->nExpr; i++){
  75622. if( sqlite3ResolveExprNames(&sNC, pList->a[i].pExpr) ){
  75623. return;
  75624. }
  75625. }
  75626. }
  75627. }
  75628. /************** End of resolve.c *********************************************/
  75629. /************** Begin file expr.c ********************************************/
  75630. /*
  75631. ** 2001 September 15
  75632. **
  75633. ** The author disclaims copyright to this source code. In place of
  75634. ** a legal notice, here is a blessing:
  75635. **
  75636. ** May you do good and not evil.
  75637. ** May you find forgiveness for yourself and forgive others.
  75638. ** May you share freely, never taking more than you give.
  75639. **
  75640. *************************************************************************
  75641. ** This file contains routines used for analyzing expressions and
  75642. ** for generating VDBE code that evaluates expressions in SQLite.
  75643. */
  75644. /*
  75645. ** Return the 'affinity' of the expression pExpr if any.
  75646. **
  75647. ** If pExpr is a column, a reference to a column via an 'AS' alias,
  75648. ** or a sub-select with a column as the return value, then the
  75649. ** affinity of that column is returned. Otherwise, 0x00 is returned,
  75650. ** indicating no affinity for the expression.
  75651. **
  75652. ** i.e. the WHERE clause expressions in the following statements all
  75653. ** have an affinity:
  75654. **
  75655. ** CREATE TABLE t1(a);
  75656. ** SELECT * FROM t1 WHERE a;
  75657. ** SELECT a AS b FROM t1 WHERE b;
  75658. ** SELECT * FROM t1 WHERE (select a from t1);
  75659. */
  75660. SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr){
  75661. int op;
  75662. pExpr = sqlite3ExprSkipCollate(pExpr);
  75663. if( pExpr->flags & EP_Generic ) return 0;
  75664. op = pExpr->op;
  75665. if( op==TK_SELECT ){
  75666. assert( pExpr->flags&EP_xIsSelect );
  75667. return sqlite3ExprAffinity(pExpr->x.pSelect->pEList->a[0].pExpr);
  75668. }
  75669. #ifndef SQLITE_OMIT_CAST
  75670. if( op==TK_CAST ){
  75671. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  75672. return sqlite3AffinityType(pExpr->u.zToken, 0);
  75673. }
  75674. #endif
  75675. if( (op==TK_AGG_COLUMN || op==TK_COLUMN || op==TK_REGISTER)
  75676. && pExpr->pTab!=0
  75677. ){
  75678. /* op==TK_REGISTER && pExpr->pTab!=0 happens when pExpr was originally
  75679. ** a TK_COLUMN but was previously evaluated and cached in a register */
  75680. int j = pExpr->iColumn;
  75681. if( j<0 ) return SQLITE_AFF_INTEGER;
  75682. assert( pExpr->pTab && j<pExpr->pTab->nCol );
  75683. return pExpr->pTab->aCol[j].affinity;
  75684. }
  75685. return pExpr->affinity;
  75686. }
  75687. /*
  75688. ** Set the collating sequence for expression pExpr to be the collating
  75689. ** sequence named by pToken. Return a pointer to a new Expr node that
  75690. ** implements the COLLATE operator.
  75691. **
  75692. ** If a memory allocation error occurs, that fact is recorded in pParse->db
  75693. ** and the pExpr parameter is returned unchanged.
  75694. */
  75695. SQLITE_PRIVATE Expr *sqlite3ExprAddCollateToken(
  75696. Parse *pParse, /* Parsing context */
  75697. Expr *pExpr, /* Add the "COLLATE" clause to this expression */
  75698. const Token *pCollName /* Name of collating sequence */
  75699. ){
  75700. if( pCollName->n>0 ){
  75701. Expr *pNew = sqlite3ExprAlloc(pParse->db, TK_COLLATE, pCollName, 1);
  75702. if( pNew ){
  75703. pNew->pLeft = pExpr;
  75704. pNew->flags |= EP_Collate|EP_Skip;
  75705. pExpr = pNew;
  75706. }
  75707. }
  75708. return pExpr;
  75709. }
  75710. SQLITE_PRIVATE Expr *sqlite3ExprAddCollateString(Parse *pParse, Expr *pExpr, const char *zC){
  75711. Token s;
  75712. assert( zC!=0 );
  75713. s.z = zC;
  75714. s.n = sqlite3Strlen30(s.z);
  75715. return sqlite3ExprAddCollateToken(pParse, pExpr, &s);
  75716. }
  75717. /*
  75718. ** Skip over any TK_COLLATE or TK_AS operators and any unlikely()
  75719. ** or likelihood() function at the root of an expression.
  75720. */
  75721. SQLITE_PRIVATE Expr *sqlite3ExprSkipCollate(Expr *pExpr){
  75722. while( pExpr && ExprHasProperty(pExpr, EP_Skip) ){
  75723. if( ExprHasProperty(pExpr, EP_Unlikely) ){
  75724. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  75725. assert( pExpr->x.pList->nExpr>0 );
  75726. assert( pExpr->op==TK_FUNCTION );
  75727. pExpr = pExpr->x.pList->a[0].pExpr;
  75728. }else{
  75729. assert( pExpr->op==TK_COLLATE || pExpr->op==TK_AS );
  75730. pExpr = pExpr->pLeft;
  75731. }
  75732. }
  75733. return pExpr;
  75734. }
  75735. /*
  75736. ** Return the collation sequence for the expression pExpr. If
  75737. ** there is no defined collating sequence, return NULL.
  75738. **
  75739. ** The collating sequence might be determined by a COLLATE operator
  75740. ** or by the presence of a column with a defined collating sequence.
  75741. ** COLLATE operators take first precedence. Left operands take
  75742. ** precedence over right operands.
  75743. */
  75744. SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr){
  75745. sqlite3 *db = pParse->db;
  75746. CollSeq *pColl = 0;
  75747. Expr *p = pExpr;
  75748. while( p ){
  75749. int op = p->op;
  75750. if( p->flags & EP_Generic ) break;
  75751. if( op==TK_CAST || op==TK_UPLUS ){
  75752. p = p->pLeft;
  75753. continue;
  75754. }
  75755. if( op==TK_COLLATE || (op==TK_REGISTER && p->op2==TK_COLLATE) ){
  75756. pColl = sqlite3GetCollSeq(pParse, ENC(db), 0, p->u.zToken);
  75757. break;
  75758. }
  75759. if( p->pTab!=0
  75760. && (op==TK_AGG_COLUMN || op==TK_COLUMN
  75761. || op==TK_REGISTER || op==TK_TRIGGER)
  75762. ){
  75763. /* op==TK_REGISTER && p->pTab!=0 happens when pExpr was originally
  75764. ** a TK_COLUMN but was previously evaluated and cached in a register */
  75765. int j = p->iColumn;
  75766. if( j>=0 ){
  75767. const char *zColl = p->pTab->aCol[j].zColl;
  75768. pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
  75769. }
  75770. break;
  75771. }
  75772. if( p->flags & EP_Collate ){
  75773. if( ALWAYS(p->pLeft) && (p->pLeft->flags & EP_Collate)!=0 ){
  75774. p = p->pLeft;
  75775. }else{
  75776. p = p->pRight;
  75777. }
  75778. }else{
  75779. break;
  75780. }
  75781. }
  75782. if( sqlite3CheckCollSeq(pParse, pColl) ){
  75783. pColl = 0;
  75784. }
  75785. return pColl;
  75786. }
  75787. /*
  75788. ** pExpr is an operand of a comparison operator. aff2 is the
  75789. ** type affinity of the other operand. This routine returns the
  75790. ** type affinity that should be used for the comparison operator.
  75791. */
  75792. SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2){
  75793. char aff1 = sqlite3ExprAffinity(pExpr);
  75794. if( aff1 && aff2 ){
  75795. /* Both sides of the comparison are columns. If one has numeric
  75796. ** affinity, use that. Otherwise use no affinity.
  75797. */
  75798. if( sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2) ){
  75799. return SQLITE_AFF_NUMERIC;
  75800. }else{
  75801. return SQLITE_AFF_NONE;
  75802. }
  75803. }else if( !aff1 && !aff2 ){
  75804. /* Neither side of the comparison is a column. Compare the
  75805. ** results directly.
  75806. */
  75807. return SQLITE_AFF_NONE;
  75808. }else{
  75809. /* One side is a column, the other is not. Use the columns affinity. */
  75810. assert( aff1==0 || aff2==0 );
  75811. return (aff1 + aff2);
  75812. }
  75813. }
  75814. /*
  75815. ** pExpr is a comparison operator. Return the type affinity that should
  75816. ** be applied to both operands prior to doing the comparison.
  75817. */
  75818. static char comparisonAffinity(Expr *pExpr){
  75819. char aff;
  75820. assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT ||
  75821. pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE ||
  75822. pExpr->op==TK_NE || pExpr->op==TK_IS || pExpr->op==TK_ISNOT );
  75823. assert( pExpr->pLeft );
  75824. aff = sqlite3ExprAffinity(pExpr->pLeft);
  75825. if( pExpr->pRight ){
  75826. aff = sqlite3CompareAffinity(pExpr->pRight, aff);
  75827. }else if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  75828. aff = sqlite3CompareAffinity(pExpr->x.pSelect->pEList->a[0].pExpr, aff);
  75829. }else if( !aff ){
  75830. aff = SQLITE_AFF_NONE;
  75831. }
  75832. return aff;
  75833. }
  75834. /*
  75835. ** pExpr is a comparison expression, eg. '=', '<', IN(...) etc.
  75836. ** idx_affinity is the affinity of an indexed column. Return true
  75837. ** if the index with affinity idx_affinity may be used to implement
  75838. ** the comparison in pExpr.
  75839. */
  75840. SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity){
  75841. char aff = comparisonAffinity(pExpr);
  75842. switch( aff ){
  75843. case SQLITE_AFF_NONE:
  75844. return 1;
  75845. case SQLITE_AFF_TEXT:
  75846. return idx_affinity==SQLITE_AFF_TEXT;
  75847. default:
  75848. return sqlite3IsNumericAffinity(idx_affinity);
  75849. }
  75850. }
  75851. /*
  75852. ** Return the P5 value that should be used for a binary comparison
  75853. ** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2.
  75854. */
  75855. static u8 binaryCompareP5(Expr *pExpr1, Expr *pExpr2, int jumpIfNull){
  75856. u8 aff = (char)sqlite3ExprAffinity(pExpr2);
  75857. aff = (u8)sqlite3CompareAffinity(pExpr1, aff) | (u8)jumpIfNull;
  75858. return aff;
  75859. }
  75860. /*
  75861. ** Return a pointer to the collation sequence that should be used by
  75862. ** a binary comparison operator comparing pLeft and pRight.
  75863. **
  75864. ** If the left hand expression has a collating sequence type, then it is
  75865. ** used. Otherwise the collation sequence for the right hand expression
  75866. ** is used, or the default (BINARY) if neither expression has a collating
  75867. ** type.
  75868. **
  75869. ** Argument pRight (but not pLeft) may be a null pointer. In this case,
  75870. ** it is not considered.
  75871. */
  75872. SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(
  75873. Parse *pParse,
  75874. Expr *pLeft,
  75875. Expr *pRight
  75876. ){
  75877. CollSeq *pColl;
  75878. assert( pLeft );
  75879. if( pLeft->flags & EP_Collate ){
  75880. pColl = sqlite3ExprCollSeq(pParse, pLeft);
  75881. }else if( pRight && (pRight->flags & EP_Collate)!=0 ){
  75882. pColl = sqlite3ExprCollSeq(pParse, pRight);
  75883. }else{
  75884. pColl = sqlite3ExprCollSeq(pParse, pLeft);
  75885. if( !pColl ){
  75886. pColl = sqlite3ExprCollSeq(pParse, pRight);
  75887. }
  75888. }
  75889. return pColl;
  75890. }
  75891. /*
  75892. ** Generate code for a comparison operator.
  75893. */
  75894. static int codeCompare(
  75895. Parse *pParse, /* The parsing (and code generating) context */
  75896. Expr *pLeft, /* The left operand */
  75897. Expr *pRight, /* The right operand */
  75898. int opcode, /* The comparison opcode */
  75899. int in1, int in2, /* Register holding operands */
  75900. int dest, /* Jump here if true. */
  75901. int jumpIfNull /* If true, jump if either operand is NULL */
  75902. ){
  75903. int p5;
  75904. int addr;
  75905. CollSeq *p4;
  75906. p4 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight);
  75907. p5 = binaryCompareP5(pLeft, pRight, jumpIfNull);
  75908. addr = sqlite3VdbeAddOp4(pParse->pVdbe, opcode, in2, dest, in1,
  75909. (void*)p4, P4_COLLSEQ);
  75910. sqlite3VdbeChangeP5(pParse->pVdbe, (u8)p5);
  75911. return addr;
  75912. }
  75913. #if SQLITE_MAX_EXPR_DEPTH>0
  75914. /*
  75915. ** Check that argument nHeight is less than or equal to the maximum
  75916. ** expression depth allowed. If it is not, leave an error message in
  75917. ** pParse.
  75918. */
  75919. SQLITE_PRIVATE int sqlite3ExprCheckHeight(Parse *pParse, int nHeight){
  75920. int rc = SQLITE_OK;
  75921. int mxHeight = pParse->db->aLimit[SQLITE_LIMIT_EXPR_DEPTH];
  75922. if( nHeight>mxHeight ){
  75923. sqlite3ErrorMsg(pParse,
  75924. "Expression tree is too large (maximum depth %d)", mxHeight
  75925. );
  75926. rc = SQLITE_ERROR;
  75927. }
  75928. return rc;
  75929. }
  75930. /* The following three functions, heightOfExpr(), heightOfExprList()
  75931. ** and heightOfSelect(), are used to determine the maximum height
  75932. ** of any expression tree referenced by the structure passed as the
  75933. ** first argument.
  75934. **
  75935. ** If this maximum height is greater than the current value pointed
  75936. ** to by pnHeight, the second parameter, then set *pnHeight to that
  75937. ** value.
  75938. */
  75939. static void heightOfExpr(Expr *p, int *pnHeight){
  75940. if( p ){
  75941. if( p->nHeight>*pnHeight ){
  75942. *pnHeight = p->nHeight;
  75943. }
  75944. }
  75945. }
  75946. static void heightOfExprList(ExprList *p, int *pnHeight){
  75947. if( p ){
  75948. int i;
  75949. for(i=0; i<p->nExpr; i++){
  75950. heightOfExpr(p->a[i].pExpr, pnHeight);
  75951. }
  75952. }
  75953. }
  75954. static void heightOfSelect(Select *p, int *pnHeight){
  75955. if( p ){
  75956. heightOfExpr(p->pWhere, pnHeight);
  75957. heightOfExpr(p->pHaving, pnHeight);
  75958. heightOfExpr(p->pLimit, pnHeight);
  75959. heightOfExpr(p->pOffset, pnHeight);
  75960. heightOfExprList(p->pEList, pnHeight);
  75961. heightOfExprList(p->pGroupBy, pnHeight);
  75962. heightOfExprList(p->pOrderBy, pnHeight);
  75963. heightOfSelect(p->pPrior, pnHeight);
  75964. }
  75965. }
  75966. /*
  75967. ** Set the Expr.nHeight variable in the structure passed as an
  75968. ** argument. An expression with no children, Expr.pList or
  75969. ** Expr.pSelect member has a height of 1. Any other expression
  75970. ** has a height equal to the maximum height of any other
  75971. ** referenced Expr plus one.
  75972. */
  75973. static void exprSetHeight(Expr *p){
  75974. int nHeight = 0;
  75975. heightOfExpr(p->pLeft, &nHeight);
  75976. heightOfExpr(p->pRight, &nHeight);
  75977. if( ExprHasProperty(p, EP_xIsSelect) ){
  75978. heightOfSelect(p->x.pSelect, &nHeight);
  75979. }else{
  75980. heightOfExprList(p->x.pList, &nHeight);
  75981. }
  75982. p->nHeight = nHeight + 1;
  75983. }
  75984. /*
  75985. ** Set the Expr.nHeight variable using the exprSetHeight() function. If
  75986. ** the height is greater than the maximum allowed expression depth,
  75987. ** leave an error in pParse.
  75988. */
  75989. SQLITE_PRIVATE void sqlite3ExprSetHeight(Parse *pParse, Expr *p){
  75990. exprSetHeight(p);
  75991. sqlite3ExprCheckHeight(pParse, p->nHeight);
  75992. }
  75993. /*
  75994. ** Return the maximum height of any expression tree referenced
  75995. ** by the select statement passed as an argument.
  75996. */
  75997. SQLITE_PRIVATE int sqlite3SelectExprHeight(Select *p){
  75998. int nHeight = 0;
  75999. heightOfSelect(p, &nHeight);
  76000. return nHeight;
  76001. }
  76002. #else
  76003. #define exprSetHeight(y)
  76004. #endif /* SQLITE_MAX_EXPR_DEPTH>0 */
  76005. /*
  76006. ** This routine is the core allocator for Expr nodes.
  76007. **
  76008. ** Construct a new expression node and return a pointer to it. Memory
  76009. ** for this node and for the pToken argument is a single allocation
  76010. ** obtained from sqlite3DbMalloc(). The calling function
  76011. ** is responsible for making sure the node eventually gets freed.
  76012. **
  76013. ** If dequote is true, then the token (if it exists) is dequoted.
  76014. ** If dequote is false, no dequoting is performance. The deQuote
  76015. ** parameter is ignored if pToken is NULL or if the token does not
  76016. ** appear to be quoted. If the quotes were of the form "..." (double-quotes)
  76017. ** then the EP_DblQuoted flag is set on the expression node.
  76018. **
  76019. ** Special case: If op==TK_INTEGER and pToken points to a string that
  76020. ** can be translated into a 32-bit integer, then the token is not
  76021. ** stored in u.zToken. Instead, the integer values is written
  76022. ** into u.iValue and the EP_IntValue flag is set. No extra storage
  76023. ** is allocated to hold the integer text and the dequote flag is ignored.
  76024. */
  76025. SQLITE_PRIVATE Expr *sqlite3ExprAlloc(
  76026. sqlite3 *db, /* Handle for sqlite3DbMallocZero() (may be null) */
  76027. int op, /* Expression opcode */
  76028. const Token *pToken, /* Token argument. Might be NULL */
  76029. int dequote /* True to dequote */
  76030. ){
  76031. Expr *pNew;
  76032. int nExtra = 0;
  76033. int iValue = 0;
  76034. if( pToken ){
  76035. if( op!=TK_INTEGER || pToken->z==0
  76036. || sqlite3GetInt32(pToken->z, &iValue)==0 ){
  76037. nExtra = pToken->n+1;
  76038. assert( iValue>=0 );
  76039. }
  76040. }
  76041. pNew = sqlite3DbMallocZero(db, sizeof(Expr)+nExtra);
  76042. if( pNew ){
  76043. pNew->op = (u8)op;
  76044. pNew->iAgg = -1;
  76045. if( pToken ){
  76046. if( nExtra==0 ){
  76047. pNew->flags |= EP_IntValue;
  76048. pNew->u.iValue = iValue;
  76049. }else{
  76050. int c;
  76051. pNew->u.zToken = (char*)&pNew[1];
  76052. assert( pToken->z!=0 || pToken->n==0 );
  76053. if( pToken->n ) memcpy(pNew->u.zToken, pToken->z, pToken->n);
  76054. pNew->u.zToken[pToken->n] = 0;
  76055. if( dequote && nExtra>=3
  76056. && ((c = pToken->z[0])=='\'' || c=='"' || c=='[' || c=='`') ){
  76057. sqlite3Dequote(pNew->u.zToken);
  76058. if( c=='"' ) pNew->flags |= EP_DblQuoted;
  76059. }
  76060. }
  76061. }
  76062. #if SQLITE_MAX_EXPR_DEPTH>0
  76063. pNew->nHeight = 1;
  76064. #endif
  76065. }
  76066. return pNew;
  76067. }
  76068. /*
  76069. ** Allocate a new expression node from a zero-terminated token that has
  76070. ** already been dequoted.
  76071. */
  76072. SQLITE_PRIVATE Expr *sqlite3Expr(
  76073. sqlite3 *db, /* Handle for sqlite3DbMallocZero() (may be null) */
  76074. int op, /* Expression opcode */
  76075. const char *zToken /* Token argument. Might be NULL */
  76076. ){
  76077. Token x;
  76078. x.z = zToken;
  76079. x.n = zToken ? sqlite3Strlen30(zToken) : 0;
  76080. return sqlite3ExprAlloc(db, op, &x, 0);
  76081. }
  76082. /*
  76083. ** Attach subtrees pLeft and pRight to the Expr node pRoot.
  76084. **
  76085. ** If pRoot==NULL that means that a memory allocation error has occurred.
  76086. ** In that case, delete the subtrees pLeft and pRight.
  76087. */
  76088. SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(
  76089. sqlite3 *db,
  76090. Expr *pRoot,
  76091. Expr *pLeft,
  76092. Expr *pRight
  76093. ){
  76094. if( pRoot==0 ){
  76095. assert( db->mallocFailed );
  76096. sqlite3ExprDelete(db, pLeft);
  76097. sqlite3ExprDelete(db, pRight);
  76098. }else{
  76099. if( pRight ){
  76100. pRoot->pRight = pRight;
  76101. pRoot->flags |= EP_Collate & pRight->flags;
  76102. }
  76103. if( pLeft ){
  76104. pRoot->pLeft = pLeft;
  76105. pRoot->flags |= EP_Collate & pLeft->flags;
  76106. }
  76107. exprSetHeight(pRoot);
  76108. }
  76109. }
  76110. /*
  76111. ** Allocate an Expr node which joins as many as two subtrees.
  76112. **
  76113. ** One or both of the subtrees can be NULL. Return a pointer to the new
  76114. ** Expr node. Or, if an OOM error occurs, set pParse->db->mallocFailed,
  76115. ** free the subtrees and return NULL.
  76116. */
  76117. SQLITE_PRIVATE Expr *sqlite3PExpr(
  76118. Parse *pParse, /* Parsing context */
  76119. int op, /* Expression opcode */
  76120. Expr *pLeft, /* Left operand */
  76121. Expr *pRight, /* Right operand */
  76122. const Token *pToken /* Argument token */
  76123. ){
  76124. Expr *p;
  76125. if( op==TK_AND && pLeft && pRight ){
  76126. /* Take advantage of short-circuit false optimization for AND */
  76127. p = sqlite3ExprAnd(pParse->db, pLeft, pRight);
  76128. }else{
  76129. p = sqlite3ExprAlloc(pParse->db, op, pToken, 1);
  76130. sqlite3ExprAttachSubtrees(pParse->db, p, pLeft, pRight);
  76131. }
  76132. if( p ) {
  76133. sqlite3ExprCheckHeight(pParse, p->nHeight);
  76134. }
  76135. return p;
  76136. }
  76137. /*
  76138. ** If the expression is always either TRUE or FALSE (respectively),
  76139. ** then return 1. If one cannot determine the truth value of the
  76140. ** expression at compile-time return 0.
  76141. **
  76142. ** This is an optimization. If is OK to return 0 here even if
  76143. ** the expression really is always false or false (a false negative).
  76144. ** But it is a bug to return 1 if the expression might have different
  76145. ** boolean values in different circumstances (a false positive.)
  76146. **
  76147. ** Note that if the expression is part of conditional for a
  76148. ** LEFT JOIN, then we cannot determine at compile-time whether or not
  76149. ** is it true or false, so always return 0.
  76150. */
  76151. static int exprAlwaysTrue(Expr *p){
  76152. int v = 0;
  76153. if( ExprHasProperty(p, EP_FromJoin) ) return 0;
  76154. if( !sqlite3ExprIsInteger(p, &v) ) return 0;
  76155. return v!=0;
  76156. }
  76157. static int exprAlwaysFalse(Expr *p){
  76158. int v = 0;
  76159. if( ExprHasProperty(p, EP_FromJoin) ) return 0;
  76160. if( !sqlite3ExprIsInteger(p, &v) ) return 0;
  76161. return v==0;
  76162. }
  76163. /*
  76164. ** Join two expressions using an AND operator. If either expression is
  76165. ** NULL, then just return the other expression.
  76166. **
  76167. ** If one side or the other of the AND is known to be false, then instead
  76168. ** of returning an AND expression, just return a constant expression with
  76169. ** a value of false.
  76170. */
  76171. SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3 *db, Expr *pLeft, Expr *pRight){
  76172. if( pLeft==0 ){
  76173. return pRight;
  76174. }else if( pRight==0 ){
  76175. return pLeft;
  76176. }else if( exprAlwaysFalse(pLeft) || exprAlwaysFalse(pRight) ){
  76177. sqlite3ExprDelete(db, pLeft);
  76178. sqlite3ExprDelete(db, pRight);
  76179. return sqlite3ExprAlloc(db, TK_INTEGER, &sqlite3IntTokens[0], 0);
  76180. }else{
  76181. Expr *pNew = sqlite3ExprAlloc(db, TK_AND, 0, 0);
  76182. sqlite3ExprAttachSubtrees(db, pNew, pLeft, pRight);
  76183. return pNew;
  76184. }
  76185. }
  76186. /*
  76187. ** Construct a new expression node for a function with multiple
  76188. ** arguments.
  76189. */
  76190. SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse *pParse, ExprList *pList, Token *pToken){
  76191. Expr *pNew;
  76192. sqlite3 *db = pParse->db;
  76193. assert( pToken );
  76194. pNew = sqlite3ExprAlloc(db, TK_FUNCTION, pToken, 1);
  76195. if( pNew==0 ){
  76196. sqlite3ExprListDelete(db, pList); /* Avoid memory leak when malloc fails */
  76197. return 0;
  76198. }
  76199. pNew->x.pList = pList;
  76200. assert( !ExprHasProperty(pNew, EP_xIsSelect) );
  76201. sqlite3ExprSetHeight(pParse, pNew);
  76202. return pNew;
  76203. }
  76204. /*
  76205. ** Assign a variable number to an expression that encodes a wildcard
  76206. ** in the original SQL statement.
  76207. **
  76208. ** Wildcards consisting of a single "?" are assigned the next sequential
  76209. ** variable number.
  76210. **
  76211. ** Wildcards of the form "?nnn" are assigned the number "nnn". We make
  76212. ** sure "nnn" is not too be to avoid a denial of service attack when
  76213. ** the SQL statement comes from an external source.
  76214. **
  76215. ** Wildcards of the form ":aaa", "@aaa", or "$aaa" are assigned the same number
  76216. ** as the previous instance of the same wildcard. Or if this is the first
  76217. ** instance of the wildcard, the next sequential variable number is
  76218. ** assigned.
  76219. */
  76220. SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr){
  76221. sqlite3 *db = pParse->db;
  76222. const char *z;
  76223. if( pExpr==0 ) return;
  76224. assert( !ExprHasProperty(pExpr, EP_IntValue|EP_Reduced|EP_TokenOnly) );
  76225. z = pExpr->u.zToken;
  76226. assert( z!=0 );
  76227. assert( z[0]!=0 );
  76228. if( z[1]==0 ){
  76229. /* Wildcard of the form "?". Assign the next variable number */
  76230. assert( z[0]=='?' );
  76231. pExpr->iColumn = (ynVar)(++pParse->nVar);
  76232. }else{
  76233. ynVar x = 0;
  76234. u32 n = sqlite3Strlen30(z);
  76235. if( z[0]=='?' ){
  76236. /* Wildcard of the form "?nnn". Convert "nnn" to an integer and
  76237. ** use it as the variable number */
  76238. i64 i;
  76239. int bOk = 0==sqlite3Atoi64(&z[1], &i, n-1, SQLITE_UTF8);
  76240. pExpr->iColumn = x = (ynVar)i;
  76241. testcase( i==0 );
  76242. testcase( i==1 );
  76243. testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]-1 );
  76244. testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] );
  76245. if( bOk==0 || i<1 || i>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
  76246. sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d",
  76247. db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]);
  76248. x = 0;
  76249. }
  76250. if( i>pParse->nVar ){
  76251. pParse->nVar = (int)i;
  76252. }
  76253. }else{
  76254. /* Wildcards like ":aaa", "$aaa" or "@aaa". Reuse the same variable
  76255. ** number as the prior appearance of the same name, or if the name
  76256. ** has never appeared before, reuse the same variable number
  76257. */
  76258. ynVar i;
  76259. for(i=0; i<pParse->nzVar; i++){
  76260. if( pParse->azVar[i] && strcmp(pParse->azVar[i],z)==0 ){
  76261. pExpr->iColumn = x = (ynVar)i+1;
  76262. break;
  76263. }
  76264. }
  76265. if( x==0 ) x = pExpr->iColumn = (ynVar)(++pParse->nVar);
  76266. }
  76267. if( x>0 ){
  76268. if( x>pParse->nzVar ){
  76269. char **a;
  76270. a = sqlite3DbRealloc(db, pParse->azVar, x*sizeof(a[0]));
  76271. if( a==0 ) return; /* Error reported through db->mallocFailed */
  76272. pParse->azVar = a;
  76273. memset(&a[pParse->nzVar], 0, (x-pParse->nzVar)*sizeof(a[0]));
  76274. pParse->nzVar = x;
  76275. }
  76276. if( z[0]!='?' || pParse->azVar[x-1]==0 ){
  76277. sqlite3DbFree(db, pParse->azVar[x-1]);
  76278. pParse->azVar[x-1] = sqlite3DbStrNDup(db, z, n);
  76279. }
  76280. }
  76281. }
  76282. if( !pParse->nErr && pParse->nVar>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
  76283. sqlite3ErrorMsg(pParse, "too many SQL variables");
  76284. }
  76285. }
  76286. /*
  76287. ** Recursively delete an expression tree.
  76288. */
  76289. SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3 *db, Expr *p){
  76290. if( p==0 ) return;
  76291. /* Sanity check: Assert that the IntValue is non-negative if it exists */
  76292. assert( !ExprHasProperty(p, EP_IntValue) || p->u.iValue>=0 );
  76293. if( !ExprHasProperty(p, EP_TokenOnly) ){
  76294. /* The Expr.x union is never used at the same time as Expr.pRight */
  76295. assert( p->x.pList==0 || p->pRight==0 );
  76296. sqlite3ExprDelete(db, p->pLeft);
  76297. sqlite3ExprDelete(db, p->pRight);
  76298. if( ExprHasProperty(p, EP_MemToken) ) sqlite3DbFree(db, p->u.zToken);
  76299. if( ExprHasProperty(p, EP_xIsSelect) ){
  76300. sqlite3SelectDelete(db, p->x.pSelect);
  76301. }else{
  76302. sqlite3ExprListDelete(db, p->x.pList);
  76303. }
  76304. }
  76305. if( !ExprHasProperty(p, EP_Static) ){
  76306. sqlite3DbFree(db, p);
  76307. }
  76308. }
  76309. /*
  76310. ** Return the number of bytes allocated for the expression structure
  76311. ** passed as the first argument. This is always one of EXPR_FULLSIZE,
  76312. ** EXPR_REDUCEDSIZE or EXPR_TOKENONLYSIZE.
  76313. */
  76314. static int exprStructSize(Expr *p){
  76315. if( ExprHasProperty(p, EP_TokenOnly) ) return EXPR_TOKENONLYSIZE;
  76316. if( ExprHasProperty(p, EP_Reduced) ) return EXPR_REDUCEDSIZE;
  76317. return EXPR_FULLSIZE;
  76318. }
  76319. /*
  76320. ** The dupedExpr*Size() routines each return the number of bytes required
  76321. ** to store a copy of an expression or expression tree. They differ in
  76322. ** how much of the tree is measured.
  76323. **
  76324. ** dupedExprStructSize() Size of only the Expr structure
  76325. ** dupedExprNodeSize() Size of Expr + space for token
  76326. ** dupedExprSize() Expr + token + subtree components
  76327. **
  76328. ***************************************************************************
  76329. **
  76330. ** The dupedExprStructSize() function returns two values OR-ed together:
  76331. ** (1) the space required for a copy of the Expr structure only and
  76332. ** (2) the EP_xxx flags that indicate what the structure size should be.
  76333. ** The return values is always one of:
  76334. **
  76335. ** EXPR_FULLSIZE
  76336. ** EXPR_REDUCEDSIZE | EP_Reduced
  76337. ** EXPR_TOKENONLYSIZE | EP_TokenOnly
  76338. **
  76339. ** The size of the structure can be found by masking the return value
  76340. ** of this routine with 0xfff. The flags can be found by masking the
  76341. ** return value with EP_Reduced|EP_TokenOnly.
  76342. **
  76343. ** Note that with flags==EXPRDUP_REDUCE, this routines works on full-size
  76344. ** (unreduced) Expr objects as they or originally constructed by the parser.
  76345. ** During expression analysis, extra information is computed and moved into
  76346. ** later parts of teh Expr object and that extra information might get chopped
  76347. ** off if the expression is reduced. Note also that it does not work to
  76348. ** make an EXPRDUP_REDUCE copy of a reduced expression. It is only legal
  76349. ** to reduce a pristine expression tree from the parser. The implementation
  76350. ** of dupedExprStructSize() contain multiple assert() statements that attempt
  76351. ** to enforce this constraint.
  76352. */
  76353. static int dupedExprStructSize(Expr *p, int flags){
  76354. int nSize;
  76355. assert( flags==EXPRDUP_REDUCE || flags==0 ); /* Only one flag value allowed */
  76356. assert( EXPR_FULLSIZE<=0xfff );
  76357. assert( (0xfff & (EP_Reduced|EP_TokenOnly))==0 );
  76358. if( 0==(flags&EXPRDUP_REDUCE) ){
  76359. nSize = EXPR_FULLSIZE;
  76360. }else{
  76361. assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) );
  76362. assert( !ExprHasProperty(p, EP_FromJoin) );
  76363. assert( !ExprHasProperty(p, EP_MemToken) );
  76364. assert( !ExprHasProperty(p, EP_NoReduce) );
  76365. if( p->pLeft || p->x.pList ){
  76366. nSize = EXPR_REDUCEDSIZE | EP_Reduced;
  76367. }else{
  76368. assert( p->pRight==0 );
  76369. nSize = EXPR_TOKENONLYSIZE | EP_TokenOnly;
  76370. }
  76371. }
  76372. return nSize;
  76373. }
  76374. /*
  76375. ** This function returns the space in bytes required to store the copy
  76376. ** of the Expr structure and a copy of the Expr.u.zToken string (if that
  76377. ** string is defined.)
  76378. */
  76379. static int dupedExprNodeSize(Expr *p, int flags){
  76380. int nByte = dupedExprStructSize(p, flags) & 0xfff;
  76381. if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
  76382. nByte += sqlite3Strlen30(p->u.zToken)+1;
  76383. }
  76384. return ROUND8(nByte);
  76385. }
  76386. /*
  76387. ** Return the number of bytes required to create a duplicate of the
  76388. ** expression passed as the first argument. The second argument is a
  76389. ** mask containing EXPRDUP_XXX flags.
  76390. **
  76391. ** The value returned includes space to create a copy of the Expr struct
  76392. ** itself and the buffer referred to by Expr.u.zToken, if any.
  76393. **
  76394. ** If the EXPRDUP_REDUCE flag is set, then the return value includes
  76395. ** space to duplicate all Expr nodes in the tree formed by Expr.pLeft
  76396. ** and Expr.pRight variables (but not for any structures pointed to or
  76397. ** descended from the Expr.x.pList or Expr.x.pSelect variables).
  76398. */
  76399. static int dupedExprSize(Expr *p, int flags){
  76400. int nByte = 0;
  76401. if( p ){
  76402. nByte = dupedExprNodeSize(p, flags);
  76403. if( flags&EXPRDUP_REDUCE ){
  76404. nByte += dupedExprSize(p->pLeft, flags) + dupedExprSize(p->pRight, flags);
  76405. }
  76406. }
  76407. return nByte;
  76408. }
  76409. /*
  76410. ** This function is similar to sqlite3ExprDup(), except that if pzBuffer
  76411. ** is not NULL then *pzBuffer is assumed to point to a buffer large enough
  76412. ** to store the copy of expression p, the copies of p->u.zToken
  76413. ** (if applicable), and the copies of the p->pLeft and p->pRight expressions,
  76414. ** if any. Before returning, *pzBuffer is set to the first byte past the
  76415. ** portion of the buffer copied into by this function.
  76416. */
  76417. static Expr *exprDup(sqlite3 *db, Expr *p, int flags, u8 **pzBuffer){
  76418. Expr *pNew = 0; /* Value to return */
  76419. if( p ){
  76420. const int isReduced = (flags&EXPRDUP_REDUCE);
  76421. u8 *zAlloc;
  76422. u32 staticFlag = 0;
  76423. assert( pzBuffer==0 || isReduced );
  76424. /* Figure out where to write the new Expr structure. */
  76425. if( pzBuffer ){
  76426. zAlloc = *pzBuffer;
  76427. staticFlag = EP_Static;
  76428. }else{
  76429. zAlloc = sqlite3DbMallocRaw(db, dupedExprSize(p, flags));
  76430. }
  76431. pNew = (Expr *)zAlloc;
  76432. if( pNew ){
  76433. /* Set nNewSize to the size allocated for the structure pointed to
  76434. ** by pNew. This is either EXPR_FULLSIZE, EXPR_REDUCEDSIZE or
  76435. ** EXPR_TOKENONLYSIZE. nToken is set to the number of bytes consumed
  76436. ** by the copy of the p->u.zToken string (if any).
  76437. */
  76438. const unsigned nStructSize = dupedExprStructSize(p, flags);
  76439. const int nNewSize = nStructSize & 0xfff;
  76440. int nToken;
  76441. if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
  76442. nToken = sqlite3Strlen30(p->u.zToken) + 1;
  76443. }else{
  76444. nToken = 0;
  76445. }
  76446. if( isReduced ){
  76447. assert( ExprHasProperty(p, EP_Reduced)==0 );
  76448. memcpy(zAlloc, p, nNewSize);
  76449. }else{
  76450. int nSize = exprStructSize(p);
  76451. memcpy(zAlloc, p, nSize);
  76452. memset(&zAlloc[nSize], 0, EXPR_FULLSIZE-nSize);
  76453. }
  76454. /* Set the EP_Reduced, EP_TokenOnly, and EP_Static flags appropriately. */
  76455. pNew->flags &= ~(EP_Reduced|EP_TokenOnly|EP_Static|EP_MemToken);
  76456. pNew->flags |= nStructSize & (EP_Reduced|EP_TokenOnly);
  76457. pNew->flags |= staticFlag;
  76458. /* Copy the p->u.zToken string, if any. */
  76459. if( nToken ){
  76460. char *zToken = pNew->u.zToken = (char*)&zAlloc[nNewSize];
  76461. memcpy(zToken, p->u.zToken, nToken);
  76462. }
  76463. if( 0==((p->flags|pNew->flags) & EP_TokenOnly) ){
  76464. /* Fill in the pNew->x.pSelect or pNew->x.pList member. */
  76465. if( ExprHasProperty(p, EP_xIsSelect) ){
  76466. pNew->x.pSelect = sqlite3SelectDup(db, p->x.pSelect, isReduced);
  76467. }else{
  76468. pNew->x.pList = sqlite3ExprListDup(db, p->x.pList, isReduced);
  76469. }
  76470. }
  76471. /* Fill in pNew->pLeft and pNew->pRight. */
  76472. if( ExprHasProperty(pNew, EP_Reduced|EP_TokenOnly) ){
  76473. zAlloc += dupedExprNodeSize(p, flags);
  76474. if( ExprHasProperty(pNew, EP_Reduced) ){
  76475. pNew->pLeft = exprDup(db, p->pLeft, EXPRDUP_REDUCE, &zAlloc);
  76476. pNew->pRight = exprDup(db, p->pRight, EXPRDUP_REDUCE, &zAlloc);
  76477. }
  76478. if( pzBuffer ){
  76479. *pzBuffer = zAlloc;
  76480. }
  76481. }else{
  76482. if( !ExprHasProperty(p, EP_TokenOnly) ){
  76483. pNew->pLeft = sqlite3ExprDup(db, p->pLeft, 0);
  76484. pNew->pRight = sqlite3ExprDup(db, p->pRight, 0);
  76485. }
  76486. }
  76487. }
  76488. }
  76489. return pNew;
  76490. }
  76491. /*
  76492. ** Create and return a deep copy of the object passed as the second
  76493. ** argument. If an OOM condition is encountered, NULL is returned
  76494. ** and the db->mallocFailed flag set.
  76495. */
  76496. #ifndef SQLITE_OMIT_CTE
  76497. static With *withDup(sqlite3 *db, With *p){
  76498. With *pRet = 0;
  76499. if( p ){
  76500. int nByte = sizeof(*p) + sizeof(p->a[0]) * (p->nCte-1);
  76501. pRet = sqlite3DbMallocZero(db, nByte);
  76502. if( pRet ){
  76503. int i;
  76504. pRet->nCte = p->nCte;
  76505. for(i=0; i<p->nCte; i++){
  76506. pRet->a[i].pSelect = sqlite3SelectDup(db, p->a[i].pSelect, 0);
  76507. pRet->a[i].pCols = sqlite3ExprListDup(db, p->a[i].pCols, 0);
  76508. pRet->a[i].zName = sqlite3DbStrDup(db, p->a[i].zName);
  76509. }
  76510. }
  76511. }
  76512. return pRet;
  76513. }
  76514. #else
  76515. # define withDup(x,y) 0
  76516. #endif
  76517. /*
  76518. ** The following group of routines make deep copies of expressions,
  76519. ** expression lists, ID lists, and select statements. The copies can
  76520. ** be deleted (by being passed to their respective ...Delete() routines)
  76521. ** without effecting the originals.
  76522. **
  76523. ** The expression list, ID, and source lists return by sqlite3ExprListDup(),
  76524. ** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded
  76525. ** by subsequent calls to sqlite*ListAppend() routines.
  76526. **
  76527. ** Any tables that the SrcList might point to are not duplicated.
  76528. **
  76529. ** The flags parameter contains a combination of the EXPRDUP_XXX flags.
  76530. ** If the EXPRDUP_REDUCE flag is set, then the structure returned is a
  76531. ** truncated version of the usual Expr structure that will be stored as
  76532. ** part of the in-memory representation of the database schema.
  76533. */
  76534. SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3 *db, Expr *p, int flags){
  76535. return exprDup(db, p, flags, 0);
  76536. }
  76537. SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3 *db, ExprList *p, int flags){
  76538. ExprList *pNew;
  76539. struct ExprList_item *pItem, *pOldItem;
  76540. int i;
  76541. if( p==0 ) return 0;
  76542. pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
  76543. if( pNew==0 ) return 0;
  76544. pNew->nExpr = i = p->nExpr;
  76545. if( (flags & EXPRDUP_REDUCE)==0 ) for(i=1; i<p->nExpr; i+=i){}
  76546. pNew->a = pItem = sqlite3DbMallocRaw(db, i*sizeof(p->a[0]) );
  76547. if( pItem==0 ){
  76548. sqlite3DbFree(db, pNew);
  76549. return 0;
  76550. }
  76551. pOldItem = p->a;
  76552. for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){
  76553. Expr *pOldExpr = pOldItem->pExpr;
  76554. pItem->pExpr = sqlite3ExprDup(db, pOldExpr, flags);
  76555. pItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
  76556. pItem->zSpan = sqlite3DbStrDup(db, pOldItem->zSpan);
  76557. pItem->sortOrder = pOldItem->sortOrder;
  76558. pItem->done = 0;
  76559. pItem->bSpanIsTab = pOldItem->bSpanIsTab;
  76560. pItem->u = pOldItem->u;
  76561. }
  76562. return pNew;
  76563. }
  76564. /*
  76565. ** If cursors, triggers, views and subqueries are all omitted from
  76566. ** the build, then none of the following routines, except for
  76567. ** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes
  76568. ** called with a NULL argument.
  76569. */
  76570. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \
  76571. || !defined(SQLITE_OMIT_SUBQUERY)
  76572. SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3 *db, SrcList *p, int flags){
  76573. SrcList *pNew;
  76574. int i;
  76575. int nByte;
  76576. if( p==0 ) return 0;
  76577. nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);
  76578. pNew = sqlite3DbMallocRaw(db, nByte );
  76579. if( pNew==0 ) return 0;
  76580. pNew->nSrc = pNew->nAlloc = p->nSrc;
  76581. for(i=0; i<p->nSrc; i++){
  76582. struct SrcList_item *pNewItem = &pNew->a[i];
  76583. struct SrcList_item *pOldItem = &p->a[i];
  76584. Table *pTab;
  76585. pNewItem->pSchema = pOldItem->pSchema;
  76586. pNewItem->zDatabase = sqlite3DbStrDup(db, pOldItem->zDatabase);
  76587. pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
  76588. pNewItem->zAlias = sqlite3DbStrDup(db, pOldItem->zAlias);
  76589. pNewItem->jointype = pOldItem->jointype;
  76590. pNewItem->iCursor = pOldItem->iCursor;
  76591. pNewItem->addrFillSub = pOldItem->addrFillSub;
  76592. pNewItem->regReturn = pOldItem->regReturn;
  76593. pNewItem->isCorrelated = pOldItem->isCorrelated;
  76594. pNewItem->viaCoroutine = pOldItem->viaCoroutine;
  76595. pNewItem->isRecursive = pOldItem->isRecursive;
  76596. pNewItem->zIndex = sqlite3DbStrDup(db, pOldItem->zIndex);
  76597. pNewItem->notIndexed = pOldItem->notIndexed;
  76598. pNewItem->pIndex = pOldItem->pIndex;
  76599. pTab = pNewItem->pTab = pOldItem->pTab;
  76600. if( pTab ){
  76601. pTab->nRef++;
  76602. }
  76603. pNewItem->pSelect = sqlite3SelectDup(db, pOldItem->pSelect, flags);
  76604. pNewItem->pOn = sqlite3ExprDup(db, pOldItem->pOn, flags);
  76605. pNewItem->pUsing = sqlite3IdListDup(db, pOldItem->pUsing);
  76606. pNewItem->colUsed = pOldItem->colUsed;
  76607. }
  76608. return pNew;
  76609. }
  76610. SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3 *db, IdList *p){
  76611. IdList *pNew;
  76612. int i;
  76613. if( p==0 ) return 0;
  76614. pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
  76615. if( pNew==0 ) return 0;
  76616. pNew->nId = p->nId;
  76617. pNew->a = sqlite3DbMallocRaw(db, p->nId*sizeof(p->a[0]) );
  76618. if( pNew->a==0 ){
  76619. sqlite3DbFree(db, pNew);
  76620. return 0;
  76621. }
  76622. /* Note that because the size of the allocation for p->a[] is not
  76623. ** necessarily a power of two, sqlite3IdListAppend() may not be called
  76624. ** on the duplicate created by this function. */
  76625. for(i=0; i<p->nId; i++){
  76626. struct IdList_item *pNewItem = &pNew->a[i];
  76627. struct IdList_item *pOldItem = &p->a[i];
  76628. pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
  76629. pNewItem->idx = pOldItem->idx;
  76630. }
  76631. return pNew;
  76632. }
  76633. SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
  76634. Select *pNew, *pPrior;
  76635. if( p==0 ) return 0;
  76636. pNew = sqlite3DbMallocRaw(db, sizeof(*p) );
  76637. if( pNew==0 ) return 0;
  76638. pNew->pEList = sqlite3ExprListDup(db, p->pEList, flags);
  76639. pNew->pSrc = sqlite3SrcListDup(db, p->pSrc, flags);
  76640. pNew->pWhere = sqlite3ExprDup(db, p->pWhere, flags);
  76641. pNew->pGroupBy = sqlite3ExprListDup(db, p->pGroupBy, flags);
  76642. pNew->pHaving = sqlite3ExprDup(db, p->pHaving, flags);
  76643. pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, flags);
  76644. pNew->op = p->op;
  76645. pNew->pPrior = pPrior = sqlite3SelectDup(db, p->pPrior, flags);
  76646. if( pPrior ) pPrior->pNext = pNew;
  76647. pNew->pNext = 0;
  76648. pNew->pLimit = sqlite3ExprDup(db, p->pLimit, flags);
  76649. pNew->pOffset = sqlite3ExprDup(db, p->pOffset, flags);
  76650. pNew->iLimit = 0;
  76651. pNew->iOffset = 0;
  76652. pNew->selFlags = p->selFlags & ~SF_UsesEphemeral;
  76653. pNew->addrOpenEphm[0] = -1;
  76654. pNew->addrOpenEphm[1] = -1;
  76655. pNew->nSelectRow = p->nSelectRow;
  76656. pNew->pWith = withDup(db, p->pWith);
  76657. sqlite3SelectSetName(pNew, p->zSelName);
  76658. return pNew;
  76659. }
  76660. #else
  76661. SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
  76662. assert( p==0 );
  76663. return 0;
  76664. }
  76665. #endif
  76666. /*
  76667. ** Add a new element to the end of an expression list. If pList is
  76668. ** initially NULL, then create a new expression list.
  76669. **
  76670. ** If a memory allocation error occurs, the entire list is freed and
  76671. ** NULL is returned. If non-NULL is returned, then it is guaranteed
  76672. ** that the new entry was successfully appended.
  76673. */
  76674. SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(
  76675. Parse *pParse, /* Parsing context */
  76676. ExprList *pList, /* List to which to append. Might be NULL */
  76677. Expr *pExpr /* Expression to be appended. Might be NULL */
  76678. ){
  76679. sqlite3 *db = pParse->db;
  76680. if( pList==0 ){
  76681. pList = sqlite3DbMallocZero(db, sizeof(ExprList) );
  76682. if( pList==0 ){
  76683. goto no_mem;
  76684. }
  76685. pList->a = sqlite3DbMallocRaw(db, sizeof(pList->a[0]));
  76686. if( pList->a==0 ) goto no_mem;
  76687. }else if( (pList->nExpr & (pList->nExpr-1))==0 ){
  76688. struct ExprList_item *a;
  76689. assert( pList->nExpr>0 );
  76690. a = sqlite3DbRealloc(db, pList->a, pList->nExpr*2*sizeof(pList->a[0]));
  76691. if( a==0 ){
  76692. goto no_mem;
  76693. }
  76694. pList->a = a;
  76695. }
  76696. assert( pList->a!=0 );
  76697. if( 1 ){
  76698. struct ExprList_item *pItem = &pList->a[pList->nExpr++];
  76699. memset(pItem, 0, sizeof(*pItem));
  76700. pItem->pExpr = pExpr;
  76701. }
  76702. return pList;
  76703. no_mem:
  76704. /* Avoid leaking memory if malloc has failed. */
  76705. sqlite3ExprDelete(db, pExpr);
  76706. sqlite3ExprListDelete(db, pList);
  76707. return 0;
  76708. }
  76709. /*
  76710. ** Set the ExprList.a[].zName element of the most recently added item
  76711. ** on the expression list.
  76712. **
  76713. ** pList might be NULL following an OOM error. But pName should never be
  76714. ** NULL. If a memory allocation fails, the pParse->db->mallocFailed flag
  76715. ** is set.
  76716. */
  76717. SQLITE_PRIVATE void sqlite3ExprListSetName(
  76718. Parse *pParse, /* Parsing context */
  76719. ExprList *pList, /* List to which to add the span. */
  76720. Token *pName, /* Name to be added */
  76721. int dequote /* True to cause the name to be dequoted */
  76722. ){
  76723. assert( pList!=0 || pParse->db->mallocFailed!=0 );
  76724. if( pList ){
  76725. struct ExprList_item *pItem;
  76726. assert( pList->nExpr>0 );
  76727. pItem = &pList->a[pList->nExpr-1];
  76728. assert( pItem->zName==0 );
  76729. pItem->zName = sqlite3DbStrNDup(pParse->db, pName->z, pName->n);
  76730. if( dequote && pItem->zName ) sqlite3Dequote(pItem->zName);
  76731. }
  76732. }
  76733. /*
  76734. ** Set the ExprList.a[].zSpan element of the most recently added item
  76735. ** on the expression list.
  76736. **
  76737. ** pList might be NULL following an OOM error. But pSpan should never be
  76738. ** NULL. If a memory allocation fails, the pParse->db->mallocFailed flag
  76739. ** is set.
  76740. */
  76741. SQLITE_PRIVATE void sqlite3ExprListSetSpan(
  76742. Parse *pParse, /* Parsing context */
  76743. ExprList *pList, /* List to which to add the span. */
  76744. ExprSpan *pSpan /* The span to be added */
  76745. ){
  76746. sqlite3 *db = pParse->db;
  76747. assert( pList!=0 || db->mallocFailed!=0 );
  76748. if( pList ){
  76749. struct ExprList_item *pItem = &pList->a[pList->nExpr-1];
  76750. assert( pList->nExpr>0 );
  76751. assert( db->mallocFailed || pItem->pExpr==pSpan->pExpr );
  76752. sqlite3DbFree(db, pItem->zSpan);
  76753. pItem->zSpan = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
  76754. (int)(pSpan->zEnd - pSpan->zStart));
  76755. }
  76756. }
  76757. /*
  76758. ** If the expression list pEList contains more than iLimit elements,
  76759. ** leave an error message in pParse.
  76760. */
  76761. SQLITE_PRIVATE void sqlite3ExprListCheckLength(
  76762. Parse *pParse,
  76763. ExprList *pEList,
  76764. const char *zObject
  76765. ){
  76766. int mx = pParse->db->aLimit[SQLITE_LIMIT_COLUMN];
  76767. testcase( pEList && pEList->nExpr==mx );
  76768. testcase( pEList && pEList->nExpr==mx+1 );
  76769. if( pEList && pEList->nExpr>mx ){
  76770. sqlite3ErrorMsg(pParse, "too many columns in %s", zObject);
  76771. }
  76772. }
  76773. /*
  76774. ** Delete an entire expression list.
  76775. */
  76776. SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3 *db, ExprList *pList){
  76777. int i;
  76778. struct ExprList_item *pItem;
  76779. if( pList==0 ) return;
  76780. assert( pList->a!=0 || pList->nExpr==0 );
  76781. for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
  76782. sqlite3ExprDelete(db, pItem->pExpr);
  76783. sqlite3DbFree(db, pItem->zName);
  76784. sqlite3DbFree(db, pItem->zSpan);
  76785. }
  76786. sqlite3DbFree(db, pList->a);
  76787. sqlite3DbFree(db, pList);
  76788. }
  76789. /*
  76790. ** These routines are Walker callbacks used to check expressions to
  76791. ** see if they are "constant" for some definition of constant. The
  76792. ** Walker.eCode value determines the type of "constant" we are looking
  76793. ** for.
  76794. **
  76795. ** These callback routines are used to implement the following:
  76796. **
  76797. ** sqlite3ExprIsConstant() pWalker->eCode==1
  76798. ** sqlite3ExprIsConstantNotJoin() pWalker->eCode==2
  76799. ** sqlite3ExprRefOneTableOnly() pWalker->eCode==3
  76800. ** sqlite3ExprIsConstantOrFunction() pWalker->eCode==4 or 5
  76801. **
  76802. ** In all cases, the callbacks set Walker.eCode=0 and abort if the expression
  76803. ** is found to not be a constant.
  76804. **
  76805. ** The sqlite3ExprIsConstantOrFunction() is used for evaluating expressions
  76806. ** in a CREATE TABLE statement. The Walker.eCode value is 5 when parsing
  76807. ** an existing schema and 4 when processing a new statement. A bound
  76808. ** parameter raises an error for new statements, but is silently converted
  76809. ** to NULL for existing schemas. This allows sqlite_master tables that
  76810. ** contain a bound parameter because they were generated by older versions
  76811. ** of SQLite to be parsed by newer versions of SQLite without raising a
  76812. ** malformed schema error.
  76813. */
  76814. static int exprNodeIsConstant(Walker *pWalker, Expr *pExpr){
  76815. /* If pWalker->eCode is 2 then any term of the expression that comes from
  76816. ** the ON or USING clauses of a left join disqualifies the expression
  76817. ** from being considered constant. */
  76818. if( pWalker->eCode==2 && ExprHasProperty(pExpr, EP_FromJoin) ){
  76819. pWalker->eCode = 0;
  76820. return WRC_Abort;
  76821. }
  76822. switch( pExpr->op ){
  76823. /* Consider functions to be constant if all their arguments are constant
  76824. ** and either pWalker->eCode==4 or 5 or the function has the
  76825. ** SQLITE_FUNC_CONST flag. */
  76826. case TK_FUNCTION:
  76827. if( pWalker->eCode>=4 || ExprHasProperty(pExpr,EP_Constant) ){
  76828. return WRC_Continue;
  76829. }else{
  76830. pWalker->eCode = 0;
  76831. return WRC_Abort;
  76832. }
  76833. case TK_ID:
  76834. case TK_COLUMN:
  76835. case TK_AGG_FUNCTION:
  76836. case TK_AGG_COLUMN:
  76837. testcase( pExpr->op==TK_ID );
  76838. testcase( pExpr->op==TK_COLUMN );
  76839. testcase( pExpr->op==TK_AGG_FUNCTION );
  76840. testcase( pExpr->op==TK_AGG_COLUMN );
  76841. if( pWalker->eCode==3 && pExpr->iTable==pWalker->u.iCur ){
  76842. return WRC_Continue;
  76843. }else{
  76844. pWalker->eCode = 0;
  76845. return WRC_Abort;
  76846. }
  76847. case TK_VARIABLE:
  76848. if( pWalker->eCode==5 ){
  76849. /* Silently convert bound parameters that appear inside of CREATE
  76850. ** statements into a NULL when parsing the CREATE statement text out
  76851. ** of the sqlite_master table */
  76852. pExpr->op = TK_NULL;
  76853. }else if( pWalker->eCode==4 ){
  76854. /* A bound parameter in a CREATE statement that originates from
  76855. ** sqlite3_prepare() causes an error */
  76856. pWalker->eCode = 0;
  76857. return WRC_Abort;
  76858. }
  76859. /* Fall through */
  76860. default:
  76861. testcase( pExpr->op==TK_SELECT ); /* selectNodeIsConstant will disallow */
  76862. testcase( pExpr->op==TK_EXISTS ); /* selectNodeIsConstant will disallow */
  76863. return WRC_Continue;
  76864. }
  76865. }
  76866. static int selectNodeIsConstant(Walker *pWalker, Select *NotUsed){
  76867. UNUSED_PARAMETER(NotUsed);
  76868. pWalker->eCode = 0;
  76869. return WRC_Abort;
  76870. }
  76871. static int exprIsConst(Expr *p, int initFlag, int iCur){
  76872. Walker w;
  76873. memset(&w, 0, sizeof(w));
  76874. w.eCode = initFlag;
  76875. w.xExprCallback = exprNodeIsConstant;
  76876. w.xSelectCallback = selectNodeIsConstant;
  76877. w.u.iCur = iCur;
  76878. sqlite3WalkExpr(&w, p);
  76879. return w.eCode;
  76880. }
  76881. /*
  76882. ** Walk an expression tree. Return non-zero if the expression is constant
  76883. ** and 0 if it involves variables or function calls.
  76884. **
  76885. ** For the purposes of this function, a double-quoted string (ex: "abc")
  76886. ** is considered a variable but a single-quoted string (ex: 'abc') is
  76887. ** a constant.
  76888. */
  76889. SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr *p){
  76890. return exprIsConst(p, 1, 0);
  76891. }
  76892. /*
  76893. ** Walk an expression tree. Return non-zero if the expression is constant
  76894. ** that does no originate from the ON or USING clauses of a join.
  76895. ** Return 0 if it involves variables or function calls or terms from
  76896. ** an ON or USING clause.
  76897. */
  76898. SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr *p){
  76899. return exprIsConst(p, 2, 0);
  76900. }
  76901. /*
  76902. ** Walk an expression tree. Return non-zero if the expression constant
  76903. ** for any single row of the table with cursor iCur. In other words, the
  76904. ** expression must not refer to any non-deterministic function nor any
  76905. ** table other than iCur.
  76906. */
  76907. SQLITE_PRIVATE int sqlite3ExprIsTableConstant(Expr *p, int iCur){
  76908. return exprIsConst(p, 3, iCur);
  76909. }
  76910. /*
  76911. ** Walk an expression tree. Return non-zero if the expression is constant
  76912. ** or a function call with constant arguments. Return and 0 if there
  76913. ** are any variables.
  76914. **
  76915. ** For the purposes of this function, a double-quoted string (ex: "abc")
  76916. ** is considered a variable but a single-quoted string (ex: 'abc') is
  76917. ** a constant.
  76918. */
  76919. SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr *p, u8 isInit){
  76920. assert( isInit==0 || isInit==1 );
  76921. return exprIsConst(p, 4+isInit, 0);
  76922. }
  76923. /*
  76924. ** If the expression p codes a constant integer that is small enough
  76925. ** to fit in a 32-bit integer, return 1 and put the value of the integer
  76926. ** in *pValue. If the expression is not an integer or if it is too big
  76927. ** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
  76928. */
  76929. SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr *p, int *pValue){
  76930. int rc = 0;
  76931. /* If an expression is an integer literal that fits in a signed 32-bit
  76932. ** integer, then the EP_IntValue flag will have already been set */
  76933. assert( p->op!=TK_INTEGER || (p->flags & EP_IntValue)!=0
  76934. || sqlite3GetInt32(p->u.zToken, &rc)==0 );
  76935. if( p->flags & EP_IntValue ){
  76936. *pValue = p->u.iValue;
  76937. return 1;
  76938. }
  76939. switch( p->op ){
  76940. case TK_UPLUS: {
  76941. rc = sqlite3ExprIsInteger(p->pLeft, pValue);
  76942. break;
  76943. }
  76944. case TK_UMINUS: {
  76945. int v;
  76946. if( sqlite3ExprIsInteger(p->pLeft, &v) ){
  76947. assert( v!=(-2147483647-1) );
  76948. *pValue = -v;
  76949. rc = 1;
  76950. }
  76951. break;
  76952. }
  76953. default: break;
  76954. }
  76955. return rc;
  76956. }
  76957. /*
  76958. ** Return FALSE if there is no chance that the expression can be NULL.
  76959. **
  76960. ** If the expression might be NULL or if the expression is too complex
  76961. ** to tell return TRUE.
  76962. **
  76963. ** This routine is used as an optimization, to skip OP_IsNull opcodes
  76964. ** when we know that a value cannot be NULL. Hence, a false positive
  76965. ** (returning TRUE when in fact the expression can never be NULL) might
  76966. ** be a small performance hit but is otherwise harmless. On the other
  76967. ** hand, a false negative (returning FALSE when the result could be NULL)
  76968. ** will likely result in an incorrect answer. So when in doubt, return
  76969. ** TRUE.
  76970. */
  76971. SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr *p){
  76972. u8 op;
  76973. while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
  76974. op = p->op;
  76975. if( op==TK_REGISTER ) op = p->op2;
  76976. switch( op ){
  76977. case TK_INTEGER:
  76978. case TK_STRING:
  76979. case TK_FLOAT:
  76980. case TK_BLOB:
  76981. return 0;
  76982. case TK_COLUMN:
  76983. assert( p->pTab!=0 );
  76984. return p->iColumn>=0 && p->pTab->aCol[p->iColumn].notNull==0;
  76985. default:
  76986. return 1;
  76987. }
  76988. }
  76989. /*
  76990. ** Return TRUE if the given expression is a constant which would be
  76991. ** unchanged by OP_Affinity with the affinity given in the second
  76992. ** argument.
  76993. **
  76994. ** This routine is used to determine if the OP_Affinity operation
  76995. ** can be omitted. When in doubt return FALSE. A false negative
  76996. ** is harmless. A false positive, however, can result in the wrong
  76997. ** answer.
  76998. */
  76999. SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr *p, char aff){
  77000. u8 op;
  77001. if( aff==SQLITE_AFF_NONE ) return 1;
  77002. while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
  77003. op = p->op;
  77004. if( op==TK_REGISTER ) op = p->op2;
  77005. switch( op ){
  77006. case TK_INTEGER: {
  77007. return aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC;
  77008. }
  77009. case TK_FLOAT: {
  77010. return aff==SQLITE_AFF_REAL || aff==SQLITE_AFF_NUMERIC;
  77011. }
  77012. case TK_STRING: {
  77013. return aff==SQLITE_AFF_TEXT;
  77014. }
  77015. case TK_BLOB: {
  77016. return 1;
  77017. }
  77018. case TK_COLUMN: {
  77019. assert( p->iTable>=0 ); /* p cannot be part of a CHECK constraint */
  77020. return p->iColumn<0
  77021. && (aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC);
  77022. }
  77023. default: {
  77024. return 0;
  77025. }
  77026. }
  77027. }
  77028. /*
  77029. ** Return TRUE if the given string is a row-id column name.
  77030. */
  77031. SQLITE_PRIVATE int sqlite3IsRowid(const char *z){
  77032. if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1;
  77033. if( sqlite3StrICmp(z, "ROWID")==0 ) return 1;
  77034. if( sqlite3StrICmp(z, "OID")==0 ) return 1;
  77035. return 0;
  77036. }
  77037. /*
  77038. ** Return true if we are able to the IN operator optimization on a
  77039. ** query of the form
  77040. **
  77041. ** x IN (SELECT ...)
  77042. **
  77043. ** Where the SELECT... clause is as specified by the parameter to this
  77044. ** routine.
  77045. **
  77046. ** The Select object passed in has already been preprocessed and no
  77047. ** errors have been found.
  77048. */
  77049. #ifndef SQLITE_OMIT_SUBQUERY
  77050. static int isCandidateForInOpt(Select *p){
  77051. SrcList *pSrc;
  77052. ExprList *pEList;
  77053. Table *pTab;
  77054. if( p==0 ) return 0; /* right-hand side of IN is SELECT */
  77055. if( p->pPrior ) return 0; /* Not a compound SELECT */
  77056. if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
  77057. testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
  77058. testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
  77059. return 0; /* No DISTINCT keyword and no aggregate functions */
  77060. }
  77061. assert( p->pGroupBy==0 ); /* Has no GROUP BY clause */
  77062. if( p->pLimit ) return 0; /* Has no LIMIT clause */
  77063. assert( p->pOffset==0 ); /* No LIMIT means no OFFSET */
  77064. if( p->pWhere ) return 0; /* Has no WHERE clause */
  77065. pSrc = p->pSrc;
  77066. assert( pSrc!=0 );
  77067. if( pSrc->nSrc!=1 ) return 0; /* Single term in FROM clause */
  77068. if( pSrc->a[0].pSelect ) return 0; /* FROM is not a subquery or view */
  77069. pTab = pSrc->a[0].pTab;
  77070. if( NEVER(pTab==0) ) return 0;
  77071. assert( pTab->pSelect==0 ); /* FROM clause is not a view */
  77072. if( IsVirtual(pTab) ) return 0; /* FROM clause not a virtual table */
  77073. pEList = p->pEList;
  77074. if( pEList->nExpr!=1 ) return 0; /* One column in the result set */
  77075. if( pEList->a[0].pExpr->op!=TK_COLUMN ) return 0; /* Result is a column */
  77076. return 1;
  77077. }
  77078. #endif /* SQLITE_OMIT_SUBQUERY */
  77079. /*
  77080. ** Code an OP_Once instruction and allocate space for its flag. Return the
  77081. ** address of the new instruction.
  77082. */
  77083. SQLITE_PRIVATE int sqlite3CodeOnce(Parse *pParse){
  77084. Vdbe *v = sqlite3GetVdbe(pParse); /* Virtual machine being coded */
  77085. return sqlite3VdbeAddOp1(v, OP_Once, pParse->nOnce++);
  77086. }
  77087. /*
  77088. ** Generate code that checks the left-most column of index table iCur to see if
  77089. ** it contains any NULL entries. Cause the register at regHasNull to be set
  77090. ** to a non-NULL value if iCur contains no NULLs. Cause register regHasNull
  77091. ** to be set to NULL if iCur contains one or more NULL values.
  77092. */
  77093. static void sqlite3SetHasNullFlag(Vdbe *v, int iCur, int regHasNull){
  77094. int j1;
  77095. sqlite3VdbeAddOp2(v, OP_Integer, 0, regHasNull);
  77096. j1 = sqlite3VdbeAddOp1(v, OP_Rewind, iCur); VdbeCoverage(v);
  77097. sqlite3VdbeAddOp3(v, OP_Column, iCur, 0, regHasNull);
  77098. sqlite3VdbeChangeP5(v, OPFLAG_TYPEOFARG);
  77099. VdbeComment((v, "first_entry_in(%d)", iCur));
  77100. sqlite3VdbeJumpHere(v, j1);
  77101. }
  77102. #ifndef SQLITE_OMIT_SUBQUERY
  77103. /*
  77104. ** The argument is an IN operator with a list (not a subquery) on the
  77105. ** right-hand side. Return TRUE if that list is constant.
  77106. */
  77107. static int sqlite3InRhsIsConstant(Expr *pIn){
  77108. Expr *pLHS;
  77109. int res;
  77110. assert( !ExprHasProperty(pIn, EP_xIsSelect) );
  77111. pLHS = pIn->pLeft;
  77112. pIn->pLeft = 0;
  77113. res = sqlite3ExprIsConstant(pIn);
  77114. pIn->pLeft = pLHS;
  77115. return res;
  77116. }
  77117. #endif
  77118. /*
  77119. ** This function is used by the implementation of the IN (...) operator.
  77120. ** The pX parameter is the expression on the RHS of the IN operator, which
  77121. ** might be either a list of expressions or a subquery.
  77122. **
  77123. ** The job of this routine is to find or create a b-tree object that can
  77124. ** be used either to test for membership in the RHS set or to iterate through
  77125. ** all members of the RHS set, skipping duplicates.
  77126. **
  77127. ** A cursor is opened on the b-tree object that is the RHS of the IN operator
  77128. ** and pX->iTable is set to the index of that cursor.
  77129. **
  77130. ** The returned value of this function indicates the b-tree type, as follows:
  77131. **
  77132. ** IN_INDEX_ROWID - The cursor was opened on a database table.
  77133. ** IN_INDEX_INDEX_ASC - The cursor was opened on an ascending index.
  77134. ** IN_INDEX_INDEX_DESC - The cursor was opened on a descending index.
  77135. ** IN_INDEX_EPH - The cursor was opened on a specially created and
  77136. ** populated epheremal table.
  77137. ** IN_INDEX_NOOP - No cursor was allocated. The IN operator must be
  77138. ** implemented as a sequence of comparisons.
  77139. **
  77140. ** An existing b-tree might be used if the RHS expression pX is a simple
  77141. ** subquery such as:
  77142. **
  77143. ** SELECT <column> FROM <table>
  77144. **
  77145. ** If the RHS of the IN operator is a list or a more complex subquery, then
  77146. ** an ephemeral table might need to be generated from the RHS and then
  77147. ** pX->iTable made to point to the ephemeral table instead of an
  77148. ** existing table.
  77149. **
  77150. ** The inFlags parameter must contain exactly one of the bits
  77151. ** IN_INDEX_MEMBERSHIP or IN_INDEX_LOOP. If inFlags contains
  77152. ** IN_INDEX_MEMBERSHIP, then the generated table will be used for a
  77153. ** fast membership test. When the IN_INDEX_LOOP bit is set, the
  77154. ** IN index will be used to loop over all values of the RHS of the
  77155. ** IN operator.
  77156. **
  77157. ** When IN_INDEX_LOOP is used (and the b-tree will be used to iterate
  77158. ** through the set members) then the b-tree must not contain duplicates.
  77159. ** An epheremal table must be used unless the selected <column> is guaranteed
  77160. ** to be unique - either because it is an INTEGER PRIMARY KEY or it
  77161. ** has a UNIQUE constraint or UNIQUE index.
  77162. **
  77163. ** When IN_INDEX_MEMBERSHIP is used (and the b-tree will be used
  77164. ** for fast set membership tests) then an epheremal table must
  77165. ** be used unless <column> is an INTEGER PRIMARY KEY or an index can
  77166. ** be found with <column> as its left-most column.
  77167. **
  77168. ** If the IN_INDEX_NOOP_OK and IN_INDEX_MEMBERSHIP are both set and
  77169. ** if the RHS of the IN operator is a list (not a subquery) then this
  77170. ** routine might decide that creating an ephemeral b-tree for membership
  77171. ** testing is too expensive and return IN_INDEX_NOOP. In that case, the
  77172. ** calling routine should implement the IN operator using a sequence
  77173. ** of Eq or Ne comparison operations.
  77174. **
  77175. ** When the b-tree is being used for membership tests, the calling function
  77176. ** might need to know whether or not the RHS side of the IN operator
  77177. ** contains a NULL. If prRhsHasNull is not a NULL pointer and
  77178. ** if there is any chance that the (...) might contain a NULL value at
  77179. ** runtime, then a register is allocated and the register number written
  77180. ** to *prRhsHasNull. If there is no chance that the (...) contains a
  77181. ** NULL value, then *prRhsHasNull is left unchanged.
  77182. **
  77183. ** If a register is allocated and its location stored in *prRhsHasNull, then
  77184. ** the value in that register will be NULL if the b-tree contains one or more
  77185. ** NULL values, and it will be some non-NULL value if the b-tree contains no
  77186. ** NULL values.
  77187. */
  77188. #ifndef SQLITE_OMIT_SUBQUERY
  77189. SQLITE_PRIVATE int sqlite3FindInIndex(Parse *pParse, Expr *pX, u32 inFlags, int *prRhsHasNull){
  77190. Select *p; /* SELECT to the right of IN operator */
  77191. int eType = 0; /* Type of RHS table. IN_INDEX_* */
  77192. int iTab = pParse->nTab++; /* Cursor of the RHS table */
  77193. int mustBeUnique; /* True if RHS must be unique */
  77194. Vdbe *v = sqlite3GetVdbe(pParse); /* Virtual machine being coded */
  77195. assert( pX->op==TK_IN );
  77196. mustBeUnique = (inFlags & IN_INDEX_LOOP)!=0;
  77197. /* Check to see if an existing table or index can be used to
  77198. ** satisfy the query. This is preferable to generating a new
  77199. ** ephemeral table.
  77200. */
  77201. p = (ExprHasProperty(pX, EP_xIsSelect) ? pX->x.pSelect : 0);
  77202. if( ALWAYS(pParse->nErr==0) && isCandidateForInOpt(p) ){
  77203. sqlite3 *db = pParse->db; /* Database connection */
  77204. Table *pTab; /* Table <table>. */
  77205. Expr *pExpr; /* Expression <column> */
  77206. i16 iCol; /* Index of column <column> */
  77207. i16 iDb; /* Database idx for pTab */
  77208. assert( p ); /* Because of isCandidateForInOpt(p) */
  77209. assert( p->pEList!=0 ); /* Because of isCandidateForInOpt(p) */
  77210. assert( p->pEList->a[0].pExpr!=0 ); /* Because of isCandidateForInOpt(p) */
  77211. assert( p->pSrc!=0 ); /* Because of isCandidateForInOpt(p) */
  77212. pTab = p->pSrc->a[0].pTab;
  77213. pExpr = p->pEList->a[0].pExpr;
  77214. iCol = (i16)pExpr->iColumn;
  77215. /* Code an OP_Transaction and OP_TableLock for <table>. */
  77216. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  77217. sqlite3CodeVerifySchema(pParse, iDb);
  77218. sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
  77219. /* This function is only called from two places. In both cases the vdbe
  77220. ** has already been allocated. So assume sqlite3GetVdbe() is always
  77221. ** successful here.
  77222. */
  77223. assert(v);
  77224. if( iCol<0 ){
  77225. int iAddr = sqlite3CodeOnce(pParse);
  77226. VdbeCoverage(v);
  77227. sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
  77228. eType = IN_INDEX_ROWID;
  77229. sqlite3VdbeJumpHere(v, iAddr);
  77230. }else{
  77231. Index *pIdx; /* Iterator variable */
  77232. /* The collation sequence used by the comparison. If an index is to
  77233. ** be used in place of a temp-table, it must be ordered according
  77234. ** to this collation sequence. */
  77235. CollSeq *pReq = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pExpr);
  77236. /* Check that the affinity that will be used to perform the
  77237. ** comparison is the same as the affinity of the column. If
  77238. ** it is not, it is not possible to use any index.
  77239. */
  77240. int affinity_ok = sqlite3IndexAffinityOk(pX, pTab->aCol[iCol].affinity);
  77241. for(pIdx=pTab->pIndex; pIdx && eType==0 && affinity_ok; pIdx=pIdx->pNext){
  77242. if( (pIdx->aiColumn[0]==iCol)
  77243. && sqlite3FindCollSeq(db, ENC(db), pIdx->azColl[0], 0)==pReq
  77244. && (!mustBeUnique || (pIdx->nKeyCol==1 && IsUniqueIndex(pIdx)))
  77245. ){
  77246. int iAddr = sqlite3CodeOnce(pParse); VdbeCoverage(v);
  77247. sqlite3VdbeAddOp3(v, OP_OpenRead, iTab, pIdx->tnum, iDb);
  77248. sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
  77249. VdbeComment((v, "%s", pIdx->zName));
  77250. assert( IN_INDEX_INDEX_DESC == IN_INDEX_INDEX_ASC+1 );
  77251. eType = IN_INDEX_INDEX_ASC + pIdx->aSortOrder[0];
  77252. if( prRhsHasNull && !pTab->aCol[iCol].notNull ){
  77253. *prRhsHasNull = ++pParse->nMem;
  77254. sqlite3SetHasNullFlag(v, iTab, *prRhsHasNull);
  77255. }
  77256. sqlite3VdbeJumpHere(v, iAddr);
  77257. }
  77258. }
  77259. }
  77260. }
  77261. /* If no preexisting index is available for the IN clause
  77262. ** and IN_INDEX_NOOP is an allowed reply
  77263. ** and the RHS of the IN operator is a list, not a subquery
  77264. ** and the RHS is not contant or has two or fewer terms,
  77265. ** then it is not worth creating an ephemeral table to evaluate
  77266. ** the IN operator so return IN_INDEX_NOOP.
  77267. */
  77268. if( eType==0
  77269. && (inFlags & IN_INDEX_NOOP_OK)
  77270. && !ExprHasProperty(pX, EP_xIsSelect)
  77271. && (!sqlite3InRhsIsConstant(pX) || pX->x.pList->nExpr<=2)
  77272. ){
  77273. eType = IN_INDEX_NOOP;
  77274. }
  77275. if( eType==0 ){
  77276. /* Could not find an existing table or index to use as the RHS b-tree.
  77277. ** We will have to generate an ephemeral table to do the job.
  77278. */
  77279. u32 savedNQueryLoop = pParse->nQueryLoop;
  77280. int rMayHaveNull = 0;
  77281. eType = IN_INDEX_EPH;
  77282. if( inFlags & IN_INDEX_LOOP ){
  77283. pParse->nQueryLoop = 0;
  77284. if( pX->pLeft->iColumn<0 && !ExprHasProperty(pX, EP_xIsSelect) ){
  77285. eType = IN_INDEX_ROWID;
  77286. }
  77287. }else if( prRhsHasNull ){
  77288. *prRhsHasNull = rMayHaveNull = ++pParse->nMem;
  77289. }
  77290. sqlite3CodeSubselect(pParse, pX, rMayHaveNull, eType==IN_INDEX_ROWID);
  77291. pParse->nQueryLoop = savedNQueryLoop;
  77292. }else{
  77293. pX->iTable = iTab;
  77294. }
  77295. return eType;
  77296. }
  77297. #endif
  77298. /*
  77299. ** Generate code for scalar subqueries used as a subquery expression, EXISTS,
  77300. ** or IN operators. Examples:
  77301. **
  77302. ** (SELECT a FROM b) -- subquery
  77303. ** EXISTS (SELECT a FROM b) -- EXISTS subquery
  77304. ** x IN (4,5,11) -- IN operator with list on right-hand side
  77305. ** x IN (SELECT a FROM b) -- IN operator with subquery on the right
  77306. **
  77307. ** The pExpr parameter describes the expression that contains the IN
  77308. ** operator or subquery.
  77309. **
  77310. ** If parameter isRowid is non-zero, then expression pExpr is guaranteed
  77311. ** to be of the form "<rowid> IN (?, ?, ?)", where <rowid> is a reference
  77312. ** to some integer key column of a table B-Tree. In this case, use an
  77313. ** intkey B-Tree to store the set of IN(...) values instead of the usual
  77314. ** (slower) variable length keys B-Tree.
  77315. **
  77316. ** If rMayHaveNull is non-zero, that means that the operation is an IN
  77317. ** (not a SELECT or EXISTS) and that the RHS might contains NULLs.
  77318. ** All this routine does is initialize the register given by rMayHaveNull
  77319. ** to NULL. Calling routines will take care of changing this register
  77320. ** value to non-NULL if the RHS is NULL-free.
  77321. **
  77322. ** For a SELECT or EXISTS operator, return the register that holds the
  77323. ** result. For IN operators or if an error occurs, the return value is 0.
  77324. */
  77325. #ifndef SQLITE_OMIT_SUBQUERY
  77326. SQLITE_PRIVATE int sqlite3CodeSubselect(
  77327. Parse *pParse, /* Parsing context */
  77328. Expr *pExpr, /* The IN, SELECT, or EXISTS operator */
  77329. int rHasNullFlag, /* Register that records whether NULLs exist in RHS */
  77330. int isRowid /* If true, LHS of IN operator is a rowid */
  77331. ){
  77332. int jmpIfDynamic = -1; /* One-time test address */
  77333. int rReg = 0; /* Register storing resulting */
  77334. Vdbe *v = sqlite3GetVdbe(pParse);
  77335. if( NEVER(v==0) ) return 0;
  77336. sqlite3ExprCachePush(pParse);
  77337. /* This code must be run in its entirety every time it is encountered
  77338. ** if any of the following is true:
  77339. **
  77340. ** * The right-hand side is a correlated subquery
  77341. ** * The right-hand side is an expression list containing variables
  77342. ** * We are inside a trigger
  77343. **
  77344. ** If all of the above are false, then we can run this code just once
  77345. ** save the results, and reuse the same result on subsequent invocations.
  77346. */
  77347. if( !ExprHasProperty(pExpr, EP_VarSelect) ){
  77348. jmpIfDynamic = sqlite3CodeOnce(pParse); VdbeCoverage(v);
  77349. }
  77350. #ifndef SQLITE_OMIT_EXPLAIN
  77351. if( pParse->explain==2 ){
  77352. char *zMsg = sqlite3MPrintf(
  77353. pParse->db, "EXECUTE %s%s SUBQUERY %d", jmpIfDynamic>=0?"":"CORRELATED ",
  77354. pExpr->op==TK_IN?"LIST":"SCALAR", pParse->iNextSelectId
  77355. );
  77356. sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
  77357. }
  77358. #endif
  77359. switch( pExpr->op ){
  77360. case TK_IN: {
  77361. char affinity; /* Affinity of the LHS of the IN */
  77362. int addr; /* Address of OP_OpenEphemeral instruction */
  77363. Expr *pLeft = pExpr->pLeft; /* the LHS of the IN operator */
  77364. KeyInfo *pKeyInfo = 0; /* Key information */
  77365. affinity = sqlite3ExprAffinity(pLeft);
  77366. /* Whether this is an 'x IN(SELECT...)' or an 'x IN(<exprlist>)'
  77367. ** expression it is handled the same way. An ephemeral table is
  77368. ** filled with single-field index keys representing the results
  77369. ** from the SELECT or the <exprlist>.
  77370. **
  77371. ** If the 'x' expression is a column value, or the SELECT...
  77372. ** statement returns a column value, then the affinity of that
  77373. ** column is used to build the index keys. If both 'x' and the
  77374. ** SELECT... statement are columns, then numeric affinity is used
  77375. ** if either column has NUMERIC or INTEGER affinity. If neither
  77376. ** 'x' nor the SELECT... statement are columns, then numeric affinity
  77377. ** is used.
  77378. */
  77379. pExpr->iTable = pParse->nTab++;
  77380. addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pExpr->iTable, !isRowid);
  77381. pKeyInfo = isRowid ? 0 : sqlite3KeyInfoAlloc(pParse->db, 1, 1);
  77382. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  77383. /* Case 1: expr IN (SELECT ...)
  77384. **
  77385. ** Generate code to write the results of the select into the temporary
  77386. ** table allocated and opened above.
  77387. */
  77388. Select *pSelect = pExpr->x.pSelect;
  77389. SelectDest dest;
  77390. ExprList *pEList;
  77391. assert( !isRowid );
  77392. sqlite3SelectDestInit(&dest, SRT_Set, pExpr->iTable);
  77393. dest.affSdst = (u8)affinity;
  77394. assert( (pExpr->iTable&0x0000FFFF)==pExpr->iTable );
  77395. pSelect->iLimit = 0;
  77396. testcase( pSelect->selFlags & SF_Distinct );
  77397. pSelect->selFlags &= ~SF_Distinct;
  77398. testcase( pKeyInfo==0 ); /* Caused by OOM in sqlite3KeyInfoAlloc() */
  77399. if( sqlite3Select(pParse, pSelect, &dest) ){
  77400. sqlite3KeyInfoUnref(pKeyInfo);
  77401. return 0;
  77402. }
  77403. pEList = pSelect->pEList;
  77404. assert( pKeyInfo!=0 ); /* OOM will cause exit after sqlite3Select() */
  77405. assert( pEList!=0 );
  77406. assert( pEList->nExpr>0 );
  77407. assert( sqlite3KeyInfoIsWriteable(pKeyInfo) );
  77408. pKeyInfo->aColl[0] = sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft,
  77409. pEList->a[0].pExpr);
  77410. }else if( ALWAYS(pExpr->x.pList!=0) ){
  77411. /* Case 2: expr IN (exprlist)
  77412. **
  77413. ** For each expression, build an index key from the evaluation and
  77414. ** store it in the temporary table. If <expr> is a column, then use
  77415. ** that columns affinity when building index keys. If <expr> is not
  77416. ** a column, use numeric affinity.
  77417. */
  77418. int i;
  77419. ExprList *pList = pExpr->x.pList;
  77420. struct ExprList_item *pItem;
  77421. int r1, r2, r3;
  77422. if( !affinity ){
  77423. affinity = SQLITE_AFF_NONE;
  77424. }
  77425. if( pKeyInfo ){
  77426. assert( sqlite3KeyInfoIsWriteable(pKeyInfo) );
  77427. pKeyInfo->aColl[0] = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
  77428. }
  77429. /* Loop through each expression in <exprlist>. */
  77430. r1 = sqlite3GetTempReg(pParse);
  77431. r2 = sqlite3GetTempReg(pParse);
  77432. if( isRowid ) sqlite3VdbeAddOp2(v, OP_Null, 0, r2);
  77433. for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){
  77434. Expr *pE2 = pItem->pExpr;
  77435. int iValToIns;
  77436. /* If the expression is not constant then we will need to
  77437. ** disable the test that was generated above that makes sure
  77438. ** this code only executes once. Because for a non-constant
  77439. ** expression we need to rerun this code each time.
  77440. */
  77441. if( jmpIfDynamic>=0 && !sqlite3ExprIsConstant(pE2) ){
  77442. sqlite3VdbeChangeToNoop(v, jmpIfDynamic);
  77443. jmpIfDynamic = -1;
  77444. }
  77445. /* Evaluate the expression and insert it into the temp table */
  77446. if( isRowid && sqlite3ExprIsInteger(pE2, &iValToIns) ){
  77447. sqlite3VdbeAddOp3(v, OP_InsertInt, pExpr->iTable, r2, iValToIns);
  77448. }else{
  77449. r3 = sqlite3ExprCodeTarget(pParse, pE2, r1);
  77450. if( isRowid ){
  77451. sqlite3VdbeAddOp2(v, OP_MustBeInt, r3,
  77452. sqlite3VdbeCurrentAddr(v)+2);
  77453. VdbeCoverage(v);
  77454. sqlite3VdbeAddOp3(v, OP_Insert, pExpr->iTable, r2, r3);
  77455. }else{
  77456. sqlite3VdbeAddOp4(v, OP_MakeRecord, r3, 1, r2, &affinity, 1);
  77457. sqlite3ExprCacheAffinityChange(pParse, r3, 1);
  77458. sqlite3VdbeAddOp2(v, OP_IdxInsert, pExpr->iTable, r2);
  77459. }
  77460. }
  77461. }
  77462. sqlite3ReleaseTempReg(pParse, r1);
  77463. sqlite3ReleaseTempReg(pParse, r2);
  77464. }
  77465. if( pKeyInfo ){
  77466. sqlite3VdbeChangeP4(v, addr, (void *)pKeyInfo, P4_KEYINFO);
  77467. }
  77468. break;
  77469. }
  77470. case TK_EXISTS:
  77471. case TK_SELECT:
  77472. default: {
  77473. /* If this has to be a scalar SELECT. Generate code to put the
  77474. ** value of this select in a memory cell and record the number
  77475. ** of the memory cell in iColumn. If this is an EXISTS, write
  77476. ** an integer 0 (not exists) or 1 (exists) into a memory cell
  77477. ** and record that memory cell in iColumn.
  77478. */
  77479. Select *pSel; /* SELECT statement to encode */
  77480. SelectDest dest; /* How to deal with SELECt result */
  77481. testcase( pExpr->op==TK_EXISTS );
  77482. testcase( pExpr->op==TK_SELECT );
  77483. assert( pExpr->op==TK_EXISTS || pExpr->op==TK_SELECT );
  77484. assert( ExprHasProperty(pExpr, EP_xIsSelect) );
  77485. pSel = pExpr->x.pSelect;
  77486. sqlite3SelectDestInit(&dest, 0, ++pParse->nMem);
  77487. if( pExpr->op==TK_SELECT ){
  77488. dest.eDest = SRT_Mem;
  77489. dest.iSdst = dest.iSDParm;
  77490. sqlite3VdbeAddOp2(v, OP_Null, 0, dest.iSDParm);
  77491. VdbeComment((v, "Init subquery result"));
  77492. }else{
  77493. dest.eDest = SRT_Exists;
  77494. sqlite3VdbeAddOp2(v, OP_Integer, 0, dest.iSDParm);
  77495. VdbeComment((v, "Init EXISTS result"));
  77496. }
  77497. sqlite3ExprDelete(pParse->db, pSel->pLimit);
  77498. pSel->pLimit = sqlite3PExpr(pParse, TK_INTEGER, 0, 0,
  77499. &sqlite3IntTokens[1]);
  77500. pSel->iLimit = 0;
  77501. if( sqlite3Select(pParse, pSel, &dest) ){
  77502. return 0;
  77503. }
  77504. rReg = dest.iSDParm;
  77505. ExprSetVVAProperty(pExpr, EP_NoReduce);
  77506. break;
  77507. }
  77508. }
  77509. if( rHasNullFlag ){
  77510. sqlite3SetHasNullFlag(v, pExpr->iTable, rHasNullFlag);
  77511. }
  77512. if( jmpIfDynamic>=0 ){
  77513. sqlite3VdbeJumpHere(v, jmpIfDynamic);
  77514. }
  77515. sqlite3ExprCachePop(pParse);
  77516. return rReg;
  77517. }
  77518. #endif /* SQLITE_OMIT_SUBQUERY */
  77519. #ifndef SQLITE_OMIT_SUBQUERY
  77520. /*
  77521. ** Generate code for an IN expression.
  77522. **
  77523. ** x IN (SELECT ...)
  77524. ** x IN (value, value, ...)
  77525. **
  77526. ** The left-hand side (LHS) is a scalar expression. The right-hand side (RHS)
  77527. ** is an array of zero or more values. The expression is true if the LHS is
  77528. ** contained within the RHS. The value of the expression is unknown (NULL)
  77529. ** if the LHS is NULL or if the LHS is not contained within the RHS and the
  77530. ** RHS contains one or more NULL values.
  77531. **
  77532. ** This routine generates code that jumps to destIfFalse if the LHS is not
  77533. ** contained within the RHS. If due to NULLs we cannot determine if the LHS
  77534. ** is contained in the RHS then jump to destIfNull. If the LHS is contained
  77535. ** within the RHS then fall through.
  77536. */
  77537. static void sqlite3ExprCodeIN(
  77538. Parse *pParse, /* Parsing and code generating context */
  77539. Expr *pExpr, /* The IN expression */
  77540. int destIfFalse, /* Jump here if LHS is not contained in the RHS */
  77541. int destIfNull /* Jump here if the results are unknown due to NULLs */
  77542. ){
  77543. int rRhsHasNull = 0; /* Register that is true if RHS contains NULL values */
  77544. char affinity; /* Comparison affinity to use */
  77545. int eType; /* Type of the RHS */
  77546. int r1; /* Temporary use register */
  77547. Vdbe *v; /* Statement under construction */
  77548. /* Compute the RHS. After this step, the table with cursor
  77549. ** pExpr->iTable will contains the values that make up the RHS.
  77550. */
  77551. v = pParse->pVdbe;
  77552. assert( v!=0 ); /* OOM detected prior to this routine */
  77553. VdbeNoopComment((v, "begin IN expr"));
  77554. eType = sqlite3FindInIndex(pParse, pExpr,
  77555. IN_INDEX_MEMBERSHIP | IN_INDEX_NOOP_OK,
  77556. destIfFalse==destIfNull ? 0 : &rRhsHasNull);
  77557. /* Figure out the affinity to use to create a key from the results
  77558. ** of the expression. affinityStr stores a static string suitable for
  77559. ** P4 of OP_MakeRecord.
  77560. */
  77561. affinity = comparisonAffinity(pExpr);
  77562. /* Code the LHS, the <expr> from "<expr> IN (...)".
  77563. */
  77564. sqlite3ExprCachePush(pParse);
  77565. r1 = sqlite3GetTempReg(pParse);
  77566. sqlite3ExprCode(pParse, pExpr->pLeft, r1);
  77567. /* If sqlite3FindInIndex() did not find or create an index that is
  77568. ** suitable for evaluating the IN operator, then evaluate using a
  77569. ** sequence of comparisons.
  77570. */
  77571. if( eType==IN_INDEX_NOOP ){
  77572. ExprList *pList = pExpr->x.pList;
  77573. CollSeq *pColl = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
  77574. int labelOk = sqlite3VdbeMakeLabel(v);
  77575. int r2, regToFree;
  77576. int regCkNull = 0;
  77577. int ii;
  77578. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  77579. if( destIfNull!=destIfFalse ){
  77580. regCkNull = sqlite3GetTempReg(pParse);
  77581. sqlite3VdbeAddOp3(v, OP_BitAnd, r1, r1, regCkNull);
  77582. }
  77583. for(ii=0; ii<pList->nExpr; ii++){
  77584. r2 = sqlite3ExprCodeTemp(pParse, pList->a[ii].pExpr, &regToFree);
  77585. if( regCkNull && sqlite3ExprCanBeNull(pList->a[ii].pExpr) ){
  77586. sqlite3VdbeAddOp3(v, OP_BitAnd, regCkNull, r2, regCkNull);
  77587. }
  77588. if( ii<pList->nExpr-1 || destIfNull!=destIfFalse ){
  77589. sqlite3VdbeAddOp4(v, OP_Eq, r1, labelOk, r2,
  77590. (void*)pColl, P4_COLLSEQ);
  77591. VdbeCoverageIf(v, ii<pList->nExpr-1);
  77592. VdbeCoverageIf(v, ii==pList->nExpr-1);
  77593. sqlite3VdbeChangeP5(v, affinity);
  77594. }else{
  77595. assert( destIfNull==destIfFalse );
  77596. sqlite3VdbeAddOp4(v, OP_Ne, r1, destIfFalse, r2,
  77597. (void*)pColl, P4_COLLSEQ); VdbeCoverage(v);
  77598. sqlite3VdbeChangeP5(v, affinity | SQLITE_JUMPIFNULL);
  77599. }
  77600. sqlite3ReleaseTempReg(pParse, regToFree);
  77601. }
  77602. if( regCkNull ){
  77603. sqlite3VdbeAddOp2(v, OP_IsNull, regCkNull, destIfNull); VdbeCoverage(v);
  77604. sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfFalse);
  77605. }
  77606. sqlite3VdbeResolveLabel(v, labelOk);
  77607. sqlite3ReleaseTempReg(pParse, regCkNull);
  77608. }else{
  77609. /* If the LHS is NULL, then the result is either false or NULL depending
  77610. ** on whether the RHS is empty or not, respectively.
  77611. */
  77612. if( sqlite3ExprCanBeNull(pExpr->pLeft) ){
  77613. if( destIfNull==destIfFalse ){
  77614. /* Shortcut for the common case where the false and NULL outcomes are
  77615. ** the same. */
  77616. sqlite3VdbeAddOp2(v, OP_IsNull, r1, destIfNull); VdbeCoverage(v);
  77617. }else{
  77618. int addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, r1); VdbeCoverage(v);
  77619. sqlite3VdbeAddOp2(v, OP_Rewind, pExpr->iTable, destIfFalse);
  77620. VdbeCoverage(v);
  77621. sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfNull);
  77622. sqlite3VdbeJumpHere(v, addr1);
  77623. }
  77624. }
  77625. if( eType==IN_INDEX_ROWID ){
  77626. /* In this case, the RHS is the ROWID of table b-tree
  77627. */
  77628. sqlite3VdbeAddOp2(v, OP_MustBeInt, r1, destIfFalse); VdbeCoverage(v);
  77629. sqlite3VdbeAddOp3(v, OP_NotExists, pExpr->iTable, destIfFalse, r1);
  77630. VdbeCoverage(v);
  77631. }else{
  77632. /* In this case, the RHS is an index b-tree.
  77633. */
  77634. sqlite3VdbeAddOp4(v, OP_Affinity, r1, 1, 0, &affinity, 1);
  77635. /* If the set membership test fails, then the result of the
  77636. ** "x IN (...)" expression must be either 0 or NULL. If the set
  77637. ** contains no NULL values, then the result is 0. If the set
  77638. ** contains one or more NULL values, then the result of the
  77639. ** expression is also NULL.
  77640. */
  77641. assert( destIfFalse!=destIfNull || rRhsHasNull==0 );
  77642. if( rRhsHasNull==0 ){
  77643. /* This branch runs if it is known at compile time that the RHS
  77644. ** cannot contain NULL values. This happens as the result
  77645. ** of a "NOT NULL" constraint in the database schema.
  77646. **
  77647. ** Also run this branch if NULL is equivalent to FALSE
  77648. ** for this particular IN operator.
  77649. */
  77650. sqlite3VdbeAddOp4Int(v, OP_NotFound, pExpr->iTable, destIfFalse, r1, 1);
  77651. VdbeCoverage(v);
  77652. }else{
  77653. /* In this branch, the RHS of the IN might contain a NULL and
  77654. ** the presence of a NULL on the RHS makes a difference in the
  77655. ** outcome.
  77656. */
  77657. int j1;
  77658. /* First check to see if the LHS is contained in the RHS. If so,
  77659. ** then the answer is TRUE the presence of NULLs in the RHS does
  77660. ** not matter. If the LHS is not contained in the RHS, then the
  77661. ** answer is NULL if the RHS contains NULLs and the answer is
  77662. ** FALSE if the RHS is NULL-free.
  77663. */
  77664. j1 = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0, r1, 1);
  77665. VdbeCoverage(v);
  77666. sqlite3VdbeAddOp2(v, OP_IsNull, rRhsHasNull, destIfNull);
  77667. VdbeCoverage(v);
  77668. sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfFalse);
  77669. sqlite3VdbeJumpHere(v, j1);
  77670. }
  77671. }
  77672. }
  77673. sqlite3ReleaseTempReg(pParse, r1);
  77674. sqlite3ExprCachePop(pParse);
  77675. VdbeComment((v, "end IN expr"));
  77676. }
  77677. #endif /* SQLITE_OMIT_SUBQUERY */
  77678. /*
  77679. ** Duplicate an 8-byte value
  77680. */
  77681. static char *dup8bytes(Vdbe *v, const char *in){
  77682. char *out = sqlite3DbMallocRaw(sqlite3VdbeDb(v), 8);
  77683. if( out ){
  77684. memcpy(out, in, 8);
  77685. }
  77686. return out;
  77687. }
  77688. #ifndef SQLITE_OMIT_FLOATING_POINT
  77689. /*
  77690. ** Generate an instruction that will put the floating point
  77691. ** value described by z[0..n-1] into register iMem.
  77692. **
  77693. ** The z[] string will probably not be zero-terminated. But the
  77694. ** z[n] character is guaranteed to be something that does not look
  77695. ** like the continuation of the number.
  77696. */
  77697. static void codeReal(Vdbe *v, const char *z, int negateFlag, int iMem){
  77698. if( ALWAYS(z!=0) ){
  77699. double value;
  77700. char *zV;
  77701. sqlite3AtoF(z, &value, sqlite3Strlen30(z), SQLITE_UTF8);
  77702. assert( !sqlite3IsNaN(value) ); /* The new AtoF never returns NaN */
  77703. if( negateFlag ) value = -value;
  77704. zV = dup8bytes(v, (char*)&value);
  77705. sqlite3VdbeAddOp4(v, OP_Real, 0, iMem, 0, zV, P4_REAL);
  77706. }
  77707. }
  77708. #endif
  77709. /*
  77710. ** Generate an instruction that will put the integer describe by
  77711. ** text z[0..n-1] into register iMem.
  77712. **
  77713. ** Expr.u.zToken is always UTF8 and zero-terminated.
  77714. */
  77715. static void codeInteger(Parse *pParse, Expr *pExpr, int negFlag, int iMem){
  77716. Vdbe *v = pParse->pVdbe;
  77717. if( pExpr->flags & EP_IntValue ){
  77718. int i = pExpr->u.iValue;
  77719. assert( i>=0 );
  77720. if( negFlag ) i = -i;
  77721. sqlite3VdbeAddOp2(v, OP_Integer, i, iMem);
  77722. }else{
  77723. int c;
  77724. i64 value;
  77725. const char *z = pExpr->u.zToken;
  77726. assert( z!=0 );
  77727. c = sqlite3DecOrHexToI64(z, &value);
  77728. if( c==0 || (c==2 && negFlag) ){
  77729. char *zV;
  77730. if( negFlag ){ value = c==2 ? SMALLEST_INT64 : -value; }
  77731. zV = dup8bytes(v, (char*)&value);
  77732. sqlite3VdbeAddOp4(v, OP_Int64, 0, iMem, 0, zV, P4_INT64);
  77733. }else{
  77734. #ifdef SQLITE_OMIT_FLOATING_POINT
  77735. sqlite3ErrorMsg(pParse, "oversized integer: %s%s", negFlag ? "-" : "", z);
  77736. #else
  77737. #ifndef SQLITE_OMIT_HEX_INTEGER
  77738. if( sqlite3_strnicmp(z,"0x",2)==0 ){
  77739. sqlite3ErrorMsg(pParse, "hex literal too big: %s", z);
  77740. }else
  77741. #endif
  77742. {
  77743. codeReal(v, z, negFlag, iMem);
  77744. }
  77745. #endif
  77746. }
  77747. }
  77748. }
  77749. /*
  77750. ** Clear a cache entry.
  77751. */
  77752. static void cacheEntryClear(Parse *pParse, struct yColCache *p){
  77753. if( p->tempReg ){
  77754. if( pParse->nTempReg<ArraySize(pParse->aTempReg) ){
  77755. pParse->aTempReg[pParse->nTempReg++] = p->iReg;
  77756. }
  77757. p->tempReg = 0;
  77758. }
  77759. }
  77760. /*
  77761. ** Record in the column cache that a particular column from a
  77762. ** particular table is stored in a particular register.
  77763. */
  77764. SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse *pParse, int iTab, int iCol, int iReg){
  77765. int i;
  77766. int minLru;
  77767. int idxLru;
  77768. struct yColCache *p;
  77769. assert( iReg>0 ); /* Register numbers are always positive */
  77770. assert( iCol>=-1 && iCol<32768 ); /* Finite column numbers */
  77771. /* The SQLITE_ColumnCache flag disables the column cache. This is used
  77772. ** for testing only - to verify that SQLite always gets the same answer
  77773. ** with and without the column cache.
  77774. */
  77775. if( OptimizationDisabled(pParse->db, SQLITE_ColumnCache) ) return;
  77776. /* First replace any existing entry.
  77777. **
  77778. ** Actually, the way the column cache is currently used, we are guaranteed
  77779. ** that the object will never already be in cache. Verify this guarantee.
  77780. */
  77781. #ifndef NDEBUG
  77782. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  77783. assert( p->iReg==0 || p->iTable!=iTab || p->iColumn!=iCol );
  77784. }
  77785. #endif
  77786. /* Find an empty slot and replace it */
  77787. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  77788. if( p->iReg==0 ){
  77789. p->iLevel = pParse->iCacheLevel;
  77790. p->iTable = iTab;
  77791. p->iColumn = iCol;
  77792. p->iReg = iReg;
  77793. p->tempReg = 0;
  77794. p->lru = pParse->iCacheCnt++;
  77795. return;
  77796. }
  77797. }
  77798. /* Replace the last recently used */
  77799. minLru = 0x7fffffff;
  77800. idxLru = -1;
  77801. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  77802. if( p->lru<minLru ){
  77803. idxLru = i;
  77804. minLru = p->lru;
  77805. }
  77806. }
  77807. if( ALWAYS(idxLru>=0) ){
  77808. p = &pParse->aColCache[idxLru];
  77809. p->iLevel = pParse->iCacheLevel;
  77810. p->iTable = iTab;
  77811. p->iColumn = iCol;
  77812. p->iReg = iReg;
  77813. p->tempReg = 0;
  77814. p->lru = pParse->iCacheCnt++;
  77815. return;
  77816. }
  77817. }
  77818. /*
  77819. ** Indicate that registers between iReg..iReg+nReg-1 are being overwritten.
  77820. ** Purge the range of registers from the column cache.
  77821. */
  77822. SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse *pParse, int iReg, int nReg){
  77823. int i;
  77824. int iLast = iReg + nReg - 1;
  77825. struct yColCache *p;
  77826. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  77827. int r = p->iReg;
  77828. if( r>=iReg && r<=iLast ){
  77829. cacheEntryClear(pParse, p);
  77830. p->iReg = 0;
  77831. }
  77832. }
  77833. }
  77834. /*
  77835. ** Remember the current column cache context. Any new entries added
  77836. ** added to the column cache after this call are removed when the
  77837. ** corresponding pop occurs.
  77838. */
  77839. SQLITE_PRIVATE void sqlite3ExprCachePush(Parse *pParse){
  77840. pParse->iCacheLevel++;
  77841. #ifdef SQLITE_DEBUG
  77842. if( pParse->db->flags & SQLITE_VdbeAddopTrace ){
  77843. printf("PUSH to %d\n", pParse->iCacheLevel);
  77844. }
  77845. #endif
  77846. }
  77847. /*
  77848. ** Remove from the column cache any entries that were added since the
  77849. ** the previous sqlite3ExprCachePush operation. In other words, restore
  77850. ** the cache to the state it was in prior the most recent Push.
  77851. */
  77852. SQLITE_PRIVATE void sqlite3ExprCachePop(Parse *pParse){
  77853. int i;
  77854. struct yColCache *p;
  77855. assert( pParse->iCacheLevel>=1 );
  77856. pParse->iCacheLevel--;
  77857. #ifdef SQLITE_DEBUG
  77858. if( pParse->db->flags & SQLITE_VdbeAddopTrace ){
  77859. printf("POP to %d\n", pParse->iCacheLevel);
  77860. }
  77861. #endif
  77862. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  77863. if( p->iReg && p->iLevel>pParse->iCacheLevel ){
  77864. cacheEntryClear(pParse, p);
  77865. p->iReg = 0;
  77866. }
  77867. }
  77868. }
  77869. /*
  77870. ** When a cached column is reused, make sure that its register is
  77871. ** no longer available as a temp register. ticket #3879: that same
  77872. ** register might be in the cache in multiple places, so be sure to
  77873. ** get them all.
  77874. */
  77875. static void sqlite3ExprCachePinRegister(Parse *pParse, int iReg){
  77876. int i;
  77877. struct yColCache *p;
  77878. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  77879. if( p->iReg==iReg ){
  77880. p->tempReg = 0;
  77881. }
  77882. }
  77883. }
  77884. /*
  77885. ** Generate code to extract the value of the iCol-th column of a table.
  77886. */
  77887. SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(
  77888. Vdbe *v, /* The VDBE under construction */
  77889. Table *pTab, /* The table containing the value */
  77890. int iTabCur, /* The table cursor. Or the PK cursor for WITHOUT ROWID */
  77891. int iCol, /* Index of the column to extract */
  77892. int regOut /* Extract the value into this register */
  77893. ){
  77894. if( iCol<0 || iCol==pTab->iPKey ){
  77895. sqlite3VdbeAddOp2(v, OP_Rowid, iTabCur, regOut);
  77896. }else{
  77897. int op = IsVirtual(pTab) ? OP_VColumn : OP_Column;
  77898. int x = iCol;
  77899. if( !HasRowid(pTab) ){
  77900. x = sqlite3ColumnOfIndex(sqlite3PrimaryKeyIndex(pTab), iCol);
  77901. }
  77902. sqlite3VdbeAddOp3(v, op, iTabCur, x, regOut);
  77903. }
  77904. if( iCol>=0 ){
  77905. sqlite3ColumnDefault(v, pTab, iCol, regOut);
  77906. }
  77907. }
  77908. /*
  77909. ** Generate code that will extract the iColumn-th column from
  77910. ** table pTab and store the column value in a register. An effort
  77911. ** is made to store the column value in register iReg, but this is
  77912. ** not guaranteed. The location of the column value is returned.
  77913. **
  77914. ** There must be an open cursor to pTab in iTable when this routine
  77915. ** is called. If iColumn<0 then code is generated that extracts the rowid.
  77916. */
  77917. SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(
  77918. Parse *pParse, /* Parsing and code generating context */
  77919. Table *pTab, /* Description of the table we are reading from */
  77920. int iColumn, /* Index of the table column */
  77921. int iTable, /* The cursor pointing to the table */
  77922. int iReg, /* Store results here */
  77923. u8 p5 /* P5 value for OP_Column */
  77924. ){
  77925. Vdbe *v = pParse->pVdbe;
  77926. int i;
  77927. struct yColCache *p;
  77928. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  77929. if( p->iReg>0 && p->iTable==iTable && p->iColumn==iColumn ){
  77930. p->lru = pParse->iCacheCnt++;
  77931. sqlite3ExprCachePinRegister(pParse, p->iReg);
  77932. return p->iReg;
  77933. }
  77934. }
  77935. assert( v!=0 );
  77936. sqlite3ExprCodeGetColumnOfTable(v, pTab, iTable, iColumn, iReg);
  77937. if( p5 ){
  77938. sqlite3VdbeChangeP5(v, p5);
  77939. }else{
  77940. sqlite3ExprCacheStore(pParse, iTable, iColumn, iReg);
  77941. }
  77942. return iReg;
  77943. }
  77944. /*
  77945. ** Clear all column cache entries.
  77946. */
  77947. SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse *pParse){
  77948. int i;
  77949. struct yColCache *p;
  77950. #if SQLITE_DEBUG
  77951. if( pParse->db->flags & SQLITE_VdbeAddopTrace ){
  77952. printf("CLEAR\n");
  77953. }
  77954. #endif
  77955. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  77956. if( p->iReg ){
  77957. cacheEntryClear(pParse, p);
  77958. p->iReg = 0;
  77959. }
  77960. }
  77961. }
  77962. /*
  77963. ** Record the fact that an affinity change has occurred on iCount
  77964. ** registers starting with iStart.
  77965. */
  77966. SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse *pParse, int iStart, int iCount){
  77967. sqlite3ExprCacheRemove(pParse, iStart, iCount);
  77968. }
  77969. /*
  77970. ** Generate code to move content from registers iFrom...iFrom+nReg-1
  77971. ** over to iTo..iTo+nReg-1. Keep the column cache up-to-date.
  77972. */
  77973. SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse *pParse, int iFrom, int iTo, int nReg){
  77974. assert( iFrom>=iTo+nReg || iFrom+nReg<=iTo );
  77975. sqlite3VdbeAddOp3(pParse->pVdbe, OP_Move, iFrom, iTo, nReg);
  77976. sqlite3ExprCacheRemove(pParse, iFrom, nReg);
  77977. }
  77978. #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
  77979. /*
  77980. ** Return true if any register in the range iFrom..iTo (inclusive)
  77981. ** is used as part of the column cache.
  77982. **
  77983. ** This routine is used within assert() and testcase() macros only
  77984. ** and does not appear in a normal build.
  77985. */
  77986. static int usedAsColumnCache(Parse *pParse, int iFrom, int iTo){
  77987. int i;
  77988. struct yColCache *p;
  77989. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  77990. int r = p->iReg;
  77991. if( r>=iFrom && r<=iTo ) return 1; /*NO_TEST*/
  77992. }
  77993. return 0;
  77994. }
  77995. #endif /* SQLITE_DEBUG || SQLITE_COVERAGE_TEST */
  77996. /*
  77997. ** Convert an expression node to a TK_REGISTER
  77998. */
  77999. static void exprToRegister(Expr *p, int iReg){
  78000. p->op2 = p->op;
  78001. p->op = TK_REGISTER;
  78002. p->iTable = iReg;
  78003. ExprClearProperty(p, EP_Skip);
  78004. }
  78005. /*
  78006. ** Generate code into the current Vdbe to evaluate the given
  78007. ** expression. Attempt to store the results in register "target".
  78008. ** Return the register where results are stored.
  78009. **
  78010. ** With this routine, there is no guarantee that results will
  78011. ** be stored in target. The result might be stored in some other
  78012. ** register if it is convenient to do so. The calling function
  78013. ** must check the return code and move the results to the desired
  78014. ** register.
  78015. */
  78016. SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target){
  78017. Vdbe *v = pParse->pVdbe; /* The VM under construction */
  78018. int op; /* The opcode being coded */
  78019. int inReg = target; /* Results stored in register inReg */
  78020. int regFree1 = 0; /* If non-zero free this temporary register */
  78021. int regFree2 = 0; /* If non-zero free this temporary register */
  78022. int r1, r2, r3, r4; /* Various register numbers */
  78023. sqlite3 *db = pParse->db; /* The database connection */
  78024. Expr tempX; /* Temporary expression node */
  78025. assert( target>0 && target<=pParse->nMem );
  78026. if( v==0 ){
  78027. assert( pParse->db->mallocFailed );
  78028. return 0;
  78029. }
  78030. if( pExpr==0 ){
  78031. op = TK_NULL;
  78032. }else{
  78033. op = pExpr->op;
  78034. }
  78035. switch( op ){
  78036. case TK_AGG_COLUMN: {
  78037. AggInfo *pAggInfo = pExpr->pAggInfo;
  78038. struct AggInfo_col *pCol = &pAggInfo->aCol[pExpr->iAgg];
  78039. if( !pAggInfo->directMode ){
  78040. assert( pCol->iMem>0 );
  78041. inReg = pCol->iMem;
  78042. break;
  78043. }else if( pAggInfo->useSortingIdx ){
  78044. sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdxPTab,
  78045. pCol->iSorterColumn, target);
  78046. break;
  78047. }
  78048. /* Otherwise, fall thru into the TK_COLUMN case */
  78049. }
  78050. case TK_COLUMN: {
  78051. int iTab = pExpr->iTable;
  78052. if( iTab<0 ){
  78053. if( pParse->ckBase>0 ){
  78054. /* Generating CHECK constraints or inserting into partial index */
  78055. inReg = pExpr->iColumn + pParse->ckBase;
  78056. break;
  78057. }else{
  78058. /* Deleting from a partial index */
  78059. iTab = pParse->iPartIdxTab;
  78060. }
  78061. }
  78062. inReg = sqlite3ExprCodeGetColumn(pParse, pExpr->pTab,
  78063. pExpr->iColumn, iTab, target,
  78064. pExpr->op2);
  78065. break;
  78066. }
  78067. case TK_INTEGER: {
  78068. codeInteger(pParse, pExpr, 0, target);
  78069. break;
  78070. }
  78071. #ifndef SQLITE_OMIT_FLOATING_POINT
  78072. case TK_FLOAT: {
  78073. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  78074. codeReal(v, pExpr->u.zToken, 0, target);
  78075. break;
  78076. }
  78077. #endif
  78078. case TK_STRING: {
  78079. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  78080. sqlite3VdbeAddOp4(v, OP_String8, 0, target, 0, pExpr->u.zToken, 0);
  78081. break;
  78082. }
  78083. case TK_NULL: {
  78084. sqlite3VdbeAddOp2(v, OP_Null, 0, target);
  78085. break;
  78086. }
  78087. #ifndef SQLITE_OMIT_BLOB_LITERAL
  78088. case TK_BLOB: {
  78089. int n;
  78090. const char *z;
  78091. char *zBlob;
  78092. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  78093. assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
  78094. assert( pExpr->u.zToken[1]=='\'' );
  78095. z = &pExpr->u.zToken[2];
  78096. n = sqlite3Strlen30(z) - 1;
  78097. assert( z[n]=='\'' );
  78098. zBlob = sqlite3HexToBlob(sqlite3VdbeDb(v), z, n);
  78099. sqlite3VdbeAddOp4(v, OP_Blob, n/2, target, 0, zBlob, P4_DYNAMIC);
  78100. break;
  78101. }
  78102. #endif
  78103. case TK_VARIABLE: {
  78104. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  78105. assert( pExpr->u.zToken!=0 );
  78106. assert( pExpr->u.zToken[0]!=0 );
  78107. sqlite3VdbeAddOp2(v, OP_Variable, pExpr->iColumn, target);
  78108. if( pExpr->u.zToken[1]!=0 ){
  78109. assert( pExpr->u.zToken[0]=='?'
  78110. || strcmp(pExpr->u.zToken, pParse->azVar[pExpr->iColumn-1])==0 );
  78111. sqlite3VdbeChangeP4(v, -1, pParse->azVar[pExpr->iColumn-1], P4_STATIC);
  78112. }
  78113. break;
  78114. }
  78115. case TK_REGISTER: {
  78116. inReg = pExpr->iTable;
  78117. break;
  78118. }
  78119. case TK_AS: {
  78120. inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
  78121. break;
  78122. }
  78123. #ifndef SQLITE_OMIT_CAST
  78124. case TK_CAST: {
  78125. /* Expressions of the form: CAST(pLeft AS token) */
  78126. inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
  78127. if( inReg!=target ){
  78128. sqlite3VdbeAddOp2(v, OP_SCopy, inReg, target);
  78129. inReg = target;
  78130. }
  78131. sqlite3VdbeAddOp2(v, OP_Cast, target,
  78132. sqlite3AffinityType(pExpr->u.zToken, 0));
  78133. testcase( usedAsColumnCache(pParse, inReg, inReg) );
  78134. sqlite3ExprCacheAffinityChange(pParse, inReg, 1);
  78135. break;
  78136. }
  78137. #endif /* SQLITE_OMIT_CAST */
  78138. case TK_LT:
  78139. case TK_LE:
  78140. case TK_GT:
  78141. case TK_GE:
  78142. case TK_NE:
  78143. case TK_EQ: {
  78144. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  78145. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
  78146. codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
  78147. r1, r2, inReg, SQLITE_STOREP2);
  78148. assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
  78149. assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
  78150. assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
  78151. assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
  78152. assert(TK_EQ==OP_Eq); testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq);
  78153. assert(TK_NE==OP_Ne); testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne);
  78154. testcase( regFree1==0 );
  78155. testcase( regFree2==0 );
  78156. break;
  78157. }
  78158. case TK_IS:
  78159. case TK_ISNOT: {
  78160. testcase( op==TK_IS );
  78161. testcase( op==TK_ISNOT );
  78162. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  78163. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
  78164. op = (op==TK_IS) ? TK_EQ : TK_NE;
  78165. codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
  78166. r1, r2, inReg, SQLITE_STOREP2 | SQLITE_NULLEQ);
  78167. VdbeCoverageIf(v, op==TK_EQ);
  78168. VdbeCoverageIf(v, op==TK_NE);
  78169. testcase( regFree1==0 );
  78170. testcase( regFree2==0 );
  78171. break;
  78172. }
  78173. case TK_AND:
  78174. case TK_OR:
  78175. case TK_PLUS:
  78176. case TK_STAR:
  78177. case TK_MINUS:
  78178. case TK_REM:
  78179. case TK_BITAND:
  78180. case TK_BITOR:
  78181. case TK_SLASH:
  78182. case TK_LSHIFT:
  78183. case TK_RSHIFT:
  78184. case TK_CONCAT: {
  78185. assert( TK_AND==OP_And ); testcase( op==TK_AND );
  78186. assert( TK_OR==OP_Or ); testcase( op==TK_OR );
  78187. assert( TK_PLUS==OP_Add ); testcase( op==TK_PLUS );
  78188. assert( TK_MINUS==OP_Subtract ); testcase( op==TK_MINUS );
  78189. assert( TK_REM==OP_Remainder ); testcase( op==TK_REM );
  78190. assert( TK_BITAND==OP_BitAnd ); testcase( op==TK_BITAND );
  78191. assert( TK_BITOR==OP_BitOr ); testcase( op==TK_BITOR );
  78192. assert( TK_SLASH==OP_Divide ); testcase( op==TK_SLASH );
  78193. assert( TK_LSHIFT==OP_ShiftLeft ); testcase( op==TK_LSHIFT );
  78194. assert( TK_RSHIFT==OP_ShiftRight ); testcase( op==TK_RSHIFT );
  78195. assert( TK_CONCAT==OP_Concat ); testcase( op==TK_CONCAT );
  78196. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  78197. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
  78198. sqlite3VdbeAddOp3(v, op, r2, r1, target);
  78199. testcase( regFree1==0 );
  78200. testcase( regFree2==0 );
  78201. break;
  78202. }
  78203. case TK_UMINUS: {
  78204. Expr *pLeft = pExpr->pLeft;
  78205. assert( pLeft );
  78206. if( pLeft->op==TK_INTEGER ){
  78207. codeInteger(pParse, pLeft, 1, target);
  78208. #ifndef SQLITE_OMIT_FLOATING_POINT
  78209. }else if( pLeft->op==TK_FLOAT ){
  78210. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  78211. codeReal(v, pLeft->u.zToken, 1, target);
  78212. #endif
  78213. }else{
  78214. tempX.op = TK_INTEGER;
  78215. tempX.flags = EP_IntValue|EP_TokenOnly;
  78216. tempX.u.iValue = 0;
  78217. r1 = sqlite3ExprCodeTemp(pParse, &tempX, &regFree1);
  78218. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree2);
  78219. sqlite3VdbeAddOp3(v, OP_Subtract, r2, r1, target);
  78220. testcase( regFree2==0 );
  78221. }
  78222. inReg = target;
  78223. break;
  78224. }
  78225. case TK_BITNOT:
  78226. case TK_NOT: {
  78227. assert( TK_BITNOT==OP_BitNot ); testcase( op==TK_BITNOT );
  78228. assert( TK_NOT==OP_Not ); testcase( op==TK_NOT );
  78229. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  78230. testcase( regFree1==0 );
  78231. inReg = target;
  78232. sqlite3VdbeAddOp2(v, op, r1, inReg);
  78233. break;
  78234. }
  78235. case TK_ISNULL:
  78236. case TK_NOTNULL: {
  78237. int addr;
  78238. assert( TK_ISNULL==OP_IsNull ); testcase( op==TK_ISNULL );
  78239. assert( TK_NOTNULL==OP_NotNull ); testcase( op==TK_NOTNULL );
  78240. sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
  78241. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  78242. testcase( regFree1==0 );
  78243. addr = sqlite3VdbeAddOp1(v, op, r1);
  78244. VdbeCoverageIf(v, op==TK_ISNULL);
  78245. VdbeCoverageIf(v, op==TK_NOTNULL);
  78246. sqlite3VdbeAddOp2(v, OP_Integer, 0, target);
  78247. sqlite3VdbeJumpHere(v, addr);
  78248. break;
  78249. }
  78250. case TK_AGG_FUNCTION: {
  78251. AggInfo *pInfo = pExpr->pAggInfo;
  78252. if( pInfo==0 ){
  78253. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  78254. sqlite3ErrorMsg(pParse, "misuse of aggregate: %s()", pExpr->u.zToken);
  78255. }else{
  78256. inReg = pInfo->aFunc[pExpr->iAgg].iMem;
  78257. }
  78258. break;
  78259. }
  78260. case TK_FUNCTION: {
  78261. ExprList *pFarg; /* List of function arguments */
  78262. int nFarg; /* Number of function arguments */
  78263. FuncDef *pDef; /* The function definition object */
  78264. int nId; /* Length of the function name in bytes */
  78265. const char *zId; /* The function name */
  78266. u32 constMask = 0; /* Mask of function arguments that are constant */
  78267. int i; /* Loop counter */
  78268. u8 enc = ENC(db); /* The text encoding used by this database */
  78269. CollSeq *pColl = 0; /* A collating sequence */
  78270. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  78271. if( ExprHasProperty(pExpr, EP_TokenOnly) ){
  78272. pFarg = 0;
  78273. }else{
  78274. pFarg = pExpr->x.pList;
  78275. }
  78276. nFarg = pFarg ? pFarg->nExpr : 0;
  78277. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  78278. zId = pExpr->u.zToken;
  78279. nId = sqlite3Strlen30(zId);
  78280. pDef = sqlite3FindFunction(db, zId, nId, nFarg, enc, 0);
  78281. if( pDef==0 || pDef->xFunc==0 ){
  78282. sqlite3ErrorMsg(pParse, "unknown function: %.*s()", nId, zId);
  78283. break;
  78284. }
  78285. /* Attempt a direct implementation of the built-in COALESCE() and
  78286. ** IFNULL() functions. This avoids unnecessary evaluation of
  78287. ** arguments past the first non-NULL argument.
  78288. */
  78289. if( pDef->funcFlags & SQLITE_FUNC_COALESCE ){
  78290. int endCoalesce = sqlite3VdbeMakeLabel(v);
  78291. assert( nFarg>=2 );
  78292. sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target);
  78293. for(i=1; i<nFarg; i++){
  78294. sqlite3VdbeAddOp2(v, OP_NotNull, target, endCoalesce);
  78295. VdbeCoverage(v);
  78296. sqlite3ExprCacheRemove(pParse, target, 1);
  78297. sqlite3ExprCachePush(pParse);
  78298. sqlite3ExprCode(pParse, pFarg->a[i].pExpr, target);
  78299. sqlite3ExprCachePop(pParse);
  78300. }
  78301. sqlite3VdbeResolveLabel(v, endCoalesce);
  78302. break;
  78303. }
  78304. /* The UNLIKELY() function is a no-op. The result is the value
  78305. ** of the first argument.
  78306. */
  78307. if( pDef->funcFlags & SQLITE_FUNC_UNLIKELY ){
  78308. assert( nFarg>=1 );
  78309. sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target);
  78310. break;
  78311. }
  78312. for(i=0; i<nFarg; i++){
  78313. if( i<32 && sqlite3ExprIsConstant(pFarg->a[i].pExpr) ){
  78314. testcase( i==31 );
  78315. constMask |= MASKBIT32(i);
  78316. }
  78317. if( (pDef->funcFlags & SQLITE_FUNC_NEEDCOLL)!=0 && !pColl ){
  78318. pColl = sqlite3ExprCollSeq(pParse, pFarg->a[i].pExpr);
  78319. }
  78320. }
  78321. if( pFarg ){
  78322. if( constMask ){
  78323. r1 = pParse->nMem+1;
  78324. pParse->nMem += nFarg;
  78325. }else{
  78326. r1 = sqlite3GetTempRange(pParse, nFarg);
  78327. }
  78328. /* For length() and typeof() functions with a column argument,
  78329. ** set the P5 parameter to the OP_Column opcode to OPFLAG_LENGTHARG
  78330. ** or OPFLAG_TYPEOFARG respectively, to avoid unnecessary data
  78331. ** loading.
  78332. */
  78333. if( (pDef->funcFlags & (SQLITE_FUNC_LENGTH|SQLITE_FUNC_TYPEOF))!=0 ){
  78334. u8 exprOp;
  78335. assert( nFarg==1 );
  78336. assert( pFarg->a[0].pExpr!=0 );
  78337. exprOp = pFarg->a[0].pExpr->op;
  78338. if( exprOp==TK_COLUMN || exprOp==TK_AGG_COLUMN ){
  78339. assert( SQLITE_FUNC_LENGTH==OPFLAG_LENGTHARG );
  78340. assert( SQLITE_FUNC_TYPEOF==OPFLAG_TYPEOFARG );
  78341. testcase( pDef->funcFlags & OPFLAG_LENGTHARG );
  78342. pFarg->a[0].pExpr->op2 =
  78343. pDef->funcFlags & (OPFLAG_LENGTHARG|OPFLAG_TYPEOFARG);
  78344. }
  78345. }
  78346. sqlite3ExprCachePush(pParse); /* Ticket 2ea2425d34be */
  78347. sqlite3ExprCodeExprList(pParse, pFarg, r1,
  78348. SQLITE_ECEL_DUP|SQLITE_ECEL_FACTOR);
  78349. sqlite3ExprCachePop(pParse); /* Ticket 2ea2425d34be */
  78350. }else{
  78351. r1 = 0;
  78352. }
  78353. #ifndef SQLITE_OMIT_VIRTUALTABLE
  78354. /* Possibly overload the function if the first argument is
  78355. ** a virtual table column.
  78356. **
  78357. ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the
  78358. ** second argument, not the first, as the argument to test to
  78359. ** see if it is a column in a virtual table. This is done because
  78360. ** the left operand of infix functions (the operand we want to
  78361. ** control overloading) ends up as the second argument to the
  78362. ** function. The expression "A glob B" is equivalent to
  78363. ** "glob(B,A). We want to use the A in "A glob B" to test
  78364. ** for function overloading. But we use the B term in "glob(B,A)".
  78365. */
  78366. if( nFarg>=2 && (pExpr->flags & EP_InfixFunc) ){
  78367. pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[1].pExpr);
  78368. }else if( nFarg>0 ){
  78369. pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[0].pExpr);
  78370. }
  78371. #endif
  78372. if( pDef->funcFlags & SQLITE_FUNC_NEEDCOLL ){
  78373. if( !pColl ) pColl = db->pDfltColl;
  78374. sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
  78375. }
  78376. sqlite3VdbeAddOp4(v, OP_Function, constMask, r1, target,
  78377. (char*)pDef, P4_FUNCDEF);
  78378. sqlite3VdbeChangeP5(v, (u8)nFarg);
  78379. if( nFarg && constMask==0 ){
  78380. sqlite3ReleaseTempRange(pParse, r1, nFarg);
  78381. }
  78382. break;
  78383. }
  78384. #ifndef SQLITE_OMIT_SUBQUERY
  78385. case TK_EXISTS:
  78386. case TK_SELECT: {
  78387. testcase( op==TK_EXISTS );
  78388. testcase( op==TK_SELECT );
  78389. inReg = sqlite3CodeSubselect(pParse, pExpr, 0, 0);
  78390. break;
  78391. }
  78392. case TK_IN: {
  78393. int destIfFalse = sqlite3VdbeMakeLabel(v);
  78394. int destIfNull = sqlite3VdbeMakeLabel(v);
  78395. sqlite3VdbeAddOp2(v, OP_Null, 0, target);
  78396. sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
  78397. sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
  78398. sqlite3VdbeResolveLabel(v, destIfFalse);
  78399. sqlite3VdbeAddOp2(v, OP_AddImm, target, 0);
  78400. sqlite3VdbeResolveLabel(v, destIfNull);
  78401. break;
  78402. }
  78403. #endif /* SQLITE_OMIT_SUBQUERY */
  78404. /*
  78405. ** x BETWEEN y AND z
  78406. **
  78407. ** This is equivalent to
  78408. **
  78409. ** x>=y AND x<=z
  78410. **
  78411. ** X is stored in pExpr->pLeft.
  78412. ** Y is stored in pExpr->pList->a[0].pExpr.
  78413. ** Z is stored in pExpr->pList->a[1].pExpr.
  78414. */
  78415. case TK_BETWEEN: {
  78416. Expr *pLeft = pExpr->pLeft;
  78417. struct ExprList_item *pLItem = pExpr->x.pList->a;
  78418. Expr *pRight = pLItem->pExpr;
  78419. r1 = sqlite3ExprCodeTemp(pParse, pLeft, &regFree1);
  78420. r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
  78421. testcase( regFree1==0 );
  78422. testcase( regFree2==0 );
  78423. r3 = sqlite3GetTempReg(pParse);
  78424. r4 = sqlite3GetTempReg(pParse);
  78425. codeCompare(pParse, pLeft, pRight, OP_Ge,
  78426. r1, r2, r3, SQLITE_STOREP2); VdbeCoverage(v);
  78427. pLItem++;
  78428. pRight = pLItem->pExpr;
  78429. sqlite3ReleaseTempReg(pParse, regFree2);
  78430. r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
  78431. testcase( regFree2==0 );
  78432. codeCompare(pParse, pLeft, pRight, OP_Le, r1, r2, r4, SQLITE_STOREP2);
  78433. VdbeCoverage(v);
  78434. sqlite3VdbeAddOp3(v, OP_And, r3, r4, target);
  78435. sqlite3ReleaseTempReg(pParse, r3);
  78436. sqlite3ReleaseTempReg(pParse, r4);
  78437. break;
  78438. }
  78439. case TK_COLLATE:
  78440. case TK_UPLUS: {
  78441. inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
  78442. break;
  78443. }
  78444. case TK_TRIGGER: {
  78445. /* If the opcode is TK_TRIGGER, then the expression is a reference
  78446. ** to a column in the new.* or old.* pseudo-tables available to
  78447. ** trigger programs. In this case Expr.iTable is set to 1 for the
  78448. ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
  78449. ** is set to the column of the pseudo-table to read, or to -1 to
  78450. ** read the rowid field.
  78451. **
  78452. ** The expression is implemented using an OP_Param opcode. The p1
  78453. ** parameter is set to 0 for an old.rowid reference, or to (i+1)
  78454. ** to reference another column of the old.* pseudo-table, where
  78455. ** i is the index of the column. For a new.rowid reference, p1 is
  78456. ** set to (n+1), where n is the number of columns in each pseudo-table.
  78457. ** For a reference to any other column in the new.* pseudo-table, p1
  78458. ** is set to (n+2+i), where n and i are as defined previously. For
  78459. ** example, if the table on which triggers are being fired is
  78460. ** declared as:
  78461. **
  78462. ** CREATE TABLE t1(a, b);
  78463. **
  78464. ** Then p1 is interpreted as follows:
  78465. **
  78466. ** p1==0 -> old.rowid p1==3 -> new.rowid
  78467. ** p1==1 -> old.a p1==4 -> new.a
  78468. ** p1==2 -> old.b p1==5 -> new.b
  78469. */
  78470. Table *pTab = pExpr->pTab;
  78471. int p1 = pExpr->iTable * (pTab->nCol+1) + 1 + pExpr->iColumn;
  78472. assert( pExpr->iTable==0 || pExpr->iTable==1 );
  78473. assert( pExpr->iColumn>=-1 && pExpr->iColumn<pTab->nCol );
  78474. assert( pTab->iPKey<0 || pExpr->iColumn!=pTab->iPKey );
  78475. assert( p1>=0 && p1<(pTab->nCol*2+2) );
  78476. sqlite3VdbeAddOp2(v, OP_Param, p1, target);
  78477. VdbeComment((v, "%s.%s -> $%d",
  78478. (pExpr->iTable ? "new" : "old"),
  78479. (pExpr->iColumn<0 ? "rowid" : pExpr->pTab->aCol[pExpr->iColumn].zName),
  78480. target
  78481. ));
  78482. #ifndef SQLITE_OMIT_FLOATING_POINT
  78483. /* If the column has REAL affinity, it may currently be stored as an
  78484. ** integer. Use OP_RealAffinity to make sure it is really real. */
  78485. if( pExpr->iColumn>=0
  78486. && pTab->aCol[pExpr->iColumn].affinity==SQLITE_AFF_REAL
  78487. ){
  78488. sqlite3VdbeAddOp1(v, OP_RealAffinity, target);
  78489. }
  78490. #endif
  78491. break;
  78492. }
  78493. /*
  78494. ** Form A:
  78495. ** CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
  78496. **
  78497. ** Form B:
  78498. ** CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
  78499. **
  78500. ** Form A is can be transformed into the equivalent form B as follows:
  78501. ** CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ...
  78502. ** WHEN x=eN THEN rN ELSE y END
  78503. **
  78504. ** X (if it exists) is in pExpr->pLeft.
  78505. ** Y is in the last element of pExpr->x.pList if pExpr->x.pList->nExpr is
  78506. ** odd. The Y is also optional. If the number of elements in x.pList
  78507. ** is even, then Y is omitted and the "otherwise" result is NULL.
  78508. ** Ei is in pExpr->pList->a[i*2] and Ri is pExpr->pList->a[i*2+1].
  78509. **
  78510. ** The result of the expression is the Ri for the first matching Ei,
  78511. ** or if there is no matching Ei, the ELSE term Y, or if there is
  78512. ** no ELSE term, NULL.
  78513. */
  78514. default: assert( op==TK_CASE ); {
  78515. int endLabel; /* GOTO label for end of CASE stmt */
  78516. int nextCase; /* GOTO label for next WHEN clause */
  78517. int nExpr; /* 2x number of WHEN terms */
  78518. int i; /* Loop counter */
  78519. ExprList *pEList; /* List of WHEN terms */
  78520. struct ExprList_item *aListelem; /* Array of WHEN terms */
  78521. Expr opCompare; /* The X==Ei expression */
  78522. Expr *pX; /* The X expression */
  78523. Expr *pTest = 0; /* X==Ei (form A) or just Ei (form B) */
  78524. VVA_ONLY( int iCacheLevel = pParse->iCacheLevel; )
  78525. assert( !ExprHasProperty(pExpr, EP_xIsSelect) && pExpr->x.pList );
  78526. assert(pExpr->x.pList->nExpr > 0);
  78527. pEList = pExpr->x.pList;
  78528. aListelem = pEList->a;
  78529. nExpr = pEList->nExpr;
  78530. endLabel = sqlite3VdbeMakeLabel(v);
  78531. if( (pX = pExpr->pLeft)!=0 ){
  78532. tempX = *pX;
  78533. testcase( pX->op==TK_COLUMN );
  78534. exprToRegister(&tempX, sqlite3ExprCodeTemp(pParse, pX, &regFree1));
  78535. testcase( regFree1==0 );
  78536. opCompare.op = TK_EQ;
  78537. opCompare.pLeft = &tempX;
  78538. pTest = &opCompare;
  78539. /* Ticket b351d95f9cd5ef17e9d9dbae18f5ca8611190001:
  78540. ** The value in regFree1 might get SCopy-ed into the file result.
  78541. ** So make sure that the regFree1 register is not reused for other
  78542. ** purposes and possibly overwritten. */
  78543. regFree1 = 0;
  78544. }
  78545. for(i=0; i<nExpr-1; i=i+2){
  78546. sqlite3ExprCachePush(pParse);
  78547. if( pX ){
  78548. assert( pTest!=0 );
  78549. opCompare.pRight = aListelem[i].pExpr;
  78550. }else{
  78551. pTest = aListelem[i].pExpr;
  78552. }
  78553. nextCase = sqlite3VdbeMakeLabel(v);
  78554. testcase( pTest->op==TK_COLUMN );
  78555. sqlite3ExprIfFalse(pParse, pTest, nextCase, SQLITE_JUMPIFNULL);
  78556. testcase( aListelem[i+1].pExpr->op==TK_COLUMN );
  78557. sqlite3ExprCode(pParse, aListelem[i+1].pExpr, target);
  78558. sqlite3VdbeAddOp2(v, OP_Goto, 0, endLabel);
  78559. sqlite3ExprCachePop(pParse);
  78560. sqlite3VdbeResolveLabel(v, nextCase);
  78561. }
  78562. if( (nExpr&1)!=0 ){
  78563. sqlite3ExprCachePush(pParse);
  78564. sqlite3ExprCode(pParse, pEList->a[nExpr-1].pExpr, target);
  78565. sqlite3ExprCachePop(pParse);
  78566. }else{
  78567. sqlite3VdbeAddOp2(v, OP_Null, 0, target);
  78568. }
  78569. assert( db->mallocFailed || pParse->nErr>0
  78570. || pParse->iCacheLevel==iCacheLevel );
  78571. sqlite3VdbeResolveLabel(v, endLabel);
  78572. break;
  78573. }
  78574. #ifndef SQLITE_OMIT_TRIGGER
  78575. case TK_RAISE: {
  78576. assert( pExpr->affinity==OE_Rollback
  78577. || pExpr->affinity==OE_Abort
  78578. || pExpr->affinity==OE_Fail
  78579. || pExpr->affinity==OE_Ignore
  78580. );
  78581. if( !pParse->pTriggerTab ){
  78582. sqlite3ErrorMsg(pParse,
  78583. "RAISE() may only be used within a trigger-program");
  78584. return 0;
  78585. }
  78586. if( pExpr->affinity==OE_Abort ){
  78587. sqlite3MayAbort(pParse);
  78588. }
  78589. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  78590. if( pExpr->affinity==OE_Ignore ){
  78591. sqlite3VdbeAddOp4(
  78592. v, OP_Halt, SQLITE_OK, OE_Ignore, 0, pExpr->u.zToken,0);
  78593. VdbeCoverage(v);
  78594. }else{
  78595. sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_TRIGGER,
  78596. pExpr->affinity, pExpr->u.zToken, 0, 0);
  78597. }
  78598. break;
  78599. }
  78600. #endif
  78601. }
  78602. sqlite3ReleaseTempReg(pParse, regFree1);
  78603. sqlite3ReleaseTempReg(pParse, regFree2);
  78604. return inReg;
  78605. }
  78606. /*
  78607. ** Factor out the code of the given expression to initialization time.
  78608. */
  78609. SQLITE_PRIVATE void sqlite3ExprCodeAtInit(
  78610. Parse *pParse, /* Parsing context */
  78611. Expr *pExpr, /* The expression to code when the VDBE initializes */
  78612. int regDest, /* Store the value in this register */
  78613. u8 reusable /* True if this expression is reusable */
  78614. ){
  78615. ExprList *p;
  78616. assert( ConstFactorOk(pParse) );
  78617. p = pParse->pConstExpr;
  78618. pExpr = sqlite3ExprDup(pParse->db, pExpr, 0);
  78619. p = sqlite3ExprListAppend(pParse, p, pExpr);
  78620. if( p ){
  78621. struct ExprList_item *pItem = &p->a[p->nExpr-1];
  78622. pItem->u.iConstExprReg = regDest;
  78623. pItem->reusable = reusable;
  78624. }
  78625. pParse->pConstExpr = p;
  78626. }
  78627. /*
  78628. ** Generate code to evaluate an expression and store the results
  78629. ** into a register. Return the register number where the results
  78630. ** are stored.
  78631. **
  78632. ** If the register is a temporary register that can be deallocated,
  78633. ** then write its number into *pReg. If the result register is not
  78634. ** a temporary, then set *pReg to zero.
  78635. **
  78636. ** If pExpr is a constant, then this routine might generate this
  78637. ** code to fill the register in the initialization section of the
  78638. ** VDBE program, in order to factor it out of the evaluation loop.
  78639. */
  78640. SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse *pParse, Expr *pExpr, int *pReg){
  78641. int r2;
  78642. pExpr = sqlite3ExprSkipCollate(pExpr);
  78643. if( ConstFactorOk(pParse)
  78644. && pExpr->op!=TK_REGISTER
  78645. && sqlite3ExprIsConstantNotJoin(pExpr)
  78646. ){
  78647. ExprList *p = pParse->pConstExpr;
  78648. int i;
  78649. *pReg = 0;
  78650. if( p ){
  78651. struct ExprList_item *pItem;
  78652. for(pItem=p->a, i=p->nExpr; i>0; pItem++, i--){
  78653. if( pItem->reusable && sqlite3ExprCompare(pItem->pExpr,pExpr,-1)==0 ){
  78654. return pItem->u.iConstExprReg;
  78655. }
  78656. }
  78657. }
  78658. r2 = ++pParse->nMem;
  78659. sqlite3ExprCodeAtInit(pParse, pExpr, r2, 1);
  78660. }else{
  78661. int r1 = sqlite3GetTempReg(pParse);
  78662. r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
  78663. if( r2==r1 ){
  78664. *pReg = r1;
  78665. }else{
  78666. sqlite3ReleaseTempReg(pParse, r1);
  78667. *pReg = 0;
  78668. }
  78669. }
  78670. return r2;
  78671. }
  78672. /*
  78673. ** Generate code that will evaluate expression pExpr and store the
  78674. ** results in register target. The results are guaranteed to appear
  78675. ** in register target.
  78676. */
  78677. SQLITE_PRIVATE void sqlite3ExprCode(Parse *pParse, Expr *pExpr, int target){
  78678. int inReg;
  78679. assert( target>0 && target<=pParse->nMem );
  78680. if( pExpr && pExpr->op==TK_REGISTER ){
  78681. sqlite3VdbeAddOp2(pParse->pVdbe, OP_Copy, pExpr->iTable, target);
  78682. }else{
  78683. inReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
  78684. assert( pParse->pVdbe || pParse->db->mallocFailed );
  78685. if( inReg!=target && pParse->pVdbe ){
  78686. sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, inReg, target);
  78687. }
  78688. }
  78689. }
  78690. /*
  78691. ** Generate code that will evaluate expression pExpr and store the
  78692. ** results in register target. The results are guaranteed to appear
  78693. ** in register target. If the expression is constant, then this routine
  78694. ** might choose to code the expression at initialization time.
  78695. */
  78696. SQLITE_PRIVATE void sqlite3ExprCodeFactorable(Parse *pParse, Expr *pExpr, int target){
  78697. if( pParse->okConstFactor && sqlite3ExprIsConstant(pExpr) ){
  78698. sqlite3ExprCodeAtInit(pParse, pExpr, target, 0);
  78699. }else{
  78700. sqlite3ExprCode(pParse, pExpr, target);
  78701. }
  78702. }
  78703. /*
  78704. ** Generate code that evaluates the given expression and puts the result
  78705. ** in register target.
  78706. **
  78707. ** Also make a copy of the expression results into another "cache" register
  78708. ** and modify the expression so that the next time it is evaluated,
  78709. ** the result is a copy of the cache register.
  78710. **
  78711. ** This routine is used for expressions that are used multiple
  78712. ** times. They are evaluated once and the results of the expression
  78713. ** are reused.
  78714. */
  78715. SQLITE_PRIVATE void sqlite3ExprCodeAndCache(Parse *pParse, Expr *pExpr, int target){
  78716. Vdbe *v = pParse->pVdbe;
  78717. int iMem;
  78718. assert( target>0 );
  78719. assert( pExpr->op!=TK_REGISTER );
  78720. sqlite3ExprCode(pParse, pExpr, target);
  78721. iMem = ++pParse->nMem;
  78722. sqlite3VdbeAddOp2(v, OP_Copy, target, iMem);
  78723. exprToRegister(pExpr, iMem);
  78724. }
  78725. #ifdef SQLITE_DEBUG
  78726. /*
  78727. ** Generate a human-readable explanation of an expression tree.
  78728. */
  78729. SQLITE_PRIVATE void sqlite3TreeViewExpr(TreeView *pView, const Expr *pExpr, u8 moreToFollow){
  78730. const char *zBinOp = 0; /* Binary operator */
  78731. const char *zUniOp = 0; /* Unary operator */
  78732. pView = sqlite3TreeViewPush(pView, moreToFollow);
  78733. if( pExpr==0 ){
  78734. sqlite3TreeViewLine(pView, "nil");
  78735. sqlite3TreeViewPop(pView);
  78736. return;
  78737. }
  78738. switch( pExpr->op ){
  78739. case TK_AGG_COLUMN: {
  78740. sqlite3TreeViewLine(pView, "AGG{%d:%d}",
  78741. pExpr->iTable, pExpr->iColumn);
  78742. break;
  78743. }
  78744. case TK_COLUMN: {
  78745. if( pExpr->iTable<0 ){
  78746. /* This only happens when coding check constraints */
  78747. sqlite3TreeViewLine(pView, "COLUMN(%d)", pExpr->iColumn);
  78748. }else{
  78749. sqlite3TreeViewLine(pView, "{%d:%d}",
  78750. pExpr->iTable, pExpr->iColumn);
  78751. }
  78752. break;
  78753. }
  78754. case TK_INTEGER: {
  78755. if( pExpr->flags & EP_IntValue ){
  78756. sqlite3TreeViewLine(pView, "%d", pExpr->u.iValue);
  78757. }else{
  78758. sqlite3TreeViewLine(pView, "%s", pExpr->u.zToken);
  78759. }
  78760. break;
  78761. }
  78762. #ifndef SQLITE_OMIT_FLOATING_POINT
  78763. case TK_FLOAT: {
  78764. sqlite3TreeViewLine(pView,"%s", pExpr->u.zToken);
  78765. break;
  78766. }
  78767. #endif
  78768. case TK_STRING: {
  78769. sqlite3TreeViewLine(pView,"%Q", pExpr->u.zToken);
  78770. break;
  78771. }
  78772. case TK_NULL: {
  78773. sqlite3TreeViewLine(pView,"NULL");
  78774. break;
  78775. }
  78776. #ifndef SQLITE_OMIT_BLOB_LITERAL
  78777. case TK_BLOB: {
  78778. sqlite3TreeViewLine(pView,"%s", pExpr->u.zToken);
  78779. break;
  78780. }
  78781. #endif
  78782. case TK_VARIABLE: {
  78783. sqlite3TreeViewLine(pView,"VARIABLE(%s,%d)",
  78784. pExpr->u.zToken, pExpr->iColumn);
  78785. break;
  78786. }
  78787. case TK_REGISTER: {
  78788. sqlite3TreeViewLine(pView,"REGISTER(%d)", pExpr->iTable);
  78789. break;
  78790. }
  78791. case TK_AS: {
  78792. sqlite3TreeViewLine(pView,"AS %Q", pExpr->u.zToken);
  78793. sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
  78794. break;
  78795. }
  78796. case TK_ID: {
  78797. sqlite3TreeViewLine(pView,"ID %Q", pExpr->u.zToken);
  78798. break;
  78799. }
  78800. #ifndef SQLITE_OMIT_CAST
  78801. case TK_CAST: {
  78802. /* Expressions of the form: CAST(pLeft AS token) */
  78803. sqlite3TreeViewLine(pView,"CAST %Q", pExpr->u.zToken);
  78804. sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
  78805. break;
  78806. }
  78807. #endif /* SQLITE_OMIT_CAST */
  78808. case TK_LT: zBinOp = "LT"; break;
  78809. case TK_LE: zBinOp = "LE"; break;
  78810. case TK_GT: zBinOp = "GT"; break;
  78811. case TK_GE: zBinOp = "GE"; break;
  78812. case TK_NE: zBinOp = "NE"; break;
  78813. case TK_EQ: zBinOp = "EQ"; break;
  78814. case TK_IS: zBinOp = "IS"; break;
  78815. case TK_ISNOT: zBinOp = "ISNOT"; break;
  78816. case TK_AND: zBinOp = "AND"; break;
  78817. case TK_OR: zBinOp = "OR"; break;
  78818. case TK_PLUS: zBinOp = "ADD"; break;
  78819. case TK_STAR: zBinOp = "MUL"; break;
  78820. case TK_MINUS: zBinOp = "SUB"; break;
  78821. case TK_REM: zBinOp = "REM"; break;
  78822. case TK_BITAND: zBinOp = "BITAND"; break;
  78823. case TK_BITOR: zBinOp = "BITOR"; break;
  78824. case TK_SLASH: zBinOp = "DIV"; break;
  78825. case TK_LSHIFT: zBinOp = "LSHIFT"; break;
  78826. case TK_RSHIFT: zBinOp = "RSHIFT"; break;
  78827. case TK_CONCAT: zBinOp = "CONCAT"; break;
  78828. case TK_DOT: zBinOp = "DOT"; break;
  78829. case TK_UMINUS: zUniOp = "UMINUS"; break;
  78830. case TK_UPLUS: zUniOp = "UPLUS"; break;
  78831. case TK_BITNOT: zUniOp = "BITNOT"; break;
  78832. case TK_NOT: zUniOp = "NOT"; break;
  78833. case TK_ISNULL: zUniOp = "ISNULL"; break;
  78834. case TK_NOTNULL: zUniOp = "NOTNULL"; break;
  78835. case TK_COLLATE: {
  78836. sqlite3TreeViewLine(pView, "COLLATE %Q", pExpr->u.zToken);
  78837. sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
  78838. break;
  78839. }
  78840. case TK_AGG_FUNCTION:
  78841. case TK_FUNCTION: {
  78842. ExprList *pFarg; /* List of function arguments */
  78843. if( ExprHasProperty(pExpr, EP_TokenOnly) ){
  78844. pFarg = 0;
  78845. }else{
  78846. pFarg = pExpr->x.pList;
  78847. }
  78848. if( pExpr->op==TK_AGG_FUNCTION ){
  78849. sqlite3TreeViewLine(pView, "AGG_FUNCTION%d %Q",
  78850. pExpr->op2, pExpr->u.zToken);
  78851. }else{
  78852. sqlite3TreeViewLine(pView, "FUNCTION %Q", pExpr->u.zToken);
  78853. }
  78854. if( pFarg ){
  78855. sqlite3TreeViewExprList(pView, pFarg, 0, 0);
  78856. }
  78857. break;
  78858. }
  78859. #ifndef SQLITE_OMIT_SUBQUERY
  78860. case TK_EXISTS: {
  78861. sqlite3TreeViewLine(pView, "EXISTS-expr");
  78862. sqlite3TreeViewSelect(pView, pExpr->x.pSelect, 0);
  78863. break;
  78864. }
  78865. case TK_SELECT: {
  78866. sqlite3TreeViewLine(pView, "SELECT-expr");
  78867. sqlite3TreeViewSelect(pView, pExpr->x.pSelect, 0);
  78868. break;
  78869. }
  78870. case TK_IN: {
  78871. sqlite3TreeViewLine(pView, "IN");
  78872. sqlite3TreeViewExpr(pView, pExpr->pLeft, 1);
  78873. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  78874. sqlite3TreeViewSelect(pView, pExpr->x.pSelect, 0);
  78875. }else{
  78876. sqlite3TreeViewExprList(pView, pExpr->x.pList, 0, 0);
  78877. }
  78878. break;
  78879. }
  78880. #endif /* SQLITE_OMIT_SUBQUERY */
  78881. /*
  78882. ** x BETWEEN y AND z
  78883. **
  78884. ** This is equivalent to
  78885. **
  78886. ** x>=y AND x<=z
  78887. **
  78888. ** X is stored in pExpr->pLeft.
  78889. ** Y is stored in pExpr->pList->a[0].pExpr.
  78890. ** Z is stored in pExpr->pList->a[1].pExpr.
  78891. */
  78892. case TK_BETWEEN: {
  78893. Expr *pX = pExpr->pLeft;
  78894. Expr *pY = pExpr->x.pList->a[0].pExpr;
  78895. Expr *pZ = pExpr->x.pList->a[1].pExpr;
  78896. sqlite3TreeViewLine(pView, "BETWEEN");
  78897. sqlite3TreeViewExpr(pView, pX, 1);
  78898. sqlite3TreeViewExpr(pView, pY, 1);
  78899. sqlite3TreeViewExpr(pView, pZ, 0);
  78900. break;
  78901. }
  78902. case TK_TRIGGER: {
  78903. /* If the opcode is TK_TRIGGER, then the expression is a reference
  78904. ** to a column in the new.* or old.* pseudo-tables available to
  78905. ** trigger programs. In this case Expr.iTable is set to 1 for the
  78906. ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
  78907. ** is set to the column of the pseudo-table to read, or to -1 to
  78908. ** read the rowid field.
  78909. */
  78910. sqlite3TreeViewLine(pView, "%s(%d)",
  78911. pExpr->iTable ? "NEW" : "OLD", pExpr->iColumn);
  78912. break;
  78913. }
  78914. case TK_CASE: {
  78915. sqlite3TreeViewLine(pView, "CASE");
  78916. sqlite3TreeViewExpr(pView, pExpr->pLeft, 1);
  78917. sqlite3TreeViewExprList(pView, pExpr->x.pList, 0, 0);
  78918. break;
  78919. }
  78920. #ifndef SQLITE_OMIT_TRIGGER
  78921. case TK_RAISE: {
  78922. const char *zType = "unk";
  78923. switch( pExpr->affinity ){
  78924. case OE_Rollback: zType = "rollback"; break;
  78925. case OE_Abort: zType = "abort"; break;
  78926. case OE_Fail: zType = "fail"; break;
  78927. case OE_Ignore: zType = "ignore"; break;
  78928. }
  78929. sqlite3TreeViewLine(pView, "RAISE %s(%Q)", zType, pExpr->u.zToken);
  78930. break;
  78931. }
  78932. #endif
  78933. default: {
  78934. sqlite3TreeViewLine(pView, "op=%d", pExpr->op);
  78935. break;
  78936. }
  78937. }
  78938. if( zBinOp ){
  78939. sqlite3TreeViewLine(pView, "%s", zBinOp);
  78940. sqlite3TreeViewExpr(pView, pExpr->pLeft, 1);
  78941. sqlite3TreeViewExpr(pView, pExpr->pRight, 0);
  78942. }else if( zUniOp ){
  78943. sqlite3TreeViewLine(pView, "%s", zUniOp);
  78944. sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
  78945. }
  78946. sqlite3TreeViewPop(pView);
  78947. }
  78948. #endif /* SQLITE_DEBUG */
  78949. #ifdef SQLITE_DEBUG
  78950. /*
  78951. ** Generate a human-readable explanation of an expression list.
  78952. */
  78953. SQLITE_PRIVATE void sqlite3TreeViewExprList(
  78954. TreeView *pView,
  78955. const ExprList *pList,
  78956. u8 moreToFollow,
  78957. const char *zLabel
  78958. ){
  78959. int i;
  78960. pView = sqlite3TreeViewPush(pView, moreToFollow);
  78961. if( zLabel==0 || zLabel[0]==0 ) zLabel = "LIST";
  78962. if( pList==0 ){
  78963. sqlite3TreeViewLine(pView, "%s (empty)", zLabel);
  78964. }else{
  78965. sqlite3TreeViewLine(pView, "%s", zLabel);
  78966. for(i=0; i<pList->nExpr; i++){
  78967. sqlite3TreeViewExpr(pView, pList->a[i].pExpr, i<pList->nExpr-1);
  78968. #if 0
  78969. if( pList->a[i].zName ){
  78970. sqlite3ExplainPrintf(pOut, " AS %s", pList->a[i].zName);
  78971. }
  78972. if( pList->a[i].bSpanIsTab ){
  78973. sqlite3ExplainPrintf(pOut, " (%s)", pList->a[i].zSpan);
  78974. }
  78975. #endif
  78976. }
  78977. }
  78978. sqlite3TreeViewPop(pView);
  78979. }
  78980. #endif /* SQLITE_DEBUG */
  78981. /*
  78982. ** Generate code that pushes the value of every element of the given
  78983. ** expression list into a sequence of registers beginning at target.
  78984. **
  78985. ** Return the number of elements evaluated.
  78986. **
  78987. ** The SQLITE_ECEL_DUP flag prevents the arguments from being
  78988. ** filled using OP_SCopy. OP_Copy must be used instead.
  78989. **
  78990. ** The SQLITE_ECEL_FACTOR argument allows constant arguments to be
  78991. ** factored out into initialization code.
  78992. */
  78993. SQLITE_PRIVATE int sqlite3ExprCodeExprList(
  78994. Parse *pParse, /* Parsing context */
  78995. ExprList *pList, /* The expression list to be coded */
  78996. int target, /* Where to write results */
  78997. u8 flags /* SQLITE_ECEL_* flags */
  78998. ){
  78999. struct ExprList_item *pItem;
  79000. int i, n;
  79001. u8 copyOp = (flags & SQLITE_ECEL_DUP) ? OP_Copy : OP_SCopy;
  79002. assert( pList!=0 );
  79003. assert( target>0 );
  79004. assert( pParse->pVdbe!=0 ); /* Never gets this far otherwise */
  79005. n = pList->nExpr;
  79006. if( !ConstFactorOk(pParse) ) flags &= ~SQLITE_ECEL_FACTOR;
  79007. for(pItem=pList->a, i=0; i<n; i++, pItem++){
  79008. Expr *pExpr = pItem->pExpr;
  79009. if( (flags & SQLITE_ECEL_FACTOR)!=0 && sqlite3ExprIsConstant(pExpr) ){
  79010. sqlite3ExprCodeAtInit(pParse, pExpr, target+i, 0);
  79011. }else{
  79012. int inReg = sqlite3ExprCodeTarget(pParse, pExpr, target+i);
  79013. if( inReg!=target+i ){
  79014. VdbeOp *pOp;
  79015. Vdbe *v = pParse->pVdbe;
  79016. if( copyOp==OP_Copy
  79017. && (pOp=sqlite3VdbeGetOp(v, -1))->opcode==OP_Copy
  79018. && pOp->p1+pOp->p3+1==inReg
  79019. && pOp->p2+pOp->p3+1==target+i
  79020. ){
  79021. pOp->p3++;
  79022. }else{
  79023. sqlite3VdbeAddOp2(v, copyOp, inReg, target+i);
  79024. }
  79025. }
  79026. }
  79027. }
  79028. return n;
  79029. }
  79030. /*
  79031. ** Generate code for a BETWEEN operator.
  79032. **
  79033. ** x BETWEEN y AND z
  79034. **
  79035. ** The above is equivalent to
  79036. **
  79037. ** x>=y AND x<=z
  79038. **
  79039. ** Code it as such, taking care to do the common subexpression
  79040. ** elimination of x.
  79041. */
  79042. static void exprCodeBetween(
  79043. Parse *pParse, /* Parsing and code generating context */
  79044. Expr *pExpr, /* The BETWEEN expression */
  79045. int dest, /* Jump here if the jump is taken */
  79046. int jumpIfTrue, /* Take the jump if the BETWEEN is true */
  79047. int jumpIfNull /* Take the jump if the BETWEEN is NULL */
  79048. ){
  79049. Expr exprAnd; /* The AND operator in x>=y AND x<=z */
  79050. Expr compLeft; /* The x>=y term */
  79051. Expr compRight; /* The x<=z term */
  79052. Expr exprX; /* The x subexpression */
  79053. int regFree1 = 0; /* Temporary use register */
  79054. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  79055. exprX = *pExpr->pLeft;
  79056. exprAnd.op = TK_AND;
  79057. exprAnd.pLeft = &compLeft;
  79058. exprAnd.pRight = &compRight;
  79059. compLeft.op = TK_GE;
  79060. compLeft.pLeft = &exprX;
  79061. compLeft.pRight = pExpr->x.pList->a[0].pExpr;
  79062. compRight.op = TK_LE;
  79063. compRight.pLeft = &exprX;
  79064. compRight.pRight = pExpr->x.pList->a[1].pExpr;
  79065. exprToRegister(&exprX, sqlite3ExprCodeTemp(pParse, &exprX, &regFree1));
  79066. if( jumpIfTrue ){
  79067. sqlite3ExprIfTrue(pParse, &exprAnd, dest, jumpIfNull);
  79068. }else{
  79069. sqlite3ExprIfFalse(pParse, &exprAnd, dest, jumpIfNull);
  79070. }
  79071. sqlite3ReleaseTempReg(pParse, regFree1);
  79072. /* Ensure adequate test coverage */
  79073. testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1==0 );
  79074. testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1!=0 );
  79075. testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1==0 );
  79076. testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1!=0 );
  79077. testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1==0 );
  79078. testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1!=0 );
  79079. testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1==0 );
  79080. testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1!=0 );
  79081. }
  79082. /*
  79083. ** Generate code for a boolean expression such that a jump is made
  79084. ** to the label "dest" if the expression is true but execution
  79085. ** continues straight thru if the expression is false.
  79086. **
  79087. ** If the expression evaluates to NULL (neither true nor false), then
  79088. ** take the jump if the jumpIfNull flag is SQLITE_JUMPIFNULL.
  79089. **
  79090. ** This code depends on the fact that certain token values (ex: TK_EQ)
  79091. ** are the same as opcode values (ex: OP_Eq) that implement the corresponding
  79092. ** operation. Special comments in vdbe.c and the mkopcodeh.awk script in
  79093. ** the make process cause these values to align. Assert()s in the code
  79094. ** below verify that the numbers are aligned correctly.
  79095. */
  79096. SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
  79097. Vdbe *v = pParse->pVdbe;
  79098. int op = 0;
  79099. int regFree1 = 0;
  79100. int regFree2 = 0;
  79101. int r1, r2;
  79102. assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
  79103. if( NEVER(v==0) ) return; /* Existence of VDBE checked by caller */
  79104. if( NEVER(pExpr==0) ) return; /* No way this can happen */
  79105. op = pExpr->op;
  79106. switch( op ){
  79107. case TK_AND: {
  79108. int d2 = sqlite3VdbeMakeLabel(v);
  79109. testcase( jumpIfNull==0 );
  79110. sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2,jumpIfNull^SQLITE_JUMPIFNULL);
  79111. sqlite3ExprCachePush(pParse);
  79112. sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
  79113. sqlite3VdbeResolveLabel(v, d2);
  79114. sqlite3ExprCachePop(pParse);
  79115. break;
  79116. }
  79117. case TK_OR: {
  79118. testcase( jumpIfNull==0 );
  79119. sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
  79120. sqlite3ExprCachePush(pParse);
  79121. sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
  79122. sqlite3ExprCachePop(pParse);
  79123. break;
  79124. }
  79125. case TK_NOT: {
  79126. testcase( jumpIfNull==0 );
  79127. sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
  79128. break;
  79129. }
  79130. case TK_LT:
  79131. case TK_LE:
  79132. case TK_GT:
  79133. case TK_GE:
  79134. case TK_NE:
  79135. case TK_EQ: {
  79136. testcase( jumpIfNull==0 );
  79137. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  79138. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
  79139. codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
  79140. r1, r2, dest, jumpIfNull);
  79141. assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
  79142. assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
  79143. assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
  79144. assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
  79145. assert(TK_EQ==OP_Eq); testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq);
  79146. assert(TK_NE==OP_Ne); testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne);
  79147. testcase( regFree1==0 );
  79148. testcase( regFree2==0 );
  79149. break;
  79150. }
  79151. case TK_IS:
  79152. case TK_ISNOT: {
  79153. testcase( op==TK_IS );
  79154. testcase( op==TK_ISNOT );
  79155. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  79156. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
  79157. op = (op==TK_IS) ? TK_EQ : TK_NE;
  79158. codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
  79159. r1, r2, dest, SQLITE_NULLEQ);
  79160. VdbeCoverageIf(v, op==TK_EQ);
  79161. VdbeCoverageIf(v, op==TK_NE);
  79162. testcase( regFree1==0 );
  79163. testcase( regFree2==0 );
  79164. break;
  79165. }
  79166. case TK_ISNULL:
  79167. case TK_NOTNULL: {
  79168. assert( TK_ISNULL==OP_IsNull ); testcase( op==TK_ISNULL );
  79169. assert( TK_NOTNULL==OP_NotNull ); testcase( op==TK_NOTNULL );
  79170. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  79171. sqlite3VdbeAddOp2(v, op, r1, dest);
  79172. VdbeCoverageIf(v, op==TK_ISNULL);
  79173. VdbeCoverageIf(v, op==TK_NOTNULL);
  79174. testcase( regFree1==0 );
  79175. break;
  79176. }
  79177. case TK_BETWEEN: {
  79178. testcase( jumpIfNull==0 );
  79179. exprCodeBetween(pParse, pExpr, dest, 1, jumpIfNull);
  79180. break;
  79181. }
  79182. #ifndef SQLITE_OMIT_SUBQUERY
  79183. case TK_IN: {
  79184. int destIfFalse = sqlite3VdbeMakeLabel(v);
  79185. int destIfNull = jumpIfNull ? dest : destIfFalse;
  79186. sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
  79187. sqlite3VdbeAddOp2(v, OP_Goto, 0, dest);
  79188. sqlite3VdbeResolveLabel(v, destIfFalse);
  79189. break;
  79190. }
  79191. #endif
  79192. default: {
  79193. if( exprAlwaysTrue(pExpr) ){
  79194. sqlite3VdbeAddOp2(v, OP_Goto, 0, dest);
  79195. }else if( exprAlwaysFalse(pExpr) ){
  79196. /* No-op */
  79197. }else{
  79198. r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
  79199. sqlite3VdbeAddOp3(v, OP_If, r1, dest, jumpIfNull!=0);
  79200. VdbeCoverage(v);
  79201. testcase( regFree1==0 );
  79202. testcase( jumpIfNull==0 );
  79203. }
  79204. break;
  79205. }
  79206. }
  79207. sqlite3ReleaseTempReg(pParse, regFree1);
  79208. sqlite3ReleaseTempReg(pParse, regFree2);
  79209. }
  79210. /*
  79211. ** Generate code for a boolean expression such that a jump is made
  79212. ** to the label "dest" if the expression is false but execution
  79213. ** continues straight thru if the expression is true.
  79214. **
  79215. ** If the expression evaluates to NULL (neither true nor false) then
  79216. ** jump if jumpIfNull is SQLITE_JUMPIFNULL or fall through if jumpIfNull
  79217. ** is 0.
  79218. */
  79219. SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
  79220. Vdbe *v = pParse->pVdbe;
  79221. int op = 0;
  79222. int regFree1 = 0;
  79223. int regFree2 = 0;
  79224. int r1, r2;
  79225. assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
  79226. if( NEVER(v==0) ) return; /* Existence of VDBE checked by caller */
  79227. if( pExpr==0 ) return;
  79228. /* The value of pExpr->op and op are related as follows:
  79229. **
  79230. ** pExpr->op op
  79231. ** --------- ----------
  79232. ** TK_ISNULL OP_NotNull
  79233. ** TK_NOTNULL OP_IsNull
  79234. ** TK_NE OP_Eq
  79235. ** TK_EQ OP_Ne
  79236. ** TK_GT OP_Le
  79237. ** TK_LE OP_Gt
  79238. ** TK_GE OP_Lt
  79239. ** TK_LT OP_Ge
  79240. **
  79241. ** For other values of pExpr->op, op is undefined and unused.
  79242. ** The value of TK_ and OP_ constants are arranged such that we
  79243. ** can compute the mapping above using the following expression.
  79244. ** Assert()s verify that the computation is correct.
  79245. */
  79246. op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1);
  79247. /* Verify correct alignment of TK_ and OP_ constants
  79248. */
  79249. assert( pExpr->op!=TK_ISNULL || op==OP_NotNull );
  79250. assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull );
  79251. assert( pExpr->op!=TK_NE || op==OP_Eq );
  79252. assert( pExpr->op!=TK_EQ || op==OP_Ne );
  79253. assert( pExpr->op!=TK_LT || op==OP_Ge );
  79254. assert( pExpr->op!=TK_LE || op==OP_Gt );
  79255. assert( pExpr->op!=TK_GT || op==OP_Le );
  79256. assert( pExpr->op!=TK_GE || op==OP_Lt );
  79257. switch( pExpr->op ){
  79258. case TK_AND: {
  79259. testcase( jumpIfNull==0 );
  79260. sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
  79261. sqlite3ExprCachePush(pParse);
  79262. sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
  79263. sqlite3ExprCachePop(pParse);
  79264. break;
  79265. }
  79266. case TK_OR: {
  79267. int d2 = sqlite3VdbeMakeLabel(v);
  79268. testcase( jumpIfNull==0 );
  79269. sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2, jumpIfNull^SQLITE_JUMPIFNULL);
  79270. sqlite3ExprCachePush(pParse);
  79271. sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
  79272. sqlite3VdbeResolveLabel(v, d2);
  79273. sqlite3ExprCachePop(pParse);
  79274. break;
  79275. }
  79276. case TK_NOT: {
  79277. testcase( jumpIfNull==0 );
  79278. sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
  79279. break;
  79280. }
  79281. case TK_LT:
  79282. case TK_LE:
  79283. case TK_GT:
  79284. case TK_GE:
  79285. case TK_NE:
  79286. case TK_EQ: {
  79287. testcase( jumpIfNull==0 );
  79288. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  79289. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
  79290. codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
  79291. r1, r2, dest, jumpIfNull);
  79292. assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
  79293. assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
  79294. assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
  79295. assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
  79296. assert(TK_EQ==OP_Eq); testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq);
  79297. assert(TK_NE==OP_Ne); testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne);
  79298. testcase( regFree1==0 );
  79299. testcase( regFree2==0 );
  79300. break;
  79301. }
  79302. case TK_IS:
  79303. case TK_ISNOT: {
  79304. testcase( pExpr->op==TK_IS );
  79305. testcase( pExpr->op==TK_ISNOT );
  79306. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  79307. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
  79308. op = (pExpr->op==TK_IS) ? TK_NE : TK_EQ;
  79309. codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
  79310. r1, r2, dest, SQLITE_NULLEQ);
  79311. VdbeCoverageIf(v, op==TK_EQ);
  79312. VdbeCoverageIf(v, op==TK_NE);
  79313. testcase( regFree1==0 );
  79314. testcase( regFree2==0 );
  79315. break;
  79316. }
  79317. case TK_ISNULL:
  79318. case TK_NOTNULL: {
  79319. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  79320. sqlite3VdbeAddOp2(v, op, r1, dest);
  79321. testcase( op==TK_ISNULL ); VdbeCoverageIf(v, op==TK_ISNULL);
  79322. testcase( op==TK_NOTNULL ); VdbeCoverageIf(v, op==TK_NOTNULL);
  79323. testcase( regFree1==0 );
  79324. break;
  79325. }
  79326. case TK_BETWEEN: {
  79327. testcase( jumpIfNull==0 );
  79328. exprCodeBetween(pParse, pExpr, dest, 0, jumpIfNull);
  79329. break;
  79330. }
  79331. #ifndef SQLITE_OMIT_SUBQUERY
  79332. case TK_IN: {
  79333. if( jumpIfNull ){
  79334. sqlite3ExprCodeIN(pParse, pExpr, dest, dest);
  79335. }else{
  79336. int destIfNull = sqlite3VdbeMakeLabel(v);
  79337. sqlite3ExprCodeIN(pParse, pExpr, dest, destIfNull);
  79338. sqlite3VdbeResolveLabel(v, destIfNull);
  79339. }
  79340. break;
  79341. }
  79342. #endif
  79343. default: {
  79344. if( exprAlwaysFalse(pExpr) ){
  79345. sqlite3VdbeAddOp2(v, OP_Goto, 0, dest);
  79346. }else if( exprAlwaysTrue(pExpr) ){
  79347. /* no-op */
  79348. }else{
  79349. r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
  79350. sqlite3VdbeAddOp3(v, OP_IfNot, r1, dest, jumpIfNull!=0);
  79351. VdbeCoverage(v);
  79352. testcase( regFree1==0 );
  79353. testcase( jumpIfNull==0 );
  79354. }
  79355. break;
  79356. }
  79357. }
  79358. sqlite3ReleaseTempReg(pParse, regFree1);
  79359. sqlite3ReleaseTempReg(pParse, regFree2);
  79360. }
  79361. /*
  79362. ** Do a deep comparison of two expression trees. Return 0 if the two
  79363. ** expressions are completely identical. Return 1 if they differ only
  79364. ** by a COLLATE operator at the top level. Return 2 if there are differences
  79365. ** other than the top-level COLLATE operator.
  79366. **
  79367. ** If any subelement of pB has Expr.iTable==(-1) then it is allowed
  79368. ** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
  79369. **
  79370. ** The pA side might be using TK_REGISTER. If that is the case and pB is
  79371. ** not using TK_REGISTER but is otherwise equivalent, then still return 0.
  79372. **
  79373. ** Sometimes this routine will return 2 even if the two expressions
  79374. ** really are equivalent. If we cannot prove that the expressions are
  79375. ** identical, we return 2 just to be safe. So if this routine
  79376. ** returns 2, then you do not really know for certain if the two
  79377. ** expressions are the same. But if you get a 0 or 1 return, then you
  79378. ** can be sure the expressions are the same. In the places where
  79379. ** this routine is used, it does not hurt to get an extra 2 - that
  79380. ** just might result in some slightly slower code. But returning
  79381. ** an incorrect 0 or 1 could lead to a malfunction.
  79382. */
  79383. SQLITE_PRIVATE int sqlite3ExprCompare(Expr *pA, Expr *pB, int iTab){
  79384. u32 combinedFlags;
  79385. if( pA==0 || pB==0 ){
  79386. return pB==pA ? 0 : 2;
  79387. }
  79388. combinedFlags = pA->flags | pB->flags;
  79389. if( combinedFlags & EP_IntValue ){
  79390. if( (pA->flags&pB->flags&EP_IntValue)!=0 && pA->u.iValue==pB->u.iValue ){
  79391. return 0;
  79392. }
  79393. return 2;
  79394. }
  79395. if( pA->op!=pB->op ){
  79396. if( pA->op==TK_COLLATE && sqlite3ExprCompare(pA->pLeft, pB, iTab)<2 ){
  79397. return 1;
  79398. }
  79399. if( pB->op==TK_COLLATE && sqlite3ExprCompare(pA, pB->pLeft, iTab)<2 ){
  79400. return 1;
  79401. }
  79402. return 2;
  79403. }
  79404. if( pA->op!=TK_COLUMN && ALWAYS(pA->op!=TK_AGG_COLUMN) && pA->u.zToken ){
  79405. if( strcmp(pA->u.zToken,pB->u.zToken)!=0 ){
  79406. return pA->op==TK_COLLATE ? 1 : 2;
  79407. }
  79408. }
  79409. if( (pA->flags & EP_Distinct)!=(pB->flags & EP_Distinct) ) return 2;
  79410. if( ALWAYS((combinedFlags & EP_TokenOnly)==0) ){
  79411. if( combinedFlags & EP_xIsSelect ) return 2;
  79412. if( sqlite3ExprCompare(pA->pLeft, pB->pLeft, iTab) ) return 2;
  79413. if( sqlite3ExprCompare(pA->pRight, pB->pRight, iTab) ) return 2;
  79414. if( sqlite3ExprListCompare(pA->x.pList, pB->x.pList, iTab) ) return 2;
  79415. if( ALWAYS((combinedFlags & EP_Reduced)==0) ){
  79416. if( pA->iColumn!=pB->iColumn ) return 2;
  79417. if( pA->iTable!=pB->iTable
  79418. && (pA->iTable!=iTab || NEVER(pB->iTable>=0)) ) return 2;
  79419. }
  79420. }
  79421. return 0;
  79422. }
  79423. /*
  79424. ** Compare two ExprList objects. Return 0 if they are identical and
  79425. ** non-zero if they differ in any way.
  79426. **
  79427. ** If any subelement of pB has Expr.iTable==(-1) then it is allowed
  79428. ** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
  79429. **
  79430. ** This routine might return non-zero for equivalent ExprLists. The
  79431. ** only consequence will be disabled optimizations. But this routine
  79432. ** must never return 0 if the two ExprList objects are different, or
  79433. ** a malfunction will result.
  79434. **
  79435. ** Two NULL pointers are considered to be the same. But a NULL pointer
  79436. ** always differs from a non-NULL pointer.
  79437. */
  79438. SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList *pA, ExprList *pB, int iTab){
  79439. int i;
  79440. if( pA==0 && pB==0 ) return 0;
  79441. if( pA==0 || pB==0 ) return 1;
  79442. if( pA->nExpr!=pB->nExpr ) return 1;
  79443. for(i=0; i<pA->nExpr; i++){
  79444. Expr *pExprA = pA->a[i].pExpr;
  79445. Expr *pExprB = pB->a[i].pExpr;
  79446. if( pA->a[i].sortOrder!=pB->a[i].sortOrder ) return 1;
  79447. if( sqlite3ExprCompare(pExprA, pExprB, iTab) ) return 1;
  79448. }
  79449. return 0;
  79450. }
  79451. /*
  79452. ** Return true if we can prove the pE2 will always be true if pE1 is
  79453. ** true. Return false if we cannot complete the proof or if pE2 might
  79454. ** be false. Examples:
  79455. **
  79456. ** pE1: x==5 pE2: x==5 Result: true
  79457. ** pE1: x>0 pE2: x==5 Result: false
  79458. ** pE1: x=21 pE2: x=21 OR y=43 Result: true
  79459. ** pE1: x!=123 pE2: x IS NOT NULL Result: true
  79460. ** pE1: x!=?1 pE2: x IS NOT NULL Result: true
  79461. ** pE1: x IS NULL pE2: x IS NOT NULL Result: false
  79462. ** pE1: x IS ?2 pE2: x IS NOT NULL Reuslt: false
  79463. **
  79464. ** When comparing TK_COLUMN nodes between pE1 and pE2, if pE2 has
  79465. ** Expr.iTable<0 then assume a table number given by iTab.
  79466. **
  79467. ** When in doubt, return false. Returning true might give a performance
  79468. ** improvement. Returning false might cause a performance reduction, but
  79469. ** it will always give the correct answer and is hence always safe.
  79470. */
  79471. SQLITE_PRIVATE int sqlite3ExprImpliesExpr(Expr *pE1, Expr *pE2, int iTab){
  79472. if( sqlite3ExprCompare(pE1, pE2, iTab)==0 ){
  79473. return 1;
  79474. }
  79475. if( pE2->op==TK_OR
  79476. && (sqlite3ExprImpliesExpr(pE1, pE2->pLeft, iTab)
  79477. || sqlite3ExprImpliesExpr(pE1, pE2->pRight, iTab) )
  79478. ){
  79479. return 1;
  79480. }
  79481. if( pE2->op==TK_NOTNULL
  79482. && sqlite3ExprCompare(pE1->pLeft, pE2->pLeft, iTab)==0
  79483. && (pE1->op!=TK_ISNULL && pE1->op!=TK_IS)
  79484. ){
  79485. return 1;
  79486. }
  79487. return 0;
  79488. }
  79489. /*
  79490. ** An instance of the following structure is used by the tree walker
  79491. ** to count references to table columns in the arguments of an
  79492. ** aggregate function, in order to implement the
  79493. ** sqlite3FunctionThisSrc() routine.
  79494. */
  79495. struct SrcCount {
  79496. SrcList *pSrc; /* One particular FROM clause in a nested query */
  79497. int nThis; /* Number of references to columns in pSrcList */
  79498. int nOther; /* Number of references to columns in other FROM clauses */
  79499. };
  79500. /*
  79501. ** Count the number of references to columns.
  79502. */
  79503. static int exprSrcCount(Walker *pWalker, Expr *pExpr){
  79504. /* The NEVER() on the second term is because sqlite3FunctionUsesThisSrc()
  79505. ** is always called before sqlite3ExprAnalyzeAggregates() and so the
  79506. ** TK_COLUMNs have not yet been converted into TK_AGG_COLUMN. If
  79507. ** sqlite3FunctionUsesThisSrc() is used differently in the future, the
  79508. ** NEVER() will need to be removed. */
  79509. if( pExpr->op==TK_COLUMN || NEVER(pExpr->op==TK_AGG_COLUMN) ){
  79510. int i;
  79511. struct SrcCount *p = pWalker->u.pSrcCount;
  79512. SrcList *pSrc = p->pSrc;
  79513. for(i=0; i<pSrc->nSrc; i++){
  79514. if( pExpr->iTable==pSrc->a[i].iCursor ) break;
  79515. }
  79516. if( i<pSrc->nSrc ){
  79517. p->nThis++;
  79518. }else{
  79519. p->nOther++;
  79520. }
  79521. }
  79522. return WRC_Continue;
  79523. }
  79524. /*
  79525. ** Determine if any of the arguments to the pExpr Function reference
  79526. ** pSrcList. Return true if they do. Also return true if the function
  79527. ** has no arguments or has only constant arguments. Return false if pExpr
  79528. ** references columns but not columns of tables found in pSrcList.
  79529. */
  79530. SQLITE_PRIVATE int sqlite3FunctionUsesThisSrc(Expr *pExpr, SrcList *pSrcList){
  79531. Walker w;
  79532. struct SrcCount cnt;
  79533. assert( pExpr->op==TK_AGG_FUNCTION );
  79534. memset(&w, 0, sizeof(w));
  79535. w.xExprCallback = exprSrcCount;
  79536. w.u.pSrcCount = &cnt;
  79537. cnt.pSrc = pSrcList;
  79538. cnt.nThis = 0;
  79539. cnt.nOther = 0;
  79540. sqlite3WalkExprList(&w, pExpr->x.pList);
  79541. return cnt.nThis>0 || cnt.nOther==0;
  79542. }
  79543. /*
  79544. ** Add a new element to the pAggInfo->aCol[] array. Return the index of
  79545. ** the new element. Return a negative number if malloc fails.
  79546. */
  79547. static int addAggInfoColumn(sqlite3 *db, AggInfo *pInfo){
  79548. int i;
  79549. pInfo->aCol = sqlite3ArrayAllocate(
  79550. db,
  79551. pInfo->aCol,
  79552. sizeof(pInfo->aCol[0]),
  79553. &pInfo->nColumn,
  79554. &i
  79555. );
  79556. return i;
  79557. }
  79558. /*
  79559. ** Add a new element to the pAggInfo->aFunc[] array. Return the index of
  79560. ** the new element. Return a negative number if malloc fails.
  79561. */
  79562. static int addAggInfoFunc(sqlite3 *db, AggInfo *pInfo){
  79563. int i;
  79564. pInfo->aFunc = sqlite3ArrayAllocate(
  79565. db,
  79566. pInfo->aFunc,
  79567. sizeof(pInfo->aFunc[0]),
  79568. &pInfo->nFunc,
  79569. &i
  79570. );
  79571. return i;
  79572. }
  79573. /*
  79574. ** This is the xExprCallback for a tree walker. It is used to
  79575. ** implement sqlite3ExprAnalyzeAggregates(). See sqlite3ExprAnalyzeAggregates
  79576. ** for additional information.
  79577. */
  79578. static int analyzeAggregate(Walker *pWalker, Expr *pExpr){
  79579. int i;
  79580. NameContext *pNC = pWalker->u.pNC;
  79581. Parse *pParse = pNC->pParse;
  79582. SrcList *pSrcList = pNC->pSrcList;
  79583. AggInfo *pAggInfo = pNC->pAggInfo;
  79584. switch( pExpr->op ){
  79585. case TK_AGG_COLUMN:
  79586. case TK_COLUMN: {
  79587. testcase( pExpr->op==TK_AGG_COLUMN );
  79588. testcase( pExpr->op==TK_COLUMN );
  79589. /* Check to see if the column is in one of the tables in the FROM
  79590. ** clause of the aggregate query */
  79591. if( ALWAYS(pSrcList!=0) ){
  79592. struct SrcList_item *pItem = pSrcList->a;
  79593. for(i=0; i<pSrcList->nSrc; i++, pItem++){
  79594. struct AggInfo_col *pCol;
  79595. assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
  79596. if( pExpr->iTable==pItem->iCursor ){
  79597. /* If we reach this point, it means that pExpr refers to a table
  79598. ** that is in the FROM clause of the aggregate query.
  79599. **
  79600. ** Make an entry for the column in pAggInfo->aCol[] if there
  79601. ** is not an entry there already.
  79602. */
  79603. int k;
  79604. pCol = pAggInfo->aCol;
  79605. for(k=0; k<pAggInfo->nColumn; k++, pCol++){
  79606. if( pCol->iTable==pExpr->iTable &&
  79607. pCol->iColumn==pExpr->iColumn ){
  79608. break;
  79609. }
  79610. }
  79611. if( (k>=pAggInfo->nColumn)
  79612. && (k = addAggInfoColumn(pParse->db, pAggInfo))>=0
  79613. ){
  79614. pCol = &pAggInfo->aCol[k];
  79615. pCol->pTab = pExpr->pTab;
  79616. pCol->iTable = pExpr->iTable;
  79617. pCol->iColumn = pExpr->iColumn;
  79618. pCol->iMem = ++pParse->nMem;
  79619. pCol->iSorterColumn = -1;
  79620. pCol->pExpr = pExpr;
  79621. if( pAggInfo->pGroupBy ){
  79622. int j, n;
  79623. ExprList *pGB = pAggInfo->pGroupBy;
  79624. struct ExprList_item *pTerm = pGB->a;
  79625. n = pGB->nExpr;
  79626. for(j=0; j<n; j++, pTerm++){
  79627. Expr *pE = pTerm->pExpr;
  79628. if( pE->op==TK_COLUMN && pE->iTable==pExpr->iTable &&
  79629. pE->iColumn==pExpr->iColumn ){
  79630. pCol->iSorterColumn = j;
  79631. break;
  79632. }
  79633. }
  79634. }
  79635. if( pCol->iSorterColumn<0 ){
  79636. pCol->iSorterColumn = pAggInfo->nSortingColumn++;
  79637. }
  79638. }
  79639. /* There is now an entry for pExpr in pAggInfo->aCol[] (either
  79640. ** because it was there before or because we just created it).
  79641. ** Convert the pExpr to be a TK_AGG_COLUMN referring to that
  79642. ** pAggInfo->aCol[] entry.
  79643. */
  79644. ExprSetVVAProperty(pExpr, EP_NoReduce);
  79645. pExpr->pAggInfo = pAggInfo;
  79646. pExpr->op = TK_AGG_COLUMN;
  79647. pExpr->iAgg = (i16)k;
  79648. break;
  79649. } /* endif pExpr->iTable==pItem->iCursor */
  79650. } /* end loop over pSrcList */
  79651. }
  79652. return WRC_Prune;
  79653. }
  79654. case TK_AGG_FUNCTION: {
  79655. if( (pNC->ncFlags & NC_InAggFunc)==0
  79656. && pWalker->walkerDepth==pExpr->op2
  79657. ){
  79658. /* Check to see if pExpr is a duplicate of another aggregate
  79659. ** function that is already in the pAggInfo structure
  79660. */
  79661. struct AggInfo_func *pItem = pAggInfo->aFunc;
  79662. for(i=0; i<pAggInfo->nFunc; i++, pItem++){
  79663. if( sqlite3ExprCompare(pItem->pExpr, pExpr, -1)==0 ){
  79664. break;
  79665. }
  79666. }
  79667. if( i>=pAggInfo->nFunc ){
  79668. /* pExpr is original. Make a new entry in pAggInfo->aFunc[]
  79669. */
  79670. u8 enc = ENC(pParse->db);
  79671. i = addAggInfoFunc(pParse->db, pAggInfo);
  79672. if( i>=0 ){
  79673. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  79674. pItem = &pAggInfo->aFunc[i];
  79675. pItem->pExpr = pExpr;
  79676. pItem->iMem = ++pParse->nMem;
  79677. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  79678. pItem->pFunc = sqlite3FindFunction(pParse->db,
  79679. pExpr->u.zToken, sqlite3Strlen30(pExpr->u.zToken),
  79680. pExpr->x.pList ? pExpr->x.pList->nExpr : 0, enc, 0);
  79681. if( pExpr->flags & EP_Distinct ){
  79682. pItem->iDistinct = pParse->nTab++;
  79683. }else{
  79684. pItem->iDistinct = -1;
  79685. }
  79686. }
  79687. }
  79688. /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
  79689. */
  79690. assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
  79691. ExprSetVVAProperty(pExpr, EP_NoReduce);
  79692. pExpr->iAgg = (i16)i;
  79693. pExpr->pAggInfo = pAggInfo;
  79694. return WRC_Prune;
  79695. }else{
  79696. return WRC_Continue;
  79697. }
  79698. }
  79699. }
  79700. return WRC_Continue;
  79701. }
  79702. static int analyzeAggregatesInSelect(Walker *pWalker, Select *pSelect){
  79703. UNUSED_PARAMETER(pWalker);
  79704. UNUSED_PARAMETER(pSelect);
  79705. return WRC_Continue;
  79706. }
  79707. /*
  79708. ** Analyze the pExpr expression looking for aggregate functions and
  79709. ** for variables that need to be added to AggInfo object that pNC->pAggInfo
  79710. ** points to. Additional entries are made on the AggInfo object as
  79711. ** necessary.
  79712. **
  79713. ** This routine should only be called after the expression has been
  79714. ** analyzed by sqlite3ResolveExprNames().
  79715. */
  79716. SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){
  79717. Walker w;
  79718. memset(&w, 0, sizeof(w));
  79719. w.xExprCallback = analyzeAggregate;
  79720. w.xSelectCallback = analyzeAggregatesInSelect;
  79721. w.u.pNC = pNC;
  79722. assert( pNC->pSrcList!=0 );
  79723. sqlite3WalkExpr(&w, pExpr);
  79724. }
  79725. /*
  79726. ** Call sqlite3ExprAnalyzeAggregates() for every expression in an
  79727. ** expression list. Return the number of errors.
  79728. **
  79729. ** If an error is found, the analysis is cut short.
  79730. */
  79731. SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){
  79732. struct ExprList_item *pItem;
  79733. int i;
  79734. if( pList ){
  79735. for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
  79736. sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr);
  79737. }
  79738. }
  79739. }
  79740. /*
  79741. ** Allocate a single new register for use to hold some intermediate result.
  79742. */
  79743. SQLITE_PRIVATE int sqlite3GetTempReg(Parse *pParse){
  79744. if( pParse->nTempReg==0 ){
  79745. return ++pParse->nMem;
  79746. }
  79747. return pParse->aTempReg[--pParse->nTempReg];
  79748. }
  79749. /*
  79750. ** Deallocate a register, making available for reuse for some other
  79751. ** purpose.
  79752. **
  79753. ** If a register is currently being used by the column cache, then
  79754. ** the deallocation is deferred until the column cache line that uses
  79755. ** the register becomes stale.
  79756. */
  79757. SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse *pParse, int iReg){
  79758. if( iReg && pParse->nTempReg<ArraySize(pParse->aTempReg) ){
  79759. int i;
  79760. struct yColCache *p;
  79761. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  79762. if( p->iReg==iReg ){
  79763. p->tempReg = 1;
  79764. return;
  79765. }
  79766. }
  79767. pParse->aTempReg[pParse->nTempReg++] = iReg;
  79768. }
  79769. }
  79770. /*
  79771. ** Allocate or deallocate a block of nReg consecutive registers
  79772. */
  79773. SQLITE_PRIVATE int sqlite3GetTempRange(Parse *pParse, int nReg){
  79774. int i, n;
  79775. i = pParse->iRangeReg;
  79776. n = pParse->nRangeReg;
  79777. if( nReg<=n ){
  79778. assert( !usedAsColumnCache(pParse, i, i+n-1) );
  79779. pParse->iRangeReg += nReg;
  79780. pParse->nRangeReg -= nReg;
  79781. }else{
  79782. i = pParse->nMem+1;
  79783. pParse->nMem += nReg;
  79784. }
  79785. return i;
  79786. }
  79787. SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse *pParse, int iReg, int nReg){
  79788. sqlite3ExprCacheRemove(pParse, iReg, nReg);
  79789. if( nReg>pParse->nRangeReg ){
  79790. pParse->nRangeReg = nReg;
  79791. pParse->iRangeReg = iReg;
  79792. }
  79793. }
  79794. /*
  79795. ** Mark all temporary registers as being unavailable for reuse.
  79796. */
  79797. SQLITE_PRIVATE void sqlite3ClearTempRegCache(Parse *pParse){
  79798. pParse->nTempReg = 0;
  79799. pParse->nRangeReg = 0;
  79800. }
  79801. /************** End of expr.c ************************************************/
  79802. /************** Begin file alter.c *******************************************/
  79803. /*
  79804. ** 2005 February 15
  79805. **
  79806. ** The author disclaims copyright to this source code. In place of
  79807. ** a legal notice, here is a blessing:
  79808. **
  79809. ** May you do good and not evil.
  79810. ** May you find forgiveness for yourself and forgive others.
  79811. ** May you share freely, never taking more than you give.
  79812. **
  79813. *************************************************************************
  79814. ** This file contains C code routines that used to generate VDBE code
  79815. ** that implements the ALTER TABLE command.
  79816. */
  79817. /*
  79818. ** The code in this file only exists if we are not omitting the
  79819. ** ALTER TABLE logic from the build.
  79820. */
  79821. #ifndef SQLITE_OMIT_ALTERTABLE
  79822. /*
  79823. ** This function is used by SQL generated to implement the
  79824. ** ALTER TABLE command. The first argument is the text of a CREATE TABLE or
  79825. ** CREATE INDEX command. The second is a table name. The table name in
  79826. ** the CREATE TABLE or CREATE INDEX statement is replaced with the third
  79827. ** argument and the result returned. Examples:
  79828. **
  79829. ** sqlite_rename_table('CREATE TABLE abc(a, b, c)', 'def')
  79830. ** -> 'CREATE TABLE def(a, b, c)'
  79831. **
  79832. ** sqlite_rename_table('CREATE INDEX i ON abc(a)', 'def')
  79833. ** -> 'CREATE INDEX i ON def(a, b, c)'
  79834. */
  79835. static void renameTableFunc(
  79836. sqlite3_context *context,
  79837. int NotUsed,
  79838. sqlite3_value **argv
  79839. ){
  79840. unsigned char const *zSql = sqlite3_value_text(argv[0]);
  79841. unsigned char const *zTableName = sqlite3_value_text(argv[1]);
  79842. int token;
  79843. Token tname;
  79844. unsigned char const *zCsr = zSql;
  79845. int len = 0;
  79846. char *zRet;
  79847. sqlite3 *db = sqlite3_context_db_handle(context);
  79848. UNUSED_PARAMETER(NotUsed);
  79849. /* The principle used to locate the table name in the CREATE TABLE
  79850. ** statement is that the table name is the first non-space token that
  79851. ** is immediately followed by a TK_LP or TK_USING token.
  79852. */
  79853. if( zSql ){
  79854. do {
  79855. if( !*zCsr ){
  79856. /* Ran out of input before finding an opening bracket. Return NULL. */
  79857. return;
  79858. }
  79859. /* Store the token that zCsr points to in tname. */
  79860. tname.z = (char*)zCsr;
  79861. tname.n = len;
  79862. /* Advance zCsr to the next token. Store that token type in 'token',
  79863. ** and its length in 'len' (to be used next iteration of this loop).
  79864. */
  79865. do {
  79866. zCsr += len;
  79867. len = sqlite3GetToken(zCsr, &token);
  79868. } while( token==TK_SPACE );
  79869. assert( len>0 );
  79870. } while( token!=TK_LP && token!=TK_USING );
  79871. zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", (int)(((u8*)tname.z) - zSql),
  79872. zSql, zTableName, tname.z+tname.n);
  79873. sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
  79874. }
  79875. }
  79876. /*
  79877. ** This C function implements an SQL user function that is used by SQL code
  79878. ** generated by the ALTER TABLE ... RENAME command to modify the definition
  79879. ** of any foreign key constraints that use the table being renamed as the
  79880. ** parent table. It is passed three arguments:
  79881. **
  79882. ** 1) The complete text of the CREATE TABLE statement being modified,
  79883. ** 2) The old name of the table being renamed, and
  79884. ** 3) The new name of the table being renamed.
  79885. **
  79886. ** It returns the new CREATE TABLE statement. For example:
  79887. **
  79888. ** sqlite_rename_parent('CREATE TABLE t1(a REFERENCES t2)', 't2', 't3')
  79889. ** -> 'CREATE TABLE t1(a REFERENCES t3)'
  79890. */
  79891. #ifndef SQLITE_OMIT_FOREIGN_KEY
  79892. static void renameParentFunc(
  79893. sqlite3_context *context,
  79894. int NotUsed,
  79895. sqlite3_value **argv
  79896. ){
  79897. sqlite3 *db = sqlite3_context_db_handle(context);
  79898. char *zOutput = 0;
  79899. char *zResult;
  79900. unsigned char const *zInput = sqlite3_value_text(argv[0]);
  79901. unsigned char const *zOld = sqlite3_value_text(argv[1]);
  79902. unsigned char const *zNew = sqlite3_value_text(argv[2]);
  79903. unsigned const char *z; /* Pointer to token */
  79904. int n; /* Length of token z */
  79905. int token; /* Type of token */
  79906. UNUSED_PARAMETER(NotUsed);
  79907. if( zInput==0 || zOld==0 ) return;
  79908. for(z=zInput; *z; z=z+n){
  79909. n = sqlite3GetToken(z, &token);
  79910. if( token==TK_REFERENCES ){
  79911. char *zParent;
  79912. do {
  79913. z += n;
  79914. n = sqlite3GetToken(z, &token);
  79915. }while( token==TK_SPACE );
  79916. zParent = sqlite3DbStrNDup(db, (const char *)z, n);
  79917. if( zParent==0 ) break;
  79918. sqlite3Dequote(zParent);
  79919. if( 0==sqlite3StrICmp((const char *)zOld, zParent) ){
  79920. char *zOut = sqlite3MPrintf(db, "%s%.*s\"%w\"",
  79921. (zOutput?zOutput:""), (int)(z-zInput), zInput, (const char *)zNew
  79922. );
  79923. sqlite3DbFree(db, zOutput);
  79924. zOutput = zOut;
  79925. zInput = &z[n];
  79926. }
  79927. sqlite3DbFree(db, zParent);
  79928. }
  79929. }
  79930. zResult = sqlite3MPrintf(db, "%s%s", (zOutput?zOutput:""), zInput),
  79931. sqlite3_result_text(context, zResult, -1, SQLITE_DYNAMIC);
  79932. sqlite3DbFree(db, zOutput);
  79933. }
  79934. #endif
  79935. #ifndef SQLITE_OMIT_TRIGGER
  79936. /* This function is used by SQL generated to implement the
  79937. ** ALTER TABLE command. The first argument is the text of a CREATE TRIGGER
  79938. ** statement. The second is a table name. The table name in the CREATE
  79939. ** TRIGGER statement is replaced with the third argument and the result
  79940. ** returned. This is analagous to renameTableFunc() above, except for CREATE
  79941. ** TRIGGER, not CREATE INDEX and CREATE TABLE.
  79942. */
  79943. static void renameTriggerFunc(
  79944. sqlite3_context *context,
  79945. int NotUsed,
  79946. sqlite3_value **argv
  79947. ){
  79948. unsigned char const *zSql = sqlite3_value_text(argv[0]);
  79949. unsigned char const *zTableName = sqlite3_value_text(argv[1]);
  79950. int token;
  79951. Token tname;
  79952. int dist = 3;
  79953. unsigned char const *zCsr = zSql;
  79954. int len = 0;
  79955. char *zRet;
  79956. sqlite3 *db = sqlite3_context_db_handle(context);
  79957. UNUSED_PARAMETER(NotUsed);
  79958. /* The principle used to locate the table name in the CREATE TRIGGER
  79959. ** statement is that the table name is the first token that is immediately
  79960. ** preceded by either TK_ON or TK_DOT and immediately followed by one
  79961. ** of TK_WHEN, TK_BEGIN or TK_FOR.
  79962. */
  79963. if( zSql ){
  79964. do {
  79965. if( !*zCsr ){
  79966. /* Ran out of input before finding the table name. Return NULL. */
  79967. return;
  79968. }
  79969. /* Store the token that zCsr points to in tname. */
  79970. tname.z = (char*)zCsr;
  79971. tname.n = len;
  79972. /* Advance zCsr to the next token. Store that token type in 'token',
  79973. ** and its length in 'len' (to be used next iteration of this loop).
  79974. */
  79975. do {
  79976. zCsr += len;
  79977. len = sqlite3GetToken(zCsr, &token);
  79978. }while( token==TK_SPACE );
  79979. assert( len>0 );
  79980. /* Variable 'dist' stores the number of tokens read since the most
  79981. ** recent TK_DOT or TK_ON. This means that when a WHEN, FOR or BEGIN
  79982. ** token is read and 'dist' equals 2, the condition stated above
  79983. ** to be met.
  79984. **
  79985. ** Note that ON cannot be a database, table or column name, so
  79986. ** there is no need to worry about syntax like
  79987. ** "CREATE TRIGGER ... ON ON.ON BEGIN ..." etc.
  79988. */
  79989. dist++;
  79990. if( token==TK_DOT || token==TK_ON ){
  79991. dist = 0;
  79992. }
  79993. } while( dist!=2 || (token!=TK_WHEN && token!=TK_FOR && token!=TK_BEGIN) );
  79994. /* Variable tname now contains the token that is the old table-name
  79995. ** in the CREATE TRIGGER statement.
  79996. */
  79997. zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", (int)(((u8*)tname.z) - zSql),
  79998. zSql, zTableName, tname.z+tname.n);
  79999. sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
  80000. }
  80001. }
  80002. #endif /* !SQLITE_OMIT_TRIGGER */
  80003. /*
  80004. ** Register built-in functions used to help implement ALTER TABLE
  80005. */
  80006. SQLITE_PRIVATE void sqlite3AlterFunctions(void){
  80007. static SQLITE_WSD FuncDef aAlterTableFuncs[] = {
  80008. FUNCTION(sqlite_rename_table, 2, 0, 0, renameTableFunc),
  80009. #ifndef SQLITE_OMIT_TRIGGER
  80010. FUNCTION(sqlite_rename_trigger, 2, 0, 0, renameTriggerFunc),
  80011. #endif
  80012. #ifndef SQLITE_OMIT_FOREIGN_KEY
  80013. FUNCTION(sqlite_rename_parent, 3, 0, 0, renameParentFunc),
  80014. #endif
  80015. };
  80016. int i;
  80017. FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
  80018. FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aAlterTableFuncs);
  80019. for(i=0; i<ArraySize(aAlterTableFuncs); i++){
  80020. sqlite3FuncDefInsert(pHash, &aFunc[i]);
  80021. }
  80022. }
  80023. /*
  80024. ** This function is used to create the text of expressions of the form:
  80025. **
  80026. ** name=<constant1> OR name=<constant2> OR ...
  80027. **
  80028. ** If argument zWhere is NULL, then a pointer string containing the text
  80029. ** "name=<constant>" is returned, where <constant> is the quoted version
  80030. ** of the string passed as argument zConstant. The returned buffer is
  80031. ** allocated using sqlite3DbMalloc(). It is the responsibility of the
  80032. ** caller to ensure that it is eventually freed.
  80033. **
  80034. ** If argument zWhere is not NULL, then the string returned is
  80035. ** "<where> OR name=<constant>", where <where> is the contents of zWhere.
  80036. ** In this case zWhere is passed to sqlite3DbFree() before returning.
  80037. **
  80038. */
  80039. static char *whereOrName(sqlite3 *db, char *zWhere, char *zConstant){
  80040. char *zNew;
  80041. if( !zWhere ){
  80042. zNew = sqlite3MPrintf(db, "name=%Q", zConstant);
  80043. }else{
  80044. zNew = sqlite3MPrintf(db, "%s OR name=%Q", zWhere, zConstant);
  80045. sqlite3DbFree(db, zWhere);
  80046. }
  80047. return zNew;
  80048. }
  80049. #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
  80050. /*
  80051. ** Generate the text of a WHERE expression which can be used to select all
  80052. ** tables that have foreign key constraints that refer to table pTab (i.e.
  80053. ** constraints for which pTab is the parent table) from the sqlite_master
  80054. ** table.
  80055. */
  80056. static char *whereForeignKeys(Parse *pParse, Table *pTab){
  80057. FKey *p;
  80058. char *zWhere = 0;
  80059. for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
  80060. zWhere = whereOrName(pParse->db, zWhere, p->pFrom->zName);
  80061. }
  80062. return zWhere;
  80063. }
  80064. #endif
  80065. /*
  80066. ** Generate the text of a WHERE expression which can be used to select all
  80067. ** temporary triggers on table pTab from the sqlite_temp_master table. If
  80068. ** table pTab has no temporary triggers, or is itself stored in the
  80069. ** temporary database, NULL is returned.
  80070. */
  80071. static char *whereTempTriggers(Parse *pParse, Table *pTab){
  80072. Trigger *pTrig;
  80073. char *zWhere = 0;
  80074. const Schema *pTempSchema = pParse->db->aDb[1].pSchema; /* Temp db schema */
  80075. /* If the table is not located in the temp-db (in which case NULL is
  80076. ** returned, loop through the tables list of triggers. For each trigger
  80077. ** that is not part of the temp-db schema, add a clause to the WHERE
  80078. ** expression being built up in zWhere.
  80079. */
  80080. if( pTab->pSchema!=pTempSchema ){
  80081. sqlite3 *db = pParse->db;
  80082. for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
  80083. if( pTrig->pSchema==pTempSchema ){
  80084. zWhere = whereOrName(db, zWhere, pTrig->zName);
  80085. }
  80086. }
  80087. }
  80088. if( zWhere ){
  80089. char *zNew = sqlite3MPrintf(pParse->db, "type='trigger' AND (%s)", zWhere);
  80090. sqlite3DbFree(pParse->db, zWhere);
  80091. zWhere = zNew;
  80092. }
  80093. return zWhere;
  80094. }
  80095. /*
  80096. ** Generate code to drop and reload the internal representation of table
  80097. ** pTab from the database, including triggers and temporary triggers.
  80098. ** Argument zName is the name of the table in the database schema at
  80099. ** the time the generated code is executed. This can be different from
  80100. ** pTab->zName if this function is being called to code part of an
  80101. ** "ALTER TABLE RENAME TO" statement.
  80102. */
  80103. static void reloadTableSchema(Parse *pParse, Table *pTab, const char *zName){
  80104. Vdbe *v;
  80105. char *zWhere;
  80106. int iDb; /* Index of database containing pTab */
  80107. #ifndef SQLITE_OMIT_TRIGGER
  80108. Trigger *pTrig;
  80109. #endif
  80110. v = sqlite3GetVdbe(pParse);
  80111. if( NEVER(v==0) ) return;
  80112. assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
  80113. iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  80114. assert( iDb>=0 );
  80115. #ifndef SQLITE_OMIT_TRIGGER
  80116. /* Drop any table triggers from the internal schema. */
  80117. for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
  80118. int iTrigDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
  80119. assert( iTrigDb==iDb || iTrigDb==1 );
  80120. sqlite3VdbeAddOp4(v, OP_DropTrigger, iTrigDb, 0, 0, pTrig->zName, 0);
  80121. }
  80122. #endif
  80123. /* Drop the table and index from the internal schema. */
  80124. sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
  80125. /* Reload the table, index and permanent trigger schemas. */
  80126. zWhere = sqlite3MPrintf(pParse->db, "tbl_name=%Q", zName);
  80127. if( !zWhere ) return;
  80128. sqlite3VdbeAddParseSchemaOp(v, iDb, zWhere);
  80129. #ifndef SQLITE_OMIT_TRIGGER
  80130. /* Now, if the table is not stored in the temp database, reload any temp
  80131. ** triggers. Don't use IN(...) in case SQLITE_OMIT_SUBQUERY is defined.
  80132. */
  80133. if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
  80134. sqlite3VdbeAddParseSchemaOp(v, 1, zWhere);
  80135. }
  80136. #endif
  80137. }
  80138. /*
  80139. ** Parameter zName is the name of a table that is about to be altered
  80140. ** (either with ALTER TABLE ... RENAME TO or ALTER TABLE ... ADD COLUMN).
  80141. ** If the table is a system table, this function leaves an error message
  80142. ** in pParse->zErr (system tables may not be altered) and returns non-zero.
  80143. **
  80144. ** Or, if zName is not a system table, zero is returned.
  80145. */
  80146. static int isSystemTable(Parse *pParse, const char *zName){
  80147. if( sqlite3Strlen30(zName)>6 && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
  80148. sqlite3ErrorMsg(pParse, "table %s may not be altered", zName);
  80149. return 1;
  80150. }
  80151. return 0;
  80152. }
  80153. /*
  80154. ** Generate code to implement the "ALTER TABLE xxx RENAME TO yyy"
  80155. ** command.
  80156. */
  80157. SQLITE_PRIVATE void sqlite3AlterRenameTable(
  80158. Parse *pParse, /* Parser context. */
  80159. SrcList *pSrc, /* The table to rename. */
  80160. Token *pName /* The new table name. */
  80161. ){
  80162. int iDb; /* Database that contains the table */
  80163. char *zDb; /* Name of database iDb */
  80164. Table *pTab; /* Table being renamed */
  80165. char *zName = 0; /* NULL-terminated version of pName */
  80166. sqlite3 *db = pParse->db; /* Database connection */
  80167. int nTabName; /* Number of UTF-8 characters in zTabName */
  80168. const char *zTabName; /* Original name of the table */
  80169. Vdbe *v;
  80170. #ifndef SQLITE_OMIT_TRIGGER
  80171. char *zWhere = 0; /* Where clause to locate temp triggers */
  80172. #endif
  80173. VTable *pVTab = 0; /* Non-zero if this is a v-tab with an xRename() */
  80174. int savedDbFlags; /* Saved value of db->flags */
  80175. savedDbFlags = db->flags;
  80176. if( NEVER(db->mallocFailed) ) goto exit_rename_table;
  80177. assert( pSrc->nSrc==1 );
  80178. assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
  80179. pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
  80180. if( !pTab ) goto exit_rename_table;
  80181. iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  80182. zDb = db->aDb[iDb].zName;
  80183. db->flags |= SQLITE_PreferBuiltin;
  80184. /* Get a NULL terminated version of the new table name. */
  80185. zName = sqlite3NameFromToken(db, pName);
  80186. if( !zName ) goto exit_rename_table;
  80187. /* Check that a table or index named 'zName' does not already exist
  80188. ** in database iDb. If so, this is an error.
  80189. */
  80190. if( sqlite3FindTable(db, zName, zDb) || sqlite3FindIndex(db, zName, zDb) ){
  80191. sqlite3ErrorMsg(pParse,
  80192. "there is already another table or index with this name: %s", zName);
  80193. goto exit_rename_table;
  80194. }
  80195. /* Make sure it is not a system table being altered, or a reserved name
  80196. ** that the table is being renamed to.
  80197. */
  80198. if( SQLITE_OK!=isSystemTable(pParse, pTab->zName) ){
  80199. goto exit_rename_table;
  80200. }
  80201. if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){ goto
  80202. exit_rename_table;
  80203. }
  80204. #ifndef SQLITE_OMIT_VIEW
  80205. if( pTab->pSelect ){
  80206. sqlite3ErrorMsg(pParse, "view %s may not be altered", pTab->zName);
  80207. goto exit_rename_table;
  80208. }
  80209. #endif
  80210. #ifndef SQLITE_OMIT_AUTHORIZATION
  80211. /* Invoke the authorization callback. */
  80212. if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
  80213. goto exit_rename_table;
  80214. }
  80215. #endif
  80216. #ifndef SQLITE_OMIT_VIRTUALTABLE
  80217. if( sqlite3ViewGetColumnNames(pParse, pTab) ){
  80218. goto exit_rename_table;
  80219. }
  80220. if( IsVirtual(pTab) ){
  80221. pVTab = sqlite3GetVTable(db, pTab);
  80222. if( pVTab->pVtab->pModule->xRename==0 ){
  80223. pVTab = 0;
  80224. }
  80225. }
  80226. #endif
  80227. /* Begin a transaction for database iDb.
  80228. ** Then modify the schema cookie (since the ALTER TABLE modifies the
  80229. ** schema). Open a statement transaction if the table is a virtual
  80230. ** table.
  80231. */
  80232. v = sqlite3GetVdbe(pParse);
  80233. if( v==0 ){
  80234. goto exit_rename_table;
  80235. }
  80236. sqlite3BeginWriteOperation(pParse, pVTab!=0, iDb);
  80237. sqlite3ChangeCookie(pParse, iDb);
  80238. /* If this is a virtual table, invoke the xRename() function if
  80239. ** one is defined. The xRename() callback will modify the names
  80240. ** of any resources used by the v-table implementation (including other
  80241. ** SQLite tables) that are identified by the name of the virtual table.
  80242. */
  80243. #ifndef SQLITE_OMIT_VIRTUALTABLE
  80244. if( pVTab ){
  80245. int i = ++pParse->nMem;
  80246. sqlite3VdbeAddOp4(v, OP_String8, 0, i, 0, zName, 0);
  80247. sqlite3VdbeAddOp4(v, OP_VRename, i, 0, 0,(const char*)pVTab, P4_VTAB);
  80248. sqlite3MayAbort(pParse);
  80249. }
  80250. #endif
  80251. /* figure out how many UTF-8 characters are in zName */
  80252. zTabName = pTab->zName;
  80253. nTabName = sqlite3Utf8CharLen(zTabName, -1);
  80254. #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
  80255. if( db->flags&SQLITE_ForeignKeys ){
  80256. /* If foreign-key support is enabled, rewrite the CREATE TABLE
  80257. ** statements corresponding to all child tables of foreign key constraints
  80258. ** for which the renamed table is the parent table. */
  80259. if( (zWhere=whereForeignKeys(pParse, pTab))!=0 ){
  80260. sqlite3NestedParse(pParse,
  80261. "UPDATE \"%w\".%s SET "
  80262. "sql = sqlite_rename_parent(sql, %Q, %Q) "
  80263. "WHERE %s;", zDb, SCHEMA_TABLE(iDb), zTabName, zName, zWhere);
  80264. sqlite3DbFree(db, zWhere);
  80265. }
  80266. }
  80267. #endif
  80268. /* Modify the sqlite_master table to use the new table name. */
  80269. sqlite3NestedParse(pParse,
  80270. "UPDATE %Q.%s SET "
  80271. #ifdef SQLITE_OMIT_TRIGGER
  80272. "sql = sqlite_rename_table(sql, %Q), "
  80273. #else
  80274. "sql = CASE "
  80275. "WHEN type = 'trigger' THEN sqlite_rename_trigger(sql, %Q)"
  80276. "ELSE sqlite_rename_table(sql, %Q) END, "
  80277. #endif
  80278. "tbl_name = %Q, "
  80279. "name = CASE "
  80280. "WHEN type='table' THEN %Q "
  80281. "WHEN name LIKE 'sqlite_autoindex%%' AND type='index' THEN "
  80282. "'sqlite_autoindex_' || %Q || substr(name,%d+18) "
  80283. "ELSE name END "
  80284. "WHERE tbl_name=%Q COLLATE nocase AND "
  80285. "(type='table' OR type='index' OR type='trigger');",
  80286. zDb, SCHEMA_TABLE(iDb), zName, zName, zName,
  80287. #ifndef SQLITE_OMIT_TRIGGER
  80288. zName,
  80289. #endif
  80290. zName, nTabName, zTabName
  80291. );
  80292. #ifndef SQLITE_OMIT_AUTOINCREMENT
  80293. /* If the sqlite_sequence table exists in this database, then update
  80294. ** it with the new table name.
  80295. */
  80296. if( sqlite3FindTable(db, "sqlite_sequence", zDb) ){
  80297. sqlite3NestedParse(pParse,
  80298. "UPDATE \"%w\".sqlite_sequence set name = %Q WHERE name = %Q",
  80299. zDb, zName, pTab->zName);
  80300. }
  80301. #endif
  80302. #ifndef SQLITE_OMIT_TRIGGER
  80303. /* If there are TEMP triggers on this table, modify the sqlite_temp_master
  80304. ** table. Don't do this if the table being ALTERed is itself located in
  80305. ** the temp database.
  80306. */
  80307. if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
  80308. sqlite3NestedParse(pParse,
  80309. "UPDATE sqlite_temp_master SET "
  80310. "sql = sqlite_rename_trigger(sql, %Q), "
  80311. "tbl_name = %Q "
  80312. "WHERE %s;", zName, zName, zWhere);
  80313. sqlite3DbFree(db, zWhere);
  80314. }
  80315. #endif
  80316. #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
  80317. if( db->flags&SQLITE_ForeignKeys ){
  80318. FKey *p;
  80319. for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
  80320. Table *pFrom = p->pFrom;
  80321. if( pFrom!=pTab ){
  80322. reloadTableSchema(pParse, p->pFrom, pFrom->zName);
  80323. }
  80324. }
  80325. }
  80326. #endif
  80327. /* Drop and reload the internal table schema. */
  80328. reloadTableSchema(pParse, pTab, zName);
  80329. exit_rename_table:
  80330. sqlite3SrcListDelete(db, pSrc);
  80331. sqlite3DbFree(db, zName);
  80332. db->flags = savedDbFlags;
  80333. }
  80334. /*
  80335. ** Generate code to make sure the file format number is at least minFormat.
  80336. ** The generated code will increase the file format number if necessary.
  80337. */
  80338. SQLITE_PRIVATE void sqlite3MinimumFileFormat(Parse *pParse, int iDb, int minFormat){
  80339. Vdbe *v;
  80340. v = sqlite3GetVdbe(pParse);
  80341. /* The VDBE should have been allocated before this routine is called.
  80342. ** If that allocation failed, we would have quit before reaching this
  80343. ** point */
  80344. if( ALWAYS(v) ){
  80345. int r1 = sqlite3GetTempReg(pParse);
  80346. int r2 = sqlite3GetTempReg(pParse);
  80347. int j1;
  80348. sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, r1, BTREE_FILE_FORMAT);
  80349. sqlite3VdbeUsesBtree(v, iDb);
  80350. sqlite3VdbeAddOp2(v, OP_Integer, minFormat, r2);
  80351. j1 = sqlite3VdbeAddOp3(v, OP_Ge, r2, 0, r1);
  80352. sqlite3VdbeChangeP5(v, SQLITE_NOTNULL); VdbeCoverage(v);
  80353. sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, r2);
  80354. sqlite3VdbeJumpHere(v, j1);
  80355. sqlite3ReleaseTempReg(pParse, r1);
  80356. sqlite3ReleaseTempReg(pParse, r2);
  80357. }
  80358. }
  80359. /*
  80360. ** This function is called after an "ALTER TABLE ... ADD" statement
  80361. ** has been parsed. Argument pColDef contains the text of the new
  80362. ** column definition.
  80363. **
  80364. ** The Table structure pParse->pNewTable was extended to include
  80365. ** the new column during parsing.
  80366. */
  80367. SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *pParse, Token *pColDef){
  80368. Table *pNew; /* Copy of pParse->pNewTable */
  80369. Table *pTab; /* Table being altered */
  80370. int iDb; /* Database number */
  80371. const char *zDb; /* Database name */
  80372. const char *zTab; /* Table name */
  80373. char *zCol; /* Null-terminated column definition */
  80374. Column *pCol; /* The new column */
  80375. Expr *pDflt; /* Default value for the new column */
  80376. sqlite3 *db; /* The database connection; */
  80377. db = pParse->db;
  80378. if( pParse->nErr || db->mallocFailed ) return;
  80379. pNew = pParse->pNewTable;
  80380. assert( pNew );
  80381. assert( sqlite3BtreeHoldsAllMutexes(db) );
  80382. iDb = sqlite3SchemaToIndex(db, pNew->pSchema);
  80383. zDb = db->aDb[iDb].zName;
  80384. zTab = &pNew->zName[16]; /* Skip the "sqlite_altertab_" prefix on the name */
  80385. pCol = &pNew->aCol[pNew->nCol-1];
  80386. pDflt = pCol->pDflt;
  80387. pTab = sqlite3FindTable(db, zTab, zDb);
  80388. assert( pTab );
  80389. #ifndef SQLITE_OMIT_AUTHORIZATION
  80390. /* Invoke the authorization callback. */
  80391. if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
  80392. return;
  80393. }
  80394. #endif
  80395. /* If the default value for the new column was specified with a
  80396. ** literal NULL, then set pDflt to 0. This simplifies checking
  80397. ** for an SQL NULL default below.
  80398. */
  80399. if( pDflt && pDflt->op==TK_NULL ){
  80400. pDflt = 0;
  80401. }
  80402. /* Check that the new column is not specified as PRIMARY KEY or UNIQUE.
  80403. ** If there is a NOT NULL constraint, then the default value for the
  80404. ** column must not be NULL.
  80405. */
  80406. if( pCol->colFlags & COLFLAG_PRIMKEY ){
  80407. sqlite3ErrorMsg(pParse, "Cannot add a PRIMARY KEY column");
  80408. return;
  80409. }
  80410. if( pNew->pIndex ){
  80411. sqlite3ErrorMsg(pParse, "Cannot add a UNIQUE column");
  80412. return;
  80413. }
  80414. if( (db->flags&SQLITE_ForeignKeys) && pNew->pFKey && pDflt ){
  80415. sqlite3ErrorMsg(pParse,
  80416. "Cannot add a REFERENCES column with non-NULL default value");
  80417. return;
  80418. }
  80419. if( pCol->notNull && !pDflt ){
  80420. sqlite3ErrorMsg(pParse,
  80421. "Cannot add a NOT NULL column with default value NULL");
  80422. return;
  80423. }
  80424. /* Ensure the default expression is something that sqlite3ValueFromExpr()
  80425. ** can handle (i.e. not CURRENT_TIME etc.)
  80426. */
  80427. if( pDflt ){
  80428. sqlite3_value *pVal = 0;
  80429. if( sqlite3ValueFromExpr(db, pDflt, SQLITE_UTF8, SQLITE_AFF_NONE, &pVal) ){
  80430. db->mallocFailed = 1;
  80431. return;
  80432. }
  80433. if( !pVal ){
  80434. sqlite3ErrorMsg(pParse, "Cannot add a column with non-constant default");
  80435. return;
  80436. }
  80437. sqlite3ValueFree(pVal);
  80438. }
  80439. /* Modify the CREATE TABLE statement. */
  80440. zCol = sqlite3DbStrNDup(db, (char*)pColDef->z, pColDef->n);
  80441. if( zCol ){
  80442. char *zEnd = &zCol[pColDef->n-1];
  80443. int savedDbFlags = db->flags;
  80444. while( zEnd>zCol && (*zEnd==';' || sqlite3Isspace(*zEnd)) ){
  80445. *zEnd-- = '\0';
  80446. }
  80447. db->flags |= SQLITE_PreferBuiltin;
  80448. sqlite3NestedParse(pParse,
  80449. "UPDATE \"%w\".%s SET "
  80450. "sql = substr(sql,1,%d) || ', ' || %Q || substr(sql,%d) "
  80451. "WHERE type = 'table' AND name = %Q",
  80452. zDb, SCHEMA_TABLE(iDb), pNew->addColOffset, zCol, pNew->addColOffset+1,
  80453. zTab
  80454. );
  80455. sqlite3DbFree(db, zCol);
  80456. db->flags = savedDbFlags;
  80457. }
  80458. /* If the default value of the new column is NULL, then set the file
  80459. ** format to 2. If the default value of the new column is not NULL,
  80460. ** the file format becomes 3.
  80461. */
  80462. sqlite3MinimumFileFormat(pParse, iDb, pDflt ? 3 : 2);
  80463. /* Reload the schema of the modified table. */
  80464. reloadTableSchema(pParse, pTab, pTab->zName);
  80465. }
  80466. /*
  80467. ** This function is called by the parser after the table-name in
  80468. ** an "ALTER TABLE <table-name> ADD" statement is parsed. Argument
  80469. ** pSrc is the full-name of the table being altered.
  80470. **
  80471. ** This routine makes a (partial) copy of the Table structure
  80472. ** for the table being altered and sets Parse.pNewTable to point
  80473. ** to it. Routines called by the parser as the column definition
  80474. ** is parsed (i.e. sqlite3AddColumn()) add the new Column data to
  80475. ** the copy. The copy of the Table structure is deleted by tokenize.c
  80476. ** after parsing is finished.
  80477. **
  80478. ** Routine sqlite3AlterFinishAddColumn() will be called to complete
  80479. ** coding the "ALTER TABLE ... ADD" statement.
  80480. */
  80481. SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *pParse, SrcList *pSrc){
  80482. Table *pNew;
  80483. Table *pTab;
  80484. Vdbe *v;
  80485. int iDb;
  80486. int i;
  80487. int nAlloc;
  80488. sqlite3 *db = pParse->db;
  80489. /* Look up the table being altered. */
  80490. assert( pParse->pNewTable==0 );
  80491. assert( sqlite3BtreeHoldsAllMutexes(db) );
  80492. if( db->mallocFailed ) goto exit_begin_add_column;
  80493. pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
  80494. if( !pTab ) goto exit_begin_add_column;
  80495. #ifndef SQLITE_OMIT_VIRTUALTABLE
  80496. if( IsVirtual(pTab) ){
  80497. sqlite3ErrorMsg(pParse, "virtual tables may not be altered");
  80498. goto exit_begin_add_column;
  80499. }
  80500. #endif
  80501. /* Make sure this is not an attempt to ALTER a view. */
  80502. if( pTab->pSelect ){
  80503. sqlite3ErrorMsg(pParse, "Cannot add a column to a view");
  80504. goto exit_begin_add_column;
  80505. }
  80506. if( SQLITE_OK!=isSystemTable(pParse, pTab->zName) ){
  80507. goto exit_begin_add_column;
  80508. }
  80509. assert( pTab->addColOffset>0 );
  80510. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  80511. /* Put a copy of the Table struct in Parse.pNewTable for the
  80512. ** sqlite3AddColumn() function and friends to modify. But modify
  80513. ** the name by adding an "sqlite_altertab_" prefix. By adding this
  80514. ** prefix, we insure that the name will not collide with an existing
  80515. ** table because user table are not allowed to have the "sqlite_"
  80516. ** prefix on their name.
  80517. */
  80518. pNew = (Table*)sqlite3DbMallocZero(db, sizeof(Table));
  80519. if( !pNew ) goto exit_begin_add_column;
  80520. pParse->pNewTable = pNew;
  80521. pNew->nRef = 1;
  80522. pNew->nCol = pTab->nCol;
  80523. assert( pNew->nCol>0 );
  80524. nAlloc = (((pNew->nCol-1)/8)*8)+8;
  80525. assert( nAlloc>=pNew->nCol && nAlloc%8==0 && nAlloc-pNew->nCol<8 );
  80526. pNew->aCol = (Column*)sqlite3DbMallocZero(db, sizeof(Column)*nAlloc);
  80527. pNew->zName = sqlite3MPrintf(db, "sqlite_altertab_%s", pTab->zName);
  80528. if( !pNew->aCol || !pNew->zName ){
  80529. db->mallocFailed = 1;
  80530. goto exit_begin_add_column;
  80531. }
  80532. memcpy(pNew->aCol, pTab->aCol, sizeof(Column)*pNew->nCol);
  80533. for(i=0; i<pNew->nCol; i++){
  80534. Column *pCol = &pNew->aCol[i];
  80535. pCol->zName = sqlite3DbStrDup(db, pCol->zName);
  80536. pCol->zColl = 0;
  80537. pCol->zType = 0;
  80538. pCol->pDflt = 0;
  80539. pCol->zDflt = 0;
  80540. }
  80541. pNew->pSchema = db->aDb[iDb].pSchema;
  80542. pNew->addColOffset = pTab->addColOffset;
  80543. pNew->nRef = 1;
  80544. /* Begin a transaction and increment the schema cookie. */
  80545. sqlite3BeginWriteOperation(pParse, 0, iDb);
  80546. v = sqlite3GetVdbe(pParse);
  80547. if( !v ) goto exit_begin_add_column;
  80548. sqlite3ChangeCookie(pParse, iDb);
  80549. exit_begin_add_column:
  80550. sqlite3SrcListDelete(db, pSrc);
  80551. return;
  80552. }
  80553. #endif /* SQLITE_ALTER_TABLE */
  80554. /************** End of alter.c ***********************************************/
  80555. /************** Begin file analyze.c *****************************************/
  80556. /*
  80557. ** 2005-07-08
  80558. **
  80559. ** The author disclaims copyright to this source code. In place of
  80560. ** a legal notice, here is a blessing:
  80561. **
  80562. ** May you do good and not evil.
  80563. ** May you find forgiveness for yourself and forgive others.
  80564. ** May you share freely, never taking more than you give.
  80565. **
  80566. *************************************************************************
  80567. ** This file contains code associated with the ANALYZE command.
  80568. **
  80569. ** The ANALYZE command gather statistics about the content of tables
  80570. ** and indices. These statistics are made available to the query planner
  80571. ** to help it make better decisions about how to perform queries.
  80572. **
  80573. ** The following system tables are or have been supported:
  80574. **
  80575. ** CREATE TABLE sqlite_stat1(tbl, idx, stat);
  80576. ** CREATE TABLE sqlite_stat2(tbl, idx, sampleno, sample);
  80577. ** CREATE TABLE sqlite_stat3(tbl, idx, nEq, nLt, nDLt, sample);
  80578. ** CREATE TABLE sqlite_stat4(tbl, idx, nEq, nLt, nDLt, sample);
  80579. **
  80580. ** Additional tables might be added in future releases of SQLite.
  80581. ** The sqlite_stat2 table is not created or used unless the SQLite version
  80582. ** is between 3.6.18 and 3.7.8, inclusive, and unless SQLite is compiled
  80583. ** with SQLITE_ENABLE_STAT2. The sqlite_stat2 table is deprecated.
  80584. ** The sqlite_stat2 table is superseded by sqlite_stat3, which is only
  80585. ** created and used by SQLite versions 3.7.9 and later and with
  80586. ** SQLITE_ENABLE_STAT3 defined. The functionality of sqlite_stat3
  80587. ** is a superset of sqlite_stat2. The sqlite_stat4 is an enhanced
  80588. ** version of sqlite_stat3 and is only available when compiled with
  80589. ** SQLITE_ENABLE_STAT4 and in SQLite versions 3.8.1 and later. It is
  80590. ** not possible to enable both STAT3 and STAT4 at the same time. If they
  80591. ** are both enabled, then STAT4 takes precedence.
  80592. **
  80593. ** For most applications, sqlite_stat1 provides all the statistics required
  80594. ** for the query planner to make good choices.
  80595. **
  80596. ** Format of sqlite_stat1:
  80597. **
  80598. ** There is normally one row per index, with the index identified by the
  80599. ** name in the idx column. The tbl column is the name of the table to
  80600. ** which the index belongs. In each such row, the stat column will be
  80601. ** a string consisting of a list of integers. The first integer in this
  80602. ** list is the number of rows in the index. (This is the same as the
  80603. ** number of rows in the table, except for partial indices.) The second
  80604. ** integer is the average number of rows in the index that have the same
  80605. ** value in the first column of the index. The third integer is the average
  80606. ** number of rows in the index that have the same value for the first two
  80607. ** columns. The N-th integer (for N>1) is the average number of rows in
  80608. ** the index which have the same value for the first N-1 columns. For
  80609. ** a K-column index, there will be K+1 integers in the stat column. If
  80610. ** the index is unique, then the last integer will be 1.
  80611. **
  80612. ** The list of integers in the stat column can optionally be followed
  80613. ** by the keyword "unordered". The "unordered" keyword, if it is present,
  80614. ** must be separated from the last integer by a single space. If the
  80615. ** "unordered" keyword is present, then the query planner assumes that
  80616. ** the index is unordered and will not use the index for a range query.
  80617. **
  80618. ** If the sqlite_stat1.idx column is NULL, then the sqlite_stat1.stat
  80619. ** column contains a single integer which is the (estimated) number of
  80620. ** rows in the table identified by sqlite_stat1.tbl.
  80621. **
  80622. ** Format of sqlite_stat2:
  80623. **
  80624. ** The sqlite_stat2 is only created and is only used if SQLite is compiled
  80625. ** with SQLITE_ENABLE_STAT2 and if the SQLite version number is between
  80626. ** 3.6.18 and 3.7.8. The "stat2" table contains additional information
  80627. ** about the distribution of keys within an index. The index is identified by
  80628. ** the "idx" column and the "tbl" column is the name of the table to which
  80629. ** the index belongs. There are usually 10 rows in the sqlite_stat2
  80630. ** table for each index.
  80631. **
  80632. ** The sqlite_stat2 entries for an index that have sampleno between 0 and 9
  80633. ** inclusive are samples of the left-most key value in the index taken at
  80634. ** evenly spaced points along the index. Let the number of samples be S
  80635. ** (10 in the standard build) and let C be the number of rows in the index.
  80636. ** Then the sampled rows are given by:
  80637. **
  80638. ** rownumber = (i*C*2 + C)/(S*2)
  80639. **
  80640. ** For i between 0 and S-1. Conceptually, the index space is divided into
  80641. ** S uniform buckets and the samples are the middle row from each bucket.
  80642. **
  80643. ** The format for sqlite_stat2 is recorded here for legacy reference. This
  80644. ** version of SQLite does not support sqlite_stat2. It neither reads nor
  80645. ** writes the sqlite_stat2 table. This version of SQLite only supports
  80646. ** sqlite_stat3.
  80647. **
  80648. ** Format for sqlite_stat3:
  80649. **
  80650. ** The sqlite_stat3 format is a subset of sqlite_stat4. Hence, the
  80651. ** sqlite_stat4 format will be described first. Further information
  80652. ** about sqlite_stat3 follows the sqlite_stat4 description.
  80653. **
  80654. ** Format for sqlite_stat4:
  80655. **
  80656. ** As with sqlite_stat2, the sqlite_stat4 table contains histogram data
  80657. ** to aid the query planner in choosing good indices based on the values
  80658. ** that indexed columns are compared against in the WHERE clauses of
  80659. ** queries.
  80660. **
  80661. ** The sqlite_stat4 table contains multiple entries for each index.
  80662. ** The idx column names the index and the tbl column is the table of the
  80663. ** index. If the idx and tbl columns are the same, then the sample is
  80664. ** of the INTEGER PRIMARY KEY. The sample column is a blob which is the
  80665. ** binary encoding of a key from the index. The nEq column is a
  80666. ** list of integers. The first integer is the approximate number
  80667. ** of entries in the index whose left-most column exactly matches
  80668. ** the left-most column of the sample. The second integer in nEq
  80669. ** is the approximate number of entries in the index where the
  80670. ** first two columns match the first two columns of the sample.
  80671. ** And so forth. nLt is another list of integers that show the approximate
  80672. ** number of entries that are strictly less than the sample. The first
  80673. ** integer in nLt contains the number of entries in the index where the
  80674. ** left-most column is less than the left-most column of the sample.
  80675. ** The K-th integer in the nLt entry is the number of index entries
  80676. ** where the first K columns are less than the first K columns of the
  80677. ** sample. The nDLt column is like nLt except that it contains the
  80678. ** number of distinct entries in the index that are less than the
  80679. ** sample.
  80680. **
  80681. ** There can be an arbitrary number of sqlite_stat4 entries per index.
  80682. ** The ANALYZE command will typically generate sqlite_stat4 tables
  80683. ** that contain between 10 and 40 samples which are distributed across
  80684. ** the key space, though not uniformly, and which include samples with
  80685. ** large nEq values.
  80686. **
  80687. ** Format for sqlite_stat3 redux:
  80688. **
  80689. ** The sqlite_stat3 table is like sqlite_stat4 except that it only
  80690. ** looks at the left-most column of the index. The sqlite_stat3.sample
  80691. ** column contains the actual value of the left-most column instead
  80692. ** of a blob encoding of the complete index key as is found in
  80693. ** sqlite_stat4.sample. The nEq, nLt, and nDLt entries of sqlite_stat3
  80694. ** all contain just a single integer which is the same as the first
  80695. ** integer in the equivalent columns in sqlite_stat4.
  80696. */
  80697. #ifndef SQLITE_OMIT_ANALYZE
  80698. #if defined(SQLITE_ENABLE_STAT4)
  80699. # define IsStat4 1
  80700. # define IsStat3 0
  80701. #elif defined(SQLITE_ENABLE_STAT3)
  80702. # define IsStat4 0
  80703. # define IsStat3 1
  80704. #else
  80705. # define IsStat4 0
  80706. # define IsStat3 0
  80707. # undef SQLITE_STAT4_SAMPLES
  80708. # define SQLITE_STAT4_SAMPLES 1
  80709. #endif
  80710. #define IsStat34 (IsStat3+IsStat4) /* 1 for STAT3 or STAT4. 0 otherwise */
  80711. /*
  80712. ** This routine generates code that opens the sqlite_statN tables.
  80713. ** The sqlite_stat1 table is always relevant. sqlite_stat2 is now
  80714. ** obsolete. sqlite_stat3 and sqlite_stat4 are only opened when
  80715. ** appropriate compile-time options are provided.
  80716. **
  80717. ** If the sqlite_statN tables do not previously exist, it is created.
  80718. **
  80719. ** Argument zWhere may be a pointer to a buffer containing a table name,
  80720. ** or it may be a NULL pointer. If it is not NULL, then all entries in
  80721. ** the sqlite_statN tables associated with the named table are deleted.
  80722. ** If zWhere==0, then code is generated to delete all stat table entries.
  80723. */
  80724. static void openStatTable(
  80725. Parse *pParse, /* Parsing context */
  80726. int iDb, /* The database we are looking in */
  80727. int iStatCur, /* Open the sqlite_stat1 table on this cursor */
  80728. const char *zWhere, /* Delete entries for this table or index */
  80729. const char *zWhereType /* Either "tbl" or "idx" */
  80730. ){
  80731. static const struct {
  80732. const char *zName;
  80733. const char *zCols;
  80734. } aTable[] = {
  80735. { "sqlite_stat1", "tbl,idx,stat" },
  80736. #if defined(SQLITE_ENABLE_STAT4)
  80737. { "sqlite_stat4", "tbl,idx,neq,nlt,ndlt,sample" },
  80738. { "sqlite_stat3", 0 },
  80739. #elif defined(SQLITE_ENABLE_STAT3)
  80740. { "sqlite_stat3", "tbl,idx,neq,nlt,ndlt,sample" },
  80741. { "sqlite_stat4", 0 },
  80742. #else
  80743. { "sqlite_stat3", 0 },
  80744. { "sqlite_stat4", 0 },
  80745. #endif
  80746. };
  80747. int i;
  80748. sqlite3 *db = pParse->db;
  80749. Db *pDb;
  80750. Vdbe *v = sqlite3GetVdbe(pParse);
  80751. int aRoot[ArraySize(aTable)];
  80752. u8 aCreateTbl[ArraySize(aTable)];
  80753. if( v==0 ) return;
  80754. assert( sqlite3BtreeHoldsAllMutexes(db) );
  80755. assert( sqlite3VdbeDb(v)==db );
  80756. pDb = &db->aDb[iDb];
  80757. /* Create new statistic tables if they do not exist, or clear them
  80758. ** if they do already exist.
  80759. */
  80760. for(i=0; i<ArraySize(aTable); i++){
  80761. const char *zTab = aTable[i].zName;
  80762. Table *pStat;
  80763. if( (pStat = sqlite3FindTable(db, zTab, pDb->zName))==0 ){
  80764. if( aTable[i].zCols ){
  80765. /* The sqlite_statN table does not exist. Create it. Note that a
  80766. ** side-effect of the CREATE TABLE statement is to leave the rootpage
  80767. ** of the new table in register pParse->regRoot. This is important
  80768. ** because the OpenWrite opcode below will be needing it. */
  80769. sqlite3NestedParse(pParse,
  80770. "CREATE TABLE %Q.%s(%s)", pDb->zName, zTab, aTable[i].zCols
  80771. );
  80772. aRoot[i] = pParse->regRoot;
  80773. aCreateTbl[i] = OPFLAG_P2ISREG;
  80774. }
  80775. }else{
  80776. /* The table already exists. If zWhere is not NULL, delete all entries
  80777. ** associated with the table zWhere. If zWhere is NULL, delete the
  80778. ** entire contents of the table. */
  80779. aRoot[i] = pStat->tnum;
  80780. aCreateTbl[i] = 0;
  80781. sqlite3TableLock(pParse, iDb, aRoot[i], 1, zTab);
  80782. if( zWhere ){
  80783. sqlite3NestedParse(pParse,
  80784. "DELETE FROM %Q.%s WHERE %s=%Q",
  80785. pDb->zName, zTab, zWhereType, zWhere
  80786. );
  80787. }else{
  80788. /* The sqlite_stat[134] table already exists. Delete all rows. */
  80789. sqlite3VdbeAddOp2(v, OP_Clear, aRoot[i], iDb);
  80790. }
  80791. }
  80792. }
  80793. /* Open the sqlite_stat[134] tables for writing. */
  80794. for(i=0; aTable[i].zCols; i++){
  80795. assert( i<ArraySize(aTable) );
  80796. sqlite3VdbeAddOp4Int(v, OP_OpenWrite, iStatCur+i, aRoot[i], iDb, 3);
  80797. sqlite3VdbeChangeP5(v, aCreateTbl[i]);
  80798. VdbeComment((v, aTable[i].zName));
  80799. }
  80800. }
  80801. /*
  80802. ** Recommended number of samples for sqlite_stat4
  80803. */
  80804. #ifndef SQLITE_STAT4_SAMPLES
  80805. # define SQLITE_STAT4_SAMPLES 24
  80806. #endif
  80807. /*
  80808. ** Three SQL functions - stat_init(), stat_push(), and stat_get() -
  80809. ** share an instance of the following structure to hold their state
  80810. ** information.
  80811. */
  80812. typedef struct Stat4Accum Stat4Accum;
  80813. typedef struct Stat4Sample Stat4Sample;
  80814. struct Stat4Sample {
  80815. tRowcnt *anEq; /* sqlite_stat4.nEq */
  80816. tRowcnt *anDLt; /* sqlite_stat4.nDLt */
  80817. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  80818. tRowcnt *anLt; /* sqlite_stat4.nLt */
  80819. union {
  80820. i64 iRowid; /* Rowid in main table of the key */
  80821. u8 *aRowid; /* Key for WITHOUT ROWID tables */
  80822. } u;
  80823. u32 nRowid; /* Sizeof aRowid[] */
  80824. u8 isPSample; /* True if a periodic sample */
  80825. int iCol; /* If !isPSample, the reason for inclusion */
  80826. u32 iHash; /* Tiebreaker hash */
  80827. #endif
  80828. };
  80829. struct Stat4Accum {
  80830. tRowcnt nRow; /* Number of rows in the entire table */
  80831. tRowcnt nPSample; /* How often to do a periodic sample */
  80832. int nCol; /* Number of columns in index + pk/rowid */
  80833. int nKeyCol; /* Number of index columns w/o the pk/rowid */
  80834. int mxSample; /* Maximum number of samples to accumulate */
  80835. Stat4Sample current; /* Current row as a Stat4Sample */
  80836. u32 iPrn; /* Pseudo-random number used for sampling */
  80837. Stat4Sample *aBest; /* Array of nCol best samples */
  80838. int iMin; /* Index in a[] of entry with minimum score */
  80839. int nSample; /* Current number of samples */
  80840. int iGet; /* Index of current sample accessed by stat_get() */
  80841. Stat4Sample *a; /* Array of mxSample Stat4Sample objects */
  80842. sqlite3 *db; /* Database connection, for malloc() */
  80843. };
  80844. /* Reclaim memory used by a Stat4Sample
  80845. */
  80846. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  80847. static void sampleClear(sqlite3 *db, Stat4Sample *p){
  80848. assert( db!=0 );
  80849. if( p->nRowid ){
  80850. sqlite3DbFree(db, p->u.aRowid);
  80851. p->nRowid = 0;
  80852. }
  80853. }
  80854. #endif
  80855. /* Initialize the BLOB value of a ROWID
  80856. */
  80857. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  80858. static void sampleSetRowid(sqlite3 *db, Stat4Sample *p, int n, const u8 *pData){
  80859. assert( db!=0 );
  80860. if( p->nRowid ) sqlite3DbFree(db, p->u.aRowid);
  80861. p->u.aRowid = sqlite3DbMallocRaw(db, n);
  80862. if( p->u.aRowid ){
  80863. p->nRowid = n;
  80864. memcpy(p->u.aRowid, pData, n);
  80865. }else{
  80866. p->nRowid = 0;
  80867. }
  80868. }
  80869. #endif
  80870. /* Initialize the INTEGER value of a ROWID.
  80871. */
  80872. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  80873. static void sampleSetRowidInt64(sqlite3 *db, Stat4Sample *p, i64 iRowid){
  80874. assert( db!=0 );
  80875. if( p->nRowid ) sqlite3DbFree(db, p->u.aRowid);
  80876. p->nRowid = 0;
  80877. p->u.iRowid = iRowid;
  80878. }
  80879. #endif
  80880. /*
  80881. ** Copy the contents of object (*pFrom) into (*pTo).
  80882. */
  80883. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  80884. static void sampleCopy(Stat4Accum *p, Stat4Sample *pTo, Stat4Sample *pFrom){
  80885. pTo->isPSample = pFrom->isPSample;
  80886. pTo->iCol = pFrom->iCol;
  80887. pTo->iHash = pFrom->iHash;
  80888. memcpy(pTo->anEq, pFrom->anEq, sizeof(tRowcnt)*p->nCol);
  80889. memcpy(pTo->anLt, pFrom->anLt, sizeof(tRowcnt)*p->nCol);
  80890. memcpy(pTo->anDLt, pFrom->anDLt, sizeof(tRowcnt)*p->nCol);
  80891. if( pFrom->nRowid ){
  80892. sampleSetRowid(p->db, pTo, pFrom->nRowid, pFrom->u.aRowid);
  80893. }else{
  80894. sampleSetRowidInt64(p->db, pTo, pFrom->u.iRowid);
  80895. }
  80896. }
  80897. #endif
  80898. /*
  80899. ** Reclaim all memory of a Stat4Accum structure.
  80900. */
  80901. static void stat4Destructor(void *pOld){
  80902. Stat4Accum *p = (Stat4Accum*)pOld;
  80903. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  80904. int i;
  80905. for(i=0; i<p->nCol; i++) sampleClear(p->db, p->aBest+i);
  80906. for(i=0; i<p->mxSample; i++) sampleClear(p->db, p->a+i);
  80907. sampleClear(p->db, &p->current);
  80908. #endif
  80909. sqlite3DbFree(p->db, p);
  80910. }
  80911. /*
  80912. ** Implementation of the stat_init(N,K,C) SQL function. The three parameters
  80913. ** are:
  80914. ** N: The number of columns in the index including the rowid/pk (note 1)
  80915. ** K: The number of columns in the index excluding the rowid/pk.
  80916. ** C: The number of rows in the index (note 2)
  80917. **
  80918. ** Note 1: In the special case of the covering index that implements a
  80919. ** WITHOUT ROWID table, N is the number of PRIMARY KEY columns, not the
  80920. ** total number of columns in the table.
  80921. **
  80922. ** Note 2: C is only used for STAT3 and STAT4.
  80923. **
  80924. ** For indexes on ordinary rowid tables, N==K+1. But for indexes on
  80925. ** WITHOUT ROWID tables, N=K+P where P is the number of columns in the
  80926. ** PRIMARY KEY of the table. The covering index that implements the
  80927. ** original WITHOUT ROWID table as N==K as a special case.
  80928. **
  80929. ** This routine allocates the Stat4Accum object in heap memory. The return
  80930. ** value is a pointer to the Stat4Accum object. The datatype of the
  80931. ** return value is BLOB, but it is really just a pointer to the Stat4Accum
  80932. ** object.
  80933. */
  80934. static void statInit(
  80935. sqlite3_context *context,
  80936. int argc,
  80937. sqlite3_value **argv
  80938. ){
  80939. Stat4Accum *p;
  80940. int nCol; /* Number of columns in index being sampled */
  80941. int nKeyCol; /* Number of key columns */
  80942. int nColUp; /* nCol rounded up for alignment */
  80943. int n; /* Bytes of space to allocate */
  80944. sqlite3 *db; /* Database connection */
  80945. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  80946. int mxSample = SQLITE_STAT4_SAMPLES;
  80947. #endif
  80948. /* Decode the three function arguments */
  80949. UNUSED_PARAMETER(argc);
  80950. nCol = sqlite3_value_int(argv[0]);
  80951. assert( nCol>0 );
  80952. nColUp = sizeof(tRowcnt)<8 ? (nCol+1)&~1 : nCol;
  80953. nKeyCol = sqlite3_value_int(argv[1]);
  80954. assert( nKeyCol<=nCol );
  80955. assert( nKeyCol>0 );
  80956. /* Allocate the space required for the Stat4Accum object */
  80957. n = sizeof(*p)
  80958. + sizeof(tRowcnt)*nColUp /* Stat4Accum.anEq */
  80959. + sizeof(tRowcnt)*nColUp /* Stat4Accum.anDLt */
  80960. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  80961. + sizeof(tRowcnt)*nColUp /* Stat4Accum.anLt */
  80962. + sizeof(Stat4Sample)*(nCol+mxSample) /* Stat4Accum.aBest[], a[] */
  80963. + sizeof(tRowcnt)*3*nColUp*(nCol+mxSample)
  80964. #endif
  80965. ;
  80966. db = sqlite3_context_db_handle(context);
  80967. p = sqlite3DbMallocZero(db, n);
  80968. if( p==0 ){
  80969. sqlite3_result_error_nomem(context);
  80970. return;
  80971. }
  80972. p->db = db;
  80973. p->nRow = 0;
  80974. p->nCol = nCol;
  80975. p->nKeyCol = nKeyCol;
  80976. p->current.anDLt = (tRowcnt*)&p[1];
  80977. p->current.anEq = &p->current.anDLt[nColUp];
  80978. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  80979. {
  80980. u8 *pSpace; /* Allocated space not yet assigned */
  80981. int i; /* Used to iterate through p->aSample[] */
  80982. p->iGet = -1;
  80983. p->mxSample = mxSample;
  80984. p->nPSample = (tRowcnt)(sqlite3_value_int64(argv[2])/(mxSample/3+1) + 1);
  80985. p->current.anLt = &p->current.anEq[nColUp];
  80986. p->iPrn = nCol*0x689e962d ^ sqlite3_value_int(argv[2])*0xd0944565;
  80987. /* Set up the Stat4Accum.a[] and aBest[] arrays */
  80988. p->a = (struct Stat4Sample*)&p->current.anLt[nColUp];
  80989. p->aBest = &p->a[mxSample];
  80990. pSpace = (u8*)(&p->a[mxSample+nCol]);
  80991. for(i=0; i<(mxSample+nCol); i++){
  80992. p->a[i].anEq = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
  80993. p->a[i].anLt = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
  80994. p->a[i].anDLt = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
  80995. }
  80996. assert( (pSpace - (u8*)p)==n );
  80997. for(i=0; i<nCol; i++){
  80998. p->aBest[i].iCol = i;
  80999. }
  81000. }
  81001. #endif
  81002. /* Return a pointer to the allocated object to the caller. Note that
  81003. ** only the pointer (the 2nd parameter) matters. The size of the object
  81004. ** (given by the 3rd parameter) is never used and can be any positive
  81005. ** value. */
  81006. sqlite3_result_blob(context, p, sizeof(*p), stat4Destructor);
  81007. }
  81008. static const FuncDef statInitFuncdef = {
  81009. 2+IsStat34, /* nArg */
  81010. SQLITE_UTF8, /* funcFlags */
  81011. 0, /* pUserData */
  81012. 0, /* pNext */
  81013. statInit, /* xFunc */
  81014. 0, /* xStep */
  81015. 0, /* xFinalize */
  81016. "stat_init", /* zName */
  81017. 0, /* pHash */
  81018. 0 /* pDestructor */
  81019. };
  81020. #ifdef SQLITE_ENABLE_STAT4
  81021. /*
  81022. ** pNew and pOld are both candidate non-periodic samples selected for
  81023. ** the same column (pNew->iCol==pOld->iCol). Ignoring this column and
  81024. ** considering only any trailing columns and the sample hash value, this
  81025. ** function returns true if sample pNew is to be preferred over pOld.
  81026. ** In other words, if we assume that the cardinalities of the selected
  81027. ** column for pNew and pOld are equal, is pNew to be preferred over pOld.
  81028. **
  81029. ** This function assumes that for each argument sample, the contents of
  81030. ** the anEq[] array from pSample->anEq[pSample->iCol+1] onwards are valid.
  81031. */
  81032. static int sampleIsBetterPost(
  81033. Stat4Accum *pAccum,
  81034. Stat4Sample *pNew,
  81035. Stat4Sample *pOld
  81036. ){
  81037. int nCol = pAccum->nCol;
  81038. int i;
  81039. assert( pNew->iCol==pOld->iCol );
  81040. for(i=pNew->iCol+1; i<nCol; i++){
  81041. if( pNew->anEq[i]>pOld->anEq[i] ) return 1;
  81042. if( pNew->anEq[i]<pOld->anEq[i] ) return 0;
  81043. }
  81044. if( pNew->iHash>pOld->iHash ) return 1;
  81045. return 0;
  81046. }
  81047. #endif
  81048. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  81049. /*
  81050. ** Return true if pNew is to be preferred over pOld.
  81051. **
  81052. ** This function assumes that for each argument sample, the contents of
  81053. ** the anEq[] array from pSample->anEq[pSample->iCol] onwards are valid.
  81054. */
  81055. static int sampleIsBetter(
  81056. Stat4Accum *pAccum,
  81057. Stat4Sample *pNew,
  81058. Stat4Sample *pOld
  81059. ){
  81060. tRowcnt nEqNew = pNew->anEq[pNew->iCol];
  81061. tRowcnt nEqOld = pOld->anEq[pOld->iCol];
  81062. assert( pOld->isPSample==0 && pNew->isPSample==0 );
  81063. assert( IsStat4 || (pNew->iCol==0 && pOld->iCol==0) );
  81064. if( (nEqNew>nEqOld) ) return 1;
  81065. #ifdef SQLITE_ENABLE_STAT4
  81066. if( nEqNew==nEqOld ){
  81067. if( pNew->iCol<pOld->iCol ) return 1;
  81068. return (pNew->iCol==pOld->iCol && sampleIsBetterPost(pAccum, pNew, pOld));
  81069. }
  81070. return 0;
  81071. #else
  81072. return (nEqNew==nEqOld && pNew->iHash>pOld->iHash);
  81073. #endif
  81074. }
  81075. /*
  81076. ** Copy the contents of sample *pNew into the p->a[] array. If necessary,
  81077. ** remove the least desirable sample from p->a[] to make room.
  81078. */
  81079. static void sampleInsert(Stat4Accum *p, Stat4Sample *pNew, int nEqZero){
  81080. Stat4Sample *pSample = 0;
  81081. int i;
  81082. assert( IsStat4 || nEqZero==0 );
  81083. #ifdef SQLITE_ENABLE_STAT4
  81084. if( pNew->isPSample==0 ){
  81085. Stat4Sample *pUpgrade = 0;
  81086. assert( pNew->anEq[pNew->iCol]>0 );
  81087. /* This sample is being added because the prefix that ends in column
  81088. ** iCol occurs many times in the table. However, if we have already
  81089. ** added a sample that shares this prefix, there is no need to add
  81090. ** this one. Instead, upgrade the priority of the highest priority
  81091. ** existing sample that shares this prefix. */
  81092. for(i=p->nSample-1; i>=0; i--){
  81093. Stat4Sample *pOld = &p->a[i];
  81094. if( pOld->anEq[pNew->iCol]==0 ){
  81095. if( pOld->isPSample ) return;
  81096. assert( pOld->iCol>pNew->iCol );
  81097. assert( sampleIsBetter(p, pNew, pOld) );
  81098. if( pUpgrade==0 || sampleIsBetter(p, pOld, pUpgrade) ){
  81099. pUpgrade = pOld;
  81100. }
  81101. }
  81102. }
  81103. if( pUpgrade ){
  81104. pUpgrade->iCol = pNew->iCol;
  81105. pUpgrade->anEq[pUpgrade->iCol] = pNew->anEq[pUpgrade->iCol];
  81106. goto find_new_min;
  81107. }
  81108. }
  81109. #endif
  81110. /* If necessary, remove sample iMin to make room for the new sample. */
  81111. if( p->nSample>=p->mxSample ){
  81112. Stat4Sample *pMin = &p->a[p->iMin];
  81113. tRowcnt *anEq = pMin->anEq;
  81114. tRowcnt *anLt = pMin->anLt;
  81115. tRowcnt *anDLt = pMin->anDLt;
  81116. sampleClear(p->db, pMin);
  81117. memmove(pMin, &pMin[1], sizeof(p->a[0])*(p->nSample-p->iMin-1));
  81118. pSample = &p->a[p->nSample-1];
  81119. pSample->nRowid = 0;
  81120. pSample->anEq = anEq;
  81121. pSample->anDLt = anDLt;
  81122. pSample->anLt = anLt;
  81123. p->nSample = p->mxSample-1;
  81124. }
  81125. /* The "rows less-than" for the rowid column must be greater than that
  81126. ** for the last sample in the p->a[] array. Otherwise, the samples would
  81127. ** be out of order. */
  81128. #ifdef SQLITE_ENABLE_STAT4
  81129. assert( p->nSample==0
  81130. || pNew->anLt[p->nCol-1] > p->a[p->nSample-1].anLt[p->nCol-1] );
  81131. #endif
  81132. /* Insert the new sample */
  81133. pSample = &p->a[p->nSample];
  81134. sampleCopy(p, pSample, pNew);
  81135. p->nSample++;
  81136. /* Zero the first nEqZero entries in the anEq[] array. */
  81137. memset(pSample->anEq, 0, sizeof(tRowcnt)*nEqZero);
  81138. #ifdef SQLITE_ENABLE_STAT4
  81139. find_new_min:
  81140. #endif
  81141. if( p->nSample>=p->mxSample ){
  81142. int iMin = -1;
  81143. for(i=0; i<p->mxSample; i++){
  81144. if( p->a[i].isPSample ) continue;
  81145. if( iMin<0 || sampleIsBetter(p, &p->a[iMin], &p->a[i]) ){
  81146. iMin = i;
  81147. }
  81148. }
  81149. assert( iMin>=0 );
  81150. p->iMin = iMin;
  81151. }
  81152. }
  81153. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  81154. /*
  81155. ** Field iChng of the index being scanned has changed. So at this point
  81156. ** p->current contains a sample that reflects the previous row of the
  81157. ** index. The value of anEq[iChng] and subsequent anEq[] elements are
  81158. ** correct at this point.
  81159. */
  81160. static void samplePushPrevious(Stat4Accum *p, int iChng){
  81161. #ifdef SQLITE_ENABLE_STAT4
  81162. int i;
  81163. /* Check if any samples from the aBest[] array should be pushed
  81164. ** into IndexSample.a[] at this point. */
  81165. for(i=(p->nCol-2); i>=iChng; i--){
  81166. Stat4Sample *pBest = &p->aBest[i];
  81167. pBest->anEq[i] = p->current.anEq[i];
  81168. if( p->nSample<p->mxSample || sampleIsBetter(p, pBest, &p->a[p->iMin]) ){
  81169. sampleInsert(p, pBest, i);
  81170. }
  81171. }
  81172. /* Update the anEq[] fields of any samples already collected. */
  81173. for(i=p->nSample-1; i>=0; i--){
  81174. int j;
  81175. for(j=iChng; j<p->nCol; j++){
  81176. if( p->a[i].anEq[j]==0 ) p->a[i].anEq[j] = p->current.anEq[j];
  81177. }
  81178. }
  81179. #endif
  81180. #if defined(SQLITE_ENABLE_STAT3) && !defined(SQLITE_ENABLE_STAT4)
  81181. if( iChng==0 ){
  81182. tRowcnt nLt = p->current.anLt[0];
  81183. tRowcnt nEq = p->current.anEq[0];
  81184. /* Check if this is to be a periodic sample. If so, add it. */
  81185. if( (nLt/p->nPSample)!=(nLt+nEq)/p->nPSample ){
  81186. p->current.isPSample = 1;
  81187. sampleInsert(p, &p->current, 0);
  81188. p->current.isPSample = 0;
  81189. }else
  81190. /* Or if it is a non-periodic sample. Add it in this case too. */
  81191. if( p->nSample<p->mxSample
  81192. || sampleIsBetter(p, &p->current, &p->a[p->iMin])
  81193. ){
  81194. sampleInsert(p, &p->current, 0);
  81195. }
  81196. }
  81197. #endif
  81198. #ifndef SQLITE_ENABLE_STAT3_OR_STAT4
  81199. UNUSED_PARAMETER( p );
  81200. UNUSED_PARAMETER( iChng );
  81201. #endif
  81202. }
  81203. /*
  81204. ** Implementation of the stat_push SQL function: stat_push(P,C,R)
  81205. ** Arguments:
  81206. **
  81207. ** P Pointer to the Stat4Accum object created by stat_init()
  81208. ** C Index of left-most column to differ from previous row
  81209. ** R Rowid for the current row. Might be a key record for
  81210. ** WITHOUT ROWID tables.
  81211. **
  81212. ** This SQL function always returns NULL. It's purpose it to accumulate
  81213. ** statistical data and/or samples in the Stat4Accum object about the
  81214. ** index being analyzed. The stat_get() SQL function will later be used to
  81215. ** extract relevant information for constructing the sqlite_statN tables.
  81216. **
  81217. ** The R parameter is only used for STAT3 and STAT4
  81218. */
  81219. static void statPush(
  81220. sqlite3_context *context,
  81221. int argc,
  81222. sqlite3_value **argv
  81223. ){
  81224. int i;
  81225. /* The three function arguments */
  81226. Stat4Accum *p = (Stat4Accum*)sqlite3_value_blob(argv[0]);
  81227. int iChng = sqlite3_value_int(argv[1]);
  81228. UNUSED_PARAMETER( argc );
  81229. UNUSED_PARAMETER( context );
  81230. assert( p->nCol>0 );
  81231. assert( iChng<p->nCol );
  81232. if( p->nRow==0 ){
  81233. /* This is the first call to this function. Do initialization. */
  81234. for(i=0; i<p->nCol; i++) p->current.anEq[i] = 1;
  81235. }else{
  81236. /* Second and subsequent calls get processed here */
  81237. samplePushPrevious(p, iChng);
  81238. /* Update anDLt[], anLt[] and anEq[] to reflect the values that apply
  81239. ** to the current row of the index. */
  81240. for(i=0; i<iChng; i++){
  81241. p->current.anEq[i]++;
  81242. }
  81243. for(i=iChng; i<p->nCol; i++){
  81244. p->current.anDLt[i]++;
  81245. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  81246. p->current.anLt[i] += p->current.anEq[i];
  81247. #endif
  81248. p->current.anEq[i] = 1;
  81249. }
  81250. }
  81251. p->nRow++;
  81252. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  81253. if( sqlite3_value_type(argv[2])==SQLITE_INTEGER ){
  81254. sampleSetRowidInt64(p->db, &p->current, sqlite3_value_int64(argv[2]));
  81255. }else{
  81256. sampleSetRowid(p->db, &p->current, sqlite3_value_bytes(argv[2]),
  81257. sqlite3_value_blob(argv[2]));
  81258. }
  81259. p->current.iHash = p->iPrn = p->iPrn*1103515245 + 12345;
  81260. #endif
  81261. #ifdef SQLITE_ENABLE_STAT4
  81262. {
  81263. tRowcnt nLt = p->current.anLt[p->nCol-1];
  81264. /* Check if this is to be a periodic sample. If so, add it. */
  81265. if( (nLt/p->nPSample)!=(nLt+1)/p->nPSample ){
  81266. p->current.isPSample = 1;
  81267. p->current.iCol = 0;
  81268. sampleInsert(p, &p->current, p->nCol-1);
  81269. p->current.isPSample = 0;
  81270. }
  81271. /* Update the aBest[] array. */
  81272. for(i=0; i<(p->nCol-1); i++){
  81273. p->current.iCol = i;
  81274. if( i>=iChng || sampleIsBetterPost(p, &p->current, &p->aBest[i]) ){
  81275. sampleCopy(p, &p->aBest[i], &p->current);
  81276. }
  81277. }
  81278. }
  81279. #endif
  81280. }
  81281. static const FuncDef statPushFuncdef = {
  81282. 2+IsStat34, /* nArg */
  81283. SQLITE_UTF8, /* funcFlags */
  81284. 0, /* pUserData */
  81285. 0, /* pNext */
  81286. statPush, /* xFunc */
  81287. 0, /* xStep */
  81288. 0, /* xFinalize */
  81289. "stat_push", /* zName */
  81290. 0, /* pHash */
  81291. 0 /* pDestructor */
  81292. };
  81293. #define STAT_GET_STAT1 0 /* "stat" column of stat1 table */
  81294. #define STAT_GET_ROWID 1 /* "rowid" column of stat[34] entry */
  81295. #define STAT_GET_NEQ 2 /* "neq" column of stat[34] entry */
  81296. #define STAT_GET_NLT 3 /* "nlt" column of stat[34] entry */
  81297. #define STAT_GET_NDLT 4 /* "ndlt" column of stat[34] entry */
  81298. /*
  81299. ** Implementation of the stat_get(P,J) SQL function. This routine is
  81300. ** used to query statistical information that has been gathered into
  81301. ** the Stat4Accum object by prior calls to stat_push(). The P parameter
  81302. ** has type BLOB but it is really just a pointer to the Stat4Accum object.
  81303. ** The content to returned is determined by the parameter J
  81304. ** which is one of the STAT_GET_xxxx values defined above.
  81305. **
  81306. ** If neither STAT3 nor STAT4 are enabled, then J is always
  81307. ** STAT_GET_STAT1 and is hence omitted and this routine becomes
  81308. ** a one-parameter function, stat_get(P), that always returns the
  81309. ** stat1 table entry information.
  81310. */
  81311. static void statGet(
  81312. sqlite3_context *context,
  81313. int argc,
  81314. sqlite3_value **argv
  81315. ){
  81316. Stat4Accum *p = (Stat4Accum*)sqlite3_value_blob(argv[0]);
  81317. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  81318. /* STAT3 and STAT4 have a parameter on this routine. */
  81319. int eCall = sqlite3_value_int(argv[1]);
  81320. assert( argc==2 );
  81321. assert( eCall==STAT_GET_STAT1 || eCall==STAT_GET_NEQ
  81322. || eCall==STAT_GET_ROWID || eCall==STAT_GET_NLT
  81323. || eCall==STAT_GET_NDLT
  81324. );
  81325. if( eCall==STAT_GET_STAT1 )
  81326. #else
  81327. assert( argc==1 );
  81328. #endif
  81329. {
  81330. /* Return the value to store in the "stat" column of the sqlite_stat1
  81331. ** table for this index.
  81332. **
  81333. ** The value is a string composed of a list of integers describing
  81334. ** the index. The first integer in the list is the total number of
  81335. ** entries in the index. There is one additional integer in the list
  81336. ** for each indexed column. This additional integer is an estimate of
  81337. ** the number of rows matched by a stabbing query on the index using
  81338. ** a key with the corresponding number of fields. In other words,
  81339. ** if the index is on columns (a,b) and the sqlite_stat1 value is
  81340. ** "100 10 2", then SQLite estimates that:
  81341. **
  81342. ** * the index contains 100 rows,
  81343. ** * "WHERE a=?" matches 10 rows, and
  81344. ** * "WHERE a=? AND b=?" matches 2 rows.
  81345. **
  81346. ** If D is the count of distinct values and K is the total number of
  81347. ** rows, then each estimate is computed as:
  81348. **
  81349. ** I = (K+D-1)/D
  81350. */
  81351. char *z;
  81352. int i;
  81353. char *zRet = sqlite3MallocZero( (p->nKeyCol+1)*25 );
  81354. if( zRet==0 ){
  81355. sqlite3_result_error_nomem(context);
  81356. return;
  81357. }
  81358. sqlite3_snprintf(24, zRet, "%llu", (u64)p->nRow);
  81359. z = zRet + sqlite3Strlen30(zRet);
  81360. for(i=0; i<p->nKeyCol; i++){
  81361. u64 nDistinct = p->current.anDLt[i] + 1;
  81362. u64 iVal = (p->nRow + nDistinct - 1) / nDistinct;
  81363. sqlite3_snprintf(24, z, " %llu", iVal);
  81364. z += sqlite3Strlen30(z);
  81365. assert( p->current.anEq[i] );
  81366. }
  81367. assert( z[0]=='\0' && z>zRet );
  81368. sqlite3_result_text(context, zRet, -1, sqlite3_free);
  81369. }
  81370. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  81371. else if( eCall==STAT_GET_ROWID ){
  81372. if( p->iGet<0 ){
  81373. samplePushPrevious(p, 0);
  81374. p->iGet = 0;
  81375. }
  81376. if( p->iGet<p->nSample ){
  81377. Stat4Sample *pS = p->a + p->iGet;
  81378. if( pS->nRowid==0 ){
  81379. sqlite3_result_int64(context, pS->u.iRowid);
  81380. }else{
  81381. sqlite3_result_blob(context, pS->u.aRowid, pS->nRowid,
  81382. SQLITE_TRANSIENT);
  81383. }
  81384. }
  81385. }else{
  81386. tRowcnt *aCnt = 0;
  81387. assert( p->iGet<p->nSample );
  81388. switch( eCall ){
  81389. case STAT_GET_NEQ: aCnt = p->a[p->iGet].anEq; break;
  81390. case STAT_GET_NLT: aCnt = p->a[p->iGet].anLt; break;
  81391. default: {
  81392. aCnt = p->a[p->iGet].anDLt;
  81393. p->iGet++;
  81394. break;
  81395. }
  81396. }
  81397. if( IsStat3 ){
  81398. sqlite3_result_int64(context, (i64)aCnt[0]);
  81399. }else{
  81400. char *zRet = sqlite3MallocZero(p->nCol * 25);
  81401. if( zRet==0 ){
  81402. sqlite3_result_error_nomem(context);
  81403. }else{
  81404. int i;
  81405. char *z = zRet;
  81406. for(i=0; i<p->nCol; i++){
  81407. sqlite3_snprintf(24, z, "%llu ", (u64)aCnt[i]);
  81408. z += sqlite3Strlen30(z);
  81409. }
  81410. assert( z[0]=='\0' && z>zRet );
  81411. z[-1] = '\0';
  81412. sqlite3_result_text(context, zRet, -1, sqlite3_free);
  81413. }
  81414. }
  81415. }
  81416. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  81417. #ifndef SQLITE_DEBUG
  81418. UNUSED_PARAMETER( argc );
  81419. #endif
  81420. }
  81421. static const FuncDef statGetFuncdef = {
  81422. 1+IsStat34, /* nArg */
  81423. SQLITE_UTF8, /* funcFlags */
  81424. 0, /* pUserData */
  81425. 0, /* pNext */
  81426. statGet, /* xFunc */
  81427. 0, /* xStep */
  81428. 0, /* xFinalize */
  81429. "stat_get", /* zName */
  81430. 0, /* pHash */
  81431. 0 /* pDestructor */
  81432. };
  81433. static void callStatGet(Vdbe *v, int regStat4, int iParam, int regOut){
  81434. assert( regOut!=regStat4 && regOut!=regStat4+1 );
  81435. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  81436. sqlite3VdbeAddOp2(v, OP_Integer, iParam, regStat4+1);
  81437. #elif SQLITE_DEBUG
  81438. assert( iParam==STAT_GET_STAT1 );
  81439. #else
  81440. UNUSED_PARAMETER( iParam );
  81441. #endif
  81442. sqlite3VdbeAddOp3(v, OP_Function, 0, regStat4, regOut);
  81443. sqlite3VdbeChangeP4(v, -1, (char*)&statGetFuncdef, P4_FUNCDEF);
  81444. sqlite3VdbeChangeP5(v, 1 + IsStat34);
  81445. }
  81446. /*
  81447. ** Generate code to do an analysis of all indices associated with
  81448. ** a single table.
  81449. */
  81450. static void analyzeOneTable(
  81451. Parse *pParse, /* Parser context */
  81452. Table *pTab, /* Table whose indices are to be analyzed */
  81453. Index *pOnlyIdx, /* If not NULL, only analyze this one index */
  81454. int iStatCur, /* Index of VdbeCursor that writes the sqlite_stat1 table */
  81455. int iMem, /* Available memory locations begin here */
  81456. int iTab /* Next available cursor */
  81457. ){
  81458. sqlite3 *db = pParse->db; /* Database handle */
  81459. Index *pIdx; /* An index to being analyzed */
  81460. int iIdxCur; /* Cursor open on index being analyzed */
  81461. int iTabCur; /* Table cursor */
  81462. Vdbe *v; /* The virtual machine being built up */
  81463. int i; /* Loop counter */
  81464. int jZeroRows = -1; /* Jump from here if number of rows is zero */
  81465. int iDb; /* Index of database containing pTab */
  81466. u8 needTableCnt = 1; /* True to count the table */
  81467. int regNewRowid = iMem++; /* Rowid for the inserted record */
  81468. int regStat4 = iMem++; /* Register to hold Stat4Accum object */
  81469. int regChng = iMem++; /* Index of changed index field */
  81470. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  81471. int regRowid = iMem++; /* Rowid argument passed to stat_push() */
  81472. #endif
  81473. int regTemp = iMem++; /* Temporary use register */
  81474. int regTabname = iMem++; /* Register containing table name */
  81475. int regIdxname = iMem++; /* Register containing index name */
  81476. int regStat1 = iMem++; /* Value for the stat column of sqlite_stat1 */
  81477. int regPrev = iMem; /* MUST BE LAST (see below) */
  81478. pParse->nMem = MAX(pParse->nMem, iMem);
  81479. v = sqlite3GetVdbe(pParse);
  81480. if( v==0 || NEVER(pTab==0) ){
  81481. return;
  81482. }
  81483. if( pTab->tnum==0 ){
  81484. /* Do not gather statistics on views or virtual tables */
  81485. return;
  81486. }
  81487. if( sqlite3_strnicmp(pTab->zName, "sqlite_", 7)==0 ){
  81488. /* Do not gather statistics on system tables */
  81489. return;
  81490. }
  81491. assert( sqlite3BtreeHoldsAllMutexes(db) );
  81492. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  81493. assert( iDb>=0 );
  81494. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  81495. #ifndef SQLITE_OMIT_AUTHORIZATION
  81496. if( sqlite3AuthCheck(pParse, SQLITE_ANALYZE, pTab->zName, 0,
  81497. db->aDb[iDb].zName ) ){
  81498. return;
  81499. }
  81500. #endif
  81501. /* Establish a read-lock on the table at the shared-cache level.
  81502. ** Open a read-only cursor on the table. Also allocate a cursor number
  81503. ** to use for scanning indexes (iIdxCur). No index cursor is opened at
  81504. ** this time though. */
  81505. sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
  81506. iTabCur = iTab++;
  81507. iIdxCur = iTab++;
  81508. pParse->nTab = MAX(pParse->nTab, iTab);
  81509. sqlite3OpenTable(pParse, iTabCur, iDb, pTab, OP_OpenRead);
  81510. sqlite3VdbeAddOp4(v, OP_String8, 0, regTabname, 0, pTab->zName, 0);
  81511. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  81512. int nCol; /* Number of columns in pIdx. "N" */
  81513. int addrRewind; /* Address of "OP_Rewind iIdxCur" */
  81514. int addrNextRow; /* Address of "next_row:" */
  81515. const char *zIdxName; /* Name of the index */
  81516. int nColTest; /* Number of columns to test for changes */
  81517. if( pOnlyIdx && pOnlyIdx!=pIdx ) continue;
  81518. if( pIdx->pPartIdxWhere==0 ) needTableCnt = 0;
  81519. if( !HasRowid(pTab) && IsPrimaryKeyIndex(pIdx) ){
  81520. nCol = pIdx->nKeyCol;
  81521. zIdxName = pTab->zName;
  81522. nColTest = nCol - 1;
  81523. }else{
  81524. nCol = pIdx->nColumn;
  81525. zIdxName = pIdx->zName;
  81526. nColTest = pIdx->uniqNotNull ? pIdx->nKeyCol-1 : nCol-1;
  81527. }
  81528. /* Populate the register containing the index name. */
  81529. sqlite3VdbeAddOp4(v, OP_String8, 0, regIdxname, 0, zIdxName, 0);
  81530. VdbeComment((v, "Analysis for %s.%s", pTab->zName, zIdxName));
  81531. /*
  81532. ** Pseudo-code for loop that calls stat_push():
  81533. **
  81534. ** Rewind csr
  81535. ** if eof(csr) goto end_of_scan;
  81536. ** regChng = 0
  81537. ** goto chng_addr_0;
  81538. **
  81539. ** next_row:
  81540. ** regChng = 0
  81541. ** if( idx(0) != regPrev(0) ) goto chng_addr_0
  81542. ** regChng = 1
  81543. ** if( idx(1) != regPrev(1) ) goto chng_addr_1
  81544. ** ...
  81545. ** regChng = N
  81546. ** goto chng_addr_N
  81547. **
  81548. ** chng_addr_0:
  81549. ** regPrev(0) = idx(0)
  81550. ** chng_addr_1:
  81551. ** regPrev(1) = idx(1)
  81552. ** ...
  81553. **
  81554. ** endDistinctTest:
  81555. ** regRowid = idx(rowid)
  81556. ** stat_push(P, regChng, regRowid)
  81557. ** Next csr
  81558. ** if !eof(csr) goto next_row;
  81559. **
  81560. ** end_of_scan:
  81561. */
  81562. /* Make sure there are enough memory cells allocated to accommodate
  81563. ** the regPrev array and a trailing rowid (the rowid slot is required
  81564. ** when building a record to insert into the sample column of
  81565. ** the sqlite_stat4 table. */
  81566. pParse->nMem = MAX(pParse->nMem, regPrev+nColTest);
  81567. /* Open a read-only cursor on the index being analyzed. */
  81568. assert( iDb==sqlite3SchemaToIndex(db, pIdx->pSchema) );
  81569. sqlite3VdbeAddOp3(v, OP_OpenRead, iIdxCur, pIdx->tnum, iDb);
  81570. sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
  81571. VdbeComment((v, "%s", pIdx->zName));
  81572. /* Invoke the stat_init() function. The arguments are:
  81573. **
  81574. ** (1) the number of columns in the index including the rowid
  81575. ** (or for a WITHOUT ROWID table, the number of PK columns),
  81576. ** (2) the number of columns in the key without the rowid/pk
  81577. ** (3) the number of rows in the index,
  81578. **
  81579. **
  81580. ** The third argument is only used for STAT3 and STAT4
  81581. */
  81582. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  81583. sqlite3VdbeAddOp2(v, OP_Count, iIdxCur, regStat4+3);
  81584. #endif
  81585. sqlite3VdbeAddOp2(v, OP_Integer, nCol, regStat4+1);
  81586. sqlite3VdbeAddOp2(v, OP_Integer, pIdx->nKeyCol, regStat4+2);
  81587. sqlite3VdbeAddOp3(v, OP_Function, 0, regStat4+1, regStat4);
  81588. sqlite3VdbeChangeP4(v, -1, (char*)&statInitFuncdef, P4_FUNCDEF);
  81589. sqlite3VdbeChangeP5(v, 2+IsStat34);
  81590. /* Implementation of the following:
  81591. **
  81592. ** Rewind csr
  81593. ** if eof(csr) goto end_of_scan;
  81594. ** regChng = 0
  81595. ** goto next_push_0;
  81596. **
  81597. */
  81598. addrRewind = sqlite3VdbeAddOp1(v, OP_Rewind, iIdxCur);
  81599. VdbeCoverage(v);
  81600. sqlite3VdbeAddOp2(v, OP_Integer, 0, regChng);
  81601. addrNextRow = sqlite3VdbeCurrentAddr(v);
  81602. if( nColTest>0 ){
  81603. int endDistinctTest = sqlite3VdbeMakeLabel(v);
  81604. int *aGotoChng; /* Array of jump instruction addresses */
  81605. aGotoChng = sqlite3DbMallocRaw(db, sizeof(int)*nColTest);
  81606. if( aGotoChng==0 ) continue;
  81607. /*
  81608. ** next_row:
  81609. ** regChng = 0
  81610. ** if( idx(0) != regPrev(0) ) goto chng_addr_0
  81611. ** regChng = 1
  81612. ** if( idx(1) != regPrev(1) ) goto chng_addr_1
  81613. ** ...
  81614. ** regChng = N
  81615. ** goto endDistinctTest
  81616. */
  81617. sqlite3VdbeAddOp0(v, OP_Goto);
  81618. addrNextRow = sqlite3VdbeCurrentAddr(v);
  81619. if( nColTest==1 && pIdx->nKeyCol==1 && IsUniqueIndex(pIdx) ){
  81620. /* For a single-column UNIQUE index, once we have found a non-NULL
  81621. ** row, we know that all the rest will be distinct, so skip
  81622. ** subsequent distinctness tests. */
  81623. sqlite3VdbeAddOp2(v, OP_NotNull, regPrev, endDistinctTest);
  81624. VdbeCoverage(v);
  81625. }
  81626. for(i=0; i<nColTest; i++){
  81627. char *pColl = (char*)sqlite3LocateCollSeq(pParse, pIdx->azColl[i]);
  81628. sqlite3VdbeAddOp2(v, OP_Integer, i, regChng);
  81629. sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regTemp);
  81630. aGotoChng[i] =
  81631. sqlite3VdbeAddOp4(v, OP_Ne, regTemp, 0, regPrev+i, pColl, P4_COLLSEQ);
  81632. sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
  81633. VdbeCoverage(v);
  81634. }
  81635. sqlite3VdbeAddOp2(v, OP_Integer, nColTest, regChng);
  81636. sqlite3VdbeAddOp2(v, OP_Goto, 0, endDistinctTest);
  81637. /*
  81638. ** chng_addr_0:
  81639. ** regPrev(0) = idx(0)
  81640. ** chng_addr_1:
  81641. ** regPrev(1) = idx(1)
  81642. ** ...
  81643. */
  81644. sqlite3VdbeJumpHere(v, addrNextRow-1);
  81645. for(i=0; i<nColTest; i++){
  81646. sqlite3VdbeJumpHere(v, aGotoChng[i]);
  81647. sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regPrev+i);
  81648. }
  81649. sqlite3VdbeResolveLabel(v, endDistinctTest);
  81650. sqlite3DbFree(db, aGotoChng);
  81651. }
  81652. /*
  81653. ** chng_addr_N:
  81654. ** regRowid = idx(rowid) // STAT34 only
  81655. ** stat_push(P, regChng, regRowid) // 3rd parameter STAT34 only
  81656. ** Next csr
  81657. ** if !eof(csr) goto next_row;
  81658. */
  81659. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  81660. assert( regRowid==(regStat4+2) );
  81661. if( HasRowid(pTab) ){
  81662. sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, regRowid);
  81663. }else{
  81664. Index *pPk = sqlite3PrimaryKeyIndex(pIdx->pTable);
  81665. int j, k, regKey;
  81666. regKey = sqlite3GetTempRange(pParse, pPk->nKeyCol);
  81667. for(j=0; j<pPk->nKeyCol; j++){
  81668. k = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[j]);
  81669. sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, k, regKey+j);
  81670. VdbeComment((v, "%s", pTab->aCol[pPk->aiColumn[j]].zName));
  81671. }
  81672. sqlite3VdbeAddOp3(v, OP_MakeRecord, regKey, pPk->nKeyCol, regRowid);
  81673. sqlite3ReleaseTempRange(pParse, regKey, pPk->nKeyCol);
  81674. }
  81675. #endif
  81676. assert( regChng==(regStat4+1) );
  81677. sqlite3VdbeAddOp3(v, OP_Function, 1, regStat4, regTemp);
  81678. sqlite3VdbeChangeP4(v, -1, (char*)&statPushFuncdef, P4_FUNCDEF);
  81679. sqlite3VdbeChangeP5(v, 2+IsStat34);
  81680. sqlite3VdbeAddOp2(v, OP_Next, iIdxCur, addrNextRow); VdbeCoverage(v);
  81681. /* Add the entry to the stat1 table. */
  81682. callStatGet(v, regStat4, STAT_GET_STAT1, regStat1);
  81683. assert( "BBB"[0]==SQLITE_AFF_TEXT );
  81684. sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regTemp, "BBB", 0);
  81685. sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid);
  81686. sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regTemp, regNewRowid);
  81687. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  81688. /* Add the entries to the stat3 or stat4 table. */
  81689. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  81690. {
  81691. int regEq = regStat1;
  81692. int regLt = regStat1+1;
  81693. int regDLt = regStat1+2;
  81694. int regSample = regStat1+3;
  81695. int regCol = regStat1+4;
  81696. int regSampleRowid = regCol + nCol;
  81697. int addrNext;
  81698. int addrIsNull;
  81699. u8 seekOp = HasRowid(pTab) ? OP_NotExists : OP_NotFound;
  81700. pParse->nMem = MAX(pParse->nMem, regCol+nCol);
  81701. addrNext = sqlite3VdbeCurrentAddr(v);
  81702. callStatGet(v, regStat4, STAT_GET_ROWID, regSampleRowid);
  81703. addrIsNull = sqlite3VdbeAddOp1(v, OP_IsNull, regSampleRowid);
  81704. VdbeCoverage(v);
  81705. callStatGet(v, regStat4, STAT_GET_NEQ, regEq);
  81706. callStatGet(v, regStat4, STAT_GET_NLT, regLt);
  81707. callStatGet(v, regStat4, STAT_GET_NDLT, regDLt);
  81708. sqlite3VdbeAddOp4Int(v, seekOp, iTabCur, addrNext, regSampleRowid, 0);
  81709. /* We know that the regSampleRowid row exists because it was read by
  81710. ** the previous loop. Thus the not-found jump of seekOp will never
  81711. ** be taken */
  81712. VdbeCoverageNeverTaken(v);
  81713. #ifdef SQLITE_ENABLE_STAT3
  81714. sqlite3ExprCodeGetColumnOfTable(v, pTab, iTabCur,
  81715. pIdx->aiColumn[0], regSample);
  81716. #else
  81717. for(i=0; i<nCol; i++){
  81718. i16 iCol = pIdx->aiColumn[i];
  81719. sqlite3ExprCodeGetColumnOfTable(v, pTab, iTabCur, iCol, regCol+i);
  81720. }
  81721. sqlite3VdbeAddOp3(v, OP_MakeRecord, regCol, nCol, regSample);
  81722. #endif
  81723. sqlite3VdbeAddOp3(v, OP_MakeRecord, regTabname, 6, regTemp);
  81724. sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur+1, regNewRowid);
  81725. sqlite3VdbeAddOp3(v, OP_Insert, iStatCur+1, regTemp, regNewRowid);
  81726. sqlite3VdbeAddOp2(v, OP_Goto, 1, addrNext); /* P1==1 for end-of-loop */
  81727. sqlite3VdbeJumpHere(v, addrIsNull);
  81728. }
  81729. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  81730. /* End of analysis */
  81731. sqlite3VdbeJumpHere(v, addrRewind);
  81732. }
  81733. /* Create a single sqlite_stat1 entry containing NULL as the index
  81734. ** name and the row count as the content.
  81735. */
  81736. if( pOnlyIdx==0 && needTableCnt ){
  81737. VdbeComment((v, "%s", pTab->zName));
  81738. sqlite3VdbeAddOp2(v, OP_Count, iTabCur, regStat1);
  81739. jZeroRows = sqlite3VdbeAddOp1(v, OP_IfNot, regStat1); VdbeCoverage(v);
  81740. sqlite3VdbeAddOp2(v, OP_Null, 0, regIdxname);
  81741. assert( "BBB"[0]==SQLITE_AFF_TEXT );
  81742. sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regTemp, "BBB", 0);
  81743. sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid);
  81744. sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regTemp, regNewRowid);
  81745. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  81746. sqlite3VdbeJumpHere(v, jZeroRows);
  81747. }
  81748. }
  81749. /*
  81750. ** Generate code that will cause the most recent index analysis to
  81751. ** be loaded into internal hash tables where is can be used.
  81752. */
  81753. static void loadAnalysis(Parse *pParse, int iDb){
  81754. Vdbe *v = sqlite3GetVdbe(pParse);
  81755. if( v ){
  81756. sqlite3VdbeAddOp1(v, OP_LoadAnalysis, iDb);
  81757. }
  81758. }
  81759. /*
  81760. ** Generate code that will do an analysis of an entire database
  81761. */
  81762. static void analyzeDatabase(Parse *pParse, int iDb){
  81763. sqlite3 *db = pParse->db;
  81764. Schema *pSchema = db->aDb[iDb].pSchema; /* Schema of database iDb */
  81765. HashElem *k;
  81766. int iStatCur;
  81767. int iMem;
  81768. int iTab;
  81769. sqlite3BeginWriteOperation(pParse, 0, iDb);
  81770. iStatCur = pParse->nTab;
  81771. pParse->nTab += 3;
  81772. openStatTable(pParse, iDb, iStatCur, 0, 0);
  81773. iMem = pParse->nMem+1;
  81774. iTab = pParse->nTab;
  81775. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  81776. for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){
  81777. Table *pTab = (Table*)sqliteHashData(k);
  81778. analyzeOneTable(pParse, pTab, 0, iStatCur, iMem, iTab);
  81779. }
  81780. loadAnalysis(pParse, iDb);
  81781. }
  81782. /*
  81783. ** Generate code that will do an analysis of a single table in
  81784. ** a database. If pOnlyIdx is not NULL then it is a single index
  81785. ** in pTab that should be analyzed.
  81786. */
  81787. static void analyzeTable(Parse *pParse, Table *pTab, Index *pOnlyIdx){
  81788. int iDb;
  81789. int iStatCur;
  81790. assert( pTab!=0 );
  81791. assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
  81792. iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  81793. sqlite3BeginWriteOperation(pParse, 0, iDb);
  81794. iStatCur = pParse->nTab;
  81795. pParse->nTab += 3;
  81796. if( pOnlyIdx ){
  81797. openStatTable(pParse, iDb, iStatCur, pOnlyIdx->zName, "idx");
  81798. }else{
  81799. openStatTable(pParse, iDb, iStatCur, pTab->zName, "tbl");
  81800. }
  81801. analyzeOneTable(pParse, pTab, pOnlyIdx, iStatCur,pParse->nMem+1,pParse->nTab);
  81802. loadAnalysis(pParse, iDb);
  81803. }
  81804. /*
  81805. ** Generate code for the ANALYZE command. The parser calls this routine
  81806. ** when it recognizes an ANALYZE command.
  81807. **
  81808. ** ANALYZE -- 1
  81809. ** ANALYZE <database> -- 2
  81810. ** ANALYZE ?<database>.?<tablename> -- 3
  81811. **
  81812. ** Form 1 causes all indices in all attached databases to be analyzed.
  81813. ** Form 2 analyzes all indices the single database named.
  81814. ** Form 3 analyzes all indices associated with the named table.
  81815. */
  81816. SQLITE_PRIVATE void sqlite3Analyze(Parse *pParse, Token *pName1, Token *pName2){
  81817. sqlite3 *db = pParse->db;
  81818. int iDb;
  81819. int i;
  81820. char *z, *zDb;
  81821. Table *pTab;
  81822. Index *pIdx;
  81823. Token *pTableName;
  81824. Vdbe *v;
  81825. /* Read the database schema. If an error occurs, leave an error message
  81826. ** and code in pParse and return NULL. */
  81827. assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
  81828. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  81829. return;
  81830. }
  81831. assert( pName2!=0 || pName1==0 );
  81832. if( pName1==0 ){
  81833. /* Form 1: Analyze everything */
  81834. for(i=0; i<db->nDb; i++){
  81835. if( i==1 ) continue; /* Do not analyze the TEMP database */
  81836. analyzeDatabase(pParse, i);
  81837. }
  81838. }else if( pName2->n==0 ){
  81839. /* Form 2: Analyze the database or table named */
  81840. iDb = sqlite3FindDb(db, pName1);
  81841. if( iDb>=0 ){
  81842. analyzeDatabase(pParse, iDb);
  81843. }else{
  81844. z = sqlite3NameFromToken(db, pName1);
  81845. if( z ){
  81846. if( (pIdx = sqlite3FindIndex(db, z, 0))!=0 ){
  81847. analyzeTable(pParse, pIdx->pTable, pIdx);
  81848. }else if( (pTab = sqlite3LocateTable(pParse, 0, z, 0))!=0 ){
  81849. analyzeTable(pParse, pTab, 0);
  81850. }
  81851. sqlite3DbFree(db, z);
  81852. }
  81853. }
  81854. }else{
  81855. /* Form 3: Analyze the fully qualified table name */
  81856. iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pTableName);
  81857. if( iDb>=0 ){
  81858. zDb = db->aDb[iDb].zName;
  81859. z = sqlite3NameFromToken(db, pTableName);
  81860. if( z ){
  81861. if( (pIdx = sqlite3FindIndex(db, z, zDb))!=0 ){
  81862. analyzeTable(pParse, pIdx->pTable, pIdx);
  81863. }else if( (pTab = sqlite3LocateTable(pParse, 0, z, zDb))!=0 ){
  81864. analyzeTable(pParse, pTab, 0);
  81865. }
  81866. sqlite3DbFree(db, z);
  81867. }
  81868. }
  81869. }
  81870. v = sqlite3GetVdbe(pParse);
  81871. if( v ) sqlite3VdbeAddOp0(v, OP_Expire);
  81872. }
  81873. /*
  81874. ** Used to pass information from the analyzer reader through to the
  81875. ** callback routine.
  81876. */
  81877. typedef struct analysisInfo analysisInfo;
  81878. struct analysisInfo {
  81879. sqlite3 *db;
  81880. const char *zDatabase;
  81881. };
  81882. /*
  81883. ** The first argument points to a nul-terminated string containing a
  81884. ** list of space separated integers. Read the first nOut of these into
  81885. ** the array aOut[].
  81886. */
  81887. static void decodeIntArray(
  81888. char *zIntArray, /* String containing int array to decode */
  81889. int nOut, /* Number of slots in aOut[] */
  81890. tRowcnt *aOut, /* Store integers here */
  81891. LogEst *aLog, /* Or, if aOut==0, here */
  81892. Index *pIndex /* Handle extra flags for this index, if not NULL */
  81893. ){
  81894. char *z = zIntArray;
  81895. int c;
  81896. int i;
  81897. tRowcnt v;
  81898. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  81899. if( z==0 ) z = "";
  81900. #else
  81901. assert( z!=0 );
  81902. #endif
  81903. for(i=0; *z && i<nOut; i++){
  81904. v = 0;
  81905. while( (c=z[0])>='0' && c<='9' ){
  81906. v = v*10 + c - '0';
  81907. z++;
  81908. }
  81909. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  81910. if( aOut ) aOut[i] = v;
  81911. if( aLog ) aLog[i] = sqlite3LogEst(v);
  81912. #else
  81913. assert( aOut==0 );
  81914. UNUSED_PARAMETER(aOut);
  81915. assert( aLog!=0 );
  81916. aLog[i] = sqlite3LogEst(v);
  81917. #endif
  81918. if( *z==' ' ) z++;
  81919. }
  81920. #ifndef SQLITE_ENABLE_STAT3_OR_STAT4
  81921. assert( pIndex!=0 );
  81922. #else
  81923. if( pIndex )
  81924. #endif
  81925. while( z[0] ){
  81926. if( sqlite3_strglob("unordered*", z)==0 ){
  81927. pIndex->bUnordered = 1;
  81928. }else if( sqlite3_strglob("sz=[0-9]*", z)==0 ){
  81929. pIndex->szIdxRow = sqlite3LogEst(sqlite3Atoi(z+3));
  81930. }
  81931. #ifdef SQLITE_ENABLE_COSTMULT
  81932. else if( sqlite3_strglob("costmult=[0-9]*",z)==0 ){
  81933. pIndex->pTable->costMult = sqlite3LogEst(sqlite3Atoi(z+9));
  81934. }
  81935. #endif
  81936. while( z[0]!=0 && z[0]!=' ' ) z++;
  81937. while( z[0]==' ' ) z++;
  81938. }
  81939. }
  81940. /*
  81941. ** This callback is invoked once for each index when reading the
  81942. ** sqlite_stat1 table.
  81943. **
  81944. ** argv[0] = name of the table
  81945. ** argv[1] = name of the index (might be NULL)
  81946. ** argv[2] = results of analysis - on integer for each column
  81947. **
  81948. ** Entries for which argv[1]==NULL simply record the number of rows in
  81949. ** the table.
  81950. */
  81951. static int analysisLoader(void *pData, int argc, char **argv, char **NotUsed){
  81952. analysisInfo *pInfo = (analysisInfo*)pData;
  81953. Index *pIndex;
  81954. Table *pTable;
  81955. const char *z;
  81956. assert( argc==3 );
  81957. UNUSED_PARAMETER2(NotUsed, argc);
  81958. if( argv==0 || argv[0]==0 || argv[2]==0 ){
  81959. return 0;
  81960. }
  81961. pTable = sqlite3FindTable(pInfo->db, argv[0], pInfo->zDatabase);
  81962. if( pTable==0 ){
  81963. return 0;
  81964. }
  81965. if( argv[1]==0 ){
  81966. pIndex = 0;
  81967. }else if( sqlite3_stricmp(argv[0],argv[1])==0 ){
  81968. pIndex = sqlite3PrimaryKeyIndex(pTable);
  81969. }else{
  81970. pIndex = sqlite3FindIndex(pInfo->db, argv[1], pInfo->zDatabase);
  81971. }
  81972. z = argv[2];
  81973. if( pIndex ){
  81974. int nCol = pIndex->nKeyCol+1;
  81975. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  81976. tRowcnt * const aiRowEst = pIndex->aiRowEst = (tRowcnt*)sqlite3MallocZero(
  81977. sizeof(tRowcnt) * nCol
  81978. );
  81979. if( aiRowEst==0 ) pInfo->db->mallocFailed = 1;
  81980. #else
  81981. tRowcnt * const aiRowEst = 0;
  81982. #endif
  81983. pIndex->bUnordered = 0;
  81984. decodeIntArray((char*)z, nCol, aiRowEst, pIndex->aiRowLogEst, pIndex);
  81985. if( pIndex->pPartIdxWhere==0 ) pTable->nRowLogEst = pIndex->aiRowLogEst[0];
  81986. }else{
  81987. Index fakeIdx;
  81988. fakeIdx.szIdxRow = pTable->szTabRow;
  81989. #ifdef SQLITE_ENABLE_COSTMULT
  81990. fakeIdx.pTable = pTable;
  81991. #endif
  81992. decodeIntArray((char*)z, 1, 0, &pTable->nRowLogEst, &fakeIdx);
  81993. pTable->szTabRow = fakeIdx.szIdxRow;
  81994. }
  81995. return 0;
  81996. }
  81997. /*
  81998. ** If the Index.aSample variable is not NULL, delete the aSample[] array
  81999. ** and its contents.
  82000. */
  82001. SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3 *db, Index *pIdx){
  82002. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  82003. if( pIdx->aSample ){
  82004. int j;
  82005. for(j=0; j<pIdx->nSample; j++){
  82006. IndexSample *p = &pIdx->aSample[j];
  82007. sqlite3DbFree(db, p->p);
  82008. }
  82009. sqlite3DbFree(db, pIdx->aSample);
  82010. }
  82011. if( db && db->pnBytesFreed==0 ){
  82012. pIdx->nSample = 0;
  82013. pIdx->aSample = 0;
  82014. }
  82015. #else
  82016. UNUSED_PARAMETER(db);
  82017. UNUSED_PARAMETER(pIdx);
  82018. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  82019. }
  82020. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  82021. /*
  82022. ** Populate the pIdx->aAvgEq[] array based on the samples currently
  82023. ** stored in pIdx->aSample[].
  82024. */
  82025. static void initAvgEq(Index *pIdx){
  82026. if( pIdx ){
  82027. IndexSample *aSample = pIdx->aSample;
  82028. IndexSample *pFinal = &aSample[pIdx->nSample-1];
  82029. int iCol;
  82030. int nCol = 1;
  82031. if( pIdx->nSampleCol>1 ){
  82032. /* If this is stat4 data, then calculate aAvgEq[] values for all
  82033. ** sample columns except the last. The last is always set to 1, as
  82034. ** once the trailing PK fields are considered all index keys are
  82035. ** unique. */
  82036. nCol = pIdx->nSampleCol-1;
  82037. pIdx->aAvgEq[nCol] = 1;
  82038. }
  82039. for(iCol=0; iCol<nCol; iCol++){
  82040. int nSample = pIdx->nSample;
  82041. int i; /* Used to iterate through samples */
  82042. tRowcnt sumEq = 0; /* Sum of the nEq values */
  82043. tRowcnt avgEq = 0;
  82044. tRowcnt nRow; /* Number of rows in index */
  82045. i64 nSum100 = 0; /* Number of terms contributing to sumEq */
  82046. i64 nDist100; /* Number of distinct values in index */
  82047. if( pIdx->aiRowEst==0 || pIdx->aiRowEst[iCol+1]==0 ){
  82048. nRow = pFinal->anLt[iCol];
  82049. nDist100 = (i64)100 * pFinal->anDLt[iCol];
  82050. nSample--;
  82051. }else{
  82052. nRow = pIdx->aiRowEst[0];
  82053. nDist100 = ((i64)100 * pIdx->aiRowEst[0]) / pIdx->aiRowEst[iCol+1];
  82054. }
  82055. pIdx->nRowEst0 = nRow;
  82056. /* Set nSum to the number of distinct (iCol+1) field prefixes that
  82057. ** occur in the stat4 table for this index. Set sumEq to the sum of
  82058. ** the nEq values for column iCol for the same set (adding the value
  82059. ** only once where there exist duplicate prefixes). */
  82060. for(i=0; i<nSample; i++){
  82061. if( i==(pIdx->nSample-1)
  82062. || aSample[i].anDLt[iCol]!=aSample[i+1].anDLt[iCol]
  82063. ){
  82064. sumEq += aSample[i].anEq[iCol];
  82065. nSum100 += 100;
  82066. }
  82067. }
  82068. if( nDist100>nSum100 ){
  82069. avgEq = ((i64)100 * (nRow - sumEq))/(nDist100 - nSum100);
  82070. }
  82071. if( avgEq==0 ) avgEq = 1;
  82072. pIdx->aAvgEq[iCol] = avgEq;
  82073. }
  82074. }
  82075. }
  82076. /*
  82077. ** Look up an index by name. Or, if the name of a WITHOUT ROWID table
  82078. ** is supplied instead, find the PRIMARY KEY index for that table.
  82079. */
  82080. static Index *findIndexOrPrimaryKey(
  82081. sqlite3 *db,
  82082. const char *zName,
  82083. const char *zDb
  82084. ){
  82085. Index *pIdx = sqlite3FindIndex(db, zName, zDb);
  82086. if( pIdx==0 ){
  82087. Table *pTab = sqlite3FindTable(db, zName, zDb);
  82088. if( pTab && !HasRowid(pTab) ) pIdx = sqlite3PrimaryKeyIndex(pTab);
  82089. }
  82090. return pIdx;
  82091. }
  82092. /*
  82093. ** Load the content from either the sqlite_stat4 or sqlite_stat3 table
  82094. ** into the relevant Index.aSample[] arrays.
  82095. **
  82096. ** Arguments zSql1 and zSql2 must point to SQL statements that return
  82097. ** data equivalent to the following (statements are different for stat3,
  82098. ** see the caller of this function for details):
  82099. **
  82100. ** zSql1: SELECT idx,count(*) FROM %Q.sqlite_stat4 GROUP BY idx
  82101. ** zSql2: SELECT idx,neq,nlt,ndlt,sample FROM %Q.sqlite_stat4
  82102. **
  82103. ** where %Q is replaced with the database name before the SQL is executed.
  82104. */
  82105. static int loadStatTbl(
  82106. sqlite3 *db, /* Database handle */
  82107. int bStat3, /* Assume single column records only */
  82108. const char *zSql1, /* SQL statement 1 (see above) */
  82109. const char *zSql2, /* SQL statement 2 (see above) */
  82110. const char *zDb /* Database name (e.g. "main") */
  82111. ){
  82112. int rc; /* Result codes from subroutines */
  82113. sqlite3_stmt *pStmt = 0; /* An SQL statement being run */
  82114. char *zSql; /* Text of the SQL statement */
  82115. Index *pPrevIdx = 0; /* Previous index in the loop */
  82116. IndexSample *pSample; /* A slot in pIdx->aSample[] */
  82117. assert( db->lookaside.bEnabled==0 );
  82118. zSql = sqlite3MPrintf(db, zSql1, zDb);
  82119. if( !zSql ){
  82120. return SQLITE_NOMEM;
  82121. }
  82122. rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
  82123. sqlite3DbFree(db, zSql);
  82124. if( rc ) return rc;
  82125. while( sqlite3_step(pStmt)==SQLITE_ROW ){
  82126. int nIdxCol = 1; /* Number of columns in stat4 records */
  82127. char *zIndex; /* Index name */
  82128. Index *pIdx; /* Pointer to the index object */
  82129. int nSample; /* Number of samples */
  82130. int nByte; /* Bytes of space required */
  82131. int i; /* Bytes of space required */
  82132. tRowcnt *pSpace;
  82133. zIndex = (char *)sqlite3_column_text(pStmt, 0);
  82134. if( zIndex==0 ) continue;
  82135. nSample = sqlite3_column_int(pStmt, 1);
  82136. pIdx = findIndexOrPrimaryKey(db, zIndex, zDb);
  82137. assert( pIdx==0 || bStat3 || pIdx->nSample==0 );
  82138. /* Index.nSample is non-zero at this point if data has already been
  82139. ** loaded from the stat4 table. In this case ignore stat3 data. */
  82140. if( pIdx==0 || pIdx->nSample ) continue;
  82141. if( bStat3==0 ){
  82142. assert( !HasRowid(pIdx->pTable) || pIdx->nColumn==pIdx->nKeyCol+1 );
  82143. if( !HasRowid(pIdx->pTable) && IsPrimaryKeyIndex(pIdx) ){
  82144. nIdxCol = pIdx->nKeyCol;
  82145. }else{
  82146. nIdxCol = pIdx->nColumn;
  82147. }
  82148. }
  82149. pIdx->nSampleCol = nIdxCol;
  82150. nByte = sizeof(IndexSample) * nSample;
  82151. nByte += sizeof(tRowcnt) * nIdxCol * 3 * nSample;
  82152. nByte += nIdxCol * sizeof(tRowcnt); /* Space for Index.aAvgEq[] */
  82153. pIdx->aSample = sqlite3DbMallocZero(db, nByte);
  82154. if( pIdx->aSample==0 ){
  82155. sqlite3_finalize(pStmt);
  82156. return SQLITE_NOMEM;
  82157. }
  82158. pSpace = (tRowcnt*)&pIdx->aSample[nSample];
  82159. pIdx->aAvgEq = pSpace; pSpace += nIdxCol;
  82160. for(i=0; i<nSample; i++){
  82161. pIdx->aSample[i].anEq = pSpace; pSpace += nIdxCol;
  82162. pIdx->aSample[i].anLt = pSpace; pSpace += nIdxCol;
  82163. pIdx->aSample[i].anDLt = pSpace; pSpace += nIdxCol;
  82164. }
  82165. assert( ((u8*)pSpace)-nByte==(u8*)(pIdx->aSample) );
  82166. }
  82167. rc = sqlite3_finalize(pStmt);
  82168. if( rc ) return rc;
  82169. zSql = sqlite3MPrintf(db, zSql2, zDb);
  82170. if( !zSql ){
  82171. return SQLITE_NOMEM;
  82172. }
  82173. rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
  82174. sqlite3DbFree(db, zSql);
  82175. if( rc ) return rc;
  82176. while( sqlite3_step(pStmt)==SQLITE_ROW ){
  82177. char *zIndex; /* Index name */
  82178. Index *pIdx; /* Pointer to the index object */
  82179. int nCol = 1; /* Number of columns in index */
  82180. zIndex = (char *)sqlite3_column_text(pStmt, 0);
  82181. if( zIndex==0 ) continue;
  82182. pIdx = findIndexOrPrimaryKey(db, zIndex, zDb);
  82183. if( pIdx==0 ) continue;
  82184. /* This next condition is true if data has already been loaded from
  82185. ** the sqlite_stat4 table. In this case ignore stat3 data. */
  82186. nCol = pIdx->nSampleCol;
  82187. if( bStat3 && nCol>1 ) continue;
  82188. if( pIdx!=pPrevIdx ){
  82189. initAvgEq(pPrevIdx);
  82190. pPrevIdx = pIdx;
  82191. }
  82192. pSample = &pIdx->aSample[pIdx->nSample];
  82193. decodeIntArray((char*)sqlite3_column_text(pStmt,1),nCol,pSample->anEq,0,0);
  82194. decodeIntArray((char*)sqlite3_column_text(pStmt,2),nCol,pSample->anLt,0,0);
  82195. decodeIntArray((char*)sqlite3_column_text(pStmt,3),nCol,pSample->anDLt,0,0);
  82196. /* Take a copy of the sample. Add two 0x00 bytes the end of the buffer.
  82197. ** This is in case the sample record is corrupted. In that case, the
  82198. ** sqlite3VdbeRecordCompare() may read up to two varints past the
  82199. ** end of the allocated buffer before it realizes it is dealing with
  82200. ** a corrupt record. Adding the two 0x00 bytes prevents this from causing
  82201. ** a buffer overread. */
  82202. pSample->n = sqlite3_column_bytes(pStmt, 4);
  82203. pSample->p = sqlite3DbMallocZero(db, pSample->n + 2);
  82204. if( pSample->p==0 ){
  82205. sqlite3_finalize(pStmt);
  82206. return SQLITE_NOMEM;
  82207. }
  82208. memcpy(pSample->p, sqlite3_column_blob(pStmt, 4), pSample->n);
  82209. pIdx->nSample++;
  82210. }
  82211. rc = sqlite3_finalize(pStmt);
  82212. if( rc==SQLITE_OK ) initAvgEq(pPrevIdx);
  82213. return rc;
  82214. }
  82215. /*
  82216. ** Load content from the sqlite_stat4 and sqlite_stat3 tables into
  82217. ** the Index.aSample[] arrays of all indices.
  82218. */
  82219. static int loadStat4(sqlite3 *db, const char *zDb){
  82220. int rc = SQLITE_OK; /* Result codes from subroutines */
  82221. assert( db->lookaside.bEnabled==0 );
  82222. if( sqlite3FindTable(db, "sqlite_stat4", zDb) ){
  82223. rc = loadStatTbl(db, 0,
  82224. "SELECT idx,count(*) FROM %Q.sqlite_stat4 GROUP BY idx",
  82225. "SELECT idx,neq,nlt,ndlt,sample FROM %Q.sqlite_stat4",
  82226. zDb
  82227. );
  82228. }
  82229. if( rc==SQLITE_OK && sqlite3FindTable(db, "sqlite_stat3", zDb) ){
  82230. rc = loadStatTbl(db, 1,
  82231. "SELECT idx,count(*) FROM %Q.sqlite_stat3 GROUP BY idx",
  82232. "SELECT idx,neq,nlt,ndlt,sqlite_record(sample) FROM %Q.sqlite_stat3",
  82233. zDb
  82234. );
  82235. }
  82236. return rc;
  82237. }
  82238. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  82239. /*
  82240. ** Load the content of the sqlite_stat1 and sqlite_stat3/4 tables. The
  82241. ** contents of sqlite_stat1 are used to populate the Index.aiRowEst[]
  82242. ** arrays. The contents of sqlite_stat3/4 are used to populate the
  82243. ** Index.aSample[] arrays.
  82244. **
  82245. ** If the sqlite_stat1 table is not present in the database, SQLITE_ERROR
  82246. ** is returned. In this case, even if SQLITE_ENABLE_STAT3/4 was defined
  82247. ** during compilation and the sqlite_stat3/4 table is present, no data is
  82248. ** read from it.
  82249. **
  82250. ** If SQLITE_ENABLE_STAT3/4 was defined during compilation and the
  82251. ** sqlite_stat4 table is not present in the database, SQLITE_ERROR is
  82252. ** returned. However, in this case, data is read from the sqlite_stat1
  82253. ** table (if it is present) before returning.
  82254. **
  82255. ** If an OOM error occurs, this function always sets db->mallocFailed.
  82256. ** This means if the caller does not care about other errors, the return
  82257. ** code may be ignored.
  82258. */
  82259. SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3 *db, int iDb){
  82260. analysisInfo sInfo;
  82261. HashElem *i;
  82262. char *zSql;
  82263. int rc;
  82264. assert( iDb>=0 && iDb<db->nDb );
  82265. assert( db->aDb[iDb].pBt!=0 );
  82266. /* Clear any prior statistics */
  82267. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  82268. for(i=sqliteHashFirst(&db->aDb[iDb].pSchema->idxHash);i;i=sqliteHashNext(i)){
  82269. Index *pIdx = sqliteHashData(i);
  82270. sqlite3DefaultRowEst(pIdx);
  82271. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  82272. sqlite3DeleteIndexSamples(db, pIdx);
  82273. pIdx->aSample = 0;
  82274. #endif
  82275. }
  82276. /* Check to make sure the sqlite_stat1 table exists */
  82277. sInfo.db = db;
  82278. sInfo.zDatabase = db->aDb[iDb].zName;
  82279. if( sqlite3FindTable(db, "sqlite_stat1", sInfo.zDatabase)==0 ){
  82280. return SQLITE_ERROR;
  82281. }
  82282. /* Load new statistics out of the sqlite_stat1 table */
  82283. zSql = sqlite3MPrintf(db,
  82284. "SELECT tbl,idx,stat FROM %Q.sqlite_stat1", sInfo.zDatabase);
  82285. if( zSql==0 ){
  82286. rc = SQLITE_NOMEM;
  82287. }else{
  82288. rc = sqlite3_exec(db, zSql, analysisLoader, &sInfo, 0);
  82289. sqlite3DbFree(db, zSql);
  82290. }
  82291. /* Load the statistics from the sqlite_stat4 table. */
  82292. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  82293. if( rc==SQLITE_OK && OptimizationEnabled(db, SQLITE_Stat34) ){
  82294. int lookasideEnabled = db->lookaside.bEnabled;
  82295. db->lookaside.bEnabled = 0;
  82296. rc = loadStat4(db, sInfo.zDatabase);
  82297. db->lookaside.bEnabled = lookasideEnabled;
  82298. }
  82299. for(i=sqliteHashFirst(&db->aDb[iDb].pSchema->idxHash);i;i=sqliteHashNext(i)){
  82300. Index *pIdx = sqliteHashData(i);
  82301. sqlite3_free(pIdx->aiRowEst);
  82302. pIdx->aiRowEst = 0;
  82303. }
  82304. #endif
  82305. if( rc==SQLITE_NOMEM ){
  82306. db->mallocFailed = 1;
  82307. }
  82308. return rc;
  82309. }
  82310. #endif /* SQLITE_OMIT_ANALYZE */
  82311. /************** End of analyze.c *********************************************/
  82312. /************** Begin file attach.c ******************************************/
  82313. /*
  82314. ** 2003 April 6
  82315. **
  82316. ** The author disclaims copyright to this source code. In place of
  82317. ** a legal notice, here is a blessing:
  82318. **
  82319. ** May you do good and not evil.
  82320. ** May you find forgiveness for yourself and forgive others.
  82321. ** May you share freely, never taking more than you give.
  82322. **
  82323. *************************************************************************
  82324. ** This file contains code used to implement the ATTACH and DETACH commands.
  82325. */
  82326. #ifndef SQLITE_OMIT_ATTACH
  82327. /*
  82328. ** Resolve an expression that was part of an ATTACH or DETACH statement. This
  82329. ** is slightly different from resolving a normal SQL expression, because simple
  82330. ** identifiers are treated as strings, not possible column names or aliases.
  82331. **
  82332. ** i.e. if the parser sees:
  82333. **
  82334. ** ATTACH DATABASE abc AS def
  82335. **
  82336. ** it treats the two expressions as literal strings 'abc' and 'def' instead of
  82337. ** looking for columns of the same name.
  82338. **
  82339. ** This only applies to the root node of pExpr, so the statement:
  82340. **
  82341. ** ATTACH DATABASE abc||def AS 'db2'
  82342. **
  82343. ** will fail because neither abc or def can be resolved.
  82344. */
  82345. static int resolveAttachExpr(NameContext *pName, Expr *pExpr)
  82346. {
  82347. int rc = SQLITE_OK;
  82348. if( pExpr ){
  82349. if( pExpr->op!=TK_ID ){
  82350. rc = sqlite3ResolveExprNames(pName, pExpr);
  82351. }else{
  82352. pExpr->op = TK_STRING;
  82353. }
  82354. }
  82355. return rc;
  82356. }
  82357. /*
  82358. ** An SQL user-function registered to do the work of an ATTACH statement. The
  82359. ** three arguments to the function come directly from an attach statement:
  82360. **
  82361. ** ATTACH DATABASE x AS y KEY z
  82362. **
  82363. ** SELECT sqlite_attach(x, y, z)
  82364. **
  82365. ** If the optional "KEY z" syntax is omitted, an SQL NULL is passed as the
  82366. ** third argument.
  82367. */
  82368. static void attachFunc(
  82369. sqlite3_context *context,
  82370. int NotUsed,
  82371. sqlite3_value **argv
  82372. ){
  82373. int i;
  82374. int rc = 0;
  82375. sqlite3 *db = sqlite3_context_db_handle(context);
  82376. const char *zName;
  82377. const char *zFile;
  82378. char *zPath = 0;
  82379. char *zErr = 0;
  82380. unsigned int flags;
  82381. Db *aNew;
  82382. char *zErrDyn = 0;
  82383. sqlite3_vfs *pVfs;
  82384. UNUSED_PARAMETER(NotUsed);
  82385. zFile = (const char *)sqlite3_value_text(argv[0]);
  82386. zName = (const char *)sqlite3_value_text(argv[1]);
  82387. if( zFile==0 ) zFile = "";
  82388. if( zName==0 ) zName = "";
  82389. /* Check for the following errors:
  82390. **
  82391. ** * Too many attached databases,
  82392. ** * Transaction currently open
  82393. ** * Specified database name already being used.
  82394. */
  82395. if( db->nDb>=db->aLimit[SQLITE_LIMIT_ATTACHED]+2 ){
  82396. zErrDyn = sqlite3MPrintf(db, "too many attached databases - max %d",
  82397. db->aLimit[SQLITE_LIMIT_ATTACHED]
  82398. );
  82399. goto attach_error;
  82400. }
  82401. if( !db->autoCommit ){
  82402. zErrDyn = sqlite3MPrintf(db, "cannot ATTACH database within transaction");
  82403. goto attach_error;
  82404. }
  82405. for(i=0; i<db->nDb; i++){
  82406. char *z = db->aDb[i].zName;
  82407. assert( z && zName );
  82408. if( sqlite3StrICmp(z, zName)==0 ){
  82409. zErrDyn = sqlite3MPrintf(db, "database %s is already in use", zName);
  82410. goto attach_error;
  82411. }
  82412. }
  82413. /* Allocate the new entry in the db->aDb[] array and initialize the schema
  82414. ** hash tables.
  82415. */
  82416. if( db->aDb==db->aDbStatic ){
  82417. aNew = sqlite3DbMallocRaw(db, sizeof(db->aDb[0])*3 );
  82418. if( aNew==0 ) return;
  82419. memcpy(aNew, db->aDb, sizeof(db->aDb[0])*2);
  82420. }else{
  82421. aNew = sqlite3DbRealloc(db, db->aDb, sizeof(db->aDb[0])*(db->nDb+1) );
  82422. if( aNew==0 ) return;
  82423. }
  82424. db->aDb = aNew;
  82425. aNew = &db->aDb[db->nDb];
  82426. memset(aNew, 0, sizeof(*aNew));
  82427. /* Open the database file. If the btree is successfully opened, use
  82428. ** it to obtain the database schema. At this point the schema may
  82429. ** or may not be initialized.
  82430. */
  82431. flags = db->openFlags;
  82432. rc = sqlite3ParseUri(db->pVfs->zName, zFile, &flags, &pVfs, &zPath, &zErr);
  82433. if( rc!=SQLITE_OK ){
  82434. if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
  82435. sqlite3_result_error(context, zErr, -1);
  82436. sqlite3_free(zErr);
  82437. return;
  82438. }
  82439. assert( pVfs );
  82440. flags |= SQLITE_OPEN_MAIN_DB;
  82441. rc = sqlite3BtreeOpen(pVfs, zPath, db, &aNew->pBt, 0, flags);
  82442. sqlite3_free( zPath );
  82443. db->nDb++;
  82444. if( rc==SQLITE_CONSTRAINT ){
  82445. rc = SQLITE_ERROR;
  82446. zErrDyn = sqlite3MPrintf(db, "database is already attached");
  82447. }else if( rc==SQLITE_OK ){
  82448. Pager *pPager;
  82449. aNew->pSchema = sqlite3SchemaGet(db, aNew->pBt);
  82450. if( !aNew->pSchema ){
  82451. rc = SQLITE_NOMEM;
  82452. }else if( aNew->pSchema->file_format && aNew->pSchema->enc!=ENC(db) ){
  82453. zErrDyn = sqlite3MPrintf(db,
  82454. "attached databases must use the same text encoding as main database");
  82455. rc = SQLITE_ERROR;
  82456. }
  82457. pPager = sqlite3BtreePager(aNew->pBt);
  82458. sqlite3PagerLockingMode(pPager, db->dfltLockMode);
  82459. sqlite3BtreeSecureDelete(aNew->pBt,
  82460. sqlite3BtreeSecureDelete(db->aDb[0].pBt,-1) );
  82461. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  82462. sqlite3BtreeSetPagerFlags(aNew->pBt, 3 | (db->flags & PAGER_FLAGS_MASK));
  82463. #endif
  82464. }
  82465. aNew->safety_level = 3;
  82466. aNew->zName = sqlite3DbStrDup(db, zName);
  82467. if( rc==SQLITE_OK && aNew->zName==0 ){
  82468. rc = SQLITE_NOMEM;
  82469. }
  82470. #ifdef SQLITE_HAS_CODEC
  82471. if( rc==SQLITE_OK ){
  82472. extern int sqlite3CodecAttach(sqlite3*, int, const void*, int);
  82473. extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
  82474. int nKey;
  82475. char *zKey;
  82476. int t = sqlite3_value_type(argv[2]);
  82477. switch( t ){
  82478. case SQLITE_INTEGER:
  82479. case SQLITE_FLOAT:
  82480. zErrDyn = sqlite3DbStrDup(db, "Invalid key value");
  82481. rc = SQLITE_ERROR;
  82482. break;
  82483. case SQLITE_TEXT:
  82484. case SQLITE_BLOB:
  82485. nKey = sqlite3_value_bytes(argv[2]);
  82486. zKey = (char *)sqlite3_value_blob(argv[2]);
  82487. rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
  82488. break;
  82489. case SQLITE_NULL:
  82490. /* No key specified. Use the key from the main database */
  82491. sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
  82492. if( nKey>0 || sqlite3BtreeGetReserve(db->aDb[0].pBt)>0 ){
  82493. rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
  82494. }
  82495. break;
  82496. }
  82497. }
  82498. #endif
  82499. /* If the file was opened successfully, read the schema for the new database.
  82500. ** If this fails, or if opening the file failed, then close the file and
  82501. ** remove the entry from the db->aDb[] array. i.e. put everything back the way
  82502. ** we found it.
  82503. */
  82504. if( rc==SQLITE_OK ){
  82505. sqlite3BtreeEnterAll(db);
  82506. rc = sqlite3Init(db, &zErrDyn);
  82507. sqlite3BtreeLeaveAll(db);
  82508. }
  82509. #ifdef SQLITE_USER_AUTHENTICATION
  82510. if( rc==SQLITE_OK ){
  82511. u8 newAuth = 0;
  82512. rc = sqlite3UserAuthCheckLogin(db, zName, &newAuth);
  82513. if( newAuth<db->auth.authLevel ){
  82514. rc = SQLITE_AUTH_USER;
  82515. }
  82516. }
  82517. #endif
  82518. if( rc ){
  82519. int iDb = db->nDb - 1;
  82520. assert( iDb>=2 );
  82521. if( db->aDb[iDb].pBt ){
  82522. sqlite3BtreeClose(db->aDb[iDb].pBt);
  82523. db->aDb[iDb].pBt = 0;
  82524. db->aDb[iDb].pSchema = 0;
  82525. }
  82526. sqlite3ResetAllSchemasOfConnection(db);
  82527. db->nDb = iDb;
  82528. if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
  82529. db->mallocFailed = 1;
  82530. sqlite3DbFree(db, zErrDyn);
  82531. zErrDyn = sqlite3MPrintf(db, "out of memory");
  82532. }else if( zErrDyn==0 ){
  82533. zErrDyn = sqlite3MPrintf(db, "unable to open database: %s", zFile);
  82534. }
  82535. goto attach_error;
  82536. }
  82537. return;
  82538. attach_error:
  82539. /* Return an error if we get here */
  82540. if( zErrDyn ){
  82541. sqlite3_result_error(context, zErrDyn, -1);
  82542. sqlite3DbFree(db, zErrDyn);
  82543. }
  82544. if( rc ) sqlite3_result_error_code(context, rc);
  82545. }
  82546. /*
  82547. ** An SQL user-function registered to do the work of an DETACH statement. The
  82548. ** three arguments to the function come directly from a detach statement:
  82549. **
  82550. ** DETACH DATABASE x
  82551. **
  82552. ** SELECT sqlite_detach(x)
  82553. */
  82554. static void detachFunc(
  82555. sqlite3_context *context,
  82556. int NotUsed,
  82557. sqlite3_value **argv
  82558. ){
  82559. const char *zName = (const char *)sqlite3_value_text(argv[0]);
  82560. sqlite3 *db = sqlite3_context_db_handle(context);
  82561. int i;
  82562. Db *pDb = 0;
  82563. char zErr[128];
  82564. UNUSED_PARAMETER(NotUsed);
  82565. if( zName==0 ) zName = "";
  82566. for(i=0; i<db->nDb; i++){
  82567. pDb = &db->aDb[i];
  82568. if( pDb->pBt==0 ) continue;
  82569. if( sqlite3StrICmp(pDb->zName, zName)==0 ) break;
  82570. }
  82571. if( i>=db->nDb ){
  82572. sqlite3_snprintf(sizeof(zErr),zErr, "no such database: %s", zName);
  82573. goto detach_error;
  82574. }
  82575. if( i<2 ){
  82576. sqlite3_snprintf(sizeof(zErr),zErr, "cannot detach database %s", zName);
  82577. goto detach_error;
  82578. }
  82579. if( !db->autoCommit ){
  82580. sqlite3_snprintf(sizeof(zErr), zErr,
  82581. "cannot DETACH database within transaction");
  82582. goto detach_error;
  82583. }
  82584. if( sqlite3BtreeIsInReadTrans(pDb->pBt) || sqlite3BtreeIsInBackup(pDb->pBt) ){
  82585. sqlite3_snprintf(sizeof(zErr),zErr, "database %s is locked", zName);
  82586. goto detach_error;
  82587. }
  82588. sqlite3BtreeClose(pDb->pBt);
  82589. pDb->pBt = 0;
  82590. pDb->pSchema = 0;
  82591. sqlite3ResetAllSchemasOfConnection(db);
  82592. return;
  82593. detach_error:
  82594. sqlite3_result_error(context, zErr, -1);
  82595. }
  82596. /*
  82597. ** This procedure generates VDBE code for a single invocation of either the
  82598. ** sqlite_detach() or sqlite_attach() SQL user functions.
  82599. */
  82600. static void codeAttach(
  82601. Parse *pParse, /* The parser context */
  82602. int type, /* Either SQLITE_ATTACH or SQLITE_DETACH */
  82603. FuncDef const *pFunc,/* FuncDef wrapper for detachFunc() or attachFunc() */
  82604. Expr *pAuthArg, /* Expression to pass to authorization callback */
  82605. Expr *pFilename, /* Name of database file */
  82606. Expr *pDbname, /* Name of the database to use internally */
  82607. Expr *pKey /* Database key for encryption extension */
  82608. ){
  82609. int rc;
  82610. NameContext sName;
  82611. Vdbe *v;
  82612. sqlite3* db = pParse->db;
  82613. int regArgs;
  82614. memset(&sName, 0, sizeof(NameContext));
  82615. sName.pParse = pParse;
  82616. if(
  82617. SQLITE_OK!=(rc = resolveAttachExpr(&sName, pFilename)) ||
  82618. SQLITE_OK!=(rc = resolveAttachExpr(&sName, pDbname)) ||
  82619. SQLITE_OK!=(rc = resolveAttachExpr(&sName, pKey))
  82620. ){
  82621. pParse->nErr++;
  82622. goto attach_end;
  82623. }
  82624. #ifndef SQLITE_OMIT_AUTHORIZATION
  82625. if( pAuthArg ){
  82626. char *zAuthArg;
  82627. if( pAuthArg->op==TK_STRING ){
  82628. zAuthArg = pAuthArg->u.zToken;
  82629. }else{
  82630. zAuthArg = 0;
  82631. }
  82632. rc = sqlite3AuthCheck(pParse, type, zAuthArg, 0, 0);
  82633. if(rc!=SQLITE_OK ){
  82634. goto attach_end;
  82635. }
  82636. }
  82637. #endif /* SQLITE_OMIT_AUTHORIZATION */
  82638. v = sqlite3GetVdbe(pParse);
  82639. regArgs = sqlite3GetTempRange(pParse, 4);
  82640. sqlite3ExprCode(pParse, pFilename, regArgs);
  82641. sqlite3ExprCode(pParse, pDbname, regArgs+1);
  82642. sqlite3ExprCode(pParse, pKey, regArgs+2);
  82643. assert( v || db->mallocFailed );
  82644. if( v ){
  82645. sqlite3VdbeAddOp3(v, OP_Function, 0, regArgs+3-pFunc->nArg, regArgs+3);
  82646. assert( pFunc->nArg==-1 || (pFunc->nArg&0xff)==pFunc->nArg );
  82647. sqlite3VdbeChangeP5(v, (u8)(pFunc->nArg));
  82648. sqlite3VdbeChangeP4(v, -1, (char *)pFunc, P4_FUNCDEF);
  82649. /* Code an OP_Expire. For an ATTACH statement, set P1 to true (expire this
  82650. ** statement only). For DETACH, set it to false (expire all existing
  82651. ** statements).
  82652. */
  82653. sqlite3VdbeAddOp1(v, OP_Expire, (type==SQLITE_ATTACH));
  82654. }
  82655. attach_end:
  82656. sqlite3ExprDelete(db, pFilename);
  82657. sqlite3ExprDelete(db, pDbname);
  82658. sqlite3ExprDelete(db, pKey);
  82659. }
  82660. /*
  82661. ** Called by the parser to compile a DETACH statement.
  82662. **
  82663. ** DETACH pDbname
  82664. */
  82665. SQLITE_PRIVATE void sqlite3Detach(Parse *pParse, Expr *pDbname){
  82666. static const FuncDef detach_func = {
  82667. 1, /* nArg */
  82668. SQLITE_UTF8, /* funcFlags */
  82669. 0, /* pUserData */
  82670. 0, /* pNext */
  82671. detachFunc, /* xFunc */
  82672. 0, /* xStep */
  82673. 0, /* xFinalize */
  82674. "sqlite_detach", /* zName */
  82675. 0, /* pHash */
  82676. 0 /* pDestructor */
  82677. };
  82678. codeAttach(pParse, SQLITE_DETACH, &detach_func, pDbname, 0, 0, pDbname);
  82679. }
  82680. /*
  82681. ** Called by the parser to compile an ATTACH statement.
  82682. **
  82683. ** ATTACH p AS pDbname KEY pKey
  82684. */
  82685. SQLITE_PRIVATE void sqlite3Attach(Parse *pParse, Expr *p, Expr *pDbname, Expr *pKey){
  82686. static const FuncDef attach_func = {
  82687. 3, /* nArg */
  82688. SQLITE_UTF8, /* funcFlags */
  82689. 0, /* pUserData */
  82690. 0, /* pNext */
  82691. attachFunc, /* xFunc */
  82692. 0, /* xStep */
  82693. 0, /* xFinalize */
  82694. "sqlite_attach", /* zName */
  82695. 0, /* pHash */
  82696. 0 /* pDestructor */
  82697. };
  82698. codeAttach(pParse, SQLITE_ATTACH, &attach_func, p, p, pDbname, pKey);
  82699. }
  82700. #endif /* SQLITE_OMIT_ATTACH */
  82701. /*
  82702. ** Initialize a DbFixer structure. This routine must be called prior
  82703. ** to passing the structure to one of the sqliteFixAAAA() routines below.
  82704. */
  82705. SQLITE_PRIVATE void sqlite3FixInit(
  82706. DbFixer *pFix, /* The fixer to be initialized */
  82707. Parse *pParse, /* Error messages will be written here */
  82708. int iDb, /* This is the database that must be used */
  82709. const char *zType, /* "view", "trigger", or "index" */
  82710. const Token *pName /* Name of the view, trigger, or index */
  82711. ){
  82712. sqlite3 *db;
  82713. db = pParse->db;
  82714. assert( db->nDb>iDb );
  82715. pFix->pParse = pParse;
  82716. pFix->zDb = db->aDb[iDb].zName;
  82717. pFix->pSchema = db->aDb[iDb].pSchema;
  82718. pFix->zType = zType;
  82719. pFix->pName = pName;
  82720. pFix->bVarOnly = (iDb==1);
  82721. }
  82722. /*
  82723. ** The following set of routines walk through the parse tree and assign
  82724. ** a specific database to all table references where the database name
  82725. ** was left unspecified in the original SQL statement. The pFix structure
  82726. ** must have been initialized by a prior call to sqlite3FixInit().
  82727. **
  82728. ** These routines are used to make sure that an index, trigger, or
  82729. ** view in one database does not refer to objects in a different database.
  82730. ** (Exception: indices, triggers, and views in the TEMP database are
  82731. ** allowed to refer to anything.) If a reference is explicitly made
  82732. ** to an object in a different database, an error message is added to
  82733. ** pParse->zErrMsg and these routines return non-zero. If everything
  82734. ** checks out, these routines return 0.
  82735. */
  82736. SQLITE_PRIVATE int sqlite3FixSrcList(
  82737. DbFixer *pFix, /* Context of the fixation */
  82738. SrcList *pList /* The Source list to check and modify */
  82739. ){
  82740. int i;
  82741. const char *zDb;
  82742. struct SrcList_item *pItem;
  82743. if( NEVER(pList==0) ) return 0;
  82744. zDb = pFix->zDb;
  82745. for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
  82746. if( pFix->bVarOnly==0 ){
  82747. if( pItem->zDatabase && sqlite3StrICmp(pItem->zDatabase, zDb) ){
  82748. sqlite3ErrorMsg(pFix->pParse,
  82749. "%s %T cannot reference objects in database %s",
  82750. pFix->zType, pFix->pName, pItem->zDatabase);
  82751. return 1;
  82752. }
  82753. sqlite3DbFree(pFix->pParse->db, pItem->zDatabase);
  82754. pItem->zDatabase = 0;
  82755. pItem->pSchema = pFix->pSchema;
  82756. }
  82757. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
  82758. if( sqlite3FixSelect(pFix, pItem->pSelect) ) return 1;
  82759. if( sqlite3FixExpr(pFix, pItem->pOn) ) return 1;
  82760. #endif
  82761. }
  82762. return 0;
  82763. }
  82764. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
  82765. SQLITE_PRIVATE int sqlite3FixSelect(
  82766. DbFixer *pFix, /* Context of the fixation */
  82767. Select *pSelect /* The SELECT statement to be fixed to one database */
  82768. ){
  82769. while( pSelect ){
  82770. if( sqlite3FixExprList(pFix, pSelect->pEList) ){
  82771. return 1;
  82772. }
  82773. if( sqlite3FixSrcList(pFix, pSelect->pSrc) ){
  82774. return 1;
  82775. }
  82776. if( sqlite3FixExpr(pFix, pSelect->pWhere) ){
  82777. return 1;
  82778. }
  82779. if( sqlite3FixExprList(pFix, pSelect->pGroupBy) ){
  82780. return 1;
  82781. }
  82782. if( sqlite3FixExpr(pFix, pSelect->pHaving) ){
  82783. return 1;
  82784. }
  82785. if( sqlite3FixExprList(pFix, pSelect->pOrderBy) ){
  82786. return 1;
  82787. }
  82788. if( sqlite3FixExpr(pFix, pSelect->pLimit) ){
  82789. return 1;
  82790. }
  82791. if( sqlite3FixExpr(pFix, pSelect->pOffset) ){
  82792. return 1;
  82793. }
  82794. pSelect = pSelect->pPrior;
  82795. }
  82796. return 0;
  82797. }
  82798. SQLITE_PRIVATE int sqlite3FixExpr(
  82799. DbFixer *pFix, /* Context of the fixation */
  82800. Expr *pExpr /* The expression to be fixed to one database */
  82801. ){
  82802. while( pExpr ){
  82803. if( pExpr->op==TK_VARIABLE ){
  82804. if( pFix->pParse->db->init.busy ){
  82805. pExpr->op = TK_NULL;
  82806. }else{
  82807. sqlite3ErrorMsg(pFix->pParse, "%s cannot use variables", pFix->zType);
  82808. return 1;
  82809. }
  82810. }
  82811. if( ExprHasProperty(pExpr, EP_TokenOnly) ) break;
  82812. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  82813. if( sqlite3FixSelect(pFix, pExpr->x.pSelect) ) return 1;
  82814. }else{
  82815. if( sqlite3FixExprList(pFix, pExpr->x.pList) ) return 1;
  82816. }
  82817. if( sqlite3FixExpr(pFix, pExpr->pRight) ){
  82818. return 1;
  82819. }
  82820. pExpr = pExpr->pLeft;
  82821. }
  82822. return 0;
  82823. }
  82824. SQLITE_PRIVATE int sqlite3FixExprList(
  82825. DbFixer *pFix, /* Context of the fixation */
  82826. ExprList *pList /* The expression to be fixed to one database */
  82827. ){
  82828. int i;
  82829. struct ExprList_item *pItem;
  82830. if( pList==0 ) return 0;
  82831. for(i=0, pItem=pList->a; i<pList->nExpr; i++, pItem++){
  82832. if( sqlite3FixExpr(pFix, pItem->pExpr) ){
  82833. return 1;
  82834. }
  82835. }
  82836. return 0;
  82837. }
  82838. #endif
  82839. #ifndef SQLITE_OMIT_TRIGGER
  82840. SQLITE_PRIVATE int sqlite3FixTriggerStep(
  82841. DbFixer *pFix, /* Context of the fixation */
  82842. TriggerStep *pStep /* The trigger step be fixed to one database */
  82843. ){
  82844. while( pStep ){
  82845. if( sqlite3FixSelect(pFix, pStep->pSelect) ){
  82846. return 1;
  82847. }
  82848. if( sqlite3FixExpr(pFix, pStep->pWhere) ){
  82849. return 1;
  82850. }
  82851. if( sqlite3FixExprList(pFix, pStep->pExprList) ){
  82852. return 1;
  82853. }
  82854. pStep = pStep->pNext;
  82855. }
  82856. return 0;
  82857. }
  82858. #endif
  82859. /************** End of attach.c **********************************************/
  82860. /************** Begin file auth.c ********************************************/
  82861. /*
  82862. ** 2003 January 11
  82863. **
  82864. ** The author disclaims copyright to this source code. In place of
  82865. ** a legal notice, here is a blessing:
  82866. **
  82867. ** May you do good and not evil.
  82868. ** May you find forgiveness for yourself and forgive others.
  82869. ** May you share freely, never taking more than you give.
  82870. **
  82871. *************************************************************************
  82872. ** This file contains code used to implement the sqlite3_set_authorizer()
  82873. ** API. This facility is an optional feature of the library. Embedded
  82874. ** systems that do not need this facility may omit it by recompiling
  82875. ** the library with -DSQLITE_OMIT_AUTHORIZATION=1
  82876. */
  82877. /*
  82878. ** All of the code in this file may be omitted by defining a single
  82879. ** macro.
  82880. */
  82881. #ifndef SQLITE_OMIT_AUTHORIZATION
  82882. /*
  82883. ** Set or clear the access authorization function.
  82884. **
  82885. ** The access authorization function is be called during the compilation
  82886. ** phase to verify that the user has read and/or write access permission on
  82887. ** various fields of the database. The first argument to the auth function
  82888. ** is a copy of the 3rd argument to this routine. The second argument
  82889. ** to the auth function is one of these constants:
  82890. **
  82891. ** SQLITE_CREATE_INDEX
  82892. ** SQLITE_CREATE_TABLE
  82893. ** SQLITE_CREATE_TEMP_INDEX
  82894. ** SQLITE_CREATE_TEMP_TABLE
  82895. ** SQLITE_CREATE_TEMP_TRIGGER
  82896. ** SQLITE_CREATE_TEMP_VIEW
  82897. ** SQLITE_CREATE_TRIGGER
  82898. ** SQLITE_CREATE_VIEW
  82899. ** SQLITE_DELETE
  82900. ** SQLITE_DROP_INDEX
  82901. ** SQLITE_DROP_TABLE
  82902. ** SQLITE_DROP_TEMP_INDEX
  82903. ** SQLITE_DROP_TEMP_TABLE
  82904. ** SQLITE_DROP_TEMP_TRIGGER
  82905. ** SQLITE_DROP_TEMP_VIEW
  82906. ** SQLITE_DROP_TRIGGER
  82907. ** SQLITE_DROP_VIEW
  82908. ** SQLITE_INSERT
  82909. ** SQLITE_PRAGMA
  82910. ** SQLITE_READ
  82911. ** SQLITE_SELECT
  82912. ** SQLITE_TRANSACTION
  82913. ** SQLITE_UPDATE
  82914. **
  82915. ** The third and fourth arguments to the auth function are the name of
  82916. ** the table and the column that are being accessed. The auth function
  82917. ** should return either SQLITE_OK, SQLITE_DENY, or SQLITE_IGNORE. If
  82918. ** SQLITE_OK is returned, it means that access is allowed. SQLITE_DENY
  82919. ** means that the SQL statement will never-run - the sqlite3_exec() call
  82920. ** will return with an error. SQLITE_IGNORE means that the SQL statement
  82921. ** should run but attempts to read the specified column will return NULL
  82922. ** and attempts to write the column will be ignored.
  82923. **
  82924. ** Setting the auth function to NULL disables this hook. The default
  82925. ** setting of the auth function is NULL.
  82926. */
  82927. SQLITE_API int sqlite3_set_authorizer(
  82928. sqlite3 *db,
  82929. int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
  82930. void *pArg
  82931. ){
  82932. #ifdef SQLITE_ENABLE_API_ARMOR
  82933. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  82934. #endif
  82935. sqlite3_mutex_enter(db->mutex);
  82936. db->xAuth = (sqlite3_xauth)xAuth;
  82937. db->pAuthArg = pArg;
  82938. sqlite3ExpirePreparedStatements(db);
  82939. sqlite3_mutex_leave(db->mutex);
  82940. return SQLITE_OK;
  82941. }
  82942. /*
  82943. ** Write an error message into pParse->zErrMsg that explains that the
  82944. ** user-supplied authorization function returned an illegal value.
  82945. */
  82946. static void sqliteAuthBadReturnCode(Parse *pParse){
  82947. sqlite3ErrorMsg(pParse, "authorizer malfunction");
  82948. pParse->rc = SQLITE_ERROR;
  82949. }
  82950. /*
  82951. ** Invoke the authorization callback for permission to read column zCol from
  82952. ** table zTab in database zDb. This function assumes that an authorization
  82953. ** callback has been registered (i.e. that sqlite3.xAuth is not NULL).
  82954. **
  82955. ** If SQLITE_IGNORE is returned and pExpr is not NULL, then pExpr is changed
  82956. ** to an SQL NULL expression. Otherwise, if pExpr is NULL, then SQLITE_IGNORE
  82957. ** is treated as SQLITE_DENY. In this case an error is left in pParse.
  82958. */
  82959. SQLITE_PRIVATE int sqlite3AuthReadCol(
  82960. Parse *pParse, /* The parser context */
  82961. const char *zTab, /* Table name */
  82962. const char *zCol, /* Column name */
  82963. int iDb /* Index of containing database. */
  82964. ){
  82965. sqlite3 *db = pParse->db; /* Database handle */
  82966. char *zDb = db->aDb[iDb].zName; /* Name of attached database */
  82967. int rc; /* Auth callback return code */
  82968. rc = db->xAuth(db->pAuthArg, SQLITE_READ, zTab,zCol,zDb,pParse->zAuthContext
  82969. #ifdef SQLITE_USER_AUTHENTICATION
  82970. ,db->auth.zAuthUser
  82971. #endif
  82972. );
  82973. if( rc==SQLITE_DENY ){
  82974. if( db->nDb>2 || iDb!=0 ){
  82975. sqlite3ErrorMsg(pParse, "access to %s.%s.%s is prohibited",zDb,zTab,zCol);
  82976. }else{
  82977. sqlite3ErrorMsg(pParse, "access to %s.%s is prohibited", zTab, zCol);
  82978. }
  82979. pParse->rc = SQLITE_AUTH;
  82980. }else if( rc!=SQLITE_IGNORE && rc!=SQLITE_OK ){
  82981. sqliteAuthBadReturnCode(pParse);
  82982. }
  82983. return rc;
  82984. }
  82985. /*
  82986. ** The pExpr should be a TK_COLUMN expression. The table referred to
  82987. ** is in pTabList or else it is the NEW or OLD table of a trigger.
  82988. ** Check to see if it is OK to read this particular column.
  82989. **
  82990. ** If the auth function returns SQLITE_IGNORE, change the TK_COLUMN
  82991. ** instruction into a TK_NULL. If the auth function returns SQLITE_DENY,
  82992. ** then generate an error.
  82993. */
  82994. SQLITE_PRIVATE void sqlite3AuthRead(
  82995. Parse *pParse, /* The parser context */
  82996. Expr *pExpr, /* The expression to check authorization on */
  82997. Schema *pSchema, /* The schema of the expression */
  82998. SrcList *pTabList /* All table that pExpr might refer to */
  82999. ){
  83000. sqlite3 *db = pParse->db;
  83001. Table *pTab = 0; /* The table being read */
  83002. const char *zCol; /* Name of the column of the table */
  83003. int iSrc; /* Index in pTabList->a[] of table being read */
  83004. int iDb; /* The index of the database the expression refers to */
  83005. int iCol; /* Index of column in table */
  83006. if( db->xAuth==0 ) return;
  83007. iDb = sqlite3SchemaToIndex(pParse->db, pSchema);
  83008. if( iDb<0 ){
  83009. /* An attempt to read a column out of a subquery or other
  83010. ** temporary table. */
  83011. return;
  83012. }
  83013. assert( pExpr->op==TK_COLUMN || pExpr->op==TK_TRIGGER );
  83014. if( pExpr->op==TK_TRIGGER ){
  83015. pTab = pParse->pTriggerTab;
  83016. }else{
  83017. assert( pTabList );
  83018. for(iSrc=0; ALWAYS(iSrc<pTabList->nSrc); iSrc++){
  83019. if( pExpr->iTable==pTabList->a[iSrc].iCursor ){
  83020. pTab = pTabList->a[iSrc].pTab;
  83021. break;
  83022. }
  83023. }
  83024. }
  83025. iCol = pExpr->iColumn;
  83026. if( NEVER(pTab==0) ) return;
  83027. if( iCol>=0 ){
  83028. assert( iCol<pTab->nCol );
  83029. zCol = pTab->aCol[iCol].zName;
  83030. }else if( pTab->iPKey>=0 ){
  83031. assert( pTab->iPKey<pTab->nCol );
  83032. zCol = pTab->aCol[pTab->iPKey].zName;
  83033. }else{
  83034. zCol = "ROWID";
  83035. }
  83036. assert( iDb>=0 && iDb<db->nDb );
  83037. if( SQLITE_IGNORE==sqlite3AuthReadCol(pParse, pTab->zName, zCol, iDb) ){
  83038. pExpr->op = TK_NULL;
  83039. }
  83040. }
  83041. /*
  83042. ** Do an authorization check using the code and arguments given. Return
  83043. ** either SQLITE_OK (zero) or SQLITE_IGNORE or SQLITE_DENY. If SQLITE_DENY
  83044. ** is returned, then the error count and error message in pParse are
  83045. ** modified appropriately.
  83046. */
  83047. SQLITE_PRIVATE int sqlite3AuthCheck(
  83048. Parse *pParse,
  83049. int code,
  83050. const char *zArg1,
  83051. const char *zArg2,
  83052. const char *zArg3
  83053. ){
  83054. sqlite3 *db = pParse->db;
  83055. int rc;
  83056. /* Don't do any authorization checks if the database is initialising
  83057. ** or if the parser is being invoked from within sqlite3_declare_vtab.
  83058. */
  83059. if( db->init.busy || IN_DECLARE_VTAB ){
  83060. return SQLITE_OK;
  83061. }
  83062. if( db->xAuth==0 ){
  83063. return SQLITE_OK;
  83064. }
  83065. rc = db->xAuth(db->pAuthArg, code, zArg1, zArg2, zArg3, pParse->zAuthContext
  83066. #ifdef SQLITE_USER_AUTHENTICATION
  83067. ,db->auth.zAuthUser
  83068. #endif
  83069. );
  83070. if( rc==SQLITE_DENY ){
  83071. sqlite3ErrorMsg(pParse, "not authorized");
  83072. pParse->rc = SQLITE_AUTH;
  83073. }else if( rc!=SQLITE_OK && rc!=SQLITE_IGNORE ){
  83074. rc = SQLITE_DENY;
  83075. sqliteAuthBadReturnCode(pParse);
  83076. }
  83077. return rc;
  83078. }
  83079. /*
  83080. ** Push an authorization context. After this routine is called, the
  83081. ** zArg3 argument to authorization callbacks will be zContext until
  83082. ** popped. Or if pParse==0, this routine is a no-op.
  83083. */
  83084. SQLITE_PRIVATE void sqlite3AuthContextPush(
  83085. Parse *pParse,
  83086. AuthContext *pContext,
  83087. const char *zContext
  83088. ){
  83089. assert( pParse );
  83090. pContext->pParse = pParse;
  83091. pContext->zAuthContext = pParse->zAuthContext;
  83092. pParse->zAuthContext = zContext;
  83093. }
  83094. /*
  83095. ** Pop an authorization context that was previously pushed
  83096. ** by sqlite3AuthContextPush
  83097. */
  83098. SQLITE_PRIVATE void sqlite3AuthContextPop(AuthContext *pContext){
  83099. if( pContext->pParse ){
  83100. pContext->pParse->zAuthContext = pContext->zAuthContext;
  83101. pContext->pParse = 0;
  83102. }
  83103. }
  83104. #endif /* SQLITE_OMIT_AUTHORIZATION */
  83105. /************** End of auth.c ************************************************/
  83106. /************** Begin file build.c *******************************************/
  83107. /*
  83108. ** 2001 September 15
  83109. **
  83110. ** The author disclaims copyright to this source code. In place of
  83111. ** a legal notice, here is a blessing:
  83112. **
  83113. ** May you do good and not evil.
  83114. ** May you find forgiveness for yourself and forgive others.
  83115. ** May you share freely, never taking more than you give.
  83116. **
  83117. *************************************************************************
  83118. ** This file contains C code routines that are called by the SQLite parser
  83119. ** when syntax rules are reduced. The routines in this file handle the
  83120. ** following kinds of SQL syntax:
  83121. **
  83122. ** CREATE TABLE
  83123. ** DROP TABLE
  83124. ** CREATE INDEX
  83125. ** DROP INDEX
  83126. ** creating ID lists
  83127. ** BEGIN TRANSACTION
  83128. ** COMMIT
  83129. ** ROLLBACK
  83130. */
  83131. /*
  83132. ** This routine is called when a new SQL statement is beginning to
  83133. ** be parsed. Initialize the pParse structure as needed.
  83134. */
  83135. SQLITE_PRIVATE void sqlite3BeginParse(Parse *pParse, int explainFlag){
  83136. pParse->explain = (u8)explainFlag;
  83137. pParse->nVar = 0;
  83138. }
  83139. #ifndef SQLITE_OMIT_SHARED_CACHE
  83140. /*
  83141. ** The TableLock structure is only used by the sqlite3TableLock() and
  83142. ** codeTableLocks() functions.
  83143. */
  83144. struct TableLock {
  83145. int iDb; /* The database containing the table to be locked */
  83146. int iTab; /* The root page of the table to be locked */
  83147. u8 isWriteLock; /* True for write lock. False for a read lock */
  83148. const char *zName; /* Name of the table */
  83149. };
  83150. /*
  83151. ** Record the fact that we want to lock a table at run-time.
  83152. **
  83153. ** The table to be locked has root page iTab and is found in database iDb.
  83154. ** A read or a write lock can be taken depending on isWritelock.
  83155. **
  83156. ** This routine just records the fact that the lock is desired. The
  83157. ** code to make the lock occur is generated by a later call to
  83158. ** codeTableLocks() which occurs during sqlite3FinishCoding().
  83159. */
  83160. SQLITE_PRIVATE void sqlite3TableLock(
  83161. Parse *pParse, /* Parsing context */
  83162. int iDb, /* Index of the database containing the table to lock */
  83163. int iTab, /* Root page number of the table to be locked */
  83164. u8 isWriteLock, /* True for a write lock */
  83165. const char *zName /* Name of the table to be locked */
  83166. ){
  83167. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  83168. int i;
  83169. int nBytes;
  83170. TableLock *p;
  83171. assert( iDb>=0 );
  83172. for(i=0; i<pToplevel->nTableLock; i++){
  83173. p = &pToplevel->aTableLock[i];
  83174. if( p->iDb==iDb && p->iTab==iTab ){
  83175. p->isWriteLock = (p->isWriteLock || isWriteLock);
  83176. return;
  83177. }
  83178. }
  83179. nBytes = sizeof(TableLock) * (pToplevel->nTableLock+1);
  83180. pToplevel->aTableLock =
  83181. sqlite3DbReallocOrFree(pToplevel->db, pToplevel->aTableLock, nBytes);
  83182. if( pToplevel->aTableLock ){
  83183. p = &pToplevel->aTableLock[pToplevel->nTableLock++];
  83184. p->iDb = iDb;
  83185. p->iTab = iTab;
  83186. p->isWriteLock = isWriteLock;
  83187. p->zName = zName;
  83188. }else{
  83189. pToplevel->nTableLock = 0;
  83190. pToplevel->db->mallocFailed = 1;
  83191. }
  83192. }
  83193. /*
  83194. ** Code an OP_TableLock instruction for each table locked by the
  83195. ** statement (configured by calls to sqlite3TableLock()).
  83196. */
  83197. static void codeTableLocks(Parse *pParse){
  83198. int i;
  83199. Vdbe *pVdbe;
  83200. pVdbe = sqlite3GetVdbe(pParse);
  83201. assert( pVdbe!=0 ); /* sqlite3GetVdbe cannot fail: VDBE already allocated */
  83202. for(i=0; i<pParse->nTableLock; i++){
  83203. TableLock *p = &pParse->aTableLock[i];
  83204. int p1 = p->iDb;
  83205. sqlite3VdbeAddOp4(pVdbe, OP_TableLock, p1, p->iTab, p->isWriteLock,
  83206. p->zName, P4_STATIC);
  83207. }
  83208. }
  83209. #else
  83210. #define codeTableLocks(x)
  83211. #endif
  83212. /*
  83213. ** Return TRUE if the given yDbMask object is empty - if it contains no
  83214. ** 1 bits. This routine is used by the DbMaskAllZero() and DbMaskNotZero()
  83215. ** macros when SQLITE_MAX_ATTACHED is greater than 30.
  83216. */
  83217. #if SQLITE_MAX_ATTACHED>30
  83218. SQLITE_PRIVATE int sqlite3DbMaskAllZero(yDbMask m){
  83219. int i;
  83220. for(i=0; i<sizeof(yDbMask); i++) if( m[i] ) return 0;
  83221. return 1;
  83222. }
  83223. #endif
  83224. /*
  83225. ** This routine is called after a single SQL statement has been
  83226. ** parsed and a VDBE program to execute that statement has been
  83227. ** prepared. This routine puts the finishing touches on the
  83228. ** VDBE program and resets the pParse structure for the next
  83229. ** parse.
  83230. **
  83231. ** Note that if an error occurred, it might be the case that
  83232. ** no VDBE code was generated.
  83233. */
  83234. SQLITE_PRIVATE void sqlite3FinishCoding(Parse *pParse){
  83235. sqlite3 *db;
  83236. Vdbe *v;
  83237. assert( pParse->pToplevel==0 );
  83238. db = pParse->db;
  83239. if( db->mallocFailed ) return;
  83240. if( pParse->nested ) return;
  83241. if( pParse->nErr ) return;
  83242. /* Begin by generating some termination code at the end of the
  83243. ** vdbe program
  83244. */
  83245. v = sqlite3GetVdbe(pParse);
  83246. assert( !pParse->isMultiWrite
  83247. || sqlite3VdbeAssertMayAbort(v, pParse->mayAbort));
  83248. if( v ){
  83249. while( sqlite3VdbeDeletePriorOpcode(v, OP_Close) ){}
  83250. sqlite3VdbeAddOp0(v, OP_Halt);
  83251. #if SQLITE_USER_AUTHENTICATION
  83252. if( pParse->nTableLock>0 && db->init.busy==0 ){
  83253. sqlite3UserAuthInit(db);
  83254. if( db->auth.authLevel<UAUTH_User ){
  83255. pParse->rc = SQLITE_AUTH_USER;
  83256. sqlite3ErrorMsg(pParse, "user not authenticated");
  83257. return;
  83258. }
  83259. }
  83260. #endif
  83261. /* The cookie mask contains one bit for each database file open.
  83262. ** (Bit 0 is for main, bit 1 is for temp, and so forth.) Bits are
  83263. ** set for each database that is used. Generate code to start a
  83264. ** transaction on each used database and to verify the schema cookie
  83265. ** on each used database.
  83266. */
  83267. if( db->mallocFailed==0
  83268. && (DbMaskNonZero(pParse->cookieMask) || pParse->pConstExpr)
  83269. ){
  83270. int iDb, i;
  83271. assert( sqlite3VdbeGetOp(v, 0)->opcode==OP_Init );
  83272. sqlite3VdbeJumpHere(v, 0);
  83273. for(iDb=0; iDb<db->nDb; iDb++){
  83274. if( DbMaskTest(pParse->cookieMask, iDb)==0 ) continue;
  83275. sqlite3VdbeUsesBtree(v, iDb);
  83276. sqlite3VdbeAddOp4Int(v,
  83277. OP_Transaction, /* Opcode */
  83278. iDb, /* P1 */
  83279. DbMaskTest(pParse->writeMask,iDb), /* P2 */
  83280. pParse->cookieValue[iDb], /* P3 */
  83281. db->aDb[iDb].pSchema->iGeneration /* P4 */
  83282. );
  83283. if( db->init.busy==0 ) sqlite3VdbeChangeP5(v, 1);
  83284. }
  83285. #ifndef SQLITE_OMIT_VIRTUALTABLE
  83286. for(i=0; i<pParse->nVtabLock; i++){
  83287. char *vtab = (char *)sqlite3GetVTable(db, pParse->apVtabLock[i]);
  83288. sqlite3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB);
  83289. }
  83290. pParse->nVtabLock = 0;
  83291. #endif
  83292. /* Once all the cookies have been verified and transactions opened,
  83293. ** obtain the required table-locks. This is a no-op unless the
  83294. ** shared-cache feature is enabled.
  83295. */
  83296. codeTableLocks(pParse);
  83297. /* Initialize any AUTOINCREMENT data structures required.
  83298. */
  83299. sqlite3AutoincrementBegin(pParse);
  83300. /* Code constant expressions that where factored out of inner loops */
  83301. if( pParse->pConstExpr ){
  83302. ExprList *pEL = pParse->pConstExpr;
  83303. pParse->okConstFactor = 0;
  83304. for(i=0; i<pEL->nExpr; i++){
  83305. sqlite3ExprCode(pParse, pEL->a[i].pExpr, pEL->a[i].u.iConstExprReg);
  83306. }
  83307. }
  83308. /* Finally, jump back to the beginning of the executable code. */
  83309. sqlite3VdbeAddOp2(v, OP_Goto, 0, 1);
  83310. }
  83311. }
  83312. /* Get the VDBE program ready for execution
  83313. */
  83314. if( v && ALWAYS(pParse->nErr==0) && !db->mallocFailed ){
  83315. assert( pParse->iCacheLevel==0 ); /* Disables and re-enables match */
  83316. /* A minimum of one cursor is required if autoincrement is used
  83317. * See ticket [a696379c1f08866] */
  83318. if( pParse->pAinc!=0 && pParse->nTab==0 ) pParse->nTab = 1;
  83319. sqlite3VdbeMakeReady(v, pParse);
  83320. pParse->rc = SQLITE_DONE;
  83321. pParse->colNamesSet = 0;
  83322. }else{
  83323. pParse->rc = SQLITE_ERROR;
  83324. }
  83325. pParse->nTab = 0;
  83326. pParse->nMem = 0;
  83327. pParse->nSet = 0;
  83328. pParse->nVar = 0;
  83329. DbMaskZero(pParse->cookieMask);
  83330. }
  83331. /*
  83332. ** Run the parser and code generator recursively in order to generate
  83333. ** code for the SQL statement given onto the end of the pParse context
  83334. ** currently under construction. When the parser is run recursively
  83335. ** this way, the final OP_Halt is not appended and other initialization
  83336. ** and finalization steps are omitted because those are handling by the
  83337. ** outermost parser.
  83338. **
  83339. ** Not everything is nestable. This facility is designed to permit
  83340. ** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER. Use
  83341. ** care if you decide to try to use this routine for some other purposes.
  83342. */
  83343. SQLITE_PRIVATE void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){
  83344. va_list ap;
  83345. char *zSql;
  83346. char *zErrMsg = 0;
  83347. sqlite3 *db = pParse->db;
  83348. # define SAVE_SZ (sizeof(Parse) - offsetof(Parse,nVar))
  83349. char saveBuf[SAVE_SZ];
  83350. if( pParse->nErr ) return;
  83351. assert( pParse->nested<10 ); /* Nesting should only be of limited depth */
  83352. va_start(ap, zFormat);
  83353. zSql = sqlite3VMPrintf(db, zFormat, ap);
  83354. va_end(ap);
  83355. if( zSql==0 ){
  83356. return; /* A malloc must have failed */
  83357. }
  83358. pParse->nested++;
  83359. memcpy(saveBuf, &pParse->nVar, SAVE_SZ);
  83360. memset(&pParse->nVar, 0, SAVE_SZ);
  83361. sqlite3RunParser(pParse, zSql, &zErrMsg);
  83362. sqlite3DbFree(db, zErrMsg);
  83363. sqlite3DbFree(db, zSql);
  83364. memcpy(&pParse->nVar, saveBuf, SAVE_SZ);
  83365. pParse->nested--;
  83366. }
  83367. #if SQLITE_USER_AUTHENTICATION
  83368. /*
  83369. ** Return TRUE if zTable is the name of the system table that stores the
  83370. ** list of users and their access credentials.
  83371. */
  83372. SQLITE_PRIVATE int sqlite3UserAuthTable(const char *zTable){
  83373. return sqlite3_stricmp(zTable, "sqlite_user")==0;
  83374. }
  83375. #endif
  83376. /*
  83377. ** Locate the in-memory structure that describes a particular database
  83378. ** table given the name of that table and (optionally) the name of the
  83379. ** database containing the table. Return NULL if not found.
  83380. **
  83381. ** If zDatabase is 0, all databases are searched for the table and the
  83382. ** first matching table is returned. (No checking for duplicate table
  83383. ** names is done.) The search order is TEMP first, then MAIN, then any
  83384. ** auxiliary databases added using the ATTACH command.
  83385. **
  83386. ** See also sqlite3LocateTable().
  83387. */
  83388. SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){
  83389. Table *p = 0;
  83390. int i;
  83391. #ifdef SQLITE_ENABLE_API_ARMOR
  83392. if( !sqlite3SafetyCheckOk(db) || zName==0 ) return 0;
  83393. #endif
  83394. /* All mutexes are required for schema access. Make sure we hold them. */
  83395. assert( zDatabase!=0 || sqlite3BtreeHoldsAllMutexes(db) );
  83396. #if SQLITE_USER_AUTHENTICATION
  83397. /* Only the admin user is allowed to know that the sqlite_user table
  83398. ** exists */
  83399. if( db->auth.authLevel<UAUTH_Admin && sqlite3UserAuthTable(zName)!=0 ){
  83400. return 0;
  83401. }
  83402. #endif
  83403. for(i=OMIT_TEMPDB; i<db->nDb; i++){
  83404. int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
  83405. if( zDatabase!=0 && sqlite3StrICmp(zDatabase, db->aDb[j].zName) ) continue;
  83406. assert( sqlite3SchemaMutexHeld(db, j, 0) );
  83407. p = sqlite3HashFind(&db->aDb[j].pSchema->tblHash, zName);
  83408. if( p ) break;
  83409. }
  83410. return p;
  83411. }
  83412. /*
  83413. ** Locate the in-memory structure that describes a particular database
  83414. ** table given the name of that table and (optionally) the name of the
  83415. ** database containing the table. Return NULL if not found. Also leave an
  83416. ** error message in pParse->zErrMsg.
  83417. **
  83418. ** The difference between this routine and sqlite3FindTable() is that this
  83419. ** routine leaves an error message in pParse->zErrMsg where
  83420. ** sqlite3FindTable() does not.
  83421. */
  83422. SQLITE_PRIVATE Table *sqlite3LocateTable(
  83423. Parse *pParse, /* context in which to report errors */
  83424. int isView, /* True if looking for a VIEW rather than a TABLE */
  83425. const char *zName, /* Name of the table we are looking for */
  83426. const char *zDbase /* Name of the database. Might be NULL */
  83427. ){
  83428. Table *p;
  83429. /* Read the database schema. If an error occurs, leave an error message
  83430. ** and code in pParse and return NULL. */
  83431. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  83432. return 0;
  83433. }
  83434. p = sqlite3FindTable(pParse->db, zName, zDbase);
  83435. if( p==0 ){
  83436. const char *zMsg = isView ? "no such view" : "no such table";
  83437. if( zDbase ){
  83438. sqlite3ErrorMsg(pParse, "%s: %s.%s", zMsg, zDbase, zName);
  83439. }else{
  83440. sqlite3ErrorMsg(pParse, "%s: %s", zMsg, zName);
  83441. }
  83442. pParse->checkSchema = 1;
  83443. }
  83444. #if SQLITE_USER_AUTHENICATION
  83445. else if( pParse->db->auth.authLevel<UAUTH_User ){
  83446. sqlite3ErrorMsg(pParse, "user not authenticated");
  83447. p = 0;
  83448. }
  83449. #endif
  83450. return p;
  83451. }
  83452. /*
  83453. ** Locate the table identified by *p.
  83454. **
  83455. ** This is a wrapper around sqlite3LocateTable(). The difference between
  83456. ** sqlite3LocateTable() and this function is that this function restricts
  83457. ** the search to schema (p->pSchema) if it is not NULL. p->pSchema may be
  83458. ** non-NULL if it is part of a view or trigger program definition. See
  83459. ** sqlite3FixSrcList() for details.
  83460. */
  83461. SQLITE_PRIVATE Table *sqlite3LocateTableItem(
  83462. Parse *pParse,
  83463. int isView,
  83464. struct SrcList_item *p
  83465. ){
  83466. const char *zDb;
  83467. assert( p->pSchema==0 || p->zDatabase==0 );
  83468. if( p->pSchema ){
  83469. int iDb = sqlite3SchemaToIndex(pParse->db, p->pSchema);
  83470. zDb = pParse->db->aDb[iDb].zName;
  83471. }else{
  83472. zDb = p->zDatabase;
  83473. }
  83474. return sqlite3LocateTable(pParse, isView, p->zName, zDb);
  83475. }
  83476. /*
  83477. ** Locate the in-memory structure that describes
  83478. ** a particular index given the name of that index
  83479. ** and the name of the database that contains the index.
  83480. ** Return NULL if not found.
  83481. **
  83482. ** If zDatabase is 0, all databases are searched for the
  83483. ** table and the first matching index is returned. (No checking
  83484. ** for duplicate index names is done.) The search order is
  83485. ** TEMP first, then MAIN, then any auxiliary databases added
  83486. ** using the ATTACH command.
  83487. */
  83488. SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){
  83489. Index *p = 0;
  83490. int i;
  83491. /* All mutexes are required for schema access. Make sure we hold them. */
  83492. assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
  83493. for(i=OMIT_TEMPDB; i<db->nDb; i++){
  83494. int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
  83495. Schema *pSchema = db->aDb[j].pSchema;
  83496. assert( pSchema );
  83497. if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zName) ) continue;
  83498. assert( sqlite3SchemaMutexHeld(db, j, 0) );
  83499. p = sqlite3HashFind(&pSchema->idxHash, zName);
  83500. if( p ) break;
  83501. }
  83502. return p;
  83503. }
  83504. /*
  83505. ** Reclaim the memory used by an index
  83506. */
  83507. static void freeIndex(sqlite3 *db, Index *p){
  83508. #ifndef SQLITE_OMIT_ANALYZE
  83509. sqlite3DeleteIndexSamples(db, p);
  83510. #endif
  83511. if( db==0 || db->pnBytesFreed==0 ) sqlite3KeyInfoUnref(p->pKeyInfo);
  83512. sqlite3ExprDelete(db, p->pPartIdxWhere);
  83513. sqlite3DbFree(db, p->zColAff);
  83514. if( p->isResized ) sqlite3DbFree(db, p->azColl);
  83515. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  83516. sqlite3_free(p->aiRowEst);
  83517. #endif
  83518. sqlite3DbFree(db, p);
  83519. }
  83520. /*
  83521. ** For the index called zIdxName which is found in the database iDb,
  83522. ** unlike that index from its Table then remove the index from
  83523. ** the index hash table and free all memory structures associated
  83524. ** with the index.
  83525. */
  83526. SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){
  83527. Index *pIndex;
  83528. Hash *pHash;
  83529. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  83530. pHash = &db->aDb[iDb].pSchema->idxHash;
  83531. pIndex = sqlite3HashInsert(pHash, zIdxName, 0);
  83532. if( ALWAYS(pIndex) ){
  83533. if( pIndex->pTable->pIndex==pIndex ){
  83534. pIndex->pTable->pIndex = pIndex->pNext;
  83535. }else{
  83536. Index *p;
  83537. /* Justification of ALWAYS(); The index must be on the list of
  83538. ** indices. */
  83539. p = pIndex->pTable->pIndex;
  83540. while( ALWAYS(p) && p->pNext!=pIndex ){ p = p->pNext; }
  83541. if( ALWAYS(p && p->pNext==pIndex) ){
  83542. p->pNext = pIndex->pNext;
  83543. }
  83544. }
  83545. freeIndex(db, pIndex);
  83546. }
  83547. db->flags |= SQLITE_InternChanges;
  83548. }
  83549. /*
  83550. ** Look through the list of open database files in db->aDb[] and if
  83551. ** any have been closed, remove them from the list. Reallocate the
  83552. ** db->aDb[] structure to a smaller size, if possible.
  83553. **
  83554. ** Entry 0 (the "main" database) and entry 1 (the "temp" database)
  83555. ** are never candidates for being collapsed.
  83556. */
  83557. SQLITE_PRIVATE void sqlite3CollapseDatabaseArray(sqlite3 *db){
  83558. int i, j;
  83559. for(i=j=2; i<db->nDb; i++){
  83560. struct Db *pDb = &db->aDb[i];
  83561. if( pDb->pBt==0 ){
  83562. sqlite3DbFree(db, pDb->zName);
  83563. pDb->zName = 0;
  83564. continue;
  83565. }
  83566. if( j<i ){
  83567. db->aDb[j] = db->aDb[i];
  83568. }
  83569. j++;
  83570. }
  83571. memset(&db->aDb[j], 0, (db->nDb-j)*sizeof(db->aDb[j]));
  83572. db->nDb = j;
  83573. if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
  83574. memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
  83575. sqlite3DbFree(db, db->aDb);
  83576. db->aDb = db->aDbStatic;
  83577. }
  83578. }
  83579. /*
  83580. ** Reset the schema for the database at index iDb. Also reset the
  83581. ** TEMP schema.
  83582. */
  83583. SQLITE_PRIVATE void sqlite3ResetOneSchema(sqlite3 *db, int iDb){
  83584. Db *pDb;
  83585. assert( iDb<db->nDb );
  83586. /* Case 1: Reset the single schema identified by iDb */
  83587. pDb = &db->aDb[iDb];
  83588. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  83589. assert( pDb->pSchema!=0 );
  83590. sqlite3SchemaClear(pDb->pSchema);
  83591. /* If any database other than TEMP is reset, then also reset TEMP
  83592. ** since TEMP might be holding triggers that reference tables in the
  83593. ** other database.
  83594. */
  83595. if( iDb!=1 ){
  83596. pDb = &db->aDb[1];
  83597. assert( pDb->pSchema!=0 );
  83598. sqlite3SchemaClear(pDb->pSchema);
  83599. }
  83600. return;
  83601. }
  83602. /*
  83603. ** Erase all schema information from all attached databases (including
  83604. ** "main" and "temp") for a single database connection.
  83605. */
  83606. SQLITE_PRIVATE void sqlite3ResetAllSchemasOfConnection(sqlite3 *db){
  83607. int i;
  83608. sqlite3BtreeEnterAll(db);
  83609. for(i=0; i<db->nDb; i++){
  83610. Db *pDb = &db->aDb[i];
  83611. if( pDb->pSchema ){
  83612. sqlite3SchemaClear(pDb->pSchema);
  83613. }
  83614. }
  83615. db->flags &= ~SQLITE_InternChanges;
  83616. sqlite3VtabUnlockList(db);
  83617. sqlite3BtreeLeaveAll(db);
  83618. sqlite3CollapseDatabaseArray(db);
  83619. }
  83620. /*
  83621. ** This routine is called when a commit occurs.
  83622. */
  83623. SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3 *db){
  83624. db->flags &= ~SQLITE_InternChanges;
  83625. }
  83626. /*
  83627. ** Delete memory allocated for the column names of a table or view (the
  83628. ** Table.aCol[] array).
  83629. */
  83630. static void sqliteDeleteColumnNames(sqlite3 *db, Table *pTable){
  83631. int i;
  83632. Column *pCol;
  83633. assert( pTable!=0 );
  83634. if( (pCol = pTable->aCol)!=0 ){
  83635. for(i=0; i<pTable->nCol; i++, pCol++){
  83636. sqlite3DbFree(db, pCol->zName);
  83637. sqlite3ExprDelete(db, pCol->pDflt);
  83638. sqlite3DbFree(db, pCol->zDflt);
  83639. sqlite3DbFree(db, pCol->zType);
  83640. sqlite3DbFree(db, pCol->zColl);
  83641. }
  83642. sqlite3DbFree(db, pTable->aCol);
  83643. }
  83644. }
  83645. /*
  83646. ** Remove the memory data structures associated with the given
  83647. ** Table. No changes are made to disk by this routine.
  83648. **
  83649. ** This routine just deletes the data structure. It does not unlink
  83650. ** the table data structure from the hash table. But it does destroy
  83651. ** memory structures of the indices and foreign keys associated with
  83652. ** the table.
  83653. **
  83654. ** The db parameter is optional. It is needed if the Table object
  83655. ** contains lookaside memory. (Table objects in the schema do not use
  83656. ** lookaside memory, but some ephemeral Table objects do.) Or the
  83657. ** db parameter can be used with db->pnBytesFreed to measure the memory
  83658. ** used by the Table object.
  83659. */
  83660. SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3 *db, Table *pTable){
  83661. Index *pIndex, *pNext;
  83662. TESTONLY( int nLookaside; ) /* Used to verify lookaside not used for schema */
  83663. assert( !pTable || pTable->nRef>0 );
  83664. /* Do not delete the table until the reference count reaches zero. */
  83665. if( !pTable ) return;
  83666. if( ((!db || db->pnBytesFreed==0) && (--pTable->nRef)>0) ) return;
  83667. /* Record the number of outstanding lookaside allocations in schema Tables
  83668. ** prior to doing any free() operations. Since schema Tables do not use
  83669. ** lookaside, this number should not change. */
  83670. TESTONLY( nLookaside = (db && (pTable->tabFlags & TF_Ephemeral)==0) ?
  83671. db->lookaside.nOut : 0 );
  83672. /* Delete all indices associated with this table. */
  83673. for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
  83674. pNext = pIndex->pNext;
  83675. assert( pIndex->pSchema==pTable->pSchema );
  83676. if( !db || db->pnBytesFreed==0 ){
  83677. char *zName = pIndex->zName;
  83678. TESTONLY ( Index *pOld = ) sqlite3HashInsert(
  83679. &pIndex->pSchema->idxHash, zName, 0
  83680. );
  83681. assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
  83682. assert( pOld==pIndex || pOld==0 );
  83683. }
  83684. freeIndex(db, pIndex);
  83685. }
  83686. /* Delete any foreign keys attached to this table. */
  83687. sqlite3FkDelete(db, pTable);
  83688. /* Delete the Table structure itself.
  83689. */
  83690. sqliteDeleteColumnNames(db, pTable);
  83691. sqlite3DbFree(db, pTable->zName);
  83692. sqlite3DbFree(db, pTable->zColAff);
  83693. sqlite3SelectDelete(db, pTable->pSelect);
  83694. #ifndef SQLITE_OMIT_CHECK
  83695. sqlite3ExprListDelete(db, pTable->pCheck);
  83696. #endif
  83697. #ifndef SQLITE_OMIT_VIRTUALTABLE
  83698. sqlite3VtabClear(db, pTable);
  83699. #endif
  83700. sqlite3DbFree(db, pTable);
  83701. /* Verify that no lookaside memory was used by schema tables */
  83702. assert( nLookaside==0 || nLookaside==db->lookaside.nOut );
  83703. }
  83704. /*
  83705. ** Unlink the given table from the hash tables and the delete the
  83706. ** table structure with all its indices and foreign keys.
  83707. */
  83708. SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){
  83709. Table *p;
  83710. Db *pDb;
  83711. assert( db!=0 );
  83712. assert( iDb>=0 && iDb<db->nDb );
  83713. assert( zTabName );
  83714. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  83715. testcase( zTabName[0]==0 ); /* Zero-length table names are allowed */
  83716. pDb = &db->aDb[iDb];
  83717. p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName, 0);
  83718. sqlite3DeleteTable(db, p);
  83719. db->flags |= SQLITE_InternChanges;
  83720. }
  83721. /*
  83722. ** Given a token, return a string that consists of the text of that
  83723. ** token. Space to hold the returned string
  83724. ** is obtained from sqliteMalloc() and must be freed by the calling
  83725. ** function.
  83726. **
  83727. ** Any quotation marks (ex: "name", 'name', [name], or `name`) that
  83728. ** surround the body of the token are removed.
  83729. **
  83730. ** Tokens are often just pointers into the original SQL text and so
  83731. ** are not \000 terminated and are not persistent. The returned string
  83732. ** is \000 terminated and is persistent.
  83733. */
  83734. SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3 *db, Token *pName){
  83735. char *zName;
  83736. if( pName ){
  83737. zName = sqlite3DbStrNDup(db, (char*)pName->z, pName->n);
  83738. sqlite3Dequote(zName);
  83739. }else{
  83740. zName = 0;
  83741. }
  83742. return zName;
  83743. }
  83744. /*
  83745. ** Open the sqlite_master table stored in database number iDb for
  83746. ** writing. The table is opened using cursor 0.
  83747. */
  83748. SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *p, int iDb){
  83749. Vdbe *v = sqlite3GetVdbe(p);
  83750. sqlite3TableLock(p, iDb, MASTER_ROOT, 1, SCHEMA_TABLE(iDb));
  83751. sqlite3VdbeAddOp4Int(v, OP_OpenWrite, 0, MASTER_ROOT, iDb, 5);
  83752. if( p->nTab==0 ){
  83753. p->nTab = 1;
  83754. }
  83755. }
  83756. /*
  83757. ** Parameter zName points to a nul-terminated buffer containing the name
  83758. ** of a database ("main", "temp" or the name of an attached db). This
  83759. ** function returns the index of the named database in db->aDb[], or
  83760. ** -1 if the named db cannot be found.
  83761. */
  83762. SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *db, const char *zName){
  83763. int i = -1; /* Database number */
  83764. if( zName ){
  83765. Db *pDb;
  83766. int n = sqlite3Strlen30(zName);
  83767. for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){
  83768. if( (!OMIT_TEMPDB || i!=1 ) && n==sqlite3Strlen30(pDb->zName) &&
  83769. 0==sqlite3StrICmp(pDb->zName, zName) ){
  83770. break;
  83771. }
  83772. }
  83773. }
  83774. return i;
  83775. }
  83776. /*
  83777. ** The token *pName contains the name of a database (either "main" or
  83778. ** "temp" or the name of an attached db). This routine returns the
  83779. ** index of the named database in db->aDb[], or -1 if the named db
  83780. ** does not exist.
  83781. */
  83782. SQLITE_PRIVATE int sqlite3FindDb(sqlite3 *db, Token *pName){
  83783. int i; /* Database number */
  83784. char *zName; /* Name we are searching for */
  83785. zName = sqlite3NameFromToken(db, pName);
  83786. i = sqlite3FindDbName(db, zName);
  83787. sqlite3DbFree(db, zName);
  83788. return i;
  83789. }
  83790. /* The table or view or trigger name is passed to this routine via tokens
  83791. ** pName1 and pName2. If the table name was fully qualified, for example:
  83792. **
  83793. ** CREATE TABLE xxx.yyy (...);
  83794. **
  83795. ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
  83796. ** the table name is not fully qualified, i.e.:
  83797. **
  83798. ** CREATE TABLE yyy(...);
  83799. **
  83800. ** Then pName1 is set to "yyy" and pName2 is "".
  83801. **
  83802. ** This routine sets the *ppUnqual pointer to point at the token (pName1 or
  83803. ** pName2) that stores the unqualified table name. The index of the
  83804. ** database "xxx" is returned.
  83805. */
  83806. SQLITE_PRIVATE int sqlite3TwoPartName(
  83807. Parse *pParse, /* Parsing and code generating context */
  83808. Token *pName1, /* The "xxx" in the name "xxx.yyy" or "xxx" */
  83809. Token *pName2, /* The "yyy" in the name "xxx.yyy" */
  83810. Token **pUnqual /* Write the unqualified object name here */
  83811. ){
  83812. int iDb; /* Database holding the object */
  83813. sqlite3 *db = pParse->db;
  83814. if( ALWAYS(pName2!=0) && pName2->n>0 ){
  83815. if( db->init.busy ) {
  83816. sqlite3ErrorMsg(pParse, "corrupt database");
  83817. pParse->nErr++;
  83818. return -1;
  83819. }
  83820. *pUnqual = pName2;
  83821. iDb = sqlite3FindDb(db, pName1);
  83822. if( iDb<0 ){
  83823. sqlite3ErrorMsg(pParse, "unknown database %T", pName1);
  83824. pParse->nErr++;
  83825. return -1;
  83826. }
  83827. }else{
  83828. assert( db->init.iDb==0 || db->init.busy );
  83829. iDb = db->init.iDb;
  83830. *pUnqual = pName1;
  83831. }
  83832. return iDb;
  83833. }
  83834. /*
  83835. ** This routine is used to check if the UTF-8 string zName is a legal
  83836. ** unqualified name for a new schema object (table, index, view or
  83837. ** trigger). All names are legal except those that begin with the string
  83838. ** "sqlite_" (in upper, lower or mixed case). This portion of the namespace
  83839. ** is reserved for internal use.
  83840. */
  83841. SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *pParse, const char *zName){
  83842. if( !pParse->db->init.busy && pParse->nested==0
  83843. && (pParse->db->flags & SQLITE_WriteSchema)==0
  83844. && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
  83845. sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s", zName);
  83846. return SQLITE_ERROR;
  83847. }
  83848. return SQLITE_OK;
  83849. }
  83850. /*
  83851. ** Return the PRIMARY KEY index of a table
  83852. */
  83853. SQLITE_PRIVATE Index *sqlite3PrimaryKeyIndex(Table *pTab){
  83854. Index *p;
  83855. for(p=pTab->pIndex; p && !IsPrimaryKeyIndex(p); p=p->pNext){}
  83856. return p;
  83857. }
  83858. /*
  83859. ** Return the column of index pIdx that corresponds to table
  83860. ** column iCol. Return -1 if not found.
  83861. */
  83862. SQLITE_PRIVATE i16 sqlite3ColumnOfIndex(Index *pIdx, i16 iCol){
  83863. int i;
  83864. for(i=0; i<pIdx->nColumn; i++){
  83865. if( iCol==pIdx->aiColumn[i] ) return i;
  83866. }
  83867. return -1;
  83868. }
  83869. /*
  83870. ** Begin constructing a new table representation in memory. This is
  83871. ** the first of several action routines that get called in response
  83872. ** to a CREATE TABLE statement. In particular, this routine is called
  83873. ** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp
  83874. ** flag is true if the table should be stored in the auxiliary database
  83875. ** file instead of in the main database file. This is normally the case
  83876. ** when the "TEMP" or "TEMPORARY" keyword occurs in between
  83877. ** CREATE and TABLE.
  83878. **
  83879. ** The new table record is initialized and put in pParse->pNewTable.
  83880. ** As more of the CREATE TABLE statement is parsed, additional action
  83881. ** routines will be called to add more information to this record.
  83882. ** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine
  83883. ** is called to complete the construction of the new table record.
  83884. */
  83885. SQLITE_PRIVATE void sqlite3StartTable(
  83886. Parse *pParse, /* Parser context */
  83887. Token *pName1, /* First part of the name of the table or view */
  83888. Token *pName2, /* Second part of the name of the table or view */
  83889. int isTemp, /* True if this is a TEMP table */
  83890. int isView, /* True if this is a VIEW */
  83891. int isVirtual, /* True if this is a VIRTUAL table */
  83892. int noErr /* Do nothing if table already exists */
  83893. ){
  83894. Table *pTable;
  83895. char *zName = 0; /* The name of the new table */
  83896. sqlite3 *db = pParse->db;
  83897. Vdbe *v;
  83898. int iDb; /* Database number to create the table in */
  83899. Token *pName; /* Unqualified name of the table to create */
  83900. /* The table or view name to create is passed to this routine via tokens
  83901. ** pName1 and pName2. If the table name was fully qualified, for example:
  83902. **
  83903. ** CREATE TABLE xxx.yyy (...);
  83904. **
  83905. ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
  83906. ** the table name is not fully qualified, i.e.:
  83907. **
  83908. ** CREATE TABLE yyy(...);
  83909. **
  83910. ** Then pName1 is set to "yyy" and pName2 is "".
  83911. **
  83912. ** The call below sets the pName pointer to point at the token (pName1 or
  83913. ** pName2) that stores the unqualified table name. The variable iDb is
  83914. ** set to the index of the database that the table or view is to be
  83915. ** created in.
  83916. */
  83917. iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
  83918. if( iDb<0 ) return;
  83919. if( !OMIT_TEMPDB && isTemp && pName2->n>0 && iDb!=1 ){
  83920. /* If creating a temp table, the name may not be qualified. Unless
  83921. ** the database name is "temp" anyway. */
  83922. sqlite3ErrorMsg(pParse, "temporary table name must be unqualified");
  83923. return;
  83924. }
  83925. if( !OMIT_TEMPDB && isTemp ) iDb = 1;
  83926. pParse->sNameToken = *pName;
  83927. zName = sqlite3NameFromToken(db, pName);
  83928. if( zName==0 ) return;
  83929. if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
  83930. goto begin_table_error;
  83931. }
  83932. if( db->init.iDb==1 ) isTemp = 1;
  83933. #ifndef SQLITE_OMIT_AUTHORIZATION
  83934. assert( (isTemp & 1)==isTemp );
  83935. {
  83936. int code;
  83937. char *zDb = db->aDb[iDb].zName;
  83938. if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
  83939. goto begin_table_error;
  83940. }
  83941. if( isView ){
  83942. if( !OMIT_TEMPDB && isTemp ){
  83943. code = SQLITE_CREATE_TEMP_VIEW;
  83944. }else{
  83945. code = SQLITE_CREATE_VIEW;
  83946. }
  83947. }else{
  83948. if( !OMIT_TEMPDB && isTemp ){
  83949. code = SQLITE_CREATE_TEMP_TABLE;
  83950. }else{
  83951. code = SQLITE_CREATE_TABLE;
  83952. }
  83953. }
  83954. if( !isVirtual && sqlite3AuthCheck(pParse, code, zName, 0, zDb) ){
  83955. goto begin_table_error;
  83956. }
  83957. }
  83958. #endif
  83959. /* Make sure the new table name does not collide with an existing
  83960. ** index or table name in the same database. Issue an error message if
  83961. ** it does. The exception is if the statement being parsed was passed
  83962. ** to an sqlite3_declare_vtab() call. In that case only the column names
  83963. ** and types will be used, so there is no need to test for namespace
  83964. ** collisions.
  83965. */
  83966. if( !IN_DECLARE_VTAB ){
  83967. char *zDb = db->aDb[iDb].zName;
  83968. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  83969. goto begin_table_error;
  83970. }
  83971. pTable = sqlite3FindTable(db, zName, zDb);
  83972. if( pTable ){
  83973. if( !noErr ){
  83974. sqlite3ErrorMsg(pParse, "table %T already exists", pName);
  83975. }else{
  83976. assert( !db->init.busy );
  83977. sqlite3CodeVerifySchema(pParse, iDb);
  83978. }
  83979. goto begin_table_error;
  83980. }
  83981. if( sqlite3FindIndex(db, zName, zDb)!=0 ){
  83982. sqlite3ErrorMsg(pParse, "there is already an index named %s", zName);
  83983. goto begin_table_error;
  83984. }
  83985. }
  83986. pTable = sqlite3DbMallocZero(db, sizeof(Table));
  83987. if( pTable==0 ){
  83988. db->mallocFailed = 1;
  83989. pParse->rc = SQLITE_NOMEM;
  83990. pParse->nErr++;
  83991. goto begin_table_error;
  83992. }
  83993. pTable->zName = zName;
  83994. pTable->iPKey = -1;
  83995. pTable->pSchema = db->aDb[iDb].pSchema;
  83996. pTable->nRef = 1;
  83997. pTable->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
  83998. assert( pParse->pNewTable==0 );
  83999. pParse->pNewTable = pTable;
  84000. /* If this is the magic sqlite_sequence table used by autoincrement,
  84001. ** then record a pointer to this table in the main database structure
  84002. ** so that INSERT can find the table easily.
  84003. */
  84004. #ifndef SQLITE_OMIT_AUTOINCREMENT
  84005. if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){
  84006. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  84007. pTable->pSchema->pSeqTab = pTable;
  84008. }
  84009. #endif
  84010. /* Begin generating the code that will insert the table record into
  84011. ** the SQLITE_MASTER table. Note in particular that we must go ahead
  84012. ** and allocate the record number for the table entry now. Before any
  84013. ** PRIMARY KEY or UNIQUE keywords are parsed. Those keywords will cause
  84014. ** indices to be created and the table record must come before the
  84015. ** indices. Hence, the record number for the table must be allocated
  84016. ** now.
  84017. */
  84018. if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){
  84019. int j1;
  84020. int fileFormat;
  84021. int reg1, reg2, reg3;
  84022. sqlite3BeginWriteOperation(pParse, 0, iDb);
  84023. #ifndef SQLITE_OMIT_VIRTUALTABLE
  84024. if( isVirtual ){
  84025. sqlite3VdbeAddOp0(v, OP_VBegin);
  84026. }
  84027. #endif
  84028. /* If the file format and encoding in the database have not been set,
  84029. ** set them now.
  84030. */
  84031. reg1 = pParse->regRowid = ++pParse->nMem;
  84032. reg2 = pParse->regRoot = ++pParse->nMem;
  84033. reg3 = ++pParse->nMem;
  84034. sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, BTREE_FILE_FORMAT);
  84035. sqlite3VdbeUsesBtree(v, iDb);
  84036. j1 = sqlite3VdbeAddOp1(v, OP_If, reg3); VdbeCoverage(v);
  84037. fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ?
  84038. 1 : SQLITE_MAX_FILE_FORMAT;
  84039. sqlite3VdbeAddOp2(v, OP_Integer, fileFormat, reg3);
  84040. sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, reg3);
  84041. sqlite3VdbeAddOp2(v, OP_Integer, ENC(db), reg3);
  84042. sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_TEXT_ENCODING, reg3);
  84043. sqlite3VdbeJumpHere(v, j1);
  84044. /* This just creates a place-holder record in the sqlite_master table.
  84045. ** The record created does not contain anything yet. It will be replaced
  84046. ** by the real entry in code generated at sqlite3EndTable().
  84047. **
  84048. ** The rowid for the new entry is left in register pParse->regRowid.
  84049. ** The root page number of the new table is left in reg pParse->regRoot.
  84050. ** The rowid and root page number values are needed by the code that
  84051. ** sqlite3EndTable will generate.
  84052. */
  84053. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
  84054. if( isView || isVirtual ){
  84055. sqlite3VdbeAddOp2(v, OP_Integer, 0, reg2);
  84056. }else
  84057. #endif
  84058. {
  84059. pParse->addrCrTab = sqlite3VdbeAddOp2(v, OP_CreateTable, iDb, reg2);
  84060. }
  84061. sqlite3OpenMasterTable(pParse, iDb);
  84062. sqlite3VdbeAddOp2(v, OP_NewRowid, 0, reg1);
  84063. sqlite3VdbeAddOp2(v, OP_Null, 0, reg3);
  84064. sqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1);
  84065. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  84066. sqlite3VdbeAddOp0(v, OP_Close);
  84067. }
  84068. /* Normal (non-error) return. */
  84069. return;
  84070. /* If an error occurs, we jump here */
  84071. begin_table_error:
  84072. sqlite3DbFree(db, zName);
  84073. return;
  84074. }
  84075. /*
  84076. ** This macro is used to compare two strings in a case-insensitive manner.
  84077. ** It is slightly faster than calling sqlite3StrICmp() directly, but
  84078. ** produces larger code.
  84079. **
  84080. ** WARNING: This macro is not compatible with the strcmp() family. It
  84081. ** returns true if the two strings are equal, otherwise false.
  84082. */
  84083. #define STRICMP(x, y) (\
  84084. sqlite3UpperToLower[*(unsigned char *)(x)]== \
  84085. sqlite3UpperToLower[*(unsigned char *)(y)] \
  84086. && sqlite3StrICmp((x)+1,(y)+1)==0 )
  84087. /*
  84088. ** Add a new column to the table currently being constructed.
  84089. **
  84090. ** The parser calls this routine once for each column declaration
  84091. ** in a CREATE TABLE statement. sqlite3StartTable() gets called
  84092. ** first to get things going. Then this routine is called for each
  84093. ** column.
  84094. */
  84095. SQLITE_PRIVATE void sqlite3AddColumn(Parse *pParse, Token *pName){
  84096. Table *p;
  84097. int i;
  84098. char *z;
  84099. Column *pCol;
  84100. sqlite3 *db = pParse->db;
  84101. if( (p = pParse->pNewTable)==0 ) return;
  84102. #if SQLITE_MAX_COLUMN
  84103. if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){
  84104. sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName);
  84105. return;
  84106. }
  84107. #endif
  84108. z = sqlite3NameFromToken(db, pName);
  84109. if( z==0 ) return;
  84110. for(i=0; i<p->nCol; i++){
  84111. if( STRICMP(z, p->aCol[i].zName) ){
  84112. sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
  84113. sqlite3DbFree(db, z);
  84114. return;
  84115. }
  84116. }
  84117. if( (p->nCol & 0x7)==0 ){
  84118. Column *aNew;
  84119. aNew = sqlite3DbRealloc(db,p->aCol,(p->nCol+8)*sizeof(p->aCol[0]));
  84120. if( aNew==0 ){
  84121. sqlite3DbFree(db, z);
  84122. return;
  84123. }
  84124. p->aCol = aNew;
  84125. }
  84126. pCol = &p->aCol[p->nCol];
  84127. memset(pCol, 0, sizeof(p->aCol[0]));
  84128. pCol->zName = z;
  84129. /* If there is no type specified, columns have the default affinity
  84130. ** 'NONE'. If there is a type specified, then sqlite3AddColumnType() will
  84131. ** be called next to set pCol->affinity correctly.
  84132. */
  84133. pCol->affinity = SQLITE_AFF_NONE;
  84134. pCol->szEst = 1;
  84135. p->nCol++;
  84136. }
  84137. /*
  84138. ** This routine is called by the parser while in the middle of
  84139. ** parsing a CREATE TABLE statement. A "NOT NULL" constraint has
  84140. ** been seen on a column. This routine sets the notNull flag on
  84141. ** the column currently under construction.
  84142. */
  84143. SQLITE_PRIVATE void sqlite3AddNotNull(Parse *pParse, int onError){
  84144. Table *p;
  84145. p = pParse->pNewTable;
  84146. if( p==0 || NEVER(p->nCol<1) ) return;
  84147. p->aCol[p->nCol-1].notNull = (u8)onError;
  84148. }
  84149. /*
  84150. ** Scan the column type name zType (length nType) and return the
  84151. ** associated affinity type.
  84152. **
  84153. ** This routine does a case-independent search of zType for the
  84154. ** substrings in the following table. If one of the substrings is
  84155. ** found, the corresponding affinity is returned. If zType contains
  84156. ** more than one of the substrings, entries toward the top of
  84157. ** the table take priority. For example, if zType is 'BLOBINT',
  84158. ** SQLITE_AFF_INTEGER is returned.
  84159. **
  84160. ** Substring | Affinity
  84161. ** --------------------------------
  84162. ** 'INT' | SQLITE_AFF_INTEGER
  84163. ** 'CHAR' | SQLITE_AFF_TEXT
  84164. ** 'CLOB' | SQLITE_AFF_TEXT
  84165. ** 'TEXT' | SQLITE_AFF_TEXT
  84166. ** 'BLOB' | SQLITE_AFF_NONE
  84167. ** 'REAL' | SQLITE_AFF_REAL
  84168. ** 'FLOA' | SQLITE_AFF_REAL
  84169. ** 'DOUB' | SQLITE_AFF_REAL
  84170. **
  84171. ** If none of the substrings in the above table are found,
  84172. ** SQLITE_AFF_NUMERIC is returned.
  84173. */
  84174. SQLITE_PRIVATE char sqlite3AffinityType(const char *zIn, u8 *pszEst){
  84175. u32 h = 0;
  84176. char aff = SQLITE_AFF_NUMERIC;
  84177. const char *zChar = 0;
  84178. if( zIn==0 ) return aff;
  84179. while( zIn[0] ){
  84180. h = (h<<8) + sqlite3UpperToLower[(*zIn)&0xff];
  84181. zIn++;
  84182. if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){ /* CHAR */
  84183. aff = SQLITE_AFF_TEXT;
  84184. zChar = zIn;
  84185. }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){ /* CLOB */
  84186. aff = SQLITE_AFF_TEXT;
  84187. }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){ /* TEXT */
  84188. aff = SQLITE_AFF_TEXT;
  84189. }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b') /* BLOB */
  84190. && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){
  84191. aff = SQLITE_AFF_NONE;
  84192. if( zIn[0]=='(' ) zChar = zIn;
  84193. #ifndef SQLITE_OMIT_FLOATING_POINT
  84194. }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l') /* REAL */
  84195. && aff==SQLITE_AFF_NUMERIC ){
  84196. aff = SQLITE_AFF_REAL;
  84197. }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a') /* FLOA */
  84198. && aff==SQLITE_AFF_NUMERIC ){
  84199. aff = SQLITE_AFF_REAL;
  84200. }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b') /* DOUB */
  84201. && aff==SQLITE_AFF_NUMERIC ){
  84202. aff = SQLITE_AFF_REAL;
  84203. #endif
  84204. }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){ /* INT */
  84205. aff = SQLITE_AFF_INTEGER;
  84206. break;
  84207. }
  84208. }
  84209. /* If pszEst is not NULL, store an estimate of the field size. The
  84210. ** estimate is scaled so that the size of an integer is 1. */
  84211. if( pszEst ){
  84212. *pszEst = 1; /* default size is approx 4 bytes */
  84213. if( aff<SQLITE_AFF_NUMERIC ){
  84214. if( zChar ){
  84215. while( zChar[0] ){
  84216. if( sqlite3Isdigit(zChar[0]) ){
  84217. int v = 0;
  84218. sqlite3GetInt32(zChar, &v);
  84219. v = v/4 + 1;
  84220. if( v>255 ) v = 255;
  84221. *pszEst = v; /* BLOB(k), VARCHAR(k), CHAR(k) -> r=(k/4+1) */
  84222. break;
  84223. }
  84224. zChar++;
  84225. }
  84226. }else{
  84227. *pszEst = 5; /* BLOB, TEXT, CLOB -> r=5 (approx 20 bytes)*/
  84228. }
  84229. }
  84230. }
  84231. return aff;
  84232. }
  84233. /*
  84234. ** This routine is called by the parser while in the middle of
  84235. ** parsing a CREATE TABLE statement. The pFirst token is the first
  84236. ** token in the sequence of tokens that describe the type of the
  84237. ** column currently under construction. pLast is the last token
  84238. ** in the sequence. Use this information to construct a string
  84239. ** that contains the typename of the column and store that string
  84240. ** in zType.
  84241. */
  84242. SQLITE_PRIVATE void sqlite3AddColumnType(Parse *pParse, Token *pType){
  84243. Table *p;
  84244. Column *pCol;
  84245. p = pParse->pNewTable;
  84246. if( p==0 || NEVER(p->nCol<1) ) return;
  84247. pCol = &p->aCol[p->nCol-1];
  84248. assert( pCol->zType==0 );
  84249. pCol->zType = sqlite3NameFromToken(pParse->db, pType);
  84250. pCol->affinity = sqlite3AffinityType(pCol->zType, &pCol->szEst);
  84251. }
  84252. /*
  84253. ** The expression is the default value for the most recently added column
  84254. ** of the table currently under construction.
  84255. **
  84256. ** Default value expressions must be constant. Raise an exception if this
  84257. ** is not the case.
  84258. **
  84259. ** This routine is called by the parser while in the middle of
  84260. ** parsing a CREATE TABLE statement.
  84261. */
  84262. SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse *pParse, ExprSpan *pSpan){
  84263. Table *p;
  84264. Column *pCol;
  84265. sqlite3 *db = pParse->db;
  84266. p = pParse->pNewTable;
  84267. if( p!=0 ){
  84268. pCol = &(p->aCol[p->nCol-1]);
  84269. if( !sqlite3ExprIsConstantOrFunction(pSpan->pExpr, db->init.busy) ){
  84270. sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
  84271. pCol->zName);
  84272. }else{
  84273. /* A copy of pExpr is used instead of the original, as pExpr contains
  84274. ** tokens that point to volatile memory. The 'span' of the expression
  84275. ** is required by pragma table_info.
  84276. */
  84277. sqlite3ExprDelete(db, pCol->pDflt);
  84278. pCol->pDflt = sqlite3ExprDup(db, pSpan->pExpr, EXPRDUP_REDUCE);
  84279. sqlite3DbFree(db, pCol->zDflt);
  84280. pCol->zDflt = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
  84281. (int)(pSpan->zEnd - pSpan->zStart));
  84282. }
  84283. }
  84284. sqlite3ExprDelete(db, pSpan->pExpr);
  84285. }
  84286. /*
  84287. ** Designate the PRIMARY KEY for the table. pList is a list of names
  84288. ** of columns that form the primary key. If pList is NULL, then the
  84289. ** most recently added column of the table is the primary key.
  84290. **
  84291. ** A table can have at most one primary key. If the table already has
  84292. ** a primary key (and this is the second primary key) then create an
  84293. ** error.
  84294. **
  84295. ** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
  84296. ** then we will try to use that column as the rowid. Set the Table.iPKey
  84297. ** field of the table under construction to be the index of the
  84298. ** INTEGER PRIMARY KEY column. Table.iPKey is set to -1 if there is
  84299. ** no INTEGER PRIMARY KEY.
  84300. **
  84301. ** If the key is not an INTEGER PRIMARY KEY, then create a unique
  84302. ** index for the key. No index is created for INTEGER PRIMARY KEYs.
  84303. */
  84304. SQLITE_PRIVATE void sqlite3AddPrimaryKey(
  84305. Parse *pParse, /* Parsing context */
  84306. ExprList *pList, /* List of field names to be indexed */
  84307. int onError, /* What to do with a uniqueness conflict */
  84308. int autoInc, /* True if the AUTOINCREMENT keyword is present */
  84309. int sortOrder /* SQLITE_SO_ASC or SQLITE_SO_DESC */
  84310. ){
  84311. Table *pTab = pParse->pNewTable;
  84312. char *zType = 0;
  84313. int iCol = -1, i;
  84314. int nTerm;
  84315. if( pTab==0 || IN_DECLARE_VTAB ) goto primary_key_exit;
  84316. if( pTab->tabFlags & TF_HasPrimaryKey ){
  84317. sqlite3ErrorMsg(pParse,
  84318. "table \"%s\" has more than one primary key", pTab->zName);
  84319. goto primary_key_exit;
  84320. }
  84321. pTab->tabFlags |= TF_HasPrimaryKey;
  84322. if( pList==0 ){
  84323. iCol = pTab->nCol - 1;
  84324. pTab->aCol[iCol].colFlags |= COLFLAG_PRIMKEY;
  84325. zType = pTab->aCol[iCol].zType;
  84326. nTerm = 1;
  84327. }else{
  84328. nTerm = pList->nExpr;
  84329. for(i=0; i<nTerm; i++){
  84330. for(iCol=0; iCol<pTab->nCol; iCol++){
  84331. if( sqlite3StrICmp(pList->a[i].zName, pTab->aCol[iCol].zName)==0 ){
  84332. pTab->aCol[iCol].colFlags |= COLFLAG_PRIMKEY;
  84333. zType = pTab->aCol[iCol].zType;
  84334. break;
  84335. }
  84336. }
  84337. }
  84338. }
  84339. if( nTerm==1
  84340. && zType && sqlite3StrICmp(zType, "INTEGER")==0
  84341. && sortOrder==SQLITE_SO_ASC
  84342. ){
  84343. pTab->iPKey = iCol;
  84344. pTab->keyConf = (u8)onError;
  84345. assert( autoInc==0 || autoInc==1 );
  84346. pTab->tabFlags |= autoInc*TF_Autoincrement;
  84347. if( pList ) pParse->iPkSortOrder = pList->a[0].sortOrder;
  84348. }else if( autoInc ){
  84349. #ifndef SQLITE_OMIT_AUTOINCREMENT
  84350. sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
  84351. "INTEGER PRIMARY KEY");
  84352. #endif
  84353. }else{
  84354. Vdbe *v = pParse->pVdbe;
  84355. Index *p;
  84356. if( v ) pParse->addrSkipPK = sqlite3VdbeAddOp0(v, OP_Noop);
  84357. p = sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0,
  84358. 0, sortOrder, 0);
  84359. if( p ){
  84360. p->idxType = SQLITE_IDXTYPE_PRIMARYKEY;
  84361. if( v ) sqlite3VdbeJumpHere(v, pParse->addrSkipPK);
  84362. }
  84363. pList = 0;
  84364. }
  84365. primary_key_exit:
  84366. sqlite3ExprListDelete(pParse->db, pList);
  84367. return;
  84368. }
  84369. /*
  84370. ** Add a new CHECK constraint to the table currently under construction.
  84371. */
  84372. SQLITE_PRIVATE void sqlite3AddCheckConstraint(
  84373. Parse *pParse, /* Parsing context */
  84374. Expr *pCheckExpr /* The check expression */
  84375. ){
  84376. #ifndef SQLITE_OMIT_CHECK
  84377. Table *pTab = pParse->pNewTable;
  84378. sqlite3 *db = pParse->db;
  84379. if( pTab && !IN_DECLARE_VTAB
  84380. && !sqlite3BtreeIsReadonly(db->aDb[db->init.iDb].pBt)
  84381. ){
  84382. pTab->pCheck = sqlite3ExprListAppend(pParse, pTab->pCheck, pCheckExpr);
  84383. if( pParse->constraintName.n ){
  84384. sqlite3ExprListSetName(pParse, pTab->pCheck, &pParse->constraintName, 1);
  84385. }
  84386. }else
  84387. #endif
  84388. {
  84389. sqlite3ExprDelete(pParse->db, pCheckExpr);
  84390. }
  84391. }
  84392. /*
  84393. ** Set the collation function of the most recently parsed table column
  84394. ** to the CollSeq given.
  84395. */
  84396. SQLITE_PRIVATE void sqlite3AddCollateType(Parse *pParse, Token *pToken){
  84397. Table *p;
  84398. int i;
  84399. char *zColl; /* Dequoted name of collation sequence */
  84400. sqlite3 *db;
  84401. if( (p = pParse->pNewTable)==0 ) return;
  84402. i = p->nCol-1;
  84403. db = pParse->db;
  84404. zColl = sqlite3NameFromToken(db, pToken);
  84405. if( !zColl ) return;
  84406. if( sqlite3LocateCollSeq(pParse, zColl) ){
  84407. Index *pIdx;
  84408. sqlite3DbFree(db, p->aCol[i].zColl);
  84409. p->aCol[i].zColl = zColl;
  84410. /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
  84411. ** then an index may have been created on this column before the
  84412. ** collation type was added. Correct this if it is the case.
  84413. */
  84414. for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
  84415. assert( pIdx->nKeyCol==1 );
  84416. if( pIdx->aiColumn[0]==i ){
  84417. pIdx->azColl[0] = p->aCol[i].zColl;
  84418. }
  84419. }
  84420. }else{
  84421. sqlite3DbFree(db, zColl);
  84422. }
  84423. }
  84424. /*
  84425. ** This function returns the collation sequence for database native text
  84426. ** encoding identified by the string zName, length nName.
  84427. **
  84428. ** If the requested collation sequence is not available, or not available
  84429. ** in the database native encoding, the collation factory is invoked to
  84430. ** request it. If the collation factory does not supply such a sequence,
  84431. ** and the sequence is available in another text encoding, then that is
  84432. ** returned instead.
  84433. **
  84434. ** If no versions of the requested collations sequence are available, or
  84435. ** another error occurs, NULL is returned and an error message written into
  84436. ** pParse.
  84437. **
  84438. ** This routine is a wrapper around sqlite3FindCollSeq(). This routine
  84439. ** invokes the collation factory if the named collation cannot be found
  84440. ** and generates an error message.
  84441. **
  84442. ** See also: sqlite3FindCollSeq(), sqlite3GetCollSeq()
  84443. */
  84444. SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName){
  84445. sqlite3 *db = pParse->db;
  84446. u8 enc = ENC(db);
  84447. u8 initbusy = db->init.busy;
  84448. CollSeq *pColl;
  84449. pColl = sqlite3FindCollSeq(db, enc, zName, initbusy);
  84450. if( !initbusy && (!pColl || !pColl->xCmp) ){
  84451. pColl = sqlite3GetCollSeq(pParse, enc, pColl, zName);
  84452. }
  84453. return pColl;
  84454. }
  84455. /*
  84456. ** Generate code that will increment the schema cookie.
  84457. **
  84458. ** The schema cookie is used to determine when the schema for the
  84459. ** database changes. After each schema change, the cookie value
  84460. ** changes. When a process first reads the schema it records the
  84461. ** cookie. Thereafter, whenever it goes to access the database,
  84462. ** it checks the cookie to make sure the schema has not changed
  84463. ** since it was last read.
  84464. **
  84465. ** This plan is not completely bullet-proof. It is possible for
  84466. ** the schema to change multiple times and for the cookie to be
  84467. ** set back to prior value. But schema changes are infrequent
  84468. ** and the probability of hitting the same cookie value is only
  84469. ** 1 chance in 2^32. So we're safe enough.
  84470. */
  84471. SQLITE_PRIVATE void sqlite3ChangeCookie(Parse *pParse, int iDb){
  84472. int r1 = sqlite3GetTempReg(pParse);
  84473. sqlite3 *db = pParse->db;
  84474. Vdbe *v = pParse->pVdbe;
  84475. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  84476. sqlite3VdbeAddOp2(v, OP_Integer, db->aDb[iDb].pSchema->schema_cookie+1, r1);
  84477. sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_SCHEMA_VERSION, r1);
  84478. sqlite3ReleaseTempReg(pParse, r1);
  84479. }
  84480. /*
  84481. ** Measure the number of characters needed to output the given
  84482. ** identifier. The number returned includes any quotes used
  84483. ** but does not include the null terminator.
  84484. **
  84485. ** The estimate is conservative. It might be larger that what is
  84486. ** really needed.
  84487. */
  84488. static int identLength(const char *z){
  84489. int n;
  84490. for(n=0; *z; n++, z++){
  84491. if( *z=='"' ){ n++; }
  84492. }
  84493. return n + 2;
  84494. }
  84495. /*
  84496. ** The first parameter is a pointer to an output buffer. The second
  84497. ** parameter is a pointer to an integer that contains the offset at
  84498. ** which to write into the output buffer. This function copies the
  84499. ** nul-terminated string pointed to by the third parameter, zSignedIdent,
  84500. ** to the specified offset in the buffer and updates *pIdx to refer
  84501. ** to the first byte after the last byte written before returning.
  84502. **
  84503. ** If the string zSignedIdent consists entirely of alpha-numeric
  84504. ** characters, does not begin with a digit and is not an SQL keyword,
  84505. ** then it is copied to the output buffer exactly as it is. Otherwise,
  84506. ** it is quoted using double-quotes.
  84507. */
  84508. static void identPut(char *z, int *pIdx, char *zSignedIdent){
  84509. unsigned char *zIdent = (unsigned char*)zSignedIdent;
  84510. int i, j, needQuote;
  84511. i = *pIdx;
  84512. for(j=0; zIdent[j]; j++){
  84513. if( !sqlite3Isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
  84514. }
  84515. needQuote = sqlite3Isdigit(zIdent[0])
  84516. || sqlite3KeywordCode(zIdent, j)!=TK_ID
  84517. || zIdent[j]!=0
  84518. || j==0;
  84519. if( needQuote ) z[i++] = '"';
  84520. for(j=0; zIdent[j]; j++){
  84521. z[i++] = zIdent[j];
  84522. if( zIdent[j]=='"' ) z[i++] = '"';
  84523. }
  84524. if( needQuote ) z[i++] = '"';
  84525. z[i] = 0;
  84526. *pIdx = i;
  84527. }
  84528. /*
  84529. ** Generate a CREATE TABLE statement appropriate for the given
  84530. ** table. Memory to hold the text of the statement is obtained
  84531. ** from sqliteMalloc() and must be freed by the calling function.
  84532. */
  84533. static char *createTableStmt(sqlite3 *db, Table *p){
  84534. int i, k, n;
  84535. char *zStmt;
  84536. char *zSep, *zSep2, *zEnd;
  84537. Column *pCol;
  84538. n = 0;
  84539. for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
  84540. n += identLength(pCol->zName) + 5;
  84541. }
  84542. n += identLength(p->zName);
  84543. if( n<50 ){
  84544. zSep = "";
  84545. zSep2 = ",";
  84546. zEnd = ")";
  84547. }else{
  84548. zSep = "\n ";
  84549. zSep2 = ",\n ";
  84550. zEnd = "\n)";
  84551. }
  84552. n += 35 + 6*p->nCol;
  84553. zStmt = sqlite3DbMallocRaw(0, n);
  84554. if( zStmt==0 ){
  84555. db->mallocFailed = 1;
  84556. return 0;
  84557. }
  84558. sqlite3_snprintf(n, zStmt, "CREATE TABLE ");
  84559. k = sqlite3Strlen30(zStmt);
  84560. identPut(zStmt, &k, p->zName);
  84561. zStmt[k++] = '(';
  84562. for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
  84563. static const char * const azType[] = {
  84564. /* SQLITE_AFF_NONE */ "",
  84565. /* SQLITE_AFF_TEXT */ " TEXT",
  84566. /* SQLITE_AFF_NUMERIC */ " NUM",
  84567. /* SQLITE_AFF_INTEGER */ " INT",
  84568. /* SQLITE_AFF_REAL */ " REAL"
  84569. };
  84570. int len;
  84571. const char *zType;
  84572. sqlite3_snprintf(n-k, &zStmt[k], zSep);
  84573. k += sqlite3Strlen30(&zStmt[k]);
  84574. zSep = zSep2;
  84575. identPut(zStmt, &k, pCol->zName);
  84576. assert( pCol->affinity-SQLITE_AFF_NONE >= 0 );
  84577. assert( pCol->affinity-SQLITE_AFF_NONE < ArraySize(azType) );
  84578. testcase( pCol->affinity==SQLITE_AFF_NONE );
  84579. testcase( pCol->affinity==SQLITE_AFF_TEXT );
  84580. testcase( pCol->affinity==SQLITE_AFF_NUMERIC );
  84581. testcase( pCol->affinity==SQLITE_AFF_INTEGER );
  84582. testcase( pCol->affinity==SQLITE_AFF_REAL );
  84583. zType = azType[pCol->affinity - SQLITE_AFF_NONE];
  84584. len = sqlite3Strlen30(zType);
  84585. assert( pCol->affinity==SQLITE_AFF_NONE
  84586. || pCol->affinity==sqlite3AffinityType(zType, 0) );
  84587. memcpy(&zStmt[k], zType, len);
  84588. k += len;
  84589. assert( k<=n );
  84590. }
  84591. sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd);
  84592. return zStmt;
  84593. }
  84594. /*
  84595. ** Resize an Index object to hold N columns total. Return SQLITE_OK
  84596. ** on success and SQLITE_NOMEM on an OOM error.
  84597. */
  84598. static int resizeIndexObject(sqlite3 *db, Index *pIdx, int N){
  84599. char *zExtra;
  84600. int nByte;
  84601. if( pIdx->nColumn>=N ) return SQLITE_OK;
  84602. assert( pIdx->isResized==0 );
  84603. nByte = (sizeof(char*) + sizeof(i16) + 1)*N;
  84604. zExtra = sqlite3DbMallocZero(db, nByte);
  84605. if( zExtra==0 ) return SQLITE_NOMEM;
  84606. memcpy(zExtra, pIdx->azColl, sizeof(char*)*pIdx->nColumn);
  84607. pIdx->azColl = (char**)zExtra;
  84608. zExtra += sizeof(char*)*N;
  84609. memcpy(zExtra, pIdx->aiColumn, sizeof(i16)*pIdx->nColumn);
  84610. pIdx->aiColumn = (i16*)zExtra;
  84611. zExtra += sizeof(i16)*N;
  84612. memcpy(zExtra, pIdx->aSortOrder, pIdx->nColumn);
  84613. pIdx->aSortOrder = (u8*)zExtra;
  84614. pIdx->nColumn = N;
  84615. pIdx->isResized = 1;
  84616. return SQLITE_OK;
  84617. }
  84618. /*
  84619. ** Estimate the total row width for a table.
  84620. */
  84621. static void estimateTableWidth(Table *pTab){
  84622. unsigned wTable = 0;
  84623. const Column *pTabCol;
  84624. int i;
  84625. for(i=pTab->nCol, pTabCol=pTab->aCol; i>0; i--, pTabCol++){
  84626. wTable += pTabCol->szEst;
  84627. }
  84628. if( pTab->iPKey<0 ) wTable++;
  84629. pTab->szTabRow = sqlite3LogEst(wTable*4);
  84630. }
  84631. /*
  84632. ** Estimate the average size of a row for an index.
  84633. */
  84634. static void estimateIndexWidth(Index *pIdx){
  84635. unsigned wIndex = 0;
  84636. int i;
  84637. const Column *aCol = pIdx->pTable->aCol;
  84638. for(i=0; i<pIdx->nColumn; i++){
  84639. i16 x = pIdx->aiColumn[i];
  84640. assert( x<pIdx->pTable->nCol );
  84641. wIndex += x<0 ? 1 : aCol[pIdx->aiColumn[i]].szEst;
  84642. }
  84643. pIdx->szIdxRow = sqlite3LogEst(wIndex*4);
  84644. }
  84645. /* Return true if value x is found any of the first nCol entries of aiCol[]
  84646. */
  84647. static int hasColumn(const i16 *aiCol, int nCol, int x){
  84648. while( nCol-- > 0 ) if( x==*(aiCol++) ) return 1;
  84649. return 0;
  84650. }
  84651. /*
  84652. ** This routine runs at the end of parsing a CREATE TABLE statement that
  84653. ** has a WITHOUT ROWID clause. The job of this routine is to convert both
  84654. ** internal schema data structures and the generated VDBE code so that they
  84655. ** are appropriate for a WITHOUT ROWID table instead of a rowid table.
  84656. ** Changes include:
  84657. **
  84658. ** (1) Convert the OP_CreateTable into an OP_CreateIndex. There is
  84659. ** no rowid btree for a WITHOUT ROWID. Instead, the canonical
  84660. ** data storage is a covering index btree.
  84661. ** (2) Bypass the creation of the sqlite_master table entry
  84662. ** for the PRIMARY KEY as the primary key index is now
  84663. ** identified by the sqlite_master table entry of the table itself.
  84664. ** (3) Set the Index.tnum of the PRIMARY KEY Index object in the
  84665. ** schema to the rootpage from the main table.
  84666. ** (4) Set all columns of the PRIMARY KEY schema object to be NOT NULL.
  84667. ** (5) Add all table columns to the PRIMARY KEY Index object
  84668. ** so that the PRIMARY KEY is a covering index. The surplus
  84669. ** columns are part of KeyInfo.nXField and are not used for
  84670. ** sorting or lookup or uniqueness checks.
  84671. ** (6) Replace the rowid tail on all automatically generated UNIQUE
  84672. ** indices with the PRIMARY KEY columns.
  84673. */
  84674. static void convertToWithoutRowidTable(Parse *pParse, Table *pTab){
  84675. Index *pIdx;
  84676. Index *pPk;
  84677. int nPk;
  84678. int i, j;
  84679. sqlite3 *db = pParse->db;
  84680. Vdbe *v = pParse->pVdbe;
  84681. /* Convert the OP_CreateTable opcode that would normally create the
  84682. ** root-page for the table into an OP_CreateIndex opcode. The index
  84683. ** created will become the PRIMARY KEY index.
  84684. */
  84685. if( pParse->addrCrTab ){
  84686. assert( v );
  84687. sqlite3VdbeGetOp(v, pParse->addrCrTab)->opcode = OP_CreateIndex;
  84688. }
  84689. /* Bypass the creation of the PRIMARY KEY btree and the sqlite_master
  84690. ** table entry.
  84691. */
  84692. if( pParse->addrSkipPK ){
  84693. assert( v );
  84694. sqlite3VdbeGetOp(v, pParse->addrSkipPK)->opcode = OP_Goto;
  84695. }
  84696. /* Locate the PRIMARY KEY index. Or, if this table was originally
  84697. ** an INTEGER PRIMARY KEY table, create a new PRIMARY KEY index.
  84698. */
  84699. if( pTab->iPKey>=0 ){
  84700. ExprList *pList;
  84701. pList = sqlite3ExprListAppend(pParse, 0, 0);
  84702. if( pList==0 ) return;
  84703. pList->a[0].zName = sqlite3DbStrDup(pParse->db,
  84704. pTab->aCol[pTab->iPKey].zName);
  84705. pList->a[0].sortOrder = pParse->iPkSortOrder;
  84706. assert( pParse->pNewTable==pTab );
  84707. pPk = sqlite3CreateIndex(pParse, 0, 0, 0, pList, pTab->keyConf, 0, 0, 0, 0);
  84708. if( pPk==0 ) return;
  84709. pPk->idxType = SQLITE_IDXTYPE_PRIMARYKEY;
  84710. pTab->iPKey = -1;
  84711. }else{
  84712. pPk = sqlite3PrimaryKeyIndex(pTab);
  84713. }
  84714. pPk->isCovering = 1;
  84715. assert( pPk!=0 );
  84716. nPk = pPk->nKeyCol;
  84717. /* Make sure every column of the PRIMARY KEY is NOT NULL */
  84718. for(i=0; i<nPk; i++){
  84719. pTab->aCol[pPk->aiColumn[i]].notNull = 1;
  84720. }
  84721. pPk->uniqNotNull = 1;
  84722. /* The root page of the PRIMARY KEY is the table root page */
  84723. pPk->tnum = pTab->tnum;
  84724. /* Update the in-memory representation of all UNIQUE indices by converting
  84725. ** the final rowid column into one or more columns of the PRIMARY KEY.
  84726. */
  84727. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  84728. int n;
  84729. if( IsPrimaryKeyIndex(pIdx) ) continue;
  84730. for(i=n=0; i<nPk; i++){
  84731. if( !hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) ) n++;
  84732. }
  84733. if( n==0 ){
  84734. /* This index is a superset of the primary key */
  84735. pIdx->nColumn = pIdx->nKeyCol;
  84736. continue;
  84737. }
  84738. if( resizeIndexObject(db, pIdx, pIdx->nKeyCol+n) ) return;
  84739. for(i=0, j=pIdx->nKeyCol; i<nPk; i++){
  84740. if( !hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) ){
  84741. pIdx->aiColumn[j] = pPk->aiColumn[i];
  84742. pIdx->azColl[j] = pPk->azColl[i];
  84743. j++;
  84744. }
  84745. }
  84746. assert( pIdx->nColumn>=pIdx->nKeyCol+n );
  84747. assert( pIdx->nColumn>=j );
  84748. }
  84749. /* Add all table columns to the PRIMARY KEY index
  84750. */
  84751. if( nPk<pTab->nCol ){
  84752. if( resizeIndexObject(db, pPk, pTab->nCol) ) return;
  84753. for(i=0, j=nPk; i<pTab->nCol; i++){
  84754. if( !hasColumn(pPk->aiColumn, j, i) ){
  84755. assert( j<pPk->nColumn );
  84756. pPk->aiColumn[j] = i;
  84757. pPk->azColl[j] = "BINARY";
  84758. j++;
  84759. }
  84760. }
  84761. assert( pPk->nColumn==j );
  84762. assert( pTab->nCol==j );
  84763. }else{
  84764. pPk->nColumn = pTab->nCol;
  84765. }
  84766. }
  84767. /*
  84768. ** This routine is called to report the final ")" that terminates
  84769. ** a CREATE TABLE statement.
  84770. **
  84771. ** The table structure that other action routines have been building
  84772. ** is added to the internal hash tables, assuming no errors have
  84773. ** occurred.
  84774. **
  84775. ** An entry for the table is made in the master table on disk, unless
  84776. ** this is a temporary table or db->init.busy==1. When db->init.busy==1
  84777. ** it means we are reading the sqlite_master table because we just
  84778. ** connected to the database or because the sqlite_master table has
  84779. ** recently changed, so the entry for this table already exists in
  84780. ** the sqlite_master table. We do not want to create it again.
  84781. **
  84782. ** If the pSelect argument is not NULL, it means that this routine
  84783. ** was called to create a table generated from a
  84784. ** "CREATE TABLE ... AS SELECT ..." statement. The column names of
  84785. ** the new table will match the result set of the SELECT.
  84786. */
  84787. SQLITE_PRIVATE void sqlite3EndTable(
  84788. Parse *pParse, /* Parse context */
  84789. Token *pCons, /* The ',' token after the last column defn. */
  84790. Token *pEnd, /* The ')' before options in the CREATE TABLE */
  84791. u8 tabOpts, /* Extra table options. Usually 0. */
  84792. Select *pSelect /* Select from a "CREATE ... AS SELECT" */
  84793. ){
  84794. Table *p; /* The new table */
  84795. sqlite3 *db = pParse->db; /* The database connection */
  84796. int iDb; /* Database in which the table lives */
  84797. Index *pIdx; /* An implied index of the table */
  84798. if( (pEnd==0 && pSelect==0) || db->mallocFailed ){
  84799. return;
  84800. }
  84801. p = pParse->pNewTable;
  84802. if( p==0 ) return;
  84803. assert( !db->init.busy || !pSelect );
  84804. /* If the db->init.busy is 1 it means we are reading the SQL off the
  84805. ** "sqlite_master" or "sqlite_temp_master" table on the disk.
  84806. ** So do not write to the disk again. Extract the root page number
  84807. ** for the table from the db->init.newTnum field. (The page number
  84808. ** should have been put there by the sqliteOpenCb routine.)
  84809. */
  84810. if( db->init.busy ){
  84811. p->tnum = db->init.newTnum;
  84812. }
  84813. /* Special processing for WITHOUT ROWID Tables */
  84814. if( tabOpts & TF_WithoutRowid ){
  84815. if( (p->tabFlags & TF_Autoincrement) ){
  84816. sqlite3ErrorMsg(pParse,
  84817. "AUTOINCREMENT not allowed on WITHOUT ROWID tables");
  84818. return;
  84819. }
  84820. if( (p->tabFlags & TF_HasPrimaryKey)==0 ){
  84821. sqlite3ErrorMsg(pParse, "PRIMARY KEY missing on table %s", p->zName);
  84822. }else{
  84823. p->tabFlags |= TF_WithoutRowid;
  84824. convertToWithoutRowidTable(pParse, p);
  84825. }
  84826. }
  84827. iDb = sqlite3SchemaToIndex(db, p->pSchema);
  84828. #ifndef SQLITE_OMIT_CHECK
  84829. /* Resolve names in all CHECK constraint expressions.
  84830. */
  84831. if( p->pCheck ){
  84832. sqlite3ResolveSelfReference(pParse, p, NC_IsCheck, 0, p->pCheck);
  84833. }
  84834. #endif /* !defined(SQLITE_OMIT_CHECK) */
  84835. /* Estimate the average row size for the table and for all implied indices */
  84836. estimateTableWidth(p);
  84837. for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
  84838. estimateIndexWidth(pIdx);
  84839. }
  84840. /* If not initializing, then create a record for the new table
  84841. ** in the SQLITE_MASTER table of the database.
  84842. **
  84843. ** If this is a TEMPORARY table, write the entry into the auxiliary
  84844. ** file instead of into the main database file.
  84845. */
  84846. if( !db->init.busy ){
  84847. int n;
  84848. Vdbe *v;
  84849. char *zType; /* "view" or "table" */
  84850. char *zType2; /* "VIEW" or "TABLE" */
  84851. char *zStmt; /* Text of the CREATE TABLE or CREATE VIEW statement */
  84852. v = sqlite3GetVdbe(pParse);
  84853. if( NEVER(v==0) ) return;
  84854. sqlite3VdbeAddOp1(v, OP_Close, 0);
  84855. /*
  84856. ** Initialize zType for the new view or table.
  84857. */
  84858. if( p->pSelect==0 ){
  84859. /* A regular table */
  84860. zType = "table";
  84861. zType2 = "TABLE";
  84862. #ifndef SQLITE_OMIT_VIEW
  84863. }else{
  84864. /* A view */
  84865. zType = "view";
  84866. zType2 = "VIEW";
  84867. #endif
  84868. }
  84869. /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
  84870. ** statement to populate the new table. The root-page number for the
  84871. ** new table is in register pParse->regRoot.
  84872. **
  84873. ** Once the SELECT has been coded by sqlite3Select(), it is in a
  84874. ** suitable state to query for the column names and types to be used
  84875. ** by the new table.
  84876. **
  84877. ** A shared-cache write-lock is not required to write to the new table,
  84878. ** as a schema-lock must have already been obtained to create it. Since
  84879. ** a schema-lock excludes all other database users, the write-lock would
  84880. ** be redundant.
  84881. */
  84882. if( pSelect ){
  84883. SelectDest dest;
  84884. Table *pSelTab;
  84885. assert(pParse->nTab==1);
  84886. sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb);
  84887. sqlite3VdbeChangeP5(v, OPFLAG_P2ISREG);
  84888. pParse->nTab = 2;
  84889. sqlite3SelectDestInit(&dest, SRT_Table, 1);
  84890. sqlite3Select(pParse, pSelect, &dest);
  84891. sqlite3VdbeAddOp1(v, OP_Close, 1);
  84892. if( pParse->nErr==0 ){
  84893. pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect);
  84894. if( pSelTab==0 ) return;
  84895. assert( p->aCol==0 );
  84896. p->nCol = pSelTab->nCol;
  84897. p->aCol = pSelTab->aCol;
  84898. pSelTab->nCol = 0;
  84899. pSelTab->aCol = 0;
  84900. sqlite3DeleteTable(db, pSelTab);
  84901. }
  84902. }
  84903. /* Compute the complete text of the CREATE statement */
  84904. if( pSelect ){
  84905. zStmt = createTableStmt(db, p);
  84906. }else{
  84907. Token *pEnd2 = tabOpts ? &pParse->sLastToken : pEnd;
  84908. n = (int)(pEnd2->z - pParse->sNameToken.z);
  84909. if( pEnd2->z[0]!=';' ) n += pEnd2->n;
  84910. zStmt = sqlite3MPrintf(db,
  84911. "CREATE %s %.*s", zType2, n, pParse->sNameToken.z
  84912. );
  84913. }
  84914. /* A slot for the record has already been allocated in the
  84915. ** SQLITE_MASTER table. We just need to update that slot with all
  84916. ** the information we've collected.
  84917. */
  84918. sqlite3NestedParse(pParse,
  84919. "UPDATE %Q.%s "
  84920. "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q "
  84921. "WHERE rowid=#%d",
  84922. db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
  84923. zType,
  84924. p->zName,
  84925. p->zName,
  84926. pParse->regRoot,
  84927. zStmt,
  84928. pParse->regRowid
  84929. );
  84930. sqlite3DbFree(db, zStmt);
  84931. sqlite3ChangeCookie(pParse, iDb);
  84932. #ifndef SQLITE_OMIT_AUTOINCREMENT
  84933. /* Check to see if we need to create an sqlite_sequence table for
  84934. ** keeping track of autoincrement keys.
  84935. */
  84936. if( p->tabFlags & TF_Autoincrement ){
  84937. Db *pDb = &db->aDb[iDb];
  84938. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  84939. if( pDb->pSchema->pSeqTab==0 ){
  84940. sqlite3NestedParse(pParse,
  84941. "CREATE TABLE %Q.sqlite_sequence(name,seq)",
  84942. pDb->zName
  84943. );
  84944. }
  84945. }
  84946. #endif
  84947. /* Reparse everything to update our internal data structures */
  84948. sqlite3VdbeAddParseSchemaOp(v, iDb,
  84949. sqlite3MPrintf(db, "tbl_name='%q' AND type!='trigger'", p->zName));
  84950. }
  84951. /* Add the table to the in-memory representation of the database.
  84952. */
  84953. if( db->init.busy ){
  84954. Table *pOld;
  84955. Schema *pSchema = p->pSchema;
  84956. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  84957. pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName, p);
  84958. if( pOld ){
  84959. assert( p==pOld ); /* Malloc must have failed inside HashInsert() */
  84960. db->mallocFailed = 1;
  84961. return;
  84962. }
  84963. pParse->pNewTable = 0;
  84964. db->flags |= SQLITE_InternChanges;
  84965. #ifndef SQLITE_OMIT_ALTERTABLE
  84966. if( !p->pSelect ){
  84967. const char *zName = (const char *)pParse->sNameToken.z;
  84968. int nName;
  84969. assert( !pSelect && pCons && pEnd );
  84970. if( pCons->z==0 ){
  84971. pCons = pEnd;
  84972. }
  84973. nName = (int)((const char *)pCons->z - zName);
  84974. p->addColOffset = 13 + sqlite3Utf8CharLen(zName, nName);
  84975. }
  84976. #endif
  84977. }
  84978. }
  84979. #ifndef SQLITE_OMIT_VIEW
  84980. /*
  84981. ** The parser calls this routine in order to create a new VIEW
  84982. */
  84983. SQLITE_PRIVATE void sqlite3CreateView(
  84984. Parse *pParse, /* The parsing context */
  84985. Token *pBegin, /* The CREATE token that begins the statement */
  84986. Token *pName1, /* The token that holds the name of the view */
  84987. Token *pName2, /* The token that holds the name of the view */
  84988. Select *pSelect, /* A SELECT statement that will become the new view */
  84989. int isTemp, /* TRUE for a TEMPORARY view */
  84990. int noErr /* Suppress error messages if VIEW already exists */
  84991. ){
  84992. Table *p;
  84993. int n;
  84994. const char *z;
  84995. Token sEnd;
  84996. DbFixer sFix;
  84997. Token *pName = 0;
  84998. int iDb;
  84999. sqlite3 *db = pParse->db;
  85000. if( pParse->nVar>0 ){
  85001. sqlite3ErrorMsg(pParse, "parameters are not allowed in views");
  85002. sqlite3SelectDelete(db, pSelect);
  85003. return;
  85004. }
  85005. sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr);
  85006. p = pParse->pNewTable;
  85007. if( p==0 || pParse->nErr ){
  85008. sqlite3SelectDelete(db, pSelect);
  85009. return;
  85010. }
  85011. sqlite3TwoPartName(pParse, pName1, pName2, &pName);
  85012. iDb = sqlite3SchemaToIndex(db, p->pSchema);
  85013. sqlite3FixInit(&sFix, pParse, iDb, "view", pName);
  85014. if( sqlite3FixSelect(&sFix, pSelect) ){
  85015. sqlite3SelectDelete(db, pSelect);
  85016. return;
  85017. }
  85018. /* Make a copy of the entire SELECT statement that defines the view.
  85019. ** This will force all the Expr.token.z values to be dynamically
  85020. ** allocated rather than point to the input string - which means that
  85021. ** they will persist after the current sqlite3_exec() call returns.
  85022. */
  85023. p->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
  85024. sqlite3SelectDelete(db, pSelect);
  85025. if( db->mallocFailed ){
  85026. return;
  85027. }
  85028. if( !db->init.busy ){
  85029. sqlite3ViewGetColumnNames(pParse, p);
  85030. }
  85031. /* Locate the end of the CREATE VIEW statement. Make sEnd point to
  85032. ** the end.
  85033. */
  85034. sEnd = pParse->sLastToken;
  85035. if( ALWAYS(sEnd.z[0]!=0) && sEnd.z[0]!=';' ){
  85036. sEnd.z += sEnd.n;
  85037. }
  85038. sEnd.n = 0;
  85039. n = (int)(sEnd.z - pBegin->z);
  85040. z = pBegin->z;
  85041. while( ALWAYS(n>0) && sqlite3Isspace(z[n-1]) ){ n--; }
  85042. sEnd.z = &z[n-1];
  85043. sEnd.n = 1;
  85044. /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */
  85045. sqlite3EndTable(pParse, 0, &sEnd, 0, 0);
  85046. return;
  85047. }
  85048. #endif /* SQLITE_OMIT_VIEW */
  85049. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
  85050. /*
  85051. ** The Table structure pTable is really a VIEW. Fill in the names of
  85052. ** the columns of the view in the pTable structure. Return the number
  85053. ** of errors. If an error is seen leave an error message in pParse->zErrMsg.
  85054. */
  85055. SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
  85056. Table *pSelTab; /* A fake table from which we get the result set */
  85057. Select *pSel; /* Copy of the SELECT that implements the view */
  85058. int nErr = 0; /* Number of errors encountered */
  85059. int n; /* Temporarily holds the number of cursors assigned */
  85060. sqlite3 *db = pParse->db; /* Database connection for malloc errors */
  85061. sqlite3_xauth xAuth; /* Saved xAuth pointer */
  85062. assert( pTable );
  85063. #ifndef SQLITE_OMIT_VIRTUALTABLE
  85064. if( sqlite3VtabCallConnect(pParse, pTable) ){
  85065. return SQLITE_ERROR;
  85066. }
  85067. if( IsVirtual(pTable) ) return 0;
  85068. #endif
  85069. #ifndef SQLITE_OMIT_VIEW
  85070. /* A positive nCol means the columns names for this view are
  85071. ** already known.
  85072. */
  85073. if( pTable->nCol>0 ) return 0;
  85074. /* A negative nCol is a special marker meaning that we are currently
  85075. ** trying to compute the column names. If we enter this routine with
  85076. ** a negative nCol, it means two or more views form a loop, like this:
  85077. **
  85078. ** CREATE VIEW one AS SELECT * FROM two;
  85079. ** CREATE VIEW two AS SELECT * FROM one;
  85080. **
  85081. ** Actually, the error above is now caught prior to reaching this point.
  85082. ** But the following test is still important as it does come up
  85083. ** in the following:
  85084. **
  85085. ** CREATE TABLE main.ex1(a);
  85086. ** CREATE TEMP VIEW ex1 AS SELECT a FROM ex1;
  85087. ** SELECT * FROM temp.ex1;
  85088. */
  85089. if( pTable->nCol<0 ){
  85090. sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
  85091. return 1;
  85092. }
  85093. assert( pTable->nCol>=0 );
  85094. /* If we get this far, it means we need to compute the table names.
  85095. ** Note that the call to sqlite3ResultSetOfSelect() will expand any
  85096. ** "*" elements in the results set of the view and will assign cursors
  85097. ** to the elements of the FROM clause. But we do not want these changes
  85098. ** to be permanent. So the computation is done on a copy of the SELECT
  85099. ** statement that defines the view.
  85100. */
  85101. assert( pTable->pSelect );
  85102. pSel = sqlite3SelectDup(db, pTable->pSelect, 0);
  85103. if( pSel ){
  85104. u8 enableLookaside = db->lookaside.bEnabled;
  85105. n = pParse->nTab;
  85106. sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
  85107. pTable->nCol = -1;
  85108. db->lookaside.bEnabled = 0;
  85109. #ifndef SQLITE_OMIT_AUTHORIZATION
  85110. xAuth = db->xAuth;
  85111. db->xAuth = 0;
  85112. pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
  85113. db->xAuth = xAuth;
  85114. #else
  85115. pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
  85116. #endif
  85117. db->lookaside.bEnabled = enableLookaside;
  85118. pParse->nTab = n;
  85119. if( pSelTab ){
  85120. assert( pTable->aCol==0 );
  85121. pTable->nCol = pSelTab->nCol;
  85122. pTable->aCol = pSelTab->aCol;
  85123. pSelTab->nCol = 0;
  85124. pSelTab->aCol = 0;
  85125. sqlite3DeleteTable(db, pSelTab);
  85126. assert( sqlite3SchemaMutexHeld(db, 0, pTable->pSchema) );
  85127. pTable->pSchema->schemaFlags |= DB_UnresetViews;
  85128. }else{
  85129. pTable->nCol = 0;
  85130. nErr++;
  85131. }
  85132. sqlite3SelectDelete(db, pSel);
  85133. } else {
  85134. nErr++;
  85135. }
  85136. #endif /* SQLITE_OMIT_VIEW */
  85137. return nErr;
  85138. }
  85139. #endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
  85140. #ifndef SQLITE_OMIT_VIEW
  85141. /*
  85142. ** Clear the column names from every VIEW in database idx.
  85143. */
  85144. static void sqliteViewResetAll(sqlite3 *db, int idx){
  85145. HashElem *i;
  85146. assert( sqlite3SchemaMutexHeld(db, idx, 0) );
  85147. if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
  85148. for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
  85149. Table *pTab = sqliteHashData(i);
  85150. if( pTab->pSelect ){
  85151. sqliteDeleteColumnNames(db, pTab);
  85152. pTab->aCol = 0;
  85153. pTab->nCol = 0;
  85154. }
  85155. }
  85156. DbClearProperty(db, idx, DB_UnresetViews);
  85157. }
  85158. #else
  85159. # define sqliteViewResetAll(A,B)
  85160. #endif /* SQLITE_OMIT_VIEW */
  85161. /*
  85162. ** This function is called by the VDBE to adjust the internal schema
  85163. ** used by SQLite when the btree layer moves a table root page. The
  85164. ** root-page of a table or index in database iDb has changed from iFrom
  85165. ** to iTo.
  85166. **
  85167. ** Ticket #1728: The symbol table might still contain information
  85168. ** on tables and/or indices that are the process of being deleted.
  85169. ** If you are unlucky, one of those deleted indices or tables might
  85170. ** have the same rootpage number as the real table or index that is
  85171. ** being moved. So we cannot stop searching after the first match
  85172. ** because the first match might be for one of the deleted indices
  85173. ** or tables and not the table/index that is actually being moved.
  85174. ** We must continue looping until all tables and indices with
  85175. ** rootpage==iFrom have been converted to have a rootpage of iTo
  85176. ** in order to be certain that we got the right one.
  85177. */
  85178. #ifndef SQLITE_OMIT_AUTOVACUUM
  85179. SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3 *db, int iDb, int iFrom, int iTo){
  85180. HashElem *pElem;
  85181. Hash *pHash;
  85182. Db *pDb;
  85183. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  85184. pDb = &db->aDb[iDb];
  85185. pHash = &pDb->pSchema->tblHash;
  85186. for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
  85187. Table *pTab = sqliteHashData(pElem);
  85188. if( pTab->tnum==iFrom ){
  85189. pTab->tnum = iTo;
  85190. }
  85191. }
  85192. pHash = &pDb->pSchema->idxHash;
  85193. for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
  85194. Index *pIdx = sqliteHashData(pElem);
  85195. if( pIdx->tnum==iFrom ){
  85196. pIdx->tnum = iTo;
  85197. }
  85198. }
  85199. }
  85200. #endif
  85201. /*
  85202. ** Write code to erase the table with root-page iTable from database iDb.
  85203. ** Also write code to modify the sqlite_master table and internal schema
  85204. ** if a root-page of another table is moved by the btree-layer whilst
  85205. ** erasing iTable (this can happen with an auto-vacuum database).
  85206. */
  85207. static void destroyRootPage(Parse *pParse, int iTable, int iDb){
  85208. Vdbe *v = sqlite3GetVdbe(pParse);
  85209. int r1 = sqlite3GetTempReg(pParse);
  85210. sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb);
  85211. sqlite3MayAbort(pParse);
  85212. #ifndef SQLITE_OMIT_AUTOVACUUM
  85213. /* OP_Destroy stores an in integer r1. If this integer
  85214. ** is non-zero, then it is the root page number of a table moved to
  85215. ** location iTable. The following code modifies the sqlite_master table to
  85216. ** reflect this.
  85217. **
  85218. ** The "#NNN" in the SQL is a special constant that means whatever value
  85219. ** is in register NNN. See grammar rules associated with the TK_REGISTER
  85220. ** token for additional information.
  85221. */
  85222. sqlite3NestedParse(pParse,
  85223. "UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d",
  85224. pParse->db->aDb[iDb].zName, SCHEMA_TABLE(iDb), iTable, r1, r1);
  85225. #endif
  85226. sqlite3ReleaseTempReg(pParse, r1);
  85227. }
  85228. /*
  85229. ** Write VDBE code to erase table pTab and all associated indices on disk.
  85230. ** Code to update the sqlite_master tables and internal schema definitions
  85231. ** in case a root-page belonging to another table is moved by the btree layer
  85232. ** is also added (this can happen with an auto-vacuum database).
  85233. */
  85234. static void destroyTable(Parse *pParse, Table *pTab){
  85235. #ifdef SQLITE_OMIT_AUTOVACUUM
  85236. Index *pIdx;
  85237. int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  85238. destroyRootPage(pParse, pTab->tnum, iDb);
  85239. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  85240. destroyRootPage(pParse, pIdx->tnum, iDb);
  85241. }
  85242. #else
  85243. /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
  85244. ** is not defined), then it is important to call OP_Destroy on the
  85245. ** table and index root-pages in order, starting with the numerically
  85246. ** largest root-page number. This guarantees that none of the root-pages
  85247. ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
  85248. ** following were coded:
  85249. **
  85250. ** OP_Destroy 4 0
  85251. ** ...
  85252. ** OP_Destroy 5 0
  85253. **
  85254. ** and root page 5 happened to be the largest root-page number in the
  85255. ** database, then root page 5 would be moved to page 4 by the
  85256. ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
  85257. ** a free-list page.
  85258. */
  85259. int iTab = pTab->tnum;
  85260. int iDestroyed = 0;
  85261. while( 1 ){
  85262. Index *pIdx;
  85263. int iLargest = 0;
  85264. if( iDestroyed==0 || iTab<iDestroyed ){
  85265. iLargest = iTab;
  85266. }
  85267. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  85268. int iIdx = pIdx->tnum;
  85269. assert( pIdx->pSchema==pTab->pSchema );
  85270. if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
  85271. iLargest = iIdx;
  85272. }
  85273. }
  85274. if( iLargest==0 ){
  85275. return;
  85276. }else{
  85277. int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  85278. assert( iDb>=0 && iDb<pParse->db->nDb );
  85279. destroyRootPage(pParse, iLargest, iDb);
  85280. iDestroyed = iLargest;
  85281. }
  85282. }
  85283. #endif
  85284. }
  85285. /*
  85286. ** Remove entries from the sqlite_statN tables (for N in (1,2,3))
  85287. ** after a DROP INDEX or DROP TABLE command.
  85288. */
  85289. static void sqlite3ClearStatTables(
  85290. Parse *pParse, /* The parsing context */
  85291. int iDb, /* The database number */
  85292. const char *zType, /* "idx" or "tbl" */
  85293. const char *zName /* Name of index or table */
  85294. ){
  85295. int i;
  85296. const char *zDbName = pParse->db->aDb[iDb].zName;
  85297. for(i=1; i<=4; i++){
  85298. char zTab[24];
  85299. sqlite3_snprintf(sizeof(zTab),zTab,"sqlite_stat%d",i);
  85300. if( sqlite3FindTable(pParse->db, zTab, zDbName) ){
  85301. sqlite3NestedParse(pParse,
  85302. "DELETE FROM %Q.%s WHERE %s=%Q",
  85303. zDbName, zTab, zType, zName
  85304. );
  85305. }
  85306. }
  85307. }
  85308. /*
  85309. ** Generate code to drop a table.
  85310. */
  85311. SQLITE_PRIVATE void sqlite3CodeDropTable(Parse *pParse, Table *pTab, int iDb, int isView){
  85312. Vdbe *v;
  85313. sqlite3 *db = pParse->db;
  85314. Trigger *pTrigger;
  85315. Db *pDb = &db->aDb[iDb];
  85316. v = sqlite3GetVdbe(pParse);
  85317. assert( v!=0 );
  85318. sqlite3BeginWriteOperation(pParse, 1, iDb);
  85319. #ifndef SQLITE_OMIT_VIRTUALTABLE
  85320. if( IsVirtual(pTab) ){
  85321. sqlite3VdbeAddOp0(v, OP_VBegin);
  85322. }
  85323. #endif
  85324. /* Drop all triggers associated with the table being dropped. Code
  85325. ** is generated to remove entries from sqlite_master and/or
  85326. ** sqlite_temp_master if required.
  85327. */
  85328. pTrigger = sqlite3TriggerList(pParse, pTab);
  85329. while( pTrigger ){
  85330. assert( pTrigger->pSchema==pTab->pSchema ||
  85331. pTrigger->pSchema==db->aDb[1].pSchema );
  85332. sqlite3DropTriggerPtr(pParse, pTrigger);
  85333. pTrigger = pTrigger->pNext;
  85334. }
  85335. #ifndef SQLITE_OMIT_AUTOINCREMENT
  85336. /* Remove any entries of the sqlite_sequence table associated with
  85337. ** the table being dropped. This is done before the table is dropped
  85338. ** at the btree level, in case the sqlite_sequence table needs to
  85339. ** move as a result of the drop (can happen in auto-vacuum mode).
  85340. */
  85341. if( pTab->tabFlags & TF_Autoincrement ){
  85342. sqlite3NestedParse(pParse,
  85343. "DELETE FROM %Q.sqlite_sequence WHERE name=%Q",
  85344. pDb->zName, pTab->zName
  85345. );
  85346. }
  85347. #endif
  85348. /* Drop all SQLITE_MASTER table and index entries that refer to the
  85349. ** table. The program name loops through the master table and deletes
  85350. ** every row that refers to a table of the same name as the one being
  85351. ** dropped. Triggers are handled separately because a trigger can be
  85352. ** created in the temp database that refers to a table in another
  85353. ** database.
  85354. */
  85355. sqlite3NestedParse(pParse,
  85356. "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'",
  85357. pDb->zName, SCHEMA_TABLE(iDb), pTab->zName);
  85358. if( !isView && !IsVirtual(pTab) ){
  85359. destroyTable(pParse, pTab);
  85360. }
  85361. /* Remove the table entry from SQLite's internal schema and modify
  85362. ** the schema cookie.
  85363. */
  85364. if( IsVirtual(pTab) ){
  85365. sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0);
  85366. }
  85367. sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
  85368. sqlite3ChangeCookie(pParse, iDb);
  85369. sqliteViewResetAll(db, iDb);
  85370. }
  85371. /*
  85372. ** This routine is called to do the work of a DROP TABLE statement.
  85373. ** pName is the name of the table to be dropped.
  85374. */
  85375. SQLITE_PRIVATE void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
  85376. Table *pTab;
  85377. Vdbe *v;
  85378. sqlite3 *db = pParse->db;
  85379. int iDb;
  85380. if( db->mallocFailed ){
  85381. goto exit_drop_table;
  85382. }
  85383. assert( pParse->nErr==0 );
  85384. assert( pName->nSrc==1 );
  85385. if( noErr ) db->suppressErr++;
  85386. pTab = sqlite3LocateTableItem(pParse, isView, &pName->a[0]);
  85387. if( noErr ) db->suppressErr--;
  85388. if( pTab==0 ){
  85389. if( noErr ) sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
  85390. goto exit_drop_table;
  85391. }
  85392. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  85393. assert( iDb>=0 && iDb<db->nDb );
  85394. /* If pTab is a virtual table, call ViewGetColumnNames() to ensure
  85395. ** it is initialized.
  85396. */
  85397. if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){
  85398. goto exit_drop_table;
  85399. }
  85400. #ifndef SQLITE_OMIT_AUTHORIZATION
  85401. {
  85402. int code;
  85403. const char *zTab = SCHEMA_TABLE(iDb);
  85404. const char *zDb = db->aDb[iDb].zName;
  85405. const char *zArg2 = 0;
  85406. if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
  85407. goto exit_drop_table;
  85408. }
  85409. if( isView ){
  85410. if( !OMIT_TEMPDB && iDb==1 ){
  85411. code = SQLITE_DROP_TEMP_VIEW;
  85412. }else{
  85413. code = SQLITE_DROP_VIEW;
  85414. }
  85415. #ifndef SQLITE_OMIT_VIRTUALTABLE
  85416. }else if( IsVirtual(pTab) ){
  85417. code = SQLITE_DROP_VTABLE;
  85418. zArg2 = sqlite3GetVTable(db, pTab)->pMod->zName;
  85419. #endif
  85420. }else{
  85421. if( !OMIT_TEMPDB && iDb==1 ){
  85422. code = SQLITE_DROP_TEMP_TABLE;
  85423. }else{
  85424. code = SQLITE_DROP_TABLE;
  85425. }
  85426. }
  85427. if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){
  85428. goto exit_drop_table;
  85429. }
  85430. if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
  85431. goto exit_drop_table;
  85432. }
  85433. }
  85434. #endif
  85435. if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
  85436. && sqlite3StrNICmp(pTab->zName, "sqlite_stat", 11)!=0 ){
  85437. sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
  85438. goto exit_drop_table;
  85439. }
  85440. #ifndef SQLITE_OMIT_VIEW
  85441. /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
  85442. ** on a table.
  85443. */
  85444. if( isView && pTab->pSelect==0 ){
  85445. sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
  85446. goto exit_drop_table;
  85447. }
  85448. if( !isView && pTab->pSelect ){
  85449. sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
  85450. goto exit_drop_table;
  85451. }
  85452. #endif
  85453. /* Generate code to remove the table from the master table
  85454. ** on disk.
  85455. */
  85456. v = sqlite3GetVdbe(pParse);
  85457. if( v ){
  85458. sqlite3BeginWriteOperation(pParse, 1, iDb);
  85459. sqlite3ClearStatTables(pParse, iDb, "tbl", pTab->zName);
  85460. sqlite3FkDropTable(pParse, pName, pTab);
  85461. sqlite3CodeDropTable(pParse, pTab, iDb, isView);
  85462. }
  85463. exit_drop_table:
  85464. sqlite3SrcListDelete(db, pName);
  85465. }
  85466. /*
  85467. ** This routine is called to create a new foreign key on the table
  85468. ** currently under construction. pFromCol determines which columns
  85469. ** in the current table point to the foreign key. If pFromCol==0 then
  85470. ** connect the key to the last column inserted. pTo is the name of
  85471. ** the table referred to (a.k.a the "parent" table). pToCol is a list
  85472. ** of tables in the parent pTo table. flags contains all
  85473. ** information about the conflict resolution algorithms specified
  85474. ** in the ON DELETE, ON UPDATE and ON INSERT clauses.
  85475. **
  85476. ** An FKey structure is created and added to the table currently
  85477. ** under construction in the pParse->pNewTable field.
  85478. **
  85479. ** The foreign key is set for IMMEDIATE processing. A subsequent call
  85480. ** to sqlite3DeferForeignKey() might change this to DEFERRED.
  85481. */
  85482. SQLITE_PRIVATE void sqlite3CreateForeignKey(
  85483. Parse *pParse, /* Parsing context */
  85484. ExprList *pFromCol, /* Columns in this table that point to other table */
  85485. Token *pTo, /* Name of the other table */
  85486. ExprList *pToCol, /* Columns in the other table */
  85487. int flags /* Conflict resolution algorithms. */
  85488. ){
  85489. sqlite3 *db = pParse->db;
  85490. #ifndef SQLITE_OMIT_FOREIGN_KEY
  85491. FKey *pFKey = 0;
  85492. FKey *pNextTo;
  85493. Table *p = pParse->pNewTable;
  85494. int nByte;
  85495. int i;
  85496. int nCol;
  85497. char *z;
  85498. assert( pTo!=0 );
  85499. if( p==0 || IN_DECLARE_VTAB ) goto fk_end;
  85500. if( pFromCol==0 ){
  85501. int iCol = p->nCol-1;
  85502. if( NEVER(iCol<0) ) goto fk_end;
  85503. if( pToCol && pToCol->nExpr!=1 ){
  85504. sqlite3ErrorMsg(pParse, "foreign key on %s"
  85505. " should reference only one column of table %T",
  85506. p->aCol[iCol].zName, pTo);
  85507. goto fk_end;
  85508. }
  85509. nCol = 1;
  85510. }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
  85511. sqlite3ErrorMsg(pParse,
  85512. "number of columns in foreign key does not match the number of "
  85513. "columns in the referenced table");
  85514. goto fk_end;
  85515. }else{
  85516. nCol = pFromCol->nExpr;
  85517. }
  85518. nByte = sizeof(*pFKey) + (nCol-1)*sizeof(pFKey->aCol[0]) + pTo->n + 1;
  85519. if( pToCol ){
  85520. for(i=0; i<pToCol->nExpr; i++){
  85521. nByte += sqlite3Strlen30(pToCol->a[i].zName) + 1;
  85522. }
  85523. }
  85524. pFKey = sqlite3DbMallocZero(db, nByte );
  85525. if( pFKey==0 ){
  85526. goto fk_end;
  85527. }
  85528. pFKey->pFrom = p;
  85529. pFKey->pNextFrom = p->pFKey;
  85530. z = (char*)&pFKey->aCol[nCol];
  85531. pFKey->zTo = z;
  85532. memcpy(z, pTo->z, pTo->n);
  85533. z[pTo->n] = 0;
  85534. sqlite3Dequote(z);
  85535. z += pTo->n+1;
  85536. pFKey->nCol = nCol;
  85537. if( pFromCol==0 ){
  85538. pFKey->aCol[0].iFrom = p->nCol-1;
  85539. }else{
  85540. for(i=0; i<nCol; i++){
  85541. int j;
  85542. for(j=0; j<p->nCol; j++){
  85543. if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){
  85544. pFKey->aCol[i].iFrom = j;
  85545. break;
  85546. }
  85547. }
  85548. if( j>=p->nCol ){
  85549. sqlite3ErrorMsg(pParse,
  85550. "unknown column \"%s\" in foreign key definition",
  85551. pFromCol->a[i].zName);
  85552. goto fk_end;
  85553. }
  85554. }
  85555. }
  85556. if( pToCol ){
  85557. for(i=0; i<nCol; i++){
  85558. int n = sqlite3Strlen30(pToCol->a[i].zName);
  85559. pFKey->aCol[i].zCol = z;
  85560. memcpy(z, pToCol->a[i].zName, n);
  85561. z[n] = 0;
  85562. z += n+1;
  85563. }
  85564. }
  85565. pFKey->isDeferred = 0;
  85566. pFKey->aAction[0] = (u8)(flags & 0xff); /* ON DELETE action */
  85567. pFKey->aAction[1] = (u8)((flags >> 8 ) & 0xff); /* ON UPDATE action */
  85568. assert( sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
  85569. pNextTo = (FKey *)sqlite3HashInsert(&p->pSchema->fkeyHash,
  85570. pFKey->zTo, (void *)pFKey
  85571. );
  85572. if( pNextTo==pFKey ){
  85573. db->mallocFailed = 1;
  85574. goto fk_end;
  85575. }
  85576. if( pNextTo ){
  85577. assert( pNextTo->pPrevTo==0 );
  85578. pFKey->pNextTo = pNextTo;
  85579. pNextTo->pPrevTo = pFKey;
  85580. }
  85581. /* Link the foreign key to the table as the last step.
  85582. */
  85583. p->pFKey = pFKey;
  85584. pFKey = 0;
  85585. fk_end:
  85586. sqlite3DbFree(db, pFKey);
  85587. #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
  85588. sqlite3ExprListDelete(db, pFromCol);
  85589. sqlite3ExprListDelete(db, pToCol);
  85590. }
  85591. /*
  85592. ** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
  85593. ** clause is seen as part of a foreign key definition. The isDeferred
  85594. ** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
  85595. ** The behavior of the most recently created foreign key is adjusted
  85596. ** accordingly.
  85597. */
  85598. SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
  85599. #ifndef SQLITE_OMIT_FOREIGN_KEY
  85600. Table *pTab;
  85601. FKey *pFKey;
  85602. if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
  85603. assert( isDeferred==0 || isDeferred==1 ); /* EV: R-30323-21917 */
  85604. pFKey->isDeferred = (u8)isDeferred;
  85605. #endif
  85606. }
  85607. /*
  85608. ** Generate code that will erase and refill index *pIdx. This is
  85609. ** used to initialize a newly created index or to recompute the
  85610. ** content of an index in response to a REINDEX command.
  85611. **
  85612. ** if memRootPage is not negative, it means that the index is newly
  85613. ** created. The register specified by memRootPage contains the
  85614. ** root page number of the index. If memRootPage is negative, then
  85615. ** the index already exists and must be cleared before being refilled and
  85616. ** the root page number of the index is taken from pIndex->tnum.
  85617. */
  85618. static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
  85619. Table *pTab = pIndex->pTable; /* The table that is indexed */
  85620. int iTab = pParse->nTab++; /* Btree cursor used for pTab */
  85621. int iIdx = pParse->nTab++; /* Btree cursor used for pIndex */
  85622. int iSorter; /* Cursor opened by OpenSorter (if in use) */
  85623. int addr1; /* Address of top of loop */
  85624. int addr2; /* Address to jump to for next iteration */
  85625. int tnum; /* Root page of index */
  85626. int iPartIdxLabel; /* Jump to this label to skip a row */
  85627. Vdbe *v; /* Generate code into this virtual machine */
  85628. KeyInfo *pKey; /* KeyInfo for index */
  85629. int regRecord; /* Register holding assembled index record */
  85630. sqlite3 *db = pParse->db; /* The database connection */
  85631. int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
  85632. #ifndef SQLITE_OMIT_AUTHORIZATION
  85633. if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
  85634. db->aDb[iDb].zName ) ){
  85635. return;
  85636. }
  85637. #endif
  85638. /* Require a write-lock on the table to perform this operation */
  85639. sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
  85640. v = sqlite3GetVdbe(pParse);
  85641. if( v==0 ) return;
  85642. if( memRootPage>=0 ){
  85643. tnum = memRootPage;
  85644. }else{
  85645. tnum = pIndex->tnum;
  85646. }
  85647. pKey = sqlite3KeyInfoOfIndex(pParse, pIndex);
  85648. /* Open the sorter cursor if we are to use one. */
  85649. iSorter = pParse->nTab++;
  85650. sqlite3VdbeAddOp4(v, OP_SorterOpen, iSorter, 0, pIndex->nKeyCol, (char*)
  85651. sqlite3KeyInfoRef(pKey), P4_KEYINFO);
  85652. /* Open the table. Loop through all rows of the table, inserting index
  85653. ** records into the sorter. */
  85654. sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
  85655. addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0); VdbeCoverage(v);
  85656. regRecord = sqlite3GetTempReg(pParse);
  85657. sqlite3GenerateIndexKey(pParse,pIndex,iTab,regRecord,0,&iPartIdxLabel,0,0);
  85658. sqlite3VdbeAddOp2(v, OP_SorterInsert, iSorter, regRecord);
  85659. sqlite3ResolvePartIdxLabel(pParse, iPartIdxLabel);
  85660. sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1); VdbeCoverage(v);
  85661. sqlite3VdbeJumpHere(v, addr1);
  85662. if( memRootPage<0 ) sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb);
  85663. sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb,
  85664. (char *)pKey, P4_KEYINFO);
  85665. sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR|((memRootPage>=0)?OPFLAG_P2ISREG:0));
  85666. addr1 = sqlite3VdbeAddOp2(v, OP_SorterSort, iSorter, 0); VdbeCoverage(v);
  85667. assert( pKey!=0 || db->mallocFailed || pParse->nErr );
  85668. if( IsUniqueIndex(pIndex) && pKey!=0 ){
  85669. int j2 = sqlite3VdbeCurrentAddr(v) + 3;
  85670. sqlite3VdbeAddOp2(v, OP_Goto, 0, j2);
  85671. addr2 = sqlite3VdbeCurrentAddr(v);
  85672. sqlite3VdbeAddOp4Int(v, OP_SorterCompare, iSorter, j2, regRecord,
  85673. pIndex->nKeyCol); VdbeCoverage(v);
  85674. sqlite3UniqueConstraint(pParse, OE_Abort, pIndex);
  85675. }else{
  85676. addr2 = sqlite3VdbeCurrentAddr(v);
  85677. }
  85678. sqlite3VdbeAddOp3(v, OP_SorterData, iSorter, regRecord, iIdx);
  85679. sqlite3VdbeAddOp3(v, OP_IdxInsert, iIdx, regRecord, 1);
  85680. sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
  85681. sqlite3ReleaseTempReg(pParse, regRecord);
  85682. sqlite3VdbeAddOp2(v, OP_SorterNext, iSorter, addr2); VdbeCoverage(v);
  85683. sqlite3VdbeJumpHere(v, addr1);
  85684. sqlite3VdbeAddOp1(v, OP_Close, iTab);
  85685. sqlite3VdbeAddOp1(v, OP_Close, iIdx);
  85686. sqlite3VdbeAddOp1(v, OP_Close, iSorter);
  85687. }
  85688. /*
  85689. ** Allocate heap space to hold an Index object with nCol columns.
  85690. **
  85691. ** Increase the allocation size to provide an extra nExtra bytes
  85692. ** of 8-byte aligned space after the Index object and return a
  85693. ** pointer to this extra space in *ppExtra.
  85694. */
  85695. SQLITE_PRIVATE Index *sqlite3AllocateIndexObject(
  85696. sqlite3 *db, /* Database connection */
  85697. i16 nCol, /* Total number of columns in the index */
  85698. int nExtra, /* Number of bytes of extra space to alloc */
  85699. char **ppExtra /* Pointer to the "extra" space */
  85700. ){
  85701. Index *p; /* Allocated index object */
  85702. int nByte; /* Bytes of space for Index object + arrays */
  85703. nByte = ROUND8(sizeof(Index)) + /* Index structure */
  85704. ROUND8(sizeof(char*)*nCol) + /* Index.azColl */
  85705. ROUND8(sizeof(LogEst)*(nCol+1) + /* Index.aiRowLogEst */
  85706. sizeof(i16)*nCol + /* Index.aiColumn */
  85707. sizeof(u8)*nCol); /* Index.aSortOrder */
  85708. p = sqlite3DbMallocZero(db, nByte + nExtra);
  85709. if( p ){
  85710. char *pExtra = ((char*)p)+ROUND8(sizeof(Index));
  85711. p->azColl = (char**)pExtra; pExtra += ROUND8(sizeof(char*)*nCol);
  85712. p->aiRowLogEst = (LogEst*)pExtra; pExtra += sizeof(LogEst)*(nCol+1);
  85713. p->aiColumn = (i16*)pExtra; pExtra += sizeof(i16)*nCol;
  85714. p->aSortOrder = (u8*)pExtra;
  85715. p->nColumn = nCol;
  85716. p->nKeyCol = nCol - 1;
  85717. *ppExtra = ((char*)p) + nByte;
  85718. }
  85719. return p;
  85720. }
  85721. /*
  85722. ** Create a new index for an SQL table. pName1.pName2 is the name of the index
  85723. ** and pTblList is the name of the table that is to be indexed. Both will
  85724. ** be NULL for a primary key or an index that is created to satisfy a
  85725. ** UNIQUE constraint. If pTable and pIndex are NULL, use pParse->pNewTable
  85726. ** as the table to be indexed. pParse->pNewTable is a table that is
  85727. ** currently being constructed by a CREATE TABLE statement.
  85728. **
  85729. ** pList is a list of columns to be indexed. pList will be NULL if this
  85730. ** is a primary key or unique-constraint on the most recent column added
  85731. ** to the table currently under construction.
  85732. **
  85733. ** If the index is created successfully, return a pointer to the new Index
  85734. ** structure. This is used by sqlite3AddPrimaryKey() to mark the index
  85735. ** as the tables primary key (Index.idxType==SQLITE_IDXTYPE_PRIMARYKEY)
  85736. */
  85737. SQLITE_PRIVATE Index *sqlite3CreateIndex(
  85738. Parse *pParse, /* All information about this parse */
  85739. Token *pName1, /* First part of index name. May be NULL */
  85740. Token *pName2, /* Second part of index name. May be NULL */
  85741. SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
  85742. ExprList *pList, /* A list of columns to be indexed */
  85743. int onError, /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
  85744. Token *pStart, /* The CREATE token that begins this statement */
  85745. Expr *pPIWhere, /* WHERE clause for partial indices */
  85746. int sortOrder, /* Sort order of primary key when pList==NULL */
  85747. int ifNotExist /* Omit error if index already exists */
  85748. ){
  85749. Index *pRet = 0; /* Pointer to return */
  85750. Table *pTab = 0; /* Table to be indexed */
  85751. Index *pIndex = 0; /* The index to be created */
  85752. char *zName = 0; /* Name of the index */
  85753. int nName; /* Number of characters in zName */
  85754. int i, j;
  85755. DbFixer sFix; /* For assigning database names to pTable */
  85756. int sortOrderMask; /* 1 to honor DESC in index. 0 to ignore. */
  85757. sqlite3 *db = pParse->db;
  85758. Db *pDb; /* The specific table containing the indexed database */
  85759. int iDb; /* Index of the database that is being written */
  85760. Token *pName = 0; /* Unqualified name of the index to create */
  85761. struct ExprList_item *pListItem; /* For looping over pList */
  85762. const Column *pTabCol; /* A column in the table */
  85763. int nExtra = 0; /* Space allocated for zExtra[] */
  85764. int nExtraCol; /* Number of extra columns needed */
  85765. char *zExtra = 0; /* Extra space after the Index object */
  85766. Index *pPk = 0; /* PRIMARY KEY index for WITHOUT ROWID tables */
  85767. assert( pParse->nErr==0 ); /* Never called with prior errors */
  85768. if( db->mallocFailed || IN_DECLARE_VTAB ){
  85769. goto exit_create_index;
  85770. }
  85771. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  85772. goto exit_create_index;
  85773. }
  85774. /*
  85775. ** Find the table that is to be indexed. Return early if not found.
  85776. */
  85777. if( pTblName!=0 ){
  85778. /* Use the two-part index name to determine the database
  85779. ** to search for the table. 'Fix' the table name to this db
  85780. ** before looking up the table.
  85781. */
  85782. assert( pName1 && pName2 );
  85783. iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
  85784. if( iDb<0 ) goto exit_create_index;
  85785. assert( pName && pName->z );
  85786. #ifndef SQLITE_OMIT_TEMPDB
  85787. /* If the index name was unqualified, check if the table
  85788. ** is a temp table. If so, set the database to 1. Do not do this
  85789. ** if initialising a database schema.
  85790. */
  85791. if( !db->init.busy ){
  85792. pTab = sqlite3SrcListLookup(pParse, pTblName);
  85793. if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
  85794. iDb = 1;
  85795. }
  85796. }
  85797. #endif
  85798. sqlite3FixInit(&sFix, pParse, iDb, "index", pName);
  85799. if( sqlite3FixSrcList(&sFix, pTblName) ){
  85800. /* Because the parser constructs pTblName from a single identifier,
  85801. ** sqlite3FixSrcList can never fail. */
  85802. assert(0);
  85803. }
  85804. pTab = sqlite3LocateTableItem(pParse, 0, &pTblName->a[0]);
  85805. assert( db->mallocFailed==0 || pTab==0 );
  85806. if( pTab==0 ) goto exit_create_index;
  85807. if( iDb==1 && db->aDb[iDb].pSchema!=pTab->pSchema ){
  85808. sqlite3ErrorMsg(pParse,
  85809. "cannot create a TEMP index on non-TEMP table \"%s\"",
  85810. pTab->zName);
  85811. goto exit_create_index;
  85812. }
  85813. if( !HasRowid(pTab) ) pPk = sqlite3PrimaryKeyIndex(pTab);
  85814. }else{
  85815. assert( pName==0 );
  85816. assert( pStart==0 );
  85817. pTab = pParse->pNewTable;
  85818. if( !pTab ) goto exit_create_index;
  85819. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  85820. }
  85821. pDb = &db->aDb[iDb];
  85822. assert( pTab!=0 );
  85823. assert( pParse->nErr==0 );
  85824. if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
  85825. && db->init.busy==0
  85826. #if SQLITE_USER_AUTHENTICATION
  85827. && sqlite3UserAuthTable(pTab->zName)==0
  85828. #endif
  85829. && sqlite3StrNICmp(&pTab->zName[7],"altertab_",9)!=0 ){
  85830. sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
  85831. goto exit_create_index;
  85832. }
  85833. #ifndef SQLITE_OMIT_VIEW
  85834. if( pTab->pSelect ){
  85835. sqlite3ErrorMsg(pParse, "views may not be indexed");
  85836. goto exit_create_index;
  85837. }
  85838. #endif
  85839. #ifndef SQLITE_OMIT_VIRTUALTABLE
  85840. if( IsVirtual(pTab) ){
  85841. sqlite3ErrorMsg(pParse, "virtual tables may not be indexed");
  85842. goto exit_create_index;
  85843. }
  85844. #endif
  85845. /*
  85846. ** Find the name of the index. Make sure there is not already another
  85847. ** index or table with the same name.
  85848. **
  85849. ** Exception: If we are reading the names of permanent indices from the
  85850. ** sqlite_master table (because some other process changed the schema) and
  85851. ** one of the index names collides with the name of a temporary table or
  85852. ** index, then we will continue to process this index.
  85853. **
  85854. ** If pName==0 it means that we are
  85855. ** dealing with a primary key or UNIQUE constraint. We have to invent our
  85856. ** own name.
  85857. */
  85858. if( pName ){
  85859. zName = sqlite3NameFromToken(db, pName);
  85860. if( zName==0 ) goto exit_create_index;
  85861. assert( pName->z!=0 );
  85862. if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
  85863. goto exit_create_index;
  85864. }
  85865. if( !db->init.busy ){
  85866. if( sqlite3FindTable(db, zName, 0)!=0 ){
  85867. sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
  85868. goto exit_create_index;
  85869. }
  85870. }
  85871. if( sqlite3FindIndex(db, zName, pDb->zName)!=0 ){
  85872. if( !ifNotExist ){
  85873. sqlite3ErrorMsg(pParse, "index %s already exists", zName);
  85874. }else{
  85875. assert( !db->init.busy );
  85876. sqlite3CodeVerifySchema(pParse, iDb);
  85877. }
  85878. goto exit_create_index;
  85879. }
  85880. }else{
  85881. int n;
  85882. Index *pLoop;
  85883. for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
  85884. zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n);
  85885. if( zName==0 ){
  85886. goto exit_create_index;
  85887. }
  85888. }
  85889. /* Check for authorization to create an index.
  85890. */
  85891. #ifndef SQLITE_OMIT_AUTHORIZATION
  85892. {
  85893. const char *zDb = pDb->zName;
  85894. if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
  85895. goto exit_create_index;
  85896. }
  85897. i = SQLITE_CREATE_INDEX;
  85898. if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
  85899. if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
  85900. goto exit_create_index;
  85901. }
  85902. }
  85903. #endif
  85904. /* If pList==0, it means this routine was called to make a primary
  85905. ** key out of the last column added to the table under construction.
  85906. ** So create a fake list to simulate this.
  85907. */
  85908. if( pList==0 ){
  85909. pList = sqlite3ExprListAppend(pParse, 0, 0);
  85910. if( pList==0 ) goto exit_create_index;
  85911. pList->a[0].zName = sqlite3DbStrDup(pParse->db,
  85912. pTab->aCol[pTab->nCol-1].zName);
  85913. pList->a[0].sortOrder = (u8)sortOrder;
  85914. }
  85915. /* Figure out how many bytes of space are required to store explicitly
  85916. ** specified collation sequence names.
  85917. */
  85918. for(i=0; i<pList->nExpr; i++){
  85919. Expr *pExpr = pList->a[i].pExpr;
  85920. if( pExpr ){
  85921. assert( pExpr->op==TK_COLLATE );
  85922. nExtra += (1 + sqlite3Strlen30(pExpr->u.zToken));
  85923. }
  85924. }
  85925. /*
  85926. ** Allocate the index structure.
  85927. */
  85928. nName = sqlite3Strlen30(zName);
  85929. nExtraCol = pPk ? pPk->nKeyCol : 1;
  85930. pIndex = sqlite3AllocateIndexObject(db, pList->nExpr + nExtraCol,
  85931. nName + nExtra + 1, &zExtra);
  85932. if( db->mallocFailed ){
  85933. goto exit_create_index;
  85934. }
  85935. assert( EIGHT_BYTE_ALIGNMENT(pIndex->aiRowLogEst) );
  85936. assert( EIGHT_BYTE_ALIGNMENT(pIndex->azColl) );
  85937. pIndex->zName = zExtra;
  85938. zExtra += nName + 1;
  85939. memcpy(pIndex->zName, zName, nName+1);
  85940. pIndex->pTable = pTab;
  85941. pIndex->onError = (u8)onError;
  85942. pIndex->uniqNotNull = onError!=OE_None;
  85943. pIndex->idxType = pName ? SQLITE_IDXTYPE_APPDEF : SQLITE_IDXTYPE_UNIQUE;
  85944. pIndex->pSchema = db->aDb[iDb].pSchema;
  85945. pIndex->nKeyCol = pList->nExpr;
  85946. if( pPIWhere ){
  85947. sqlite3ResolveSelfReference(pParse, pTab, NC_PartIdx, pPIWhere, 0);
  85948. pIndex->pPartIdxWhere = pPIWhere;
  85949. pPIWhere = 0;
  85950. }
  85951. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  85952. /* Check to see if we should honor DESC requests on index columns
  85953. */
  85954. if( pDb->pSchema->file_format>=4 ){
  85955. sortOrderMask = -1; /* Honor DESC */
  85956. }else{
  85957. sortOrderMask = 0; /* Ignore DESC */
  85958. }
  85959. /* Scan the names of the columns of the table to be indexed and
  85960. ** load the column indices into the Index structure. Report an error
  85961. ** if any column is not found.
  85962. **
  85963. ** TODO: Add a test to make sure that the same column is not named
  85964. ** more than once within the same index. Only the first instance of
  85965. ** the column will ever be used by the optimizer. Note that using the
  85966. ** same column more than once cannot be an error because that would
  85967. ** break backwards compatibility - it needs to be a warning.
  85968. */
  85969. for(i=0, pListItem=pList->a; i<pList->nExpr; i++, pListItem++){
  85970. const char *zColName = pListItem->zName;
  85971. int requestedSortOrder;
  85972. char *zColl; /* Collation sequence name */
  85973. for(j=0, pTabCol=pTab->aCol; j<pTab->nCol; j++, pTabCol++){
  85974. if( sqlite3StrICmp(zColName, pTabCol->zName)==0 ) break;
  85975. }
  85976. if( j>=pTab->nCol ){
  85977. sqlite3ErrorMsg(pParse, "table %s has no column named %s",
  85978. pTab->zName, zColName);
  85979. pParse->checkSchema = 1;
  85980. goto exit_create_index;
  85981. }
  85982. assert( j<=0x7fff );
  85983. pIndex->aiColumn[i] = (i16)j;
  85984. if( pListItem->pExpr ){
  85985. int nColl;
  85986. assert( pListItem->pExpr->op==TK_COLLATE );
  85987. zColl = pListItem->pExpr->u.zToken;
  85988. nColl = sqlite3Strlen30(zColl) + 1;
  85989. assert( nExtra>=nColl );
  85990. memcpy(zExtra, zColl, nColl);
  85991. zColl = zExtra;
  85992. zExtra += nColl;
  85993. nExtra -= nColl;
  85994. }else{
  85995. zColl = pTab->aCol[j].zColl;
  85996. if( !zColl ) zColl = "BINARY";
  85997. }
  85998. if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl) ){
  85999. goto exit_create_index;
  86000. }
  86001. pIndex->azColl[i] = zColl;
  86002. requestedSortOrder = pListItem->sortOrder & sortOrderMask;
  86003. pIndex->aSortOrder[i] = (u8)requestedSortOrder;
  86004. if( pTab->aCol[j].notNull==0 ) pIndex->uniqNotNull = 0;
  86005. }
  86006. if( pPk ){
  86007. for(j=0; j<pPk->nKeyCol; j++){
  86008. int x = pPk->aiColumn[j];
  86009. if( hasColumn(pIndex->aiColumn, pIndex->nKeyCol, x) ){
  86010. pIndex->nColumn--;
  86011. }else{
  86012. pIndex->aiColumn[i] = x;
  86013. pIndex->azColl[i] = pPk->azColl[j];
  86014. pIndex->aSortOrder[i] = pPk->aSortOrder[j];
  86015. i++;
  86016. }
  86017. }
  86018. assert( i==pIndex->nColumn );
  86019. }else{
  86020. pIndex->aiColumn[i] = -1;
  86021. pIndex->azColl[i] = "BINARY";
  86022. }
  86023. sqlite3DefaultRowEst(pIndex);
  86024. if( pParse->pNewTable==0 ) estimateIndexWidth(pIndex);
  86025. if( pTab==pParse->pNewTable ){
  86026. /* This routine has been called to create an automatic index as a
  86027. ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
  86028. ** a PRIMARY KEY or UNIQUE clause following the column definitions.
  86029. ** i.e. one of:
  86030. **
  86031. ** CREATE TABLE t(x PRIMARY KEY, y);
  86032. ** CREATE TABLE t(x, y, UNIQUE(x, y));
  86033. **
  86034. ** Either way, check to see if the table already has such an index. If
  86035. ** so, don't bother creating this one. This only applies to
  86036. ** automatically created indices. Users can do as they wish with
  86037. ** explicit indices.
  86038. **
  86039. ** Two UNIQUE or PRIMARY KEY constraints are considered equivalent
  86040. ** (and thus suppressing the second one) even if they have different
  86041. ** sort orders.
  86042. **
  86043. ** If there are different collating sequences or if the columns of
  86044. ** the constraint occur in different orders, then the constraints are
  86045. ** considered distinct and both result in separate indices.
  86046. */
  86047. Index *pIdx;
  86048. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  86049. int k;
  86050. assert( IsUniqueIndex(pIdx) );
  86051. assert( pIdx->idxType!=SQLITE_IDXTYPE_APPDEF );
  86052. assert( IsUniqueIndex(pIndex) );
  86053. if( pIdx->nKeyCol!=pIndex->nKeyCol ) continue;
  86054. for(k=0; k<pIdx->nKeyCol; k++){
  86055. const char *z1;
  86056. const char *z2;
  86057. if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
  86058. z1 = pIdx->azColl[k];
  86059. z2 = pIndex->azColl[k];
  86060. if( z1!=z2 && sqlite3StrICmp(z1, z2) ) break;
  86061. }
  86062. if( k==pIdx->nKeyCol ){
  86063. if( pIdx->onError!=pIndex->onError ){
  86064. /* This constraint creates the same index as a previous
  86065. ** constraint specified somewhere in the CREATE TABLE statement.
  86066. ** However the ON CONFLICT clauses are different. If both this
  86067. ** constraint and the previous equivalent constraint have explicit
  86068. ** ON CONFLICT clauses this is an error. Otherwise, use the
  86069. ** explicitly specified behavior for the index.
  86070. */
  86071. if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
  86072. sqlite3ErrorMsg(pParse,
  86073. "conflicting ON CONFLICT clauses specified", 0);
  86074. }
  86075. if( pIdx->onError==OE_Default ){
  86076. pIdx->onError = pIndex->onError;
  86077. }
  86078. }
  86079. goto exit_create_index;
  86080. }
  86081. }
  86082. }
  86083. /* Link the new Index structure to its table and to the other
  86084. ** in-memory database structures.
  86085. */
  86086. if( db->init.busy ){
  86087. Index *p;
  86088. assert( sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
  86089. p = sqlite3HashInsert(&pIndex->pSchema->idxHash,
  86090. pIndex->zName, pIndex);
  86091. if( p ){
  86092. assert( p==pIndex ); /* Malloc must have failed */
  86093. db->mallocFailed = 1;
  86094. goto exit_create_index;
  86095. }
  86096. db->flags |= SQLITE_InternChanges;
  86097. if( pTblName!=0 ){
  86098. pIndex->tnum = db->init.newTnum;
  86099. }
  86100. }
  86101. /* If this is the initial CREATE INDEX statement (or CREATE TABLE if the
  86102. ** index is an implied index for a UNIQUE or PRIMARY KEY constraint) then
  86103. ** emit code to allocate the index rootpage on disk and make an entry for
  86104. ** the index in the sqlite_master table and populate the index with
  86105. ** content. But, do not do this if we are simply reading the sqlite_master
  86106. ** table to parse the schema, or if this index is the PRIMARY KEY index
  86107. ** of a WITHOUT ROWID table.
  86108. **
  86109. ** If pTblName==0 it means this index is generated as an implied PRIMARY KEY
  86110. ** or UNIQUE index in a CREATE TABLE statement. Since the table
  86111. ** has just been created, it contains no data and the index initialization
  86112. ** step can be skipped.
  86113. */
  86114. else if( pParse->nErr==0 && (HasRowid(pTab) || pTblName!=0) ){
  86115. Vdbe *v;
  86116. char *zStmt;
  86117. int iMem = ++pParse->nMem;
  86118. v = sqlite3GetVdbe(pParse);
  86119. if( v==0 ) goto exit_create_index;
  86120. /* Create the rootpage for the index
  86121. */
  86122. sqlite3BeginWriteOperation(pParse, 1, iDb);
  86123. sqlite3VdbeAddOp2(v, OP_CreateIndex, iDb, iMem);
  86124. /* Gather the complete text of the CREATE INDEX statement into
  86125. ** the zStmt variable
  86126. */
  86127. if( pStart ){
  86128. int n = (int)(pParse->sLastToken.z - pName->z) + pParse->sLastToken.n;
  86129. if( pName->z[n-1]==';' ) n--;
  86130. /* A named index with an explicit CREATE INDEX statement */
  86131. zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s",
  86132. onError==OE_None ? "" : " UNIQUE", n, pName->z);
  86133. }else{
  86134. /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
  86135. /* zStmt = sqlite3MPrintf(""); */
  86136. zStmt = 0;
  86137. }
  86138. /* Add an entry in sqlite_master for this index
  86139. */
  86140. sqlite3NestedParse(pParse,
  86141. "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);",
  86142. db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
  86143. pIndex->zName,
  86144. pTab->zName,
  86145. iMem,
  86146. zStmt
  86147. );
  86148. sqlite3DbFree(db, zStmt);
  86149. /* Fill the index with data and reparse the schema. Code an OP_Expire
  86150. ** to invalidate all pre-compiled statements.
  86151. */
  86152. if( pTblName ){
  86153. sqlite3RefillIndex(pParse, pIndex, iMem);
  86154. sqlite3ChangeCookie(pParse, iDb);
  86155. sqlite3VdbeAddParseSchemaOp(v, iDb,
  86156. sqlite3MPrintf(db, "name='%q' AND type='index'", pIndex->zName));
  86157. sqlite3VdbeAddOp1(v, OP_Expire, 0);
  86158. }
  86159. }
  86160. /* When adding an index to the list of indices for a table, make
  86161. ** sure all indices labeled OE_Replace come after all those labeled
  86162. ** OE_Ignore. This is necessary for the correct constraint check
  86163. ** processing (in sqlite3GenerateConstraintChecks()) as part of
  86164. ** UPDATE and INSERT statements.
  86165. */
  86166. if( db->init.busy || pTblName==0 ){
  86167. if( onError!=OE_Replace || pTab->pIndex==0
  86168. || pTab->pIndex->onError==OE_Replace){
  86169. pIndex->pNext = pTab->pIndex;
  86170. pTab->pIndex = pIndex;
  86171. }else{
  86172. Index *pOther = pTab->pIndex;
  86173. while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){
  86174. pOther = pOther->pNext;
  86175. }
  86176. pIndex->pNext = pOther->pNext;
  86177. pOther->pNext = pIndex;
  86178. }
  86179. pRet = pIndex;
  86180. pIndex = 0;
  86181. }
  86182. /* Clean up before exiting */
  86183. exit_create_index:
  86184. if( pIndex ) freeIndex(db, pIndex);
  86185. sqlite3ExprDelete(db, pPIWhere);
  86186. sqlite3ExprListDelete(db, pList);
  86187. sqlite3SrcListDelete(db, pTblName);
  86188. sqlite3DbFree(db, zName);
  86189. return pRet;
  86190. }
  86191. /*
  86192. ** Fill the Index.aiRowEst[] array with default information - information
  86193. ** to be used when we have not run the ANALYZE command.
  86194. **
  86195. ** aiRowEst[0] is supposed to contain the number of elements in the index.
  86196. ** Since we do not know, guess 1 million. aiRowEst[1] is an estimate of the
  86197. ** number of rows in the table that match any particular value of the
  86198. ** first column of the index. aiRowEst[2] is an estimate of the number
  86199. ** of rows that match any particular combination of the first 2 columns
  86200. ** of the index. And so forth. It must always be the case that
  86201. *
  86202. ** aiRowEst[N]<=aiRowEst[N-1]
  86203. ** aiRowEst[N]>=1
  86204. **
  86205. ** Apart from that, we have little to go on besides intuition as to
  86206. ** how aiRowEst[] should be initialized. The numbers generated here
  86207. ** are based on typical values found in actual indices.
  86208. */
  86209. SQLITE_PRIVATE void sqlite3DefaultRowEst(Index *pIdx){
  86210. /* 10, 9, 8, 7, 6 */
  86211. LogEst aVal[] = { 33, 32, 30, 28, 26 };
  86212. LogEst *a = pIdx->aiRowLogEst;
  86213. int nCopy = MIN(ArraySize(aVal), pIdx->nKeyCol);
  86214. int i;
  86215. /* Set the first entry (number of rows in the index) to the estimated
  86216. ** number of rows in the table. Or 10, if the estimated number of rows
  86217. ** in the table is less than that. */
  86218. a[0] = pIdx->pTable->nRowLogEst;
  86219. if( a[0]<33 ) a[0] = 33; assert( 33==sqlite3LogEst(10) );
  86220. /* Estimate that a[1] is 10, a[2] is 9, a[3] is 8, a[4] is 7, a[5] is
  86221. ** 6 and each subsequent value (if any) is 5. */
  86222. memcpy(&a[1], aVal, nCopy*sizeof(LogEst));
  86223. for(i=nCopy+1; i<=pIdx->nKeyCol; i++){
  86224. a[i] = 23; assert( 23==sqlite3LogEst(5) );
  86225. }
  86226. assert( 0==sqlite3LogEst(1) );
  86227. if( IsUniqueIndex(pIdx) ) a[pIdx->nKeyCol] = 0;
  86228. }
  86229. /*
  86230. ** This routine will drop an existing named index. This routine
  86231. ** implements the DROP INDEX statement.
  86232. */
  86233. SQLITE_PRIVATE void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
  86234. Index *pIndex;
  86235. Vdbe *v;
  86236. sqlite3 *db = pParse->db;
  86237. int iDb;
  86238. assert( pParse->nErr==0 ); /* Never called with prior errors */
  86239. if( db->mallocFailed ){
  86240. goto exit_drop_index;
  86241. }
  86242. assert( pName->nSrc==1 );
  86243. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  86244. goto exit_drop_index;
  86245. }
  86246. pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
  86247. if( pIndex==0 ){
  86248. if( !ifExists ){
  86249. sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0);
  86250. }else{
  86251. sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
  86252. }
  86253. pParse->checkSchema = 1;
  86254. goto exit_drop_index;
  86255. }
  86256. if( pIndex->idxType!=SQLITE_IDXTYPE_APPDEF ){
  86257. sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
  86258. "or PRIMARY KEY constraint cannot be dropped", 0);
  86259. goto exit_drop_index;
  86260. }
  86261. iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
  86262. #ifndef SQLITE_OMIT_AUTHORIZATION
  86263. {
  86264. int code = SQLITE_DROP_INDEX;
  86265. Table *pTab = pIndex->pTable;
  86266. const char *zDb = db->aDb[iDb].zName;
  86267. const char *zTab = SCHEMA_TABLE(iDb);
  86268. if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
  86269. goto exit_drop_index;
  86270. }
  86271. if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX;
  86272. if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
  86273. goto exit_drop_index;
  86274. }
  86275. }
  86276. #endif
  86277. /* Generate code to remove the index and from the master table */
  86278. v = sqlite3GetVdbe(pParse);
  86279. if( v ){
  86280. sqlite3BeginWriteOperation(pParse, 1, iDb);
  86281. sqlite3NestedParse(pParse,
  86282. "DELETE FROM %Q.%s WHERE name=%Q AND type='index'",
  86283. db->aDb[iDb].zName, SCHEMA_TABLE(iDb), pIndex->zName
  86284. );
  86285. sqlite3ClearStatTables(pParse, iDb, "idx", pIndex->zName);
  86286. sqlite3ChangeCookie(pParse, iDb);
  86287. destroyRootPage(pParse, pIndex->tnum, iDb);
  86288. sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0);
  86289. }
  86290. exit_drop_index:
  86291. sqlite3SrcListDelete(db, pName);
  86292. }
  86293. /*
  86294. ** pArray is a pointer to an array of objects. Each object in the
  86295. ** array is szEntry bytes in size. This routine uses sqlite3DbRealloc()
  86296. ** to extend the array so that there is space for a new object at the end.
  86297. **
  86298. ** When this function is called, *pnEntry contains the current size of
  86299. ** the array (in entries - so the allocation is ((*pnEntry) * szEntry) bytes
  86300. ** in total).
  86301. **
  86302. ** If the realloc() is successful (i.e. if no OOM condition occurs), the
  86303. ** space allocated for the new object is zeroed, *pnEntry updated to
  86304. ** reflect the new size of the array and a pointer to the new allocation
  86305. ** returned. *pIdx is set to the index of the new array entry in this case.
  86306. **
  86307. ** Otherwise, if the realloc() fails, *pIdx is set to -1, *pnEntry remains
  86308. ** unchanged and a copy of pArray returned.
  86309. */
  86310. SQLITE_PRIVATE void *sqlite3ArrayAllocate(
  86311. sqlite3 *db, /* Connection to notify of malloc failures */
  86312. void *pArray, /* Array of objects. Might be reallocated */
  86313. int szEntry, /* Size of each object in the array */
  86314. int *pnEntry, /* Number of objects currently in use */
  86315. int *pIdx /* Write the index of a new slot here */
  86316. ){
  86317. char *z;
  86318. int n = *pnEntry;
  86319. if( (n & (n-1))==0 ){
  86320. int sz = (n==0) ? 1 : 2*n;
  86321. void *pNew = sqlite3DbRealloc(db, pArray, sz*szEntry);
  86322. if( pNew==0 ){
  86323. *pIdx = -1;
  86324. return pArray;
  86325. }
  86326. pArray = pNew;
  86327. }
  86328. z = (char*)pArray;
  86329. memset(&z[n * szEntry], 0, szEntry);
  86330. *pIdx = n;
  86331. ++*pnEntry;
  86332. return pArray;
  86333. }
  86334. /*
  86335. ** Append a new element to the given IdList. Create a new IdList if
  86336. ** need be.
  86337. **
  86338. ** A new IdList is returned, or NULL if malloc() fails.
  86339. */
  86340. SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3 *db, IdList *pList, Token *pToken){
  86341. int i;
  86342. if( pList==0 ){
  86343. pList = sqlite3DbMallocZero(db, sizeof(IdList) );
  86344. if( pList==0 ) return 0;
  86345. }
  86346. pList->a = sqlite3ArrayAllocate(
  86347. db,
  86348. pList->a,
  86349. sizeof(pList->a[0]),
  86350. &pList->nId,
  86351. &i
  86352. );
  86353. if( i<0 ){
  86354. sqlite3IdListDelete(db, pList);
  86355. return 0;
  86356. }
  86357. pList->a[i].zName = sqlite3NameFromToken(db, pToken);
  86358. return pList;
  86359. }
  86360. /*
  86361. ** Delete an IdList.
  86362. */
  86363. SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3 *db, IdList *pList){
  86364. int i;
  86365. if( pList==0 ) return;
  86366. for(i=0; i<pList->nId; i++){
  86367. sqlite3DbFree(db, pList->a[i].zName);
  86368. }
  86369. sqlite3DbFree(db, pList->a);
  86370. sqlite3DbFree(db, pList);
  86371. }
  86372. /*
  86373. ** Return the index in pList of the identifier named zId. Return -1
  86374. ** if not found.
  86375. */
  86376. SQLITE_PRIVATE int sqlite3IdListIndex(IdList *pList, const char *zName){
  86377. int i;
  86378. if( pList==0 ) return -1;
  86379. for(i=0; i<pList->nId; i++){
  86380. if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
  86381. }
  86382. return -1;
  86383. }
  86384. /*
  86385. ** Expand the space allocated for the given SrcList object by
  86386. ** creating nExtra new slots beginning at iStart. iStart is zero based.
  86387. ** New slots are zeroed.
  86388. **
  86389. ** For example, suppose a SrcList initially contains two entries: A,B.
  86390. ** To append 3 new entries onto the end, do this:
  86391. **
  86392. ** sqlite3SrcListEnlarge(db, pSrclist, 3, 2);
  86393. **
  86394. ** After the call above it would contain: A, B, nil, nil, nil.
  86395. ** If the iStart argument had been 1 instead of 2, then the result
  86396. ** would have been: A, nil, nil, nil, B. To prepend the new slots,
  86397. ** the iStart value would be 0. The result then would
  86398. ** be: nil, nil, nil, A, B.
  86399. **
  86400. ** If a memory allocation fails the SrcList is unchanged. The
  86401. ** db->mallocFailed flag will be set to true.
  86402. */
  86403. SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(
  86404. sqlite3 *db, /* Database connection to notify of OOM errors */
  86405. SrcList *pSrc, /* The SrcList to be enlarged */
  86406. int nExtra, /* Number of new slots to add to pSrc->a[] */
  86407. int iStart /* Index in pSrc->a[] of first new slot */
  86408. ){
  86409. int i;
  86410. /* Sanity checking on calling parameters */
  86411. assert( iStart>=0 );
  86412. assert( nExtra>=1 );
  86413. assert( pSrc!=0 );
  86414. assert( iStart<=pSrc->nSrc );
  86415. /* Allocate additional space if needed */
  86416. if( (u32)pSrc->nSrc+nExtra>pSrc->nAlloc ){
  86417. SrcList *pNew;
  86418. int nAlloc = pSrc->nSrc+nExtra;
  86419. int nGot;
  86420. pNew = sqlite3DbRealloc(db, pSrc,
  86421. sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc->a[0]) );
  86422. if( pNew==0 ){
  86423. assert( db->mallocFailed );
  86424. return pSrc;
  86425. }
  86426. pSrc = pNew;
  86427. nGot = (sqlite3DbMallocSize(db, pNew) - sizeof(*pSrc))/sizeof(pSrc->a[0])+1;
  86428. pSrc->nAlloc = nGot;
  86429. }
  86430. /* Move existing slots that come after the newly inserted slots
  86431. ** out of the way */
  86432. for(i=pSrc->nSrc-1; i>=iStart; i--){
  86433. pSrc->a[i+nExtra] = pSrc->a[i];
  86434. }
  86435. pSrc->nSrc += nExtra;
  86436. /* Zero the newly allocated slots */
  86437. memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra);
  86438. for(i=iStart; i<iStart+nExtra; i++){
  86439. pSrc->a[i].iCursor = -1;
  86440. }
  86441. /* Return a pointer to the enlarged SrcList */
  86442. return pSrc;
  86443. }
  86444. /*
  86445. ** Append a new table name to the given SrcList. Create a new SrcList if
  86446. ** need be. A new entry is created in the SrcList even if pTable is NULL.
  86447. **
  86448. ** A SrcList is returned, or NULL if there is an OOM error. The returned
  86449. ** SrcList might be the same as the SrcList that was input or it might be
  86450. ** a new one. If an OOM error does occurs, then the prior value of pList
  86451. ** that is input to this routine is automatically freed.
  86452. **
  86453. ** If pDatabase is not null, it means that the table has an optional
  86454. ** database name prefix. Like this: "database.table". The pDatabase
  86455. ** points to the table name and the pTable points to the database name.
  86456. ** The SrcList.a[].zName field is filled with the table name which might
  86457. ** come from pTable (if pDatabase is NULL) or from pDatabase.
  86458. ** SrcList.a[].zDatabase is filled with the database name from pTable,
  86459. ** or with NULL if no database is specified.
  86460. **
  86461. ** In other words, if call like this:
  86462. **
  86463. ** sqlite3SrcListAppend(D,A,B,0);
  86464. **
  86465. ** Then B is a table name and the database name is unspecified. If called
  86466. ** like this:
  86467. **
  86468. ** sqlite3SrcListAppend(D,A,B,C);
  86469. **
  86470. ** Then C is the table name and B is the database name. If C is defined
  86471. ** then so is B. In other words, we never have a case where:
  86472. **
  86473. ** sqlite3SrcListAppend(D,A,0,C);
  86474. **
  86475. ** Both pTable and pDatabase are assumed to be quoted. They are dequoted
  86476. ** before being added to the SrcList.
  86477. */
  86478. SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(
  86479. sqlite3 *db, /* Connection to notify of malloc failures */
  86480. SrcList *pList, /* Append to this SrcList. NULL creates a new SrcList */
  86481. Token *pTable, /* Table to append */
  86482. Token *pDatabase /* Database of the table */
  86483. ){
  86484. struct SrcList_item *pItem;
  86485. assert( pDatabase==0 || pTable!=0 ); /* Cannot have C without B */
  86486. if( pList==0 ){
  86487. pList = sqlite3DbMallocZero(db, sizeof(SrcList) );
  86488. if( pList==0 ) return 0;
  86489. pList->nAlloc = 1;
  86490. }
  86491. pList = sqlite3SrcListEnlarge(db, pList, 1, pList->nSrc);
  86492. if( db->mallocFailed ){
  86493. sqlite3SrcListDelete(db, pList);
  86494. return 0;
  86495. }
  86496. pItem = &pList->a[pList->nSrc-1];
  86497. if( pDatabase && pDatabase->z==0 ){
  86498. pDatabase = 0;
  86499. }
  86500. if( pDatabase ){
  86501. Token *pTemp = pDatabase;
  86502. pDatabase = pTable;
  86503. pTable = pTemp;
  86504. }
  86505. pItem->zName = sqlite3NameFromToken(db, pTable);
  86506. pItem->zDatabase = sqlite3NameFromToken(db, pDatabase);
  86507. return pList;
  86508. }
  86509. /*
  86510. ** Assign VdbeCursor index numbers to all tables in a SrcList
  86511. */
  86512. SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
  86513. int i;
  86514. struct SrcList_item *pItem;
  86515. assert(pList || pParse->db->mallocFailed );
  86516. if( pList ){
  86517. for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
  86518. if( pItem->iCursor>=0 ) break;
  86519. pItem->iCursor = pParse->nTab++;
  86520. if( pItem->pSelect ){
  86521. sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
  86522. }
  86523. }
  86524. }
  86525. }
  86526. /*
  86527. ** Delete an entire SrcList including all its substructure.
  86528. */
  86529. SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){
  86530. int i;
  86531. struct SrcList_item *pItem;
  86532. if( pList==0 ) return;
  86533. for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
  86534. sqlite3DbFree(db, pItem->zDatabase);
  86535. sqlite3DbFree(db, pItem->zName);
  86536. sqlite3DbFree(db, pItem->zAlias);
  86537. sqlite3DbFree(db, pItem->zIndex);
  86538. sqlite3DeleteTable(db, pItem->pTab);
  86539. sqlite3SelectDelete(db, pItem->pSelect);
  86540. sqlite3ExprDelete(db, pItem->pOn);
  86541. sqlite3IdListDelete(db, pItem->pUsing);
  86542. }
  86543. sqlite3DbFree(db, pList);
  86544. }
  86545. /*
  86546. ** This routine is called by the parser to add a new term to the
  86547. ** end of a growing FROM clause. The "p" parameter is the part of
  86548. ** the FROM clause that has already been constructed. "p" is NULL
  86549. ** if this is the first term of the FROM clause. pTable and pDatabase
  86550. ** are the name of the table and database named in the FROM clause term.
  86551. ** pDatabase is NULL if the database name qualifier is missing - the
  86552. ** usual case. If the term has an alias, then pAlias points to the
  86553. ** alias token. If the term is a subquery, then pSubquery is the
  86554. ** SELECT statement that the subquery encodes. The pTable and
  86555. ** pDatabase parameters are NULL for subqueries. The pOn and pUsing
  86556. ** parameters are the content of the ON and USING clauses.
  86557. **
  86558. ** Return a new SrcList which encodes is the FROM with the new
  86559. ** term added.
  86560. */
  86561. SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(
  86562. Parse *pParse, /* Parsing context */
  86563. SrcList *p, /* The left part of the FROM clause already seen */
  86564. Token *pTable, /* Name of the table to add to the FROM clause */
  86565. Token *pDatabase, /* Name of the database containing pTable */
  86566. Token *pAlias, /* The right-hand side of the AS subexpression */
  86567. Select *pSubquery, /* A subquery used in place of a table name */
  86568. Expr *pOn, /* The ON clause of a join */
  86569. IdList *pUsing /* The USING clause of a join */
  86570. ){
  86571. struct SrcList_item *pItem;
  86572. sqlite3 *db = pParse->db;
  86573. if( !p && (pOn || pUsing) ){
  86574. sqlite3ErrorMsg(pParse, "a JOIN clause is required before %s",
  86575. (pOn ? "ON" : "USING")
  86576. );
  86577. goto append_from_error;
  86578. }
  86579. p = sqlite3SrcListAppend(db, p, pTable, pDatabase);
  86580. if( p==0 || NEVER(p->nSrc==0) ){
  86581. goto append_from_error;
  86582. }
  86583. pItem = &p->a[p->nSrc-1];
  86584. assert( pAlias!=0 );
  86585. if( pAlias->n ){
  86586. pItem->zAlias = sqlite3NameFromToken(db, pAlias);
  86587. }
  86588. pItem->pSelect = pSubquery;
  86589. pItem->pOn = pOn;
  86590. pItem->pUsing = pUsing;
  86591. return p;
  86592. append_from_error:
  86593. assert( p==0 );
  86594. sqlite3ExprDelete(db, pOn);
  86595. sqlite3IdListDelete(db, pUsing);
  86596. sqlite3SelectDelete(db, pSubquery);
  86597. return 0;
  86598. }
  86599. /*
  86600. ** Add an INDEXED BY or NOT INDEXED clause to the most recently added
  86601. ** element of the source-list passed as the second argument.
  86602. */
  86603. SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pIndexedBy){
  86604. assert( pIndexedBy!=0 );
  86605. if( p && ALWAYS(p->nSrc>0) ){
  86606. struct SrcList_item *pItem = &p->a[p->nSrc-1];
  86607. assert( pItem->notIndexed==0 && pItem->zIndex==0 );
  86608. if( pIndexedBy->n==1 && !pIndexedBy->z ){
  86609. /* A "NOT INDEXED" clause was supplied. See parse.y
  86610. ** construct "indexed_opt" for details. */
  86611. pItem->notIndexed = 1;
  86612. }else{
  86613. pItem->zIndex = sqlite3NameFromToken(pParse->db, pIndexedBy);
  86614. }
  86615. }
  86616. }
  86617. /*
  86618. ** When building up a FROM clause in the parser, the join operator
  86619. ** is initially attached to the left operand. But the code generator
  86620. ** expects the join operator to be on the right operand. This routine
  86621. ** Shifts all join operators from left to right for an entire FROM
  86622. ** clause.
  86623. **
  86624. ** Example: Suppose the join is like this:
  86625. **
  86626. ** A natural cross join B
  86627. **
  86628. ** The operator is "natural cross join". The A and B operands are stored
  86629. ** in p->a[0] and p->a[1], respectively. The parser initially stores the
  86630. ** operator with A. This routine shifts that operator over to B.
  86631. */
  86632. SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList *p){
  86633. if( p ){
  86634. int i;
  86635. assert( p->a || p->nSrc==0 );
  86636. for(i=p->nSrc-1; i>0; i--){
  86637. p->a[i].jointype = p->a[i-1].jointype;
  86638. }
  86639. p->a[0].jointype = 0;
  86640. }
  86641. }
  86642. /*
  86643. ** Begin a transaction
  86644. */
  86645. SQLITE_PRIVATE void sqlite3BeginTransaction(Parse *pParse, int type){
  86646. sqlite3 *db;
  86647. Vdbe *v;
  86648. int i;
  86649. assert( pParse!=0 );
  86650. db = pParse->db;
  86651. assert( db!=0 );
  86652. /* if( db->aDb[0].pBt==0 ) return; */
  86653. if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ){
  86654. return;
  86655. }
  86656. v = sqlite3GetVdbe(pParse);
  86657. if( !v ) return;
  86658. if( type!=TK_DEFERRED ){
  86659. for(i=0; i<db->nDb; i++){
  86660. sqlite3VdbeAddOp2(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1);
  86661. sqlite3VdbeUsesBtree(v, i);
  86662. }
  86663. }
  86664. sqlite3VdbeAddOp2(v, OP_AutoCommit, 0, 0);
  86665. }
  86666. /*
  86667. ** Commit a transaction
  86668. */
  86669. SQLITE_PRIVATE void sqlite3CommitTransaction(Parse *pParse){
  86670. Vdbe *v;
  86671. assert( pParse!=0 );
  86672. assert( pParse->db!=0 );
  86673. if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "COMMIT", 0, 0) ){
  86674. return;
  86675. }
  86676. v = sqlite3GetVdbe(pParse);
  86677. if( v ){
  86678. sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 0);
  86679. }
  86680. }
  86681. /*
  86682. ** Rollback a transaction
  86683. */
  86684. SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse *pParse){
  86685. Vdbe *v;
  86686. assert( pParse!=0 );
  86687. assert( pParse->db!=0 );
  86688. if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", 0, 0) ){
  86689. return;
  86690. }
  86691. v = sqlite3GetVdbe(pParse);
  86692. if( v ){
  86693. sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 1);
  86694. }
  86695. }
  86696. /*
  86697. ** This function is called by the parser when it parses a command to create,
  86698. ** release or rollback an SQL savepoint.
  86699. */
  86700. SQLITE_PRIVATE void sqlite3Savepoint(Parse *pParse, int op, Token *pName){
  86701. char *zName = sqlite3NameFromToken(pParse->db, pName);
  86702. if( zName ){
  86703. Vdbe *v = sqlite3GetVdbe(pParse);
  86704. #ifndef SQLITE_OMIT_AUTHORIZATION
  86705. static const char * const az[] = { "BEGIN", "RELEASE", "ROLLBACK" };
  86706. assert( !SAVEPOINT_BEGIN && SAVEPOINT_RELEASE==1 && SAVEPOINT_ROLLBACK==2 );
  86707. #endif
  86708. if( !v || sqlite3AuthCheck(pParse, SQLITE_SAVEPOINT, az[op], zName, 0) ){
  86709. sqlite3DbFree(pParse->db, zName);
  86710. return;
  86711. }
  86712. sqlite3VdbeAddOp4(v, OP_Savepoint, op, 0, 0, zName, P4_DYNAMIC);
  86713. }
  86714. }
  86715. /*
  86716. ** Make sure the TEMP database is open and available for use. Return
  86717. ** the number of errors. Leave any error messages in the pParse structure.
  86718. */
  86719. SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *pParse){
  86720. sqlite3 *db = pParse->db;
  86721. if( db->aDb[1].pBt==0 && !pParse->explain ){
  86722. int rc;
  86723. Btree *pBt;
  86724. static const int flags =
  86725. SQLITE_OPEN_READWRITE |
  86726. SQLITE_OPEN_CREATE |
  86727. SQLITE_OPEN_EXCLUSIVE |
  86728. SQLITE_OPEN_DELETEONCLOSE |
  86729. SQLITE_OPEN_TEMP_DB;
  86730. rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pBt, 0, flags);
  86731. if( rc!=SQLITE_OK ){
  86732. sqlite3ErrorMsg(pParse, "unable to open a temporary database "
  86733. "file for storing temporary tables");
  86734. pParse->rc = rc;
  86735. return 1;
  86736. }
  86737. db->aDb[1].pBt = pBt;
  86738. assert( db->aDb[1].pSchema );
  86739. if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1, 0) ){
  86740. db->mallocFailed = 1;
  86741. return 1;
  86742. }
  86743. }
  86744. return 0;
  86745. }
  86746. /*
  86747. ** Record the fact that the schema cookie will need to be verified
  86748. ** for database iDb. The code to actually verify the schema cookie
  86749. ** will occur at the end of the top-level VDBE and will be generated
  86750. ** later, by sqlite3FinishCoding().
  86751. */
  86752. SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
  86753. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  86754. sqlite3 *db = pToplevel->db;
  86755. assert( iDb>=0 && iDb<db->nDb );
  86756. assert( db->aDb[iDb].pBt!=0 || iDb==1 );
  86757. assert( iDb<SQLITE_MAX_ATTACHED+2 );
  86758. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  86759. if( DbMaskTest(pToplevel->cookieMask, iDb)==0 ){
  86760. DbMaskSet(pToplevel->cookieMask, iDb);
  86761. pToplevel->cookieValue[iDb] = db->aDb[iDb].pSchema->schema_cookie;
  86762. if( !OMIT_TEMPDB && iDb==1 ){
  86763. sqlite3OpenTempDatabase(pToplevel);
  86764. }
  86765. }
  86766. }
  86767. /*
  86768. ** If argument zDb is NULL, then call sqlite3CodeVerifySchema() for each
  86769. ** attached database. Otherwise, invoke it for the database named zDb only.
  86770. */
  86771. SQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse *pParse, const char *zDb){
  86772. sqlite3 *db = pParse->db;
  86773. int i;
  86774. for(i=0; i<db->nDb; i++){
  86775. Db *pDb = &db->aDb[i];
  86776. if( pDb->pBt && (!zDb || 0==sqlite3StrICmp(zDb, pDb->zName)) ){
  86777. sqlite3CodeVerifySchema(pParse, i);
  86778. }
  86779. }
  86780. }
  86781. /*
  86782. ** Generate VDBE code that prepares for doing an operation that
  86783. ** might change the database.
  86784. **
  86785. ** This routine starts a new transaction if we are not already within
  86786. ** a transaction. If we are already within a transaction, then a checkpoint
  86787. ** is set if the setStatement parameter is true. A checkpoint should
  86788. ** be set for operations that might fail (due to a constraint) part of
  86789. ** the way through and which will need to undo some writes without having to
  86790. ** rollback the whole transaction. For operations where all constraints
  86791. ** can be checked before any changes are made to the database, it is never
  86792. ** necessary to undo a write and the checkpoint should not be set.
  86793. */
  86794. SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
  86795. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  86796. sqlite3CodeVerifySchema(pParse, iDb);
  86797. DbMaskSet(pToplevel->writeMask, iDb);
  86798. pToplevel->isMultiWrite |= setStatement;
  86799. }
  86800. /*
  86801. ** Indicate that the statement currently under construction might write
  86802. ** more than one entry (example: deleting one row then inserting another,
  86803. ** inserting multiple rows in a table, or inserting a row and index entries.)
  86804. ** If an abort occurs after some of these writes have completed, then it will
  86805. ** be necessary to undo the completed writes.
  86806. */
  86807. SQLITE_PRIVATE void sqlite3MultiWrite(Parse *pParse){
  86808. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  86809. pToplevel->isMultiWrite = 1;
  86810. }
  86811. /*
  86812. ** The code generator calls this routine if is discovers that it is
  86813. ** possible to abort a statement prior to completion. In order to
  86814. ** perform this abort without corrupting the database, we need to make
  86815. ** sure that the statement is protected by a statement transaction.
  86816. **
  86817. ** Technically, we only need to set the mayAbort flag if the
  86818. ** isMultiWrite flag was previously set. There is a time dependency
  86819. ** such that the abort must occur after the multiwrite. This makes
  86820. ** some statements involving the REPLACE conflict resolution algorithm
  86821. ** go a little faster. But taking advantage of this time dependency
  86822. ** makes it more difficult to prove that the code is correct (in
  86823. ** particular, it prevents us from writing an effective
  86824. ** implementation of sqlite3AssertMayAbort()) and so we have chosen
  86825. ** to take the safe route and skip the optimization.
  86826. */
  86827. SQLITE_PRIVATE void sqlite3MayAbort(Parse *pParse){
  86828. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  86829. pToplevel->mayAbort = 1;
  86830. }
  86831. /*
  86832. ** Code an OP_Halt that causes the vdbe to return an SQLITE_CONSTRAINT
  86833. ** error. The onError parameter determines which (if any) of the statement
  86834. ** and/or current transaction is rolled back.
  86835. */
  86836. SQLITE_PRIVATE void sqlite3HaltConstraint(
  86837. Parse *pParse, /* Parsing context */
  86838. int errCode, /* extended error code */
  86839. int onError, /* Constraint type */
  86840. char *p4, /* Error message */
  86841. i8 p4type, /* P4_STATIC or P4_TRANSIENT */
  86842. u8 p5Errmsg /* P5_ErrMsg type */
  86843. ){
  86844. Vdbe *v = sqlite3GetVdbe(pParse);
  86845. assert( (errCode&0xff)==SQLITE_CONSTRAINT );
  86846. if( onError==OE_Abort ){
  86847. sqlite3MayAbort(pParse);
  86848. }
  86849. sqlite3VdbeAddOp4(v, OP_Halt, errCode, onError, 0, p4, p4type);
  86850. if( p5Errmsg ) sqlite3VdbeChangeP5(v, p5Errmsg);
  86851. }
  86852. /*
  86853. ** Code an OP_Halt due to UNIQUE or PRIMARY KEY constraint violation.
  86854. */
  86855. SQLITE_PRIVATE void sqlite3UniqueConstraint(
  86856. Parse *pParse, /* Parsing context */
  86857. int onError, /* Constraint type */
  86858. Index *pIdx /* The index that triggers the constraint */
  86859. ){
  86860. char *zErr;
  86861. int j;
  86862. StrAccum errMsg;
  86863. Table *pTab = pIdx->pTable;
  86864. sqlite3StrAccumInit(&errMsg, 0, 0, 200);
  86865. errMsg.db = pParse->db;
  86866. for(j=0; j<pIdx->nKeyCol; j++){
  86867. char *zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
  86868. if( j ) sqlite3StrAccumAppend(&errMsg, ", ", 2);
  86869. sqlite3StrAccumAppendAll(&errMsg, pTab->zName);
  86870. sqlite3StrAccumAppend(&errMsg, ".", 1);
  86871. sqlite3StrAccumAppendAll(&errMsg, zCol);
  86872. }
  86873. zErr = sqlite3StrAccumFinish(&errMsg);
  86874. sqlite3HaltConstraint(pParse,
  86875. IsPrimaryKeyIndex(pIdx) ? SQLITE_CONSTRAINT_PRIMARYKEY
  86876. : SQLITE_CONSTRAINT_UNIQUE,
  86877. onError, zErr, P4_DYNAMIC, P5_ConstraintUnique);
  86878. }
  86879. /*
  86880. ** Code an OP_Halt due to non-unique rowid.
  86881. */
  86882. SQLITE_PRIVATE void sqlite3RowidConstraint(
  86883. Parse *pParse, /* Parsing context */
  86884. int onError, /* Conflict resolution algorithm */
  86885. Table *pTab /* The table with the non-unique rowid */
  86886. ){
  86887. char *zMsg;
  86888. int rc;
  86889. if( pTab->iPKey>=0 ){
  86890. zMsg = sqlite3MPrintf(pParse->db, "%s.%s", pTab->zName,
  86891. pTab->aCol[pTab->iPKey].zName);
  86892. rc = SQLITE_CONSTRAINT_PRIMARYKEY;
  86893. }else{
  86894. zMsg = sqlite3MPrintf(pParse->db, "%s.rowid", pTab->zName);
  86895. rc = SQLITE_CONSTRAINT_ROWID;
  86896. }
  86897. sqlite3HaltConstraint(pParse, rc, onError, zMsg, P4_DYNAMIC,
  86898. P5_ConstraintUnique);
  86899. }
  86900. /*
  86901. ** Check to see if pIndex uses the collating sequence pColl. Return
  86902. ** true if it does and false if it does not.
  86903. */
  86904. #ifndef SQLITE_OMIT_REINDEX
  86905. static int collationMatch(const char *zColl, Index *pIndex){
  86906. int i;
  86907. assert( zColl!=0 );
  86908. for(i=0; i<pIndex->nColumn; i++){
  86909. const char *z = pIndex->azColl[i];
  86910. assert( z!=0 || pIndex->aiColumn[i]<0 );
  86911. if( pIndex->aiColumn[i]>=0 && 0==sqlite3StrICmp(z, zColl) ){
  86912. return 1;
  86913. }
  86914. }
  86915. return 0;
  86916. }
  86917. #endif
  86918. /*
  86919. ** Recompute all indices of pTab that use the collating sequence pColl.
  86920. ** If pColl==0 then recompute all indices of pTab.
  86921. */
  86922. #ifndef SQLITE_OMIT_REINDEX
  86923. static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){
  86924. Index *pIndex; /* An index associated with pTab */
  86925. for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
  86926. if( zColl==0 || collationMatch(zColl, pIndex) ){
  86927. int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  86928. sqlite3BeginWriteOperation(pParse, 0, iDb);
  86929. sqlite3RefillIndex(pParse, pIndex, -1);
  86930. }
  86931. }
  86932. }
  86933. #endif
  86934. /*
  86935. ** Recompute all indices of all tables in all databases where the
  86936. ** indices use the collating sequence pColl. If pColl==0 then recompute
  86937. ** all indices everywhere.
  86938. */
  86939. #ifndef SQLITE_OMIT_REINDEX
  86940. static void reindexDatabases(Parse *pParse, char const *zColl){
  86941. Db *pDb; /* A single database */
  86942. int iDb; /* The database index number */
  86943. sqlite3 *db = pParse->db; /* The database connection */
  86944. HashElem *k; /* For looping over tables in pDb */
  86945. Table *pTab; /* A table in the database */
  86946. assert( sqlite3BtreeHoldsAllMutexes(db) ); /* Needed for schema access */
  86947. for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
  86948. assert( pDb!=0 );
  86949. for(k=sqliteHashFirst(&pDb->pSchema->tblHash); k; k=sqliteHashNext(k)){
  86950. pTab = (Table*)sqliteHashData(k);
  86951. reindexTable(pParse, pTab, zColl);
  86952. }
  86953. }
  86954. }
  86955. #endif
  86956. /*
  86957. ** Generate code for the REINDEX command.
  86958. **
  86959. ** REINDEX -- 1
  86960. ** REINDEX <collation> -- 2
  86961. ** REINDEX ?<database>.?<tablename> -- 3
  86962. ** REINDEX ?<database>.?<indexname> -- 4
  86963. **
  86964. ** Form 1 causes all indices in all attached databases to be rebuilt.
  86965. ** Form 2 rebuilds all indices in all databases that use the named
  86966. ** collating function. Forms 3 and 4 rebuild the named index or all
  86967. ** indices associated with the named table.
  86968. */
  86969. #ifndef SQLITE_OMIT_REINDEX
  86970. SQLITE_PRIVATE void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
  86971. CollSeq *pColl; /* Collating sequence to be reindexed, or NULL */
  86972. char *z; /* Name of a table or index */
  86973. const char *zDb; /* Name of the database */
  86974. Table *pTab; /* A table in the database */
  86975. Index *pIndex; /* An index associated with pTab */
  86976. int iDb; /* The database index number */
  86977. sqlite3 *db = pParse->db; /* The database connection */
  86978. Token *pObjName; /* Name of the table or index to be reindexed */
  86979. /* Read the database schema. If an error occurs, leave an error message
  86980. ** and code in pParse and return NULL. */
  86981. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  86982. return;
  86983. }
  86984. if( pName1==0 ){
  86985. reindexDatabases(pParse, 0);
  86986. return;
  86987. }else if( NEVER(pName2==0) || pName2->z==0 ){
  86988. char *zColl;
  86989. assert( pName1->z );
  86990. zColl = sqlite3NameFromToken(pParse->db, pName1);
  86991. if( !zColl ) return;
  86992. pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
  86993. if( pColl ){
  86994. reindexDatabases(pParse, zColl);
  86995. sqlite3DbFree(db, zColl);
  86996. return;
  86997. }
  86998. sqlite3DbFree(db, zColl);
  86999. }
  87000. iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
  87001. if( iDb<0 ) return;
  87002. z = sqlite3NameFromToken(db, pObjName);
  87003. if( z==0 ) return;
  87004. zDb = db->aDb[iDb].zName;
  87005. pTab = sqlite3FindTable(db, z, zDb);
  87006. if( pTab ){
  87007. reindexTable(pParse, pTab, 0);
  87008. sqlite3DbFree(db, z);
  87009. return;
  87010. }
  87011. pIndex = sqlite3FindIndex(db, z, zDb);
  87012. sqlite3DbFree(db, z);
  87013. if( pIndex ){
  87014. sqlite3BeginWriteOperation(pParse, 0, iDb);
  87015. sqlite3RefillIndex(pParse, pIndex, -1);
  87016. return;
  87017. }
  87018. sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
  87019. }
  87020. #endif
  87021. /*
  87022. ** Return a KeyInfo structure that is appropriate for the given Index.
  87023. **
  87024. ** The KeyInfo structure for an index is cached in the Index object.
  87025. ** So there might be multiple references to the returned pointer. The
  87026. ** caller should not try to modify the KeyInfo object.
  87027. **
  87028. ** The caller should invoke sqlite3KeyInfoUnref() on the returned object
  87029. ** when it has finished using it.
  87030. */
  87031. SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoOfIndex(Parse *pParse, Index *pIdx){
  87032. if( pParse->nErr ) return 0;
  87033. #ifndef SQLITE_OMIT_SHARED_CACHE
  87034. if( pIdx->pKeyInfo && pIdx->pKeyInfo->db!=pParse->db ){
  87035. sqlite3KeyInfoUnref(pIdx->pKeyInfo);
  87036. pIdx->pKeyInfo = 0;
  87037. }
  87038. #endif
  87039. if( pIdx->pKeyInfo==0 ){
  87040. int i;
  87041. int nCol = pIdx->nColumn;
  87042. int nKey = pIdx->nKeyCol;
  87043. KeyInfo *pKey;
  87044. if( pIdx->uniqNotNull ){
  87045. pKey = sqlite3KeyInfoAlloc(pParse->db, nKey, nCol-nKey);
  87046. }else{
  87047. pKey = sqlite3KeyInfoAlloc(pParse->db, nCol, 0);
  87048. }
  87049. if( pKey ){
  87050. assert( sqlite3KeyInfoIsWriteable(pKey) );
  87051. for(i=0; i<nCol; i++){
  87052. char *zColl = pIdx->azColl[i];
  87053. assert( zColl!=0 );
  87054. pKey->aColl[i] = strcmp(zColl,"BINARY")==0 ? 0 :
  87055. sqlite3LocateCollSeq(pParse, zColl);
  87056. pKey->aSortOrder[i] = pIdx->aSortOrder[i];
  87057. }
  87058. if( pParse->nErr ){
  87059. sqlite3KeyInfoUnref(pKey);
  87060. }else{
  87061. pIdx->pKeyInfo = pKey;
  87062. }
  87063. }
  87064. }
  87065. return sqlite3KeyInfoRef(pIdx->pKeyInfo);
  87066. }
  87067. #ifndef SQLITE_OMIT_CTE
  87068. /*
  87069. ** This routine is invoked once per CTE by the parser while parsing a
  87070. ** WITH clause.
  87071. */
  87072. SQLITE_PRIVATE With *sqlite3WithAdd(
  87073. Parse *pParse, /* Parsing context */
  87074. With *pWith, /* Existing WITH clause, or NULL */
  87075. Token *pName, /* Name of the common-table */
  87076. ExprList *pArglist, /* Optional column name list for the table */
  87077. Select *pQuery /* Query used to initialize the table */
  87078. ){
  87079. sqlite3 *db = pParse->db;
  87080. With *pNew;
  87081. char *zName;
  87082. /* Check that the CTE name is unique within this WITH clause. If
  87083. ** not, store an error in the Parse structure. */
  87084. zName = sqlite3NameFromToken(pParse->db, pName);
  87085. if( zName && pWith ){
  87086. int i;
  87087. for(i=0; i<pWith->nCte; i++){
  87088. if( sqlite3StrICmp(zName, pWith->a[i].zName)==0 ){
  87089. sqlite3ErrorMsg(pParse, "duplicate WITH table name: %s", zName);
  87090. }
  87091. }
  87092. }
  87093. if( pWith ){
  87094. int nByte = sizeof(*pWith) + (sizeof(pWith->a[1]) * pWith->nCte);
  87095. pNew = sqlite3DbRealloc(db, pWith, nByte);
  87096. }else{
  87097. pNew = sqlite3DbMallocZero(db, sizeof(*pWith));
  87098. }
  87099. assert( zName!=0 || pNew==0 );
  87100. assert( db->mallocFailed==0 || pNew==0 );
  87101. if( pNew==0 ){
  87102. sqlite3ExprListDelete(db, pArglist);
  87103. sqlite3SelectDelete(db, pQuery);
  87104. sqlite3DbFree(db, zName);
  87105. pNew = pWith;
  87106. }else{
  87107. pNew->a[pNew->nCte].pSelect = pQuery;
  87108. pNew->a[pNew->nCte].pCols = pArglist;
  87109. pNew->a[pNew->nCte].zName = zName;
  87110. pNew->a[pNew->nCte].zErr = 0;
  87111. pNew->nCte++;
  87112. }
  87113. return pNew;
  87114. }
  87115. /*
  87116. ** Free the contents of the With object passed as the second argument.
  87117. */
  87118. SQLITE_PRIVATE void sqlite3WithDelete(sqlite3 *db, With *pWith){
  87119. if( pWith ){
  87120. int i;
  87121. for(i=0; i<pWith->nCte; i++){
  87122. struct Cte *pCte = &pWith->a[i];
  87123. sqlite3ExprListDelete(db, pCte->pCols);
  87124. sqlite3SelectDelete(db, pCte->pSelect);
  87125. sqlite3DbFree(db, pCte->zName);
  87126. }
  87127. sqlite3DbFree(db, pWith);
  87128. }
  87129. }
  87130. #endif /* !defined(SQLITE_OMIT_CTE) */
  87131. /************** End of build.c ***********************************************/
  87132. /************** Begin file callback.c ****************************************/
  87133. /*
  87134. ** 2005 May 23
  87135. **
  87136. ** The author disclaims copyright to this source code. In place of
  87137. ** a legal notice, here is a blessing:
  87138. **
  87139. ** May you do good and not evil.
  87140. ** May you find forgiveness for yourself and forgive others.
  87141. ** May you share freely, never taking more than you give.
  87142. **
  87143. *************************************************************************
  87144. **
  87145. ** This file contains functions used to access the internal hash tables
  87146. ** of user defined functions and collation sequences.
  87147. */
  87148. /*
  87149. ** Invoke the 'collation needed' callback to request a collation sequence
  87150. ** in the encoding enc of name zName, length nName.
  87151. */
  87152. static void callCollNeeded(sqlite3 *db, int enc, const char *zName){
  87153. assert( !db->xCollNeeded || !db->xCollNeeded16 );
  87154. if( db->xCollNeeded ){
  87155. char *zExternal = sqlite3DbStrDup(db, zName);
  87156. if( !zExternal ) return;
  87157. db->xCollNeeded(db->pCollNeededArg, db, enc, zExternal);
  87158. sqlite3DbFree(db, zExternal);
  87159. }
  87160. #ifndef SQLITE_OMIT_UTF16
  87161. if( db->xCollNeeded16 ){
  87162. char const *zExternal;
  87163. sqlite3_value *pTmp = sqlite3ValueNew(db);
  87164. sqlite3ValueSetStr(pTmp, -1, zName, SQLITE_UTF8, SQLITE_STATIC);
  87165. zExternal = sqlite3ValueText(pTmp, SQLITE_UTF16NATIVE);
  87166. if( zExternal ){
  87167. db->xCollNeeded16(db->pCollNeededArg, db, (int)ENC(db), zExternal);
  87168. }
  87169. sqlite3ValueFree(pTmp);
  87170. }
  87171. #endif
  87172. }
  87173. /*
  87174. ** This routine is called if the collation factory fails to deliver a
  87175. ** collation function in the best encoding but there may be other versions
  87176. ** of this collation function (for other text encodings) available. Use one
  87177. ** of these instead if they exist. Avoid a UTF-8 <-> UTF-16 conversion if
  87178. ** possible.
  87179. */
  87180. static int synthCollSeq(sqlite3 *db, CollSeq *pColl){
  87181. CollSeq *pColl2;
  87182. char *z = pColl->zName;
  87183. int i;
  87184. static const u8 aEnc[] = { SQLITE_UTF16BE, SQLITE_UTF16LE, SQLITE_UTF8 };
  87185. for(i=0; i<3; i++){
  87186. pColl2 = sqlite3FindCollSeq(db, aEnc[i], z, 0);
  87187. if( pColl2->xCmp!=0 ){
  87188. memcpy(pColl, pColl2, sizeof(CollSeq));
  87189. pColl->xDel = 0; /* Do not copy the destructor */
  87190. return SQLITE_OK;
  87191. }
  87192. }
  87193. return SQLITE_ERROR;
  87194. }
  87195. /*
  87196. ** This function is responsible for invoking the collation factory callback
  87197. ** or substituting a collation sequence of a different encoding when the
  87198. ** requested collation sequence is not available in the desired encoding.
  87199. **
  87200. ** If it is not NULL, then pColl must point to the database native encoding
  87201. ** collation sequence with name zName, length nName.
  87202. **
  87203. ** The return value is either the collation sequence to be used in database
  87204. ** db for collation type name zName, length nName, or NULL, if no collation
  87205. ** sequence can be found. If no collation is found, leave an error message.
  87206. **
  87207. ** See also: sqlite3LocateCollSeq(), sqlite3FindCollSeq()
  87208. */
  87209. SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(
  87210. Parse *pParse, /* Parsing context */
  87211. u8 enc, /* The desired encoding for the collating sequence */
  87212. CollSeq *pColl, /* Collating sequence with native encoding, or NULL */
  87213. const char *zName /* Collating sequence name */
  87214. ){
  87215. CollSeq *p;
  87216. sqlite3 *db = pParse->db;
  87217. p = pColl;
  87218. if( !p ){
  87219. p = sqlite3FindCollSeq(db, enc, zName, 0);
  87220. }
  87221. if( !p || !p->xCmp ){
  87222. /* No collation sequence of this type for this encoding is registered.
  87223. ** Call the collation factory to see if it can supply us with one.
  87224. */
  87225. callCollNeeded(db, enc, zName);
  87226. p = sqlite3FindCollSeq(db, enc, zName, 0);
  87227. }
  87228. if( p && !p->xCmp && synthCollSeq(db, p) ){
  87229. p = 0;
  87230. }
  87231. assert( !p || p->xCmp );
  87232. if( p==0 ){
  87233. sqlite3ErrorMsg(pParse, "no such collation sequence: %s", zName);
  87234. }
  87235. return p;
  87236. }
  87237. /*
  87238. ** This routine is called on a collation sequence before it is used to
  87239. ** check that it is defined. An undefined collation sequence exists when
  87240. ** a database is loaded that contains references to collation sequences
  87241. ** that have not been defined by sqlite3_create_collation() etc.
  87242. **
  87243. ** If required, this routine calls the 'collation needed' callback to
  87244. ** request a definition of the collating sequence. If this doesn't work,
  87245. ** an equivalent collating sequence that uses a text encoding different
  87246. ** from the main database is substituted, if one is available.
  87247. */
  87248. SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *pParse, CollSeq *pColl){
  87249. if( pColl ){
  87250. const char *zName = pColl->zName;
  87251. sqlite3 *db = pParse->db;
  87252. CollSeq *p = sqlite3GetCollSeq(pParse, ENC(db), pColl, zName);
  87253. if( !p ){
  87254. return SQLITE_ERROR;
  87255. }
  87256. assert( p==pColl );
  87257. }
  87258. return SQLITE_OK;
  87259. }
  87260. /*
  87261. ** Locate and return an entry from the db.aCollSeq hash table. If the entry
  87262. ** specified by zName and nName is not found and parameter 'create' is
  87263. ** true, then create a new entry. Otherwise return NULL.
  87264. **
  87265. ** Each pointer stored in the sqlite3.aCollSeq hash table contains an
  87266. ** array of three CollSeq structures. The first is the collation sequence
  87267. ** preferred for UTF-8, the second UTF-16le, and the third UTF-16be.
  87268. **
  87269. ** Stored immediately after the three collation sequences is a copy of
  87270. ** the collation sequence name. A pointer to this string is stored in
  87271. ** each collation sequence structure.
  87272. */
  87273. static CollSeq *findCollSeqEntry(
  87274. sqlite3 *db, /* Database connection */
  87275. const char *zName, /* Name of the collating sequence */
  87276. int create /* Create a new entry if true */
  87277. ){
  87278. CollSeq *pColl;
  87279. pColl = sqlite3HashFind(&db->aCollSeq, zName);
  87280. if( 0==pColl && create ){
  87281. int nName = sqlite3Strlen30(zName);
  87282. pColl = sqlite3DbMallocZero(db, 3*sizeof(*pColl) + nName + 1);
  87283. if( pColl ){
  87284. CollSeq *pDel = 0;
  87285. pColl[0].zName = (char*)&pColl[3];
  87286. pColl[0].enc = SQLITE_UTF8;
  87287. pColl[1].zName = (char*)&pColl[3];
  87288. pColl[1].enc = SQLITE_UTF16LE;
  87289. pColl[2].zName = (char*)&pColl[3];
  87290. pColl[2].enc = SQLITE_UTF16BE;
  87291. memcpy(pColl[0].zName, zName, nName);
  87292. pColl[0].zName[nName] = 0;
  87293. pDel = sqlite3HashInsert(&db->aCollSeq, pColl[0].zName, pColl);
  87294. /* If a malloc() failure occurred in sqlite3HashInsert(), it will
  87295. ** return the pColl pointer to be deleted (because it wasn't added
  87296. ** to the hash table).
  87297. */
  87298. assert( pDel==0 || pDel==pColl );
  87299. if( pDel!=0 ){
  87300. db->mallocFailed = 1;
  87301. sqlite3DbFree(db, pDel);
  87302. pColl = 0;
  87303. }
  87304. }
  87305. }
  87306. return pColl;
  87307. }
  87308. /*
  87309. ** Parameter zName points to a UTF-8 encoded string nName bytes long.
  87310. ** Return the CollSeq* pointer for the collation sequence named zName
  87311. ** for the encoding 'enc' from the database 'db'.
  87312. **
  87313. ** If the entry specified is not found and 'create' is true, then create a
  87314. ** new entry. Otherwise return NULL.
  87315. **
  87316. ** A separate function sqlite3LocateCollSeq() is a wrapper around
  87317. ** this routine. sqlite3LocateCollSeq() invokes the collation factory
  87318. ** if necessary and generates an error message if the collating sequence
  87319. ** cannot be found.
  87320. **
  87321. ** See also: sqlite3LocateCollSeq(), sqlite3GetCollSeq()
  87322. */
  87323. SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(
  87324. sqlite3 *db,
  87325. u8 enc,
  87326. const char *zName,
  87327. int create
  87328. ){
  87329. CollSeq *pColl;
  87330. if( zName ){
  87331. pColl = findCollSeqEntry(db, zName, create);
  87332. }else{
  87333. pColl = db->pDfltColl;
  87334. }
  87335. assert( SQLITE_UTF8==1 && SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
  87336. assert( enc>=SQLITE_UTF8 && enc<=SQLITE_UTF16BE );
  87337. if( pColl ) pColl += enc-1;
  87338. return pColl;
  87339. }
  87340. /* During the search for the best function definition, this procedure
  87341. ** is called to test how well the function passed as the first argument
  87342. ** matches the request for a function with nArg arguments in a system
  87343. ** that uses encoding enc. The value returned indicates how well the
  87344. ** request is matched. A higher value indicates a better match.
  87345. **
  87346. ** If nArg is -1 that means to only return a match (non-zero) if p->nArg
  87347. ** is also -1. In other words, we are searching for a function that
  87348. ** takes a variable number of arguments.
  87349. **
  87350. ** If nArg is -2 that means that we are searching for any function
  87351. ** regardless of the number of arguments it uses, so return a positive
  87352. ** match score for any
  87353. **
  87354. ** The returned value is always between 0 and 6, as follows:
  87355. **
  87356. ** 0: Not a match.
  87357. ** 1: UTF8/16 conversion required and function takes any number of arguments.
  87358. ** 2: UTF16 byte order change required and function takes any number of args.
  87359. ** 3: encoding matches and function takes any number of arguments
  87360. ** 4: UTF8/16 conversion required - argument count matches exactly
  87361. ** 5: UTF16 byte order conversion required - argument count matches exactly
  87362. ** 6: Perfect match: encoding and argument count match exactly.
  87363. **
  87364. ** If nArg==(-2) then any function with a non-null xStep or xFunc is
  87365. ** a perfect match and any function with both xStep and xFunc NULL is
  87366. ** a non-match.
  87367. */
  87368. #define FUNC_PERFECT_MATCH 6 /* The score for a perfect match */
  87369. static int matchQuality(
  87370. FuncDef *p, /* The function we are evaluating for match quality */
  87371. int nArg, /* Desired number of arguments. (-1)==any */
  87372. u8 enc /* Desired text encoding */
  87373. ){
  87374. int match;
  87375. /* nArg of -2 is a special case */
  87376. if( nArg==(-2) ) return (p->xFunc==0 && p->xStep==0) ? 0 : FUNC_PERFECT_MATCH;
  87377. /* Wrong number of arguments means "no match" */
  87378. if( p->nArg!=nArg && p->nArg>=0 ) return 0;
  87379. /* Give a better score to a function with a specific number of arguments
  87380. ** than to function that accepts any number of arguments. */
  87381. if( p->nArg==nArg ){
  87382. match = 4;
  87383. }else{
  87384. match = 1;
  87385. }
  87386. /* Bonus points if the text encoding matches */
  87387. if( enc==(p->funcFlags & SQLITE_FUNC_ENCMASK) ){
  87388. match += 2; /* Exact encoding match */
  87389. }else if( (enc & p->funcFlags & 2)!=0 ){
  87390. match += 1; /* Both are UTF16, but with different byte orders */
  87391. }
  87392. return match;
  87393. }
  87394. /*
  87395. ** Search a FuncDefHash for a function with the given name. Return
  87396. ** a pointer to the matching FuncDef if found, or 0 if there is no match.
  87397. */
  87398. static FuncDef *functionSearch(
  87399. FuncDefHash *pHash, /* Hash table to search */
  87400. int h, /* Hash of the name */
  87401. const char *zFunc, /* Name of function */
  87402. int nFunc /* Number of bytes in zFunc */
  87403. ){
  87404. FuncDef *p;
  87405. for(p=pHash->a[h]; p; p=p->pHash){
  87406. if( sqlite3StrNICmp(p->zName, zFunc, nFunc)==0 && p->zName[nFunc]==0 ){
  87407. return p;
  87408. }
  87409. }
  87410. return 0;
  87411. }
  87412. /*
  87413. ** Insert a new FuncDef into a FuncDefHash hash table.
  87414. */
  87415. SQLITE_PRIVATE void sqlite3FuncDefInsert(
  87416. FuncDefHash *pHash, /* The hash table into which to insert */
  87417. FuncDef *pDef /* The function definition to insert */
  87418. ){
  87419. FuncDef *pOther;
  87420. int nName = sqlite3Strlen30(pDef->zName);
  87421. u8 c1 = (u8)pDef->zName[0];
  87422. int h = (sqlite3UpperToLower[c1] + nName) % ArraySize(pHash->a);
  87423. pOther = functionSearch(pHash, h, pDef->zName, nName);
  87424. if( pOther ){
  87425. assert( pOther!=pDef && pOther->pNext!=pDef );
  87426. pDef->pNext = pOther->pNext;
  87427. pOther->pNext = pDef;
  87428. }else{
  87429. pDef->pNext = 0;
  87430. pDef->pHash = pHash->a[h];
  87431. pHash->a[h] = pDef;
  87432. }
  87433. }
  87434. /*
  87435. ** Locate a user function given a name, a number of arguments and a flag
  87436. ** indicating whether the function prefers UTF-16 over UTF-8. Return a
  87437. ** pointer to the FuncDef structure that defines that function, or return
  87438. ** NULL if the function does not exist.
  87439. **
  87440. ** If the createFlag argument is true, then a new (blank) FuncDef
  87441. ** structure is created and liked into the "db" structure if a
  87442. ** no matching function previously existed.
  87443. **
  87444. ** If nArg is -2, then the first valid function found is returned. A
  87445. ** function is valid if either xFunc or xStep is non-zero. The nArg==(-2)
  87446. ** case is used to see if zName is a valid function name for some number
  87447. ** of arguments. If nArg is -2, then createFlag must be 0.
  87448. **
  87449. ** If createFlag is false, then a function with the required name and
  87450. ** number of arguments may be returned even if the eTextRep flag does not
  87451. ** match that requested.
  87452. */
  87453. SQLITE_PRIVATE FuncDef *sqlite3FindFunction(
  87454. sqlite3 *db, /* An open database */
  87455. const char *zName, /* Name of the function. Not null-terminated */
  87456. int nName, /* Number of characters in the name */
  87457. int nArg, /* Number of arguments. -1 means any number */
  87458. u8 enc, /* Preferred text encoding */
  87459. u8 createFlag /* Create new entry if true and does not otherwise exist */
  87460. ){
  87461. FuncDef *p; /* Iterator variable */
  87462. FuncDef *pBest = 0; /* Best match found so far */
  87463. int bestScore = 0; /* Score of best match */
  87464. int h; /* Hash value */
  87465. assert( nArg>=(-2) );
  87466. assert( nArg>=(-1) || createFlag==0 );
  87467. h = (sqlite3UpperToLower[(u8)zName[0]] + nName) % ArraySize(db->aFunc.a);
  87468. /* First search for a match amongst the application-defined functions.
  87469. */
  87470. p = functionSearch(&db->aFunc, h, zName, nName);
  87471. while( p ){
  87472. int score = matchQuality(p, nArg, enc);
  87473. if( score>bestScore ){
  87474. pBest = p;
  87475. bestScore = score;
  87476. }
  87477. p = p->pNext;
  87478. }
  87479. /* If no match is found, search the built-in functions.
  87480. **
  87481. ** If the SQLITE_PreferBuiltin flag is set, then search the built-in
  87482. ** functions even if a prior app-defined function was found. And give
  87483. ** priority to built-in functions.
  87484. **
  87485. ** Except, if createFlag is true, that means that we are trying to
  87486. ** install a new function. Whatever FuncDef structure is returned it will
  87487. ** have fields overwritten with new information appropriate for the
  87488. ** new function. But the FuncDefs for built-in functions are read-only.
  87489. ** So we must not search for built-ins when creating a new function.
  87490. */
  87491. if( !createFlag && (pBest==0 || (db->flags & SQLITE_PreferBuiltin)!=0) ){
  87492. FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
  87493. bestScore = 0;
  87494. p = functionSearch(pHash, h, zName, nName);
  87495. while( p ){
  87496. int score = matchQuality(p, nArg, enc);
  87497. if( score>bestScore ){
  87498. pBest = p;
  87499. bestScore = score;
  87500. }
  87501. p = p->pNext;
  87502. }
  87503. }
  87504. /* If the createFlag parameter is true and the search did not reveal an
  87505. ** exact match for the name, number of arguments and encoding, then add a
  87506. ** new entry to the hash table and return it.
  87507. */
  87508. if( createFlag && bestScore<FUNC_PERFECT_MATCH &&
  87509. (pBest = sqlite3DbMallocZero(db, sizeof(*pBest)+nName+1))!=0 ){
  87510. pBest->zName = (char *)&pBest[1];
  87511. pBest->nArg = (u16)nArg;
  87512. pBest->funcFlags = enc;
  87513. memcpy(pBest->zName, zName, nName);
  87514. pBest->zName[nName] = 0;
  87515. sqlite3FuncDefInsert(&db->aFunc, pBest);
  87516. }
  87517. if( pBest && (pBest->xStep || pBest->xFunc || createFlag) ){
  87518. return pBest;
  87519. }
  87520. return 0;
  87521. }
  87522. /*
  87523. ** Free all resources held by the schema structure. The void* argument points
  87524. ** at a Schema struct. This function does not call sqlite3DbFree(db, ) on the
  87525. ** pointer itself, it just cleans up subsidiary resources (i.e. the contents
  87526. ** of the schema hash tables).
  87527. **
  87528. ** The Schema.cache_size variable is not cleared.
  87529. */
  87530. SQLITE_PRIVATE void sqlite3SchemaClear(void *p){
  87531. Hash temp1;
  87532. Hash temp2;
  87533. HashElem *pElem;
  87534. Schema *pSchema = (Schema *)p;
  87535. temp1 = pSchema->tblHash;
  87536. temp2 = pSchema->trigHash;
  87537. sqlite3HashInit(&pSchema->trigHash);
  87538. sqlite3HashClear(&pSchema->idxHash);
  87539. for(pElem=sqliteHashFirst(&temp2); pElem; pElem=sqliteHashNext(pElem)){
  87540. sqlite3DeleteTrigger(0, (Trigger*)sqliteHashData(pElem));
  87541. }
  87542. sqlite3HashClear(&temp2);
  87543. sqlite3HashInit(&pSchema->tblHash);
  87544. for(pElem=sqliteHashFirst(&temp1); pElem; pElem=sqliteHashNext(pElem)){
  87545. Table *pTab = sqliteHashData(pElem);
  87546. sqlite3DeleteTable(0, pTab);
  87547. }
  87548. sqlite3HashClear(&temp1);
  87549. sqlite3HashClear(&pSchema->fkeyHash);
  87550. pSchema->pSeqTab = 0;
  87551. if( pSchema->schemaFlags & DB_SchemaLoaded ){
  87552. pSchema->iGeneration++;
  87553. pSchema->schemaFlags &= ~DB_SchemaLoaded;
  87554. }
  87555. }
  87556. /*
  87557. ** Find and return the schema associated with a BTree. Create
  87558. ** a new one if necessary.
  87559. */
  87560. SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *db, Btree *pBt){
  87561. Schema * p;
  87562. if( pBt ){
  87563. p = (Schema *)sqlite3BtreeSchema(pBt, sizeof(Schema), sqlite3SchemaClear);
  87564. }else{
  87565. p = (Schema *)sqlite3DbMallocZero(0, sizeof(Schema));
  87566. }
  87567. if( !p ){
  87568. db->mallocFailed = 1;
  87569. }else if ( 0==p->file_format ){
  87570. sqlite3HashInit(&p->tblHash);
  87571. sqlite3HashInit(&p->idxHash);
  87572. sqlite3HashInit(&p->trigHash);
  87573. sqlite3HashInit(&p->fkeyHash);
  87574. p->enc = SQLITE_UTF8;
  87575. }
  87576. return p;
  87577. }
  87578. /************** End of callback.c ********************************************/
  87579. /************** Begin file delete.c ******************************************/
  87580. /*
  87581. ** 2001 September 15
  87582. **
  87583. ** The author disclaims copyright to this source code. In place of
  87584. ** a legal notice, here is a blessing:
  87585. **
  87586. ** May you do good and not evil.
  87587. ** May you find forgiveness for yourself and forgive others.
  87588. ** May you share freely, never taking more than you give.
  87589. **
  87590. *************************************************************************
  87591. ** This file contains C code routines that are called by the parser
  87592. ** in order to generate code for DELETE FROM statements.
  87593. */
  87594. /*
  87595. ** While a SrcList can in general represent multiple tables and subqueries
  87596. ** (as in the FROM clause of a SELECT statement) in this case it contains
  87597. ** the name of a single table, as one might find in an INSERT, DELETE,
  87598. ** or UPDATE statement. Look up that table in the symbol table and
  87599. ** return a pointer. Set an error message and return NULL if the table
  87600. ** name is not found or if any other error occurs.
  87601. **
  87602. ** The following fields are initialized appropriate in pSrc:
  87603. **
  87604. ** pSrc->a[0].pTab Pointer to the Table object
  87605. ** pSrc->a[0].pIndex Pointer to the INDEXED BY index, if there is one
  87606. **
  87607. */
  87608. SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse *pParse, SrcList *pSrc){
  87609. struct SrcList_item *pItem = pSrc->a;
  87610. Table *pTab;
  87611. assert( pItem && pSrc->nSrc==1 );
  87612. pTab = sqlite3LocateTableItem(pParse, 0, pItem);
  87613. sqlite3DeleteTable(pParse->db, pItem->pTab);
  87614. pItem->pTab = pTab;
  87615. if( pTab ){
  87616. pTab->nRef++;
  87617. }
  87618. if( sqlite3IndexedByLookup(pParse, pItem) ){
  87619. pTab = 0;
  87620. }
  87621. return pTab;
  87622. }
  87623. /*
  87624. ** Check to make sure the given table is writable. If it is not
  87625. ** writable, generate an error message and return 1. If it is
  87626. ** writable return 0;
  87627. */
  87628. SQLITE_PRIVATE int sqlite3IsReadOnly(Parse *pParse, Table *pTab, int viewOk){
  87629. /* A table is not writable under the following circumstances:
  87630. **
  87631. ** 1) It is a virtual table and no implementation of the xUpdate method
  87632. ** has been provided, or
  87633. ** 2) It is a system table (i.e. sqlite_master), this call is not
  87634. ** part of a nested parse and writable_schema pragma has not
  87635. ** been specified.
  87636. **
  87637. ** In either case leave an error message in pParse and return non-zero.
  87638. */
  87639. if( ( IsVirtual(pTab)
  87640. && sqlite3GetVTable(pParse->db, pTab)->pMod->pModule->xUpdate==0 )
  87641. || ( (pTab->tabFlags & TF_Readonly)!=0
  87642. && (pParse->db->flags & SQLITE_WriteSchema)==0
  87643. && pParse->nested==0 )
  87644. ){
  87645. sqlite3ErrorMsg(pParse, "table %s may not be modified", pTab->zName);
  87646. return 1;
  87647. }
  87648. #ifndef SQLITE_OMIT_VIEW
  87649. if( !viewOk && pTab->pSelect ){
  87650. sqlite3ErrorMsg(pParse,"cannot modify %s because it is a view",pTab->zName);
  87651. return 1;
  87652. }
  87653. #endif
  87654. return 0;
  87655. }
  87656. #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
  87657. /*
  87658. ** Evaluate a view and store its result in an ephemeral table. The
  87659. ** pWhere argument is an optional WHERE clause that restricts the
  87660. ** set of rows in the view that are to be added to the ephemeral table.
  87661. */
  87662. SQLITE_PRIVATE void sqlite3MaterializeView(
  87663. Parse *pParse, /* Parsing context */
  87664. Table *pView, /* View definition */
  87665. Expr *pWhere, /* Optional WHERE clause to be added */
  87666. int iCur /* Cursor number for ephemeral table */
  87667. ){
  87668. SelectDest dest;
  87669. Select *pSel;
  87670. SrcList *pFrom;
  87671. sqlite3 *db = pParse->db;
  87672. int iDb = sqlite3SchemaToIndex(db, pView->pSchema);
  87673. pWhere = sqlite3ExprDup(db, pWhere, 0);
  87674. pFrom = sqlite3SrcListAppend(db, 0, 0, 0);
  87675. if( pFrom ){
  87676. assert( pFrom->nSrc==1 );
  87677. pFrom->a[0].zName = sqlite3DbStrDup(db, pView->zName);
  87678. pFrom->a[0].zDatabase = sqlite3DbStrDup(db, db->aDb[iDb].zName);
  87679. assert( pFrom->a[0].pOn==0 );
  87680. assert( pFrom->a[0].pUsing==0 );
  87681. }
  87682. pSel = sqlite3SelectNew(pParse, 0, pFrom, pWhere, 0, 0, 0, 0, 0, 0);
  87683. sqlite3SelectDestInit(&dest, SRT_EphemTab, iCur);
  87684. sqlite3Select(pParse, pSel, &dest);
  87685. sqlite3SelectDelete(db, pSel);
  87686. }
  87687. #endif /* !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER) */
  87688. #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
  87689. /*
  87690. ** Generate an expression tree to implement the WHERE, ORDER BY,
  87691. ** and LIMIT/OFFSET portion of DELETE and UPDATE statements.
  87692. **
  87693. ** DELETE FROM table_wxyz WHERE a<5 ORDER BY a LIMIT 1;
  87694. ** \__________________________/
  87695. ** pLimitWhere (pInClause)
  87696. */
  87697. SQLITE_PRIVATE Expr *sqlite3LimitWhere(
  87698. Parse *pParse, /* The parser context */
  87699. SrcList *pSrc, /* the FROM clause -- which tables to scan */
  87700. Expr *pWhere, /* The WHERE clause. May be null */
  87701. ExprList *pOrderBy, /* The ORDER BY clause. May be null */
  87702. Expr *pLimit, /* The LIMIT clause. May be null */
  87703. Expr *pOffset, /* The OFFSET clause. May be null */
  87704. char *zStmtType /* Either DELETE or UPDATE. For err msgs. */
  87705. ){
  87706. Expr *pWhereRowid = NULL; /* WHERE rowid .. */
  87707. Expr *pInClause = NULL; /* WHERE rowid IN ( select ) */
  87708. Expr *pSelectRowid = NULL; /* SELECT rowid ... */
  87709. ExprList *pEList = NULL; /* Expression list contaning only pSelectRowid */
  87710. SrcList *pSelectSrc = NULL; /* SELECT rowid FROM x ... (dup of pSrc) */
  87711. Select *pSelect = NULL; /* Complete SELECT tree */
  87712. /* Check that there isn't an ORDER BY without a LIMIT clause.
  87713. */
  87714. if( pOrderBy && (pLimit == 0) ) {
  87715. sqlite3ErrorMsg(pParse, "ORDER BY without LIMIT on %s", zStmtType);
  87716. goto limit_where_cleanup_2;
  87717. }
  87718. /* We only need to generate a select expression if there
  87719. ** is a limit/offset term to enforce.
  87720. */
  87721. if( pLimit == 0 ) {
  87722. /* if pLimit is null, pOffset will always be null as well. */
  87723. assert( pOffset == 0 );
  87724. return pWhere;
  87725. }
  87726. /* Generate a select expression tree to enforce the limit/offset
  87727. ** term for the DELETE or UPDATE statement. For example:
  87728. ** DELETE FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
  87729. ** becomes:
  87730. ** DELETE FROM table_a WHERE rowid IN (
  87731. ** SELECT rowid FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
  87732. ** );
  87733. */
  87734. pSelectRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0);
  87735. if( pSelectRowid == 0 ) goto limit_where_cleanup_2;
  87736. pEList = sqlite3ExprListAppend(pParse, 0, pSelectRowid);
  87737. if( pEList == 0 ) goto limit_where_cleanup_2;
  87738. /* duplicate the FROM clause as it is needed by both the DELETE/UPDATE tree
  87739. ** and the SELECT subtree. */
  87740. pSelectSrc = sqlite3SrcListDup(pParse->db, pSrc, 0);
  87741. if( pSelectSrc == 0 ) {
  87742. sqlite3ExprListDelete(pParse->db, pEList);
  87743. goto limit_where_cleanup_2;
  87744. }
  87745. /* generate the SELECT expression tree. */
  87746. pSelect = sqlite3SelectNew(pParse,pEList,pSelectSrc,pWhere,0,0,
  87747. pOrderBy,0,pLimit,pOffset);
  87748. if( pSelect == 0 ) return 0;
  87749. /* now generate the new WHERE rowid IN clause for the DELETE/UDPATE */
  87750. pWhereRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0);
  87751. if( pWhereRowid == 0 ) goto limit_where_cleanup_1;
  87752. pInClause = sqlite3PExpr(pParse, TK_IN, pWhereRowid, 0, 0);
  87753. if( pInClause == 0 ) goto limit_where_cleanup_1;
  87754. pInClause->x.pSelect = pSelect;
  87755. pInClause->flags |= EP_xIsSelect;
  87756. sqlite3ExprSetHeight(pParse, pInClause);
  87757. return pInClause;
  87758. /* something went wrong. clean up anything allocated. */
  87759. limit_where_cleanup_1:
  87760. sqlite3SelectDelete(pParse->db, pSelect);
  87761. return 0;
  87762. limit_where_cleanup_2:
  87763. sqlite3ExprDelete(pParse->db, pWhere);
  87764. sqlite3ExprListDelete(pParse->db, pOrderBy);
  87765. sqlite3ExprDelete(pParse->db, pLimit);
  87766. sqlite3ExprDelete(pParse->db, pOffset);
  87767. return 0;
  87768. }
  87769. #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) */
  87770. /* && !defined(SQLITE_OMIT_SUBQUERY) */
  87771. /*
  87772. ** Generate code for a DELETE FROM statement.
  87773. **
  87774. ** DELETE FROM table_wxyz WHERE a<5 AND b NOT NULL;
  87775. ** \________/ \________________/
  87776. ** pTabList pWhere
  87777. */
  87778. SQLITE_PRIVATE void sqlite3DeleteFrom(
  87779. Parse *pParse, /* The parser context */
  87780. SrcList *pTabList, /* The table from which we should delete things */
  87781. Expr *pWhere /* The WHERE clause. May be null */
  87782. ){
  87783. Vdbe *v; /* The virtual database engine */
  87784. Table *pTab; /* The table from which records will be deleted */
  87785. const char *zDb; /* Name of database holding pTab */
  87786. int i; /* Loop counter */
  87787. WhereInfo *pWInfo; /* Information about the WHERE clause */
  87788. Index *pIdx; /* For looping over indices of the table */
  87789. int iTabCur; /* Cursor number for the table */
  87790. int iDataCur; /* VDBE cursor for the canonical data source */
  87791. int iIdxCur; /* Cursor number of the first index */
  87792. int nIdx; /* Number of indices */
  87793. sqlite3 *db; /* Main database structure */
  87794. AuthContext sContext; /* Authorization context */
  87795. NameContext sNC; /* Name context to resolve expressions in */
  87796. int iDb; /* Database number */
  87797. int memCnt = -1; /* Memory cell used for change counting */
  87798. int rcauth; /* Value returned by authorization callback */
  87799. int okOnePass; /* True for one-pass algorithm without the FIFO */
  87800. int aiCurOnePass[2]; /* The write cursors opened by WHERE_ONEPASS */
  87801. u8 *aToOpen = 0; /* Open cursor iTabCur+j if aToOpen[j] is true */
  87802. Index *pPk; /* The PRIMARY KEY index on the table */
  87803. int iPk = 0; /* First of nPk registers holding PRIMARY KEY value */
  87804. i16 nPk = 1; /* Number of columns in the PRIMARY KEY */
  87805. int iKey; /* Memory cell holding key of row to be deleted */
  87806. i16 nKey; /* Number of memory cells in the row key */
  87807. int iEphCur = 0; /* Ephemeral table holding all primary key values */
  87808. int iRowSet = 0; /* Register for rowset of rows to delete */
  87809. int addrBypass = 0; /* Address of jump over the delete logic */
  87810. int addrLoop = 0; /* Top of the delete loop */
  87811. int addrDelete = 0; /* Jump directly to the delete logic */
  87812. int addrEphOpen = 0; /* Instruction to open the Ephemeral table */
  87813. #ifndef SQLITE_OMIT_TRIGGER
  87814. int isView; /* True if attempting to delete from a view */
  87815. Trigger *pTrigger; /* List of table triggers, if required */
  87816. #endif
  87817. memset(&sContext, 0, sizeof(sContext));
  87818. db = pParse->db;
  87819. if( pParse->nErr || db->mallocFailed ){
  87820. goto delete_from_cleanup;
  87821. }
  87822. assert( pTabList->nSrc==1 );
  87823. /* Locate the table which we want to delete. This table has to be
  87824. ** put in an SrcList structure because some of the subroutines we
  87825. ** will be calling are designed to work with multiple tables and expect
  87826. ** an SrcList* parameter instead of just a Table* parameter.
  87827. */
  87828. pTab = sqlite3SrcListLookup(pParse, pTabList);
  87829. if( pTab==0 ) goto delete_from_cleanup;
  87830. /* Figure out if we have any triggers and if the table being
  87831. ** deleted from is a view
  87832. */
  87833. #ifndef SQLITE_OMIT_TRIGGER
  87834. pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
  87835. isView = pTab->pSelect!=0;
  87836. #else
  87837. # define pTrigger 0
  87838. # define isView 0
  87839. #endif
  87840. #ifdef SQLITE_OMIT_VIEW
  87841. # undef isView
  87842. # define isView 0
  87843. #endif
  87844. /* If pTab is really a view, make sure it has been initialized.
  87845. */
  87846. if( sqlite3ViewGetColumnNames(pParse, pTab) ){
  87847. goto delete_from_cleanup;
  87848. }
  87849. if( sqlite3IsReadOnly(pParse, pTab, (pTrigger?1:0)) ){
  87850. goto delete_from_cleanup;
  87851. }
  87852. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  87853. assert( iDb<db->nDb );
  87854. zDb = db->aDb[iDb].zName;
  87855. rcauth = sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb);
  87856. assert( rcauth==SQLITE_OK || rcauth==SQLITE_DENY || rcauth==SQLITE_IGNORE );
  87857. if( rcauth==SQLITE_DENY ){
  87858. goto delete_from_cleanup;
  87859. }
  87860. assert(!isView || pTrigger);
  87861. /* Assign cursor numbers to the table and all its indices.
  87862. */
  87863. assert( pTabList->nSrc==1 );
  87864. iTabCur = pTabList->a[0].iCursor = pParse->nTab++;
  87865. for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){
  87866. pParse->nTab++;
  87867. }
  87868. /* Start the view context
  87869. */
  87870. if( isView ){
  87871. sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
  87872. }
  87873. /* Begin generating code.
  87874. */
  87875. v = sqlite3GetVdbe(pParse);
  87876. if( v==0 ){
  87877. goto delete_from_cleanup;
  87878. }
  87879. if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
  87880. sqlite3BeginWriteOperation(pParse, 1, iDb);
  87881. /* If we are trying to delete from a view, realize that view into
  87882. ** an ephemeral table.
  87883. */
  87884. #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
  87885. if( isView ){
  87886. sqlite3MaterializeView(pParse, pTab, pWhere, iTabCur);
  87887. iDataCur = iIdxCur = iTabCur;
  87888. }
  87889. #endif
  87890. /* Resolve the column names in the WHERE clause.
  87891. */
  87892. memset(&sNC, 0, sizeof(sNC));
  87893. sNC.pParse = pParse;
  87894. sNC.pSrcList = pTabList;
  87895. if( sqlite3ResolveExprNames(&sNC, pWhere) ){
  87896. goto delete_from_cleanup;
  87897. }
  87898. /* Initialize the counter of the number of rows deleted, if
  87899. ** we are counting rows.
  87900. */
  87901. if( db->flags & SQLITE_CountRows ){
  87902. memCnt = ++pParse->nMem;
  87903. sqlite3VdbeAddOp2(v, OP_Integer, 0, memCnt);
  87904. }
  87905. #ifndef SQLITE_OMIT_TRUNCATE_OPTIMIZATION
  87906. /* Special case: A DELETE without a WHERE clause deletes everything.
  87907. ** It is easier just to erase the whole table. Prior to version 3.6.5,
  87908. ** this optimization caused the row change count (the value returned by
  87909. ** API function sqlite3_count_changes) to be set incorrectly. */
  87910. if( rcauth==SQLITE_OK && pWhere==0 && !pTrigger && !IsVirtual(pTab)
  87911. && 0==sqlite3FkRequired(pParse, pTab, 0, 0)
  87912. ){
  87913. assert( !isView );
  87914. sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
  87915. if( HasRowid(pTab) ){
  87916. sqlite3VdbeAddOp4(v, OP_Clear, pTab->tnum, iDb, memCnt,
  87917. pTab->zName, P4_STATIC);
  87918. }
  87919. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  87920. assert( pIdx->pSchema==pTab->pSchema );
  87921. sqlite3VdbeAddOp2(v, OP_Clear, pIdx->tnum, iDb);
  87922. }
  87923. }else
  87924. #endif /* SQLITE_OMIT_TRUNCATE_OPTIMIZATION */
  87925. {
  87926. if( HasRowid(pTab) ){
  87927. /* For a rowid table, initialize the RowSet to an empty set */
  87928. pPk = 0;
  87929. nPk = 1;
  87930. iRowSet = ++pParse->nMem;
  87931. sqlite3VdbeAddOp2(v, OP_Null, 0, iRowSet);
  87932. }else{
  87933. /* For a WITHOUT ROWID table, create an ephemeral table used to
  87934. ** hold all primary keys for rows to be deleted. */
  87935. pPk = sqlite3PrimaryKeyIndex(pTab);
  87936. assert( pPk!=0 );
  87937. nPk = pPk->nKeyCol;
  87938. iPk = pParse->nMem+1;
  87939. pParse->nMem += nPk;
  87940. iEphCur = pParse->nTab++;
  87941. addrEphOpen = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iEphCur, nPk);
  87942. sqlite3VdbeSetP4KeyInfo(pParse, pPk);
  87943. }
  87944. /* Construct a query to find the rowid or primary key for every row
  87945. ** to be deleted, based on the WHERE clause.
  87946. */
  87947. pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0, 0,
  87948. WHERE_ONEPASS_DESIRED|WHERE_DUPLICATES_OK,
  87949. iTabCur+1);
  87950. if( pWInfo==0 ) goto delete_from_cleanup;
  87951. okOnePass = sqlite3WhereOkOnePass(pWInfo, aiCurOnePass);
  87952. /* Keep track of the number of rows to be deleted */
  87953. if( db->flags & SQLITE_CountRows ){
  87954. sqlite3VdbeAddOp2(v, OP_AddImm, memCnt, 1);
  87955. }
  87956. /* Extract the rowid or primary key for the current row */
  87957. if( pPk ){
  87958. for(i=0; i<nPk; i++){
  87959. sqlite3ExprCodeGetColumnOfTable(v, pTab, iTabCur,
  87960. pPk->aiColumn[i], iPk+i);
  87961. }
  87962. iKey = iPk;
  87963. }else{
  87964. iKey = pParse->nMem + 1;
  87965. iKey = sqlite3ExprCodeGetColumn(pParse, pTab, -1, iTabCur, iKey, 0);
  87966. if( iKey>pParse->nMem ) pParse->nMem = iKey;
  87967. }
  87968. if( okOnePass ){
  87969. /* For ONEPASS, no need to store the rowid/primary-key. There is only
  87970. ** one, so just keep it in its register(s) and fall through to the
  87971. ** delete code.
  87972. */
  87973. nKey = nPk; /* OP_Found will use an unpacked key */
  87974. aToOpen = sqlite3DbMallocRaw(db, nIdx+2);
  87975. if( aToOpen==0 ){
  87976. sqlite3WhereEnd(pWInfo);
  87977. goto delete_from_cleanup;
  87978. }
  87979. memset(aToOpen, 1, nIdx+1);
  87980. aToOpen[nIdx+1] = 0;
  87981. if( aiCurOnePass[0]>=0 ) aToOpen[aiCurOnePass[0]-iTabCur] = 0;
  87982. if( aiCurOnePass[1]>=0 ) aToOpen[aiCurOnePass[1]-iTabCur] = 0;
  87983. if( addrEphOpen ) sqlite3VdbeChangeToNoop(v, addrEphOpen);
  87984. addrDelete = sqlite3VdbeAddOp0(v, OP_Goto); /* Jump to DELETE logic */
  87985. }else if( pPk ){
  87986. /* Construct a composite key for the row to be deleted and remember it */
  87987. iKey = ++pParse->nMem;
  87988. nKey = 0; /* Zero tells OP_Found to use a composite key */
  87989. sqlite3VdbeAddOp4(v, OP_MakeRecord, iPk, nPk, iKey,
  87990. sqlite3IndexAffinityStr(v, pPk), nPk);
  87991. sqlite3VdbeAddOp2(v, OP_IdxInsert, iEphCur, iKey);
  87992. }else{
  87993. /* Get the rowid of the row to be deleted and remember it in the RowSet */
  87994. nKey = 1; /* OP_Seek always uses a single rowid */
  87995. sqlite3VdbeAddOp2(v, OP_RowSetAdd, iRowSet, iKey);
  87996. }
  87997. /* End of the WHERE loop */
  87998. sqlite3WhereEnd(pWInfo);
  87999. if( okOnePass ){
  88000. /* Bypass the delete logic below if the WHERE loop found zero rows */
  88001. addrBypass = sqlite3VdbeMakeLabel(v);
  88002. sqlite3VdbeAddOp2(v, OP_Goto, 0, addrBypass);
  88003. sqlite3VdbeJumpHere(v, addrDelete);
  88004. }
  88005. /* Unless this is a view, open cursors for the table we are
  88006. ** deleting from and all its indices. If this is a view, then the
  88007. ** only effect this statement has is to fire the INSTEAD OF
  88008. ** triggers.
  88009. */
  88010. if( !isView ){
  88011. testcase( IsVirtual(pTab) );
  88012. sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, iTabCur, aToOpen,
  88013. &iDataCur, &iIdxCur);
  88014. assert( pPk || IsVirtual(pTab) || iDataCur==iTabCur );
  88015. assert( pPk || IsVirtual(pTab) || iIdxCur==iDataCur+1 );
  88016. }
  88017. /* Set up a loop over the rowids/primary-keys that were found in the
  88018. ** where-clause loop above.
  88019. */
  88020. if( okOnePass ){
  88021. /* Just one row. Hence the top-of-loop is a no-op */
  88022. assert( nKey==nPk ); /* OP_Found will use an unpacked key */
  88023. assert( !IsVirtual(pTab) );
  88024. if( aToOpen[iDataCur-iTabCur] ){
  88025. assert( pPk!=0 );
  88026. sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, addrBypass, iKey, nKey);
  88027. VdbeCoverage(v);
  88028. }
  88029. }else if( pPk ){
  88030. addrLoop = sqlite3VdbeAddOp1(v, OP_Rewind, iEphCur); VdbeCoverage(v);
  88031. sqlite3VdbeAddOp2(v, OP_RowKey, iEphCur, iKey);
  88032. assert( nKey==0 ); /* OP_Found will use a composite key */
  88033. }else{
  88034. addrLoop = sqlite3VdbeAddOp3(v, OP_RowSetRead, iRowSet, 0, iKey);
  88035. VdbeCoverage(v);
  88036. assert( nKey==1 );
  88037. }
  88038. /* Delete the row */
  88039. #ifndef SQLITE_OMIT_VIRTUALTABLE
  88040. if( IsVirtual(pTab) ){
  88041. const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
  88042. sqlite3VtabMakeWritable(pParse, pTab);
  88043. sqlite3VdbeAddOp4(v, OP_VUpdate, 0, 1, iKey, pVTab, P4_VTAB);
  88044. sqlite3VdbeChangeP5(v, OE_Abort);
  88045. sqlite3MayAbort(pParse);
  88046. }else
  88047. #endif
  88048. {
  88049. int count = (pParse->nested==0); /* True to count changes */
  88050. sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
  88051. iKey, nKey, count, OE_Default, okOnePass);
  88052. }
  88053. /* End of the loop over all rowids/primary-keys. */
  88054. if( okOnePass ){
  88055. sqlite3VdbeResolveLabel(v, addrBypass);
  88056. }else if( pPk ){
  88057. sqlite3VdbeAddOp2(v, OP_Next, iEphCur, addrLoop+1); VdbeCoverage(v);
  88058. sqlite3VdbeJumpHere(v, addrLoop);
  88059. }else{
  88060. sqlite3VdbeAddOp2(v, OP_Goto, 0, addrLoop);
  88061. sqlite3VdbeJumpHere(v, addrLoop);
  88062. }
  88063. /* Close the cursors open on the table and its indexes. */
  88064. if( !isView && !IsVirtual(pTab) ){
  88065. if( !pPk ) sqlite3VdbeAddOp1(v, OP_Close, iDataCur);
  88066. for(i=0, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
  88067. sqlite3VdbeAddOp1(v, OP_Close, iIdxCur + i);
  88068. }
  88069. }
  88070. } /* End non-truncate path */
  88071. /* Update the sqlite_sequence table by storing the content of the
  88072. ** maximum rowid counter values recorded while inserting into
  88073. ** autoincrement tables.
  88074. */
  88075. if( pParse->nested==0 && pParse->pTriggerTab==0 ){
  88076. sqlite3AutoincrementEnd(pParse);
  88077. }
  88078. /* Return the number of rows that were deleted. If this routine is
  88079. ** generating code because of a call to sqlite3NestedParse(), do not
  88080. ** invoke the callback function.
  88081. */
  88082. if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
  88083. sqlite3VdbeAddOp2(v, OP_ResultRow, memCnt, 1);
  88084. sqlite3VdbeSetNumCols(v, 1);
  88085. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows deleted", SQLITE_STATIC);
  88086. }
  88087. delete_from_cleanup:
  88088. sqlite3AuthContextPop(&sContext);
  88089. sqlite3SrcListDelete(db, pTabList);
  88090. sqlite3ExprDelete(db, pWhere);
  88091. sqlite3DbFree(db, aToOpen);
  88092. return;
  88093. }
  88094. /* Make sure "isView" and other macros defined above are undefined. Otherwise
  88095. ** they may interfere with compilation of other functions in this file
  88096. ** (or in another file, if this file becomes part of the amalgamation). */
  88097. #ifdef isView
  88098. #undef isView
  88099. #endif
  88100. #ifdef pTrigger
  88101. #undef pTrigger
  88102. #endif
  88103. /*
  88104. ** This routine generates VDBE code that causes a single row of a
  88105. ** single table to be deleted. Both the original table entry and
  88106. ** all indices are removed.
  88107. **
  88108. ** Preconditions:
  88109. **
  88110. ** 1. iDataCur is an open cursor on the btree that is the canonical data
  88111. ** store for the table. (This will be either the table itself,
  88112. ** in the case of a rowid table, or the PRIMARY KEY index in the case
  88113. ** of a WITHOUT ROWID table.)
  88114. **
  88115. ** 2. Read/write cursors for all indices of pTab must be open as
  88116. ** cursor number iIdxCur+i for the i-th index.
  88117. **
  88118. ** 3. The primary key for the row to be deleted must be stored in a
  88119. ** sequence of nPk memory cells starting at iPk. If nPk==0 that means
  88120. ** that a search record formed from OP_MakeRecord is contained in the
  88121. ** single memory location iPk.
  88122. */
  88123. SQLITE_PRIVATE void sqlite3GenerateRowDelete(
  88124. Parse *pParse, /* Parsing context */
  88125. Table *pTab, /* Table containing the row to be deleted */
  88126. Trigger *pTrigger, /* List of triggers to (potentially) fire */
  88127. int iDataCur, /* Cursor from which column data is extracted */
  88128. int iIdxCur, /* First index cursor */
  88129. int iPk, /* First memory cell containing the PRIMARY KEY */
  88130. i16 nPk, /* Number of PRIMARY KEY memory cells */
  88131. u8 count, /* If non-zero, increment the row change counter */
  88132. u8 onconf, /* Default ON CONFLICT policy for triggers */
  88133. u8 bNoSeek /* iDataCur is already pointing to the row to delete */
  88134. ){
  88135. Vdbe *v = pParse->pVdbe; /* Vdbe */
  88136. int iOld = 0; /* First register in OLD.* array */
  88137. int iLabel; /* Label resolved to end of generated code */
  88138. u8 opSeek; /* Seek opcode */
  88139. /* Vdbe is guaranteed to have been allocated by this stage. */
  88140. assert( v );
  88141. VdbeModuleComment((v, "BEGIN: GenRowDel(%d,%d,%d,%d)",
  88142. iDataCur, iIdxCur, iPk, (int)nPk));
  88143. /* Seek cursor iCur to the row to delete. If this row no longer exists
  88144. ** (this can happen if a trigger program has already deleted it), do
  88145. ** not attempt to delete it or fire any DELETE triggers. */
  88146. iLabel = sqlite3VdbeMakeLabel(v);
  88147. opSeek = HasRowid(pTab) ? OP_NotExists : OP_NotFound;
  88148. if( !bNoSeek ){
  88149. sqlite3VdbeAddOp4Int(v, opSeek, iDataCur, iLabel, iPk, nPk);
  88150. VdbeCoverageIf(v, opSeek==OP_NotExists);
  88151. VdbeCoverageIf(v, opSeek==OP_NotFound);
  88152. }
  88153. /* If there are any triggers to fire, allocate a range of registers to
  88154. ** use for the old.* references in the triggers. */
  88155. if( sqlite3FkRequired(pParse, pTab, 0, 0) || pTrigger ){
  88156. u32 mask; /* Mask of OLD.* columns in use */
  88157. int iCol; /* Iterator used while populating OLD.* */
  88158. int addrStart; /* Start of BEFORE trigger programs */
  88159. /* TODO: Could use temporary registers here. Also could attempt to
  88160. ** avoid copying the contents of the rowid register. */
  88161. mask = sqlite3TriggerColmask(
  88162. pParse, pTrigger, 0, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onconf
  88163. );
  88164. mask |= sqlite3FkOldmask(pParse, pTab);
  88165. iOld = pParse->nMem+1;
  88166. pParse->nMem += (1 + pTab->nCol);
  88167. /* Populate the OLD.* pseudo-table register array. These values will be
  88168. ** used by any BEFORE and AFTER triggers that exist. */
  88169. sqlite3VdbeAddOp2(v, OP_Copy, iPk, iOld);
  88170. for(iCol=0; iCol<pTab->nCol; iCol++){
  88171. testcase( mask!=0xffffffff && iCol==31 );
  88172. testcase( mask!=0xffffffff && iCol==32 );
  88173. if( mask==0xffffffff || (iCol<=31 && (mask & MASKBIT32(iCol))!=0) ){
  88174. sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, iCol, iOld+iCol+1);
  88175. }
  88176. }
  88177. /* Invoke BEFORE DELETE trigger programs. */
  88178. addrStart = sqlite3VdbeCurrentAddr(v);
  88179. sqlite3CodeRowTrigger(pParse, pTrigger,
  88180. TK_DELETE, 0, TRIGGER_BEFORE, pTab, iOld, onconf, iLabel
  88181. );
  88182. /* If any BEFORE triggers were coded, then seek the cursor to the
  88183. ** row to be deleted again. It may be that the BEFORE triggers moved
  88184. ** the cursor or of already deleted the row that the cursor was
  88185. ** pointing to.
  88186. */
  88187. if( addrStart<sqlite3VdbeCurrentAddr(v) ){
  88188. sqlite3VdbeAddOp4Int(v, opSeek, iDataCur, iLabel, iPk, nPk);
  88189. VdbeCoverageIf(v, opSeek==OP_NotExists);
  88190. VdbeCoverageIf(v, opSeek==OP_NotFound);
  88191. }
  88192. /* Do FK processing. This call checks that any FK constraints that
  88193. ** refer to this table (i.e. constraints attached to other tables)
  88194. ** are not violated by deleting this row. */
  88195. sqlite3FkCheck(pParse, pTab, iOld, 0, 0, 0);
  88196. }
  88197. /* Delete the index and table entries. Skip this step if pTab is really
  88198. ** a view (in which case the only effect of the DELETE statement is to
  88199. ** fire the INSTEAD OF triggers). */
  88200. if( pTab->pSelect==0 ){
  88201. sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur, 0);
  88202. sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, (count?OPFLAG_NCHANGE:0));
  88203. if( count ){
  88204. sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_TRANSIENT);
  88205. }
  88206. }
  88207. /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
  88208. ** handle rows (possibly in other tables) that refer via a foreign key
  88209. ** to the row just deleted. */
  88210. sqlite3FkActions(pParse, pTab, 0, iOld, 0, 0);
  88211. /* Invoke AFTER DELETE trigger programs. */
  88212. sqlite3CodeRowTrigger(pParse, pTrigger,
  88213. TK_DELETE, 0, TRIGGER_AFTER, pTab, iOld, onconf, iLabel
  88214. );
  88215. /* Jump here if the row had already been deleted before any BEFORE
  88216. ** trigger programs were invoked. Or if a trigger program throws a
  88217. ** RAISE(IGNORE) exception. */
  88218. sqlite3VdbeResolveLabel(v, iLabel);
  88219. VdbeModuleComment((v, "END: GenRowDel()"));
  88220. }
  88221. /*
  88222. ** This routine generates VDBE code that causes the deletion of all
  88223. ** index entries associated with a single row of a single table, pTab
  88224. **
  88225. ** Preconditions:
  88226. **
  88227. ** 1. A read/write cursor "iDataCur" must be open on the canonical storage
  88228. ** btree for the table pTab. (This will be either the table itself
  88229. ** for rowid tables or to the primary key index for WITHOUT ROWID
  88230. ** tables.)
  88231. **
  88232. ** 2. Read/write cursors for all indices of pTab must be open as
  88233. ** cursor number iIdxCur+i for the i-th index. (The pTab->pIndex
  88234. ** index is the 0-th index.)
  88235. **
  88236. ** 3. The "iDataCur" cursor must be already be positioned on the row
  88237. ** that is to be deleted.
  88238. */
  88239. SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(
  88240. Parse *pParse, /* Parsing and code generating context */
  88241. Table *pTab, /* Table containing the row to be deleted */
  88242. int iDataCur, /* Cursor of table holding data. */
  88243. int iIdxCur, /* First index cursor */
  88244. int *aRegIdx /* Only delete if aRegIdx!=0 && aRegIdx[i]>0 */
  88245. ){
  88246. int i; /* Index loop counter */
  88247. int r1 = -1; /* Register holding an index key */
  88248. int iPartIdxLabel; /* Jump destination for skipping partial index entries */
  88249. Index *pIdx; /* Current index */
  88250. Index *pPrior = 0; /* Prior index */
  88251. Vdbe *v; /* The prepared statement under construction */
  88252. Index *pPk; /* PRIMARY KEY index, or NULL for rowid tables */
  88253. v = pParse->pVdbe;
  88254. pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab);
  88255. for(i=0, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
  88256. assert( iIdxCur+i!=iDataCur || pPk==pIdx );
  88257. if( aRegIdx!=0 && aRegIdx[i]==0 ) continue;
  88258. if( pIdx==pPk ) continue;
  88259. VdbeModuleComment((v, "GenRowIdxDel for %s", pIdx->zName));
  88260. r1 = sqlite3GenerateIndexKey(pParse, pIdx, iDataCur, 0, 1,
  88261. &iPartIdxLabel, pPrior, r1);
  88262. sqlite3VdbeAddOp3(v, OP_IdxDelete, iIdxCur+i, r1,
  88263. pIdx->uniqNotNull ? pIdx->nKeyCol : pIdx->nColumn);
  88264. sqlite3ResolvePartIdxLabel(pParse, iPartIdxLabel);
  88265. pPrior = pIdx;
  88266. }
  88267. }
  88268. /*
  88269. ** Generate code that will assemble an index key and stores it in register
  88270. ** regOut. The key with be for index pIdx which is an index on pTab.
  88271. ** iCur is the index of a cursor open on the pTab table and pointing to
  88272. ** the entry that needs indexing. If pTab is a WITHOUT ROWID table, then
  88273. ** iCur must be the cursor of the PRIMARY KEY index.
  88274. **
  88275. ** Return a register number which is the first in a block of
  88276. ** registers that holds the elements of the index key. The
  88277. ** block of registers has already been deallocated by the time
  88278. ** this routine returns.
  88279. **
  88280. ** If *piPartIdxLabel is not NULL, fill it in with a label and jump
  88281. ** to that label if pIdx is a partial index that should be skipped.
  88282. ** The label should be resolved using sqlite3ResolvePartIdxLabel().
  88283. ** A partial index should be skipped if its WHERE clause evaluates
  88284. ** to false or null. If pIdx is not a partial index, *piPartIdxLabel
  88285. ** will be set to zero which is an empty label that is ignored by
  88286. ** sqlite3ResolvePartIdxLabel().
  88287. **
  88288. ** The pPrior and regPrior parameters are used to implement a cache to
  88289. ** avoid unnecessary register loads. If pPrior is not NULL, then it is
  88290. ** a pointer to a different index for which an index key has just been
  88291. ** computed into register regPrior. If the current pIdx index is generating
  88292. ** its key into the same sequence of registers and if pPrior and pIdx share
  88293. ** a column in common, then the register corresponding to that column already
  88294. ** holds the correct value and the loading of that register is skipped.
  88295. ** This optimization is helpful when doing a DELETE or an INTEGRITY_CHECK
  88296. ** on a table with multiple indices, and especially with the ROWID or
  88297. ** PRIMARY KEY columns of the index.
  88298. */
  88299. SQLITE_PRIVATE int sqlite3GenerateIndexKey(
  88300. Parse *pParse, /* Parsing context */
  88301. Index *pIdx, /* The index for which to generate a key */
  88302. int iDataCur, /* Cursor number from which to take column data */
  88303. int regOut, /* Put the new key into this register if not 0 */
  88304. int prefixOnly, /* Compute only a unique prefix of the key */
  88305. int *piPartIdxLabel, /* OUT: Jump to this label to skip partial index */
  88306. Index *pPrior, /* Previously generated index key */
  88307. int regPrior /* Register holding previous generated key */
  88308. ){
  88309. Vdbe *v = pParse->pVdbe;
  88310. int j;
  88311. Table *pTab = pIdx->pTable;
  88312. int regBase;
  88313. int nCol;
  88314. if( piPartIdxLabel ){
  88315. if( pIdx->pPartIdxWhere ){
  88316. *piPartIdxLabel = sqlite3VdbeMakeLabel(v);
  88317. pParse->iPartIdxTab = iDataCur;
  88318. sqlite3ExprCachePush(pParse);
  88319. sqlite3ExprIfFalse(pParse, pIdx->pPartIdxWhere, *piPartIdxLabel,
  88320. SQLITE_JUMPIFNULL);
  88321. }else{
  88322. *piPartIdxLabel = 0;
  88323. }
  88324. }
  88325. nCol = (prefixOnly && pIdx->uniqNotNull) ? pIdx->nKeyCol : pIdx->nColumn;
  88326. regBase = sqlite3GetTempRange(pParse, nCol);
  88327. if( pPrior && (regBase!=regPrior || pPrior->pPartIdxWhere) ) pPrior = 0;
  88328. for(j=0; j<nCol; j++){
  88329. if( pPrior && pPrior->aiColumn[j]==pIdx->aiColumn[j] ) continue;
  88330. sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, pIdx->aiColumn[j],
  88331. regBase+j);
  88332. /* If the column affinity is REAL but the number is an integer, then it
  88333. ** might be stored in the table as an integer (using a compact
  88334. ** representation) then converted to REAL by an OP_RealAffinity opcode.
  88335. ** But we are getting ready to store this value back into an index, where
  88336. ** it should be converted by to INTEGER again. So omit the OP_RealAffinity
  88337. ** opcode if it is present */
  88338. sqlite3VdbeDeletePriorOpcode(v, OP_RealAffinity);
  88339. }
  88340. if( regOut ){
  88341. sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regOut);
  88342. }
  88343. sqlite3ReleaseTempRange(pParse, regBase, nCol);
  88344. return regBase;
  88345. }
  88346. /*
  88347. ** If a prior call to sqlite3GenerateIndexKey() generated a jump-over label
  88348. ** because it was a partial index, then this routine should be called to
  88349. ** resolve that label.
  88350. */
  88351. SQLITE_PRIVATE void sqlite3ResolvePartIdxLabel(Parse *pParse, int iLabel){
  88352. if( iLabel ){
  88353. sqlite3VdbeResolveLabel(pParse->pVdbe, iLabel);
  88354. sqlite3ExprCachePop(pParse);
  88355. }
  88356. }
  88357. /************** End of delete.c **********************************************/
  88358. /************** Begin file func.c ********************************************/
  88359. /*
  88360. ** 2002 February 23
  88361. **
  88362. ** The author disclaims copyright to this source code. In place of
  88363. ** a legal notice, here is a blessing:
  88364. **
  88365. ** May you do good and not evil.
  88366. ** May you find forgiveness for yourself and forgive others.
  88367. ** May you share freely, never taking more than you give.
  88368. **
  88369. *************************************************************************
  88370. ** This file contains the C-language implementations for many of the SQL
  88371. ** functions of SQLite. (Some function, and in particular the date and
  88372. ** time functions, are implemented separately.)
  88373. */
  88374. /* #include <stdlib.h> */
  88375. /* #include <assert.h> */
  88376. /*
  88377. ** Return the collating function associated with a function.
  88378. */
  88379. static CollSeq *sqlite3GetFuncCollSeq(sqlite3_context *context){
  88380. VdbeOp *pOp = &context->pVdbe->aOp[context->iOp-1];
  88381. assert( pOp->opcode==OP_CollSeq );
  88382. assert( pOp->p4type==P4_COLLSEQ );
  88383. return pOp->p4.pColl;
  88384. }
  88385. /*
  88386. ** Indicate that the accumulator load should be skipped on this
  88387. ** iteration of the aggregate loop.
  88388. */
  88389. static void sqlite3SkipAccumulatorLoad(sqlite3_context *context){
  88390. context->skipFlag = 1;
  88391. }
  88392. /*
  88393. ** Implementation of the non-aggregate min() and max() functions
  88394. */
  88395. static void minmaxFunc(
  88396. sqlite3_context *context,
  88397. int argc,
  88398. sqlite3_value **argv
  88399. ){
  88400. int i;
  88401. int mask; /* 0 for min() or 0xffffffff for max() */
  88402. int iBest;
  88403. CollSeq *pColl;
  88404. assert( argc>1 );
  88405. mask = sqlite3_user_data(context)==0 ? 0 : -1;
  88406. pColl = sqlite3GetFuncCollSeq(context);
  88407. assert( pColl );
  88408. assert( mask==-1 || mask==0 );
  88409. iBest = 0;
  88410. if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
  88411. for(i=1; i<argc; i++){
  88412. if( sqlite3_value_type(argv[i])==SQLITE_NULL ) return;
  88413. if( (sqlite3MemCompare(argv[iBest], argv[i], pColl)^mask)>=0 ){
  88414. testcase( mask==0 );
  88415. iBest = i;
  88416. }
  88417. }
  88418. sqlite3_result_value(context, argv[iBest]);
  88419. }
  88420. /*
  88421. ** Return the type of the argument.
  88422. */
  88423. static void typeofFunc(
  88424. sqlite3_context *context,
  88425. int NotUsed,
  88426. sqlite3_value **argv
  88427. ){
  88428. const char *z = 0;
  88429. UNUSED_PARAMETER(NotUsed);
  88430. switch( sqlite3_value_type(argv[0]) ){
  88431. case SQLITE_INTEGER: z = "integer"; break;
  88432. case SQLITE_TEXT: z = "text"; break;
  88433. case SQLITE_FLOAT: z = "real"; break;
  88434. case SQLITE_BLOB: z = "blob"; break;
  88435. default: z = "null"; break;
  88436. }
  88437. sqlite3_result_text(context, z, -1, SQLITE_STATIC);
  88438. }
  88439. /*
  88440. ** Implementation of the length() function
  88441. */
  88442. static void lengthFunc(
  88443. sqlite3_context *context,
  88444. int argc,
  88445. sqlite3_value **argv
  88446. ){
  88447. int len;
  88448. assert( argc==1 );
  88449. UNUSED_PARAMETER(argc);
  88450. switch( sqlite3_value_type(argv[0]) ){
  88451. case SQLITE_BLOB:
  88452. case SQLITE_INTEGER:
  88453. case SQLITE_FLOAT: {
  88454. sqlite3_result_int(context, sqlite3_value_bytes(argv[0]));
  88455. break;
  88456. }
  88457. case SQLITE_TEXT: {
  88458. const unsigned char *z = sqlite3_value_text(argv[0]);
  88459. if( z==0 ) return;
  88460. len = 0;
  88461. while( *z ){
  88462. len++;
  88463. SQLITE_SKIP_UTF8(z);
  88464. }
  88465. sqlite3_result_int(context, len);
  88466. break;
  88467. }
  88468. default: {
  88469. sqlite3_result_null(context);
  88470. break;
  88471. }
  88472. }
  88473. }
  88474. /*
  88475. ** Implementation of the abs() function.
  88476. **
  88477. ** IMP: R-23979-26855 The abs(X) function returns the absolute value of
  88478. ** the numeric argument X.
  88479. */
  88480. static void absFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
  88481. assert( argc==1 );
  88482. UNUSED_PARAMETER(argc);
  88483. switch( sqlite3_value_type(argv[0]) ){
  88484. case SQLITE_INTEGER: {
  88485. i64 iVal = sqlite3_value_int64(argv[0]);
  88486. if( iVal<0 ){
  88487. if( iVal==SMALLEST_INT64 ){
  88488. /* IMP: R-31676-45509 If X is the integer -9223372036854775808
  88489. ** then abs(X) throws an integer overflow error since there is no
  88490. ** equivalent positive 64-bit two complement value. */
  88491. sqlite3_result_error(context, "integer overflow", -1);
  88492. return;
  88493. }
  88494. iVal = -iVal;
  88495. }
  88496. sqlite3_result_int64(context, iVal);
  88497. break;
  88498. }
  88499. case SQLITE_NULL: {
  88500. /* IMP: R-37434-19929 Abs(X) returns NULL if X is NULL. */
  88501. sqlite3_result_null(context);
  88502. break;
  88503. }
  88504. default: {
  88505. /* Because sqlite3_value_double() returns 0.0 if the argument is not
  88506. ** something that can be converted into a number, we have:
  88507. ** IMP: R-57326-31541 Abs(X) return 0.0 if X is a string or blob that
  88508. ** cannot be converted to a numeric value.
  88509. */
  88510. double rVal = sqlite3_value_double(argv[0]);
  88511. if( rVal<0 ) rVal = -rVal;
  88512. sqlite3_result_double(context, rVal);
  88513. break;
  88514. }
  88515. }
  88516. }
  88517. /*
  88518. ** Implementation of the instr() function.
  88519. **
  88520. ** instr(haystack,needle) finds the first occurrence of needle
  88521. ** in haystack and returns the number of previous characters plus 1,
  88522. ** or 0 if needle does not occur within haystack.
  88523. **
  88524. ** If both haystack and needle are BLOBs, then the result is one more than
  88525. ** the number of bytes in haystack prior to the first occurrence of needle,
  88526. ** or 0 if needle never occurs in haystack.
  88527. */
  88528. static void instrFunc(
  88529. sqlite3_context *context,
  88530. int argc,
  88531. sqlite3_value **argv
  88532. ){
  88533. const unsigned char *zHaystack;
  88534. const unsigned char *zNeedle;
  88535. int nHaystack;
  88536. int nNeedle;
  88537. int typeHaystack, typeNeedle;
  88538. int N = 1;
  88539. int isText;
  88540. UNUSED_PARAMETER(argc);
  88541. typeHaystack = sqlite3_value_type(argv[0]);
  88542. typeNeedle = sqlite3_value_type(argv[1]);
  88543. if( typeHaystack==SQLITE_NULL || typeNeedle==SQLITE_NULL ) return;
  88544. nHaystack = sqlite3_value_bytes(argv[0]);
  88545. nNeedle = sqlite3_value_bytes(argv[1]);
  88546. if( typeHaystack==SQLITE_BLOB && typeNeedle==SQLITE_BLOB ){
  88547. zHaystack = sqlite3_value_blob(argv[0]);
  88548. zNeedle = sqlite3_value_blob(argv[1]);
  88549. isText = 0;
  88550. }else{
  88551. zHaystack = sqlite3_value_text(argv[0]);
  88552. zNeedle = sqlite3_value_text(argv[1]);
  88553. isText = 1;
  88554. }
  88555. while( nNeedle<=nHaystack && memcmp(zHaystack, zNeedle, nNeedle)!=0 ){
  88556. N++;
  88557. do{
  88558. nHaystack--;
  88559. zHaystack++;
  88560. }while( isText && (zHaystack[0]&0xc0)==0x80 );
  88561. }
  88562. if( nNeedle>nHaystack ) N = 0;
  88563. sqlite3_result_int(context, N);
  88564. }
  88565. /*
  88566. ** Implementation of the printf() function.
  88567. */
  88568. static void printfFunc(
  88569. sqlite3_context *context,
  88570. int argc,
  88571. sqlite3_value **argv
  88572. ){
  88573. PrintfArguments x;
  88574. StrAccum str;
  88575. const char *zFormat;
  88576. int n;
  88577. if( argc>=1 && (zFormat = (const char*)sqlite3_value_text(argv[0]))!=0 ){
  88578. x.nArg = argc-1;
  88579. x.nUsed = 0;
  88580. x.apArg = argv+1;
  88581. sqlite3StrAccumInit(&str, 0, 0, SQLITE_MAX_LENGTH);
  88582. str.db = sqlite3_context_db_handle(context);
  88583. sqlite3XPrintf(&str, SQLITE_PRINTF_SQLFUNC, zFormat, &x);
  88584. n = str.nChar;
  88585. sqlite3_result_text(context, sqlite3StrAccumFinish(&str), n,
  88586. SQLITE_DYNAMIC);
  88587. }
  88588. }
  88589. /*
  88590. ** Implementation of the substr() function.
  88591. **
  88592. ** substr(x,p1,p2) returns p2 characters of x[] beginning with p1.
  88593. ** p1 is 1-indexed. So substr(x,1,1) returns the first character
  88594. ** of x. If x is text, then we actually count UTF-8 characters.
  88595. ** If x is a blob, then we count bytes.
  88596. **
  88597. ** If p1 is negative, then we begin abs(p1) from the end of x[].
  88598. **
  88599. ** If p2 is negative, return the p2 characters preceding p1.
  88600. */
  88601. static void substrFunc(
  88602. sqlite3_context *context,
  88603. int argc,
  88604. sqlite3_value **argv
  88605. ){
  88606. const unsigned char *z;
  88607. const unsigned char *z2;
  88608. int len;
  88609. int p0type;
  88610. i64 p1, p2;
  88611. int negP2 = 0;
  88612. assert( argc==3 || argc==2 );
  88613. if( sqlite3_value_type(argv[1])==SQLITE_NULL
  88614. || (argc==3 && sqlite3_value_type(argv[2])==SQLITE_NULL)
  88615. ){
  88616. return;
  88617. }
  88618. p0type = sqlite3_value_type(argv[0]);
  88619. p1 = sqlite3_value_int(argv[1]);
  88620. if( p0type==SQLITE_BLOB ){
  88621. len = sqlite3_value_bytes(argv[0]);
  88622. z = sqlite3_value_blob(argv[0]);
  88623. if( z==0 ) return;
  88624. assert( len==sqlite3_value_bytes(argv[0]) );
  88625. }else{
  88626. z = sqlite3_value_text(argv[0]);
  88627. if( z==0 ) return;
  88628. len = 0;
  88629. if( p1<0 ){
  88630. for(z2=z; *z2; len++){
  88631. SQLITE_SKIP_UTF8(z2);
  88632. }
  88633. }
  88634. }
  88635. if( argc==3 ){
  88636. p2 = sqlite3_value_int(argv[2]);
  88637. if( p2<0 ){
  88638. p2 = -p2;
  88639. negP2 = 1;
  88640. }
  88641. }else{
  88642. p2 = sqlite3_context_db_handle(context)->aLimit[SQLITE_LIMIT_LENGTH];
  88643. }
  88644. if( p1<0 ){
  88645. p1 += len;
  88646. if( p1<0 ){
  88647. p2 += p1;
  88648. if( p2<0 ) p2 = 0;
  88649. p1 = 0;
  88650. }
  88651. }else if( p1>0 ){
  88652. p1--;
  88653. }else if( p2>0 ){
  88654. p2--;
  88655. }
  88656. if( negP2 ){
  88657. p1 -= p2;
  88658. if( p1<0 ){
  88659. p2 += p1;
  88660. p1 = 0;
  88661. }
  88662. }
  88663. assert( p1>=0 && p2>=0 );
  88664. if( p0type!=SQLITE_BLOB ){
  88665. while( *z && p1 ){
  88666. SQLITE_SKIP_UTF8(z);
  88667. p1--;
  88668. }
  88669. for(z2=z; *z2 && p2; p2--){
  88670. SQLITE_SKIP_UTF8(z2);
  88671. }
  88672. sqlite3_result_text64(context, (char*)z, z2-z, SQLITE_TRANSIENT,
  88673. SQLITE_UTF8);
  88674. }else{
  88675. if( p1+p2>len ){
  88676. p2 = len-p1;
  88677. if( p2<0 ) p2 = 0;
  88678. }
  88679. sqlite3_result_blob64(context, (char*)&z[p1], (u64)p2, SQLITE_TRANSIENT);
  88680. }
  88681. }
  88682. /*
  88683. ** Implementation of the round() function
  88684. */
  88685. #ifndef SQLITE_OMIT_FLOATING_POINT
  88686. static void roundFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
  88687. int n = 0;
  88688. double r;
  88689. char *zBuf;
  88690. assert( argc==1 || argc==2 );
  88691. if( argc==2 ){
  88692. if( SQLITE_NULL==sqlite3_value_type(argv[1]) ) return;
  88693. n = sqlite3_value_int(argv[1]);
  88694. if( n>30 ) n = 30;
  88695. if( n<0 ) n = 0;
  88696. }
  88697. if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
  88698. r = sqlite3_value_double(argv[0]);
  88699. /* If Y==0 and X will fit in a 64-bit int,
  88700. ** handle the rounding directly,
  88701. ** otherwise use printf.
  88702. */
  88703. if( n==0 && r>=0 && r<LARGEST_INT64-1 ){
  88704. r = (double)((sqlite_int64)(r+0.5));
  88705. }else if( n==0 && r<0 && (-r)<LARGEST_INT64-1 ){
  88706. r = -(double)((sqlite_int64)((-r)+0.5));
  88707. }else{
  88708. zBuf = sqlite3_mprintf("%.*f",n,r);
  88709. if( zBuf==0 ){
  88710. sqlite3_result_error_nomem(context);
  88711. return;
  88712. }
  88713. sqlite3AtoF(zBuf, &r, sqlite3Strlen30(zBuf), SQLITE_UTF8);
  88714. sqlite3_free(zBuf);
  88715. }
  88716. sqlite3_result_double(context, r);
  88717. }
  88718. #endif
  88719. /*
  88720. ** Allocate nByte bytes of space using sqlite3_malloc(). If the
  88721. ** allocation fails, call sqlite3_result_error_nomem() to notify
  88722. ** the database handle that malloc() has failed and return NULL.
  88723. ** If nByte is larger than the maximum string or blob length, then
  88724. ** raise an SQLITE_TOOBIG exception and return NULL.
  88725. */
  88726. static void *contextMalloc(sqlite3_context *context, i64 nByte){
  88727. char *z;
  88728. sqlite3 *db = sqlite3_context_db_handle(context);
  88729. assert( nByte>0 );
  88730. testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH] );
  88731. testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
  88732. if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  88733. sqlite3_result_error_toobig(context);
  88734. z = 0;
  88735. }else{
  88736. z = sqlite3Malloc(nByte);
  88737. if( !z ){
  88738. sqlite3_result_error_nomem(context);
  88739. }
  88740. }
  88741. return z;
  88742. }
  88743. /*
  88744. ** Implementation of the upper() and lower() SQL functions.
  88745. */
  88746. static void upperFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
  88747. char *z1;
  88748. const char *z2;
  88749. int i, n;
  88750. UNUSED_PARAMETER(argc);
  88751. z2 = (char*)sqlite3_value_text(argv[0]);
  88752. n = sqlite3_value_bytes(argv[0]);
  88753. /* Verify that the call to _bytes() does not invalidate the _text() pointer */
  88754. assert( z2==(char*)sqlite3_value_text(argv[0]) );
  88755. if( z2 ){
  88756. z1 = contextMalloc(context, ((i64)n)+1);
  88757. if( z1 ){
  88758. for(i=0; i<n; i++){
  88759. z1[i] = (char)sqlite3Toupper(z2[i]);
  88760. }
  88761. sqlite3_result_text(context, z1, n, sqlite3_free);
  88762. }
  88763. }
  88764. }
  88765. static void lowerFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
  88766. char *z1;
  88767. const char *z2;
  88768. int i, n;
  88769. UNUSED_PARAMETER(argc);
  88770. z2 = (char*)sqlite3_value_text(argv[0]);
  88771. n = sqlite3_value_bytes(argv[0]);
  88772. /* Verify that the call to _bytes() does not invalidate the _text() pointer */
  88773. assert( z2==(char*)sqlite3_value_text(argv[0]) );
  88774. if( z2 ){
  88775. z1 = contextMalloc(context, ((i64)n)+1);
  88776. if( z1 ){
  88777. for(i=0; i<n; i++){
  88778. z1[i] = sqlite3Tolower(z2[i]);
  88779. }
  88780. sqlite3_result_text(context, z1, n, sqlite3_free);
  88781. }
  88782. }
  88783. }
  88784. /*
  88785. ** Some functions like COALESCE() and IFNULL() and UNLIKELY() are implemented
  88786. ** as VDBE code so that unused argument values do not have to be computed.
  88787. ** However, we still need some kind of function implementation for this
  88788. ** routines in the function table. The noopFunc macro provides this.
  88789. ** noopFunc will never be called so it doesn't matter what the implementation
  88790. ** is. We might as well use the "version()" function as a substitute.
  88791. */
  88792. #define noopFunc versionFunc /* Substitute function - never called */
  88793. /*
  88794. ** Implementation of random(). Return a random integer.
  88795. */
  88796. static void randomFunc(
  88797. sqlite3_context *context,
  88798. int NotUsed,
  88799. sqlite3_value **NotUsed2
  88800. ){
  88801. sqlite_int64 r;
  88802. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  88803. sqlite3_randomness(sizeof(r), &r);
  88804. if( r<0 ){
  88805. /* We need to prevent a random number of 0x8000000000000000
  88806. ** (or -9223372036854775808) since when you do abs() of that
  88807. ** number of you get the same value back again. To do this
  88808. ** in a way that is testable, mask the sign bit off of negative
  88809. ** values, resulting in a positive value. Then take the
  88810. ** 2s complement of that positive value. The end result can
  88811. ** therefore be no less than -9223372036854775807.
  88812. */
  88813. r = -(r & LARGEST_INT64);
  88814. }
  88815. sqlite3_result_int64(context, r);
  88816. }
  88817. /*
  88818. ** Implementation of randomblob(N). Return a random blob
  88819. ** that is N bytes long.
  88820. */
  88821. static void randomBlob(
  88822. sqlite3_context *context,
  88823. int argc,
  88824. sqlite3_value **argv
  88825. ){
  88826. int n;
  88827. unsigned char *p;
  88828. assert( argc==1 );
  88829. UNUSED_PARAMETER(argc);
  88830. n = sqlite3_value_int(argv[0]);
  88831. if( n<1 ){
  88832. n = 1;
  88833. }
  88834. p = contextMalloc(context, n);
  88835. if( p ){
  88836. sqlite3_randomness(n, p);
  88837. sqlite3_result_blob(context, (char*)p, n, sqlite3_free);
  88838. }
  88839. }
  88840. /*
  88841. ** Implementation of the last_insert_rowid() SQL function. The return
  88842. ** value is the same as the sqlite3_last_insert_rowid() API function.
  88843. */
  88844. static void last_insert_rowid(
  88845. sqlite3_context *context,
  88846. int NotUsed,
  88847. sqlite3_value **NotUsed2
  88848. ){
  88849. sqlite3 *db = sqlite3_context_db_handle(context);
  88850. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  88851. /* IMP: R-51513-12026 The last_insert_rowid() SQL function is a
  88852. ** wrapper around the sqlite3_last_insert_rowid() C/C++ interface
  88853. ** function. */
  88854. sqlite3_result_int64(context, sqlite3_last_insert_rowid(db));
  88855. }
  88856. /*
  88857. ** Implementation of the changes() SQL function.
  88858. **
  88859. ** IMP: R-62073-11209 The changes() SQL function is a wrapper
  88860. ** around the sqlite3_changes() C/C++ function and hence follows the same
  88861. ** rules for counting changes.
  88862. */
  88863. static void changes(
  88864. sqlite3_context *context,
  88865. int NotUsed,
  88866. sqlite3_value **NotUsed2
  88867. ){
  88868. sqlite3 *db = sqlite3_context_db_handle(context);
  88869. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  88870. sqlite3_result_int(context, sqlite3_changes(db));
  88871. }
  88872. /*
  88873. ** Implementation of the total_changes() SQL function. The return value is
  88874. ** the same as the sqlite3_total_changes() API function.
  88875. */
  88876. static void total_changes(
  88877. sqlite3_context *context,
  88878. int NotUsed,
  88879. sqlite3_value **NotUsed2
  88880. ){
  88881. sqlite3 *db = sqlite3_context_db_handle(context);
  88882. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  88883. /* IMP: R-52756-41993 This function is a wrapper around the
  88884. ** sqlite3_total_changes() C/C++ interface. */
  88885. sqlite3_result_int(context, sqlite3_total_changes(db));
  88886. }
  88887. /*
  88888. ** A structure defining how to do GLOB-style comparisons.
  88889. */
  88890. struct compareInfo {
  88891. u8 matchAll;
  88892. u8 matchOne;
  88893. u8 matchSet;
  88894. u8 noCase;
  88895. };
  88896. /*
  88897. ** For LIKE and GLOB matching on EBCDIC machines, assume that every
  88898. ** character is exactly one byte in size. Also, all characters are
  88899. ** able to participate in upper-case-to-lower-case mappings in EBCDIC
  88900. ** whereas only characters less than 0x80 do in ASCII.
  88901. */
  88902. #if defined(SQLITE_EBCDIC)
  88903. # define sqlite3Utf8Read(A) (*((*A)++))
  88904. # define GlobUpperToLower(A) A = sqlite3UpperToLower[A]
  88905. # define GlobUpperToLowerAscii(A) A = sqlite3UpperToLower[A]
  88906. #else
  88907. # define GlobUpperToLower(A) if( A<=0x7f ){ A = sqlite3UpperToLower[A]; }
  88908. # define GlobUpperToLowerAscii(A) A = sqlite3UpperToLower[A]
  88909. #endif
  88910. static const struct compareInfo globInfo = { '*', '?', '[', 0 };
  88911. /* The correct SQL-92 behavior is for the LIKE operator to ignore
  88912. ** case. Thus 'a' LIKE 'A' would be true. */
  88913. static const struct compareInfo likeInfoNorm = { '%', '_', 0, 1 };
  88914. /* If SQLITE_CASE_SENSITIVE_LIKE is defined, then the LIKE operator
  88915. ** is case sensitive causing 'a' LIKE 'A' to be false */
  88916. static const struct compareInfo likeInfoAlt = { '%', '_', 0, 0 };
  88917. /*
  88918. ** Compare two UTF-8 strings for equality where the first string can
  88919. ** potentially be a "glob" or "like" expression. Return true (1) if they
  88920. ** are the same and false (0) if they are different.
  88921. **
  88922. ** Globbing rules:
  88923. **
  88924. ** '*' Matches any sequence of zero or more characters.
  88925. **
  88926. ** '?' Matches exactly one character.
  88927. **
  88928. ** [...] Matches one character from the enclosed list of
  88929. ** characters.
  88930. **
  88931. ** [^...] Matches one character not in the enclosed list.
  88932. **
  88933. ** With the [...] and [^...] matching, a ']' character can be included
  88934. ** in the list by making it the first character after '[' or '^'. A
  88935. ** range of characters can be specified using '-'. Example:
  88936. ** "[a-z]" matches any single lower-case letter. To match a '-', make
  88937. ** it the last character in the list.
  88938. **
  88939. ** Like matching rules:
  88940. **
  88941. ** '%' Matches any sequence of zero or more characters
  88942. **
  88943. *** '_' Matches any one character
  88944. **
  88945. ** Ec Where E is the "esc" character and c is any other
  88946. ** character, including '%', '_', and esc, match exactly c.
  88947. **
  88948. ** The comments through this routine usually assume glob matching.
  88949. **
  88950. ** This routine is usually quick, but can be N**2 in the worst case.
  88951. */
  88952. static int patternCompare(
  88953. const u8 *zPattern, /* The glob pattern */
  88954. const u8 *zString, /* The string to compare against the glob */
  88955. const struct compareInfo *pInfo, /* Information about how to do the compare */
  88956. u32 esc /* The escape character */
  88957. ){
  88958. u32 c, c2; /* Next pattern and input string chars */
  88959. u32 matchOne = pInfo->matchOne; /* "?" or "_" */
  88960. u32 matchAll = pInfo->matchAll; /* "*" or "%" */
  88961. u32 matchOther; /* "[" or the escape character */
  88962. u8 noCase = pInfo->noCase; /* True if uppercase==lowercase */
  88963. const u8 *zEscaped = 0; /* One past the last escaped input char */
  88964. /* The GLOB operator does not have an ESCAPE clause. And LIKE does not
  88965. ** have the matchSet operator. So we either have to look for one or
  88966. ** the other, never both. Hence the single variable matchOther is used
  88967. ** to store the one we have to look for.
  88968. */
  88969. matchOther = esc ? esc : pInfo->matchSet;
  88970. while( (c = sqlite3Utf8Read(&zPattern))!=0 ){
  88971. if( c==matchAll ){ /* Match "*" */
  88972. /* Skip over multiple "*" characters in the pattern. If there
  88973. ** are also "?" characters, skip those as well, but consume a
  88974. ** single character of the input string for each "?" skipped */
  88975. while( (c=sqlite3Utf8Read(&zPattern)) == matchAll
  88976. || c == matchOne ){
  88977. if( c==matchOne && sqlite3Utf8Read(&zString)==0 ){
  88978. return 0;
  88979. }
  88980. }
  88981. if( c==0 ){
  88982. return 1; /* "*" at the end of the pattern matches */
  88983. }else if( c==matchOther ){
  88984. if( esc ){
  88985. c = sqlite3Utf8Read(&zPattern);
  88986. if( c==0 ) return 0;
  88987. }else{
  88988. /* "[...]" immediately follows the "*". We have to do a slow
  88989. ** recursive search in this case, but it is an unusual case. */
  88990. assert( matchOther<0x80 ); /* '[' is a single-byte character */
  88991. while( *zString
  88992. && patternCompare(&zPattern[-1],zString,pInfo,esc)==0 ){
  88993. SQLITE_SKIP_UTF8(zString);
  88994. }
  88995. return *zString!=0;
  88996. }
  88997. }
  88998. /* At this point variable c contains the first character of the
  88999. ** pattern string past the "*". Search in the input string for the
  89000. ** first matching character and recursively contine the match from
  89001. ** that point.
  89002. **
  89003. ** For a case-insensitive search, set variable cx to be the same as
  89004. ** c but in the other case and search the input string for either
  89005. ** c or cx.
  89006. */
  89007. if( c<=0x80 ){
  89008. u32 cx;
  89009. if( noCase ){
  89010. cx = sqlite3Toupper(c);
  89011. c = sqlite3Tolower(c);
  89012. }else{
  89013. cx = c;
  89014. }
  89015. while( (c2 = *(zString++))!=0 ){
  89016. if( c2!=c && c2!=cx ) continue;
  89017. if( patternCompare(zPattern,zString,pInfo,esc) ) return 1;
  89018. }
  89019. }else{
  89020. while( (c2 = sqlite3Utf8Read(&zString))!=0 ){
  89021. if( c2!=c ) continue;
  89022. if( patternCompare(zPattern,zString,pInfo,esc) ) return 1;
  89023. }
  89024. }
  89025. return 0;
  89026. }
  89027. if( c==matchOther ){
  89028. if( esc ){
  89029. c = sqlite3Utf8Read(&zPattern);
  89030. if( c==0 ) return 0;
  89031. zEscaped = zPattern;
  89032. }else{
  89033. u32 prior_c = 0;
  89034. int seen = 0;
  89035. int invert = 0;
  89036. c = sqlite3Utf8Read(&zString);
  89037. if( c==0 ) return 0;
  89038. c2 = sqlite3Utf8Read(&zPattern);
  89039. if( c2=='^' ){
  89040. invert = 1;
  89041. c2 = sqlite3Utf8Read(&zPattern);
  89042. }
  89043. if( c2==']' ){
  89044. if( c==']' ) seen = 1;
  89045. c2 = sqlite3Utf8Read(&zPattern);
  89046. }
  89047. while( c2 && c2!=']' ){
  89048. if( c2=='-' && zPattern[0]!=']' && zPattern[0]!=0 && prior_c>0 ){
  89049. c2 = sqlite3Utf8Read(&zPattern);
  89050. if( c>=prior_c && c<=c2 ) seen = 1;
  89051. prior_c = 0;
  89052. }else{
  89053. if( c==c2 ){
  89054. seen = 1;
  89055. }
  89056. prior_c = c2;
  89057. }
  89058. c2 = sqlite3Utf8Read(&zPattern);
  89059. }
  89060. if( c2==0 || (seen ^ invert)==0 ){
  89061. return 0;
  89062. }
  89063. continue;
  89064. }
  89065. }
  89066. c2 = sqlite3Utf8Read(&zString);
  89067. if( c==c2 ) continue;
  89068. if( noCase && c<0x80 && c2<0x80 && sqlite3Tolower(c)==sqlite3Tolower(c2) ){
  89069. continue;
  89070. }
  89071. if( c==matchOne && zPattern!=zEscaped && c2!=0 ) continue;
  89072. return 0;
  89073. }
  89074. return *zString==0;
  89075. }
  89076. /*
  89077. ** The sqlite3_strglob() interface.
  89078. */
  89079. SQLITE_API int sqlite3_strglob(const char *zGlobPattern, const char *zString){
  89080. return patternCompare((u8*)zGlobPattern, (u8*)zString, &globInfo, 0)==0;
  89081. }
  89082. /*
  89083. ** Count the number of times that the LIKE operator (or GLOB which is
  89084. ** just a variation of LIKE) gets called. This is used for testing
  89085. ** only.
  89086. */
  89087. #ifdef SQLITE_TEST
  89088. SQLITE_API int sqlite3_like_count = 0;
  89089. #endif
  89090. /*
  89091. ** Implementation of the like() SQL function. This function implements
  89092. ** the build-in LIKE operator. The first argument to the function is the
  89093. ** pattern and the second argument is the string. So, the SQL statements:
  89094. **
  89095. ** A LIKE B
  89096. **
  89097. ** is implemented as like(B,A).
  89098. **
  89099. ** This same function (with a different compareInfo structure) computes
  89100. ** the GLOB operator.
  89101. */
  89102. static void likeFunc(
  89103. sqlite3_context *context,
  89104. int argc,
  89105. sqlite3_value **argv
  89106. ){
  89107. const unsigned char *zA, *zB;
  89108. u32 escape = 0;
  89109. int nPat;
  89110. sqlite3 *db = sqlite3_context_db_handle(context);
  89111. zB = sqlite3_value_text(argv[0]);
  89112. zA = sqlite3_value_text(argv[1]);
  89113. /* Limit the length of the LIKE or GLOB pattern to avoid problems
  89114. ** of deep recursion and N*N behavior in patternCompare().
  89115. */
  89116. nPat = sqlite3_value_bytes(argv[0]);
  89117. testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] );
  89118. testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]+1 );
  89119. if( nPat > db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] ){
  89120. sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
  89121. return;
  89122. }
  89123. assert( zB==sqlite3_value_text(argv[0]) ); /* Encoding did not change */
  89124. if( argc==3 ){
  89125. /* The escape character string must consist of a single UTF-8 character.
  89126. ** Otherwise, return an error.
  89127. */
  89128. const unsigned char *zEsc = sqlite3_value_text(argv[2]);
  89129. if( zEsc==0 ) return;
  89130. if( sqlite3Utf8CharLen((char*)zEsc, -1)!=1 ){
  89131. sqlite3_result_error(context,
  89132. "ESCAPE expression must be a single character", -1);
  89133. return;
  89134. }
  89135. escape = sqlite3Utf8Read(&zEsc);
  89136. }
  89137. if( zA && zB ){
  89138. struct compareInfo *pInfo = sqlite3_user_data(context);
  89139. #ifdef SQLITE_TEST
  89140. sqlite3_like_count++;
  89141. #endif
  89142. sqlite3_result_int(context, patternCompare(zB, zA, pInfo, escape));
  89143. }
  89144. }
  89145. /*
  89146. ** Implementation of the NULLIF(x,y) function. The result is the first
  89147. ** argument if the arguments are different. The result is NULL if the
  89148. ** arguments are equal to each other.
  89149. */
  89150. static void nullifFunc(
  89151. sqlite3_context *context,
  89152. int NotUsed,
  89153. sqlite3_value **argv
  89154. ){
  89155. CollSeq *pColl = sqlite3GetFuncCollSeq(context);
  89156. UNUSED_PARAMETER(NotUsed);
  89157. if( sqlite3MemCompare(argv[0], argv[1], pColl)!=0 ){
  89158. sqlite3_result_value(context, argv[0]);
  89159. }
  89160. }
  89161. /*
  89162. ** Implementation of the sqlite_version() function. The result is the version
  89163. ** of the SQLite library that is running.
  89164. */
  89165. static void versionFunc(
  89166. sqlite3_context *context,
  89167. int NotUsed,
  89168. sqlite3_value **NotUsed2
  89169. ){
  89170. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  89171. /* IMP: R-48699-48617 This function is an SQL wrapper around the
  89172. ** sqlite3_libversion() C-interface. */
  89173. sqlite3_result_text(context, sqlite3_libversion(), -1, SQLITE_STATIC);
  89174. }
  89175. /*
  89176. ** Implementation of the sqlite_source_id() function. The result is a string
  89177. ** that identifies the particular version of the source code used to build
  89178. ** SQLite.
  89179. */
  89180. static void sourceidFunc(
  89181. sqlite3_context *context,
  89182. int NotUsed,
  89183. sqlite3_value **NotUsed2
  89184. ){
  89185. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  89186. /* IMP: R-24470-31136 This function is an SQL wrapper around the
  89187. ** sqlite3_sourceid() C interface. */
  89188. sqlite3_result_text(context, sqlite3_sourceid(), -1, SQLITE_STATIC);
  89189. }
  89190. /*
  89191. ** Implementation of the sqlite_log() function. This is a wrapper around
  89192. ** sqlite3_log(). The return value is NULL. The function exists purely for
  89193. ** its side-effects.
  89194. */
  89195. static void errlogFunc(
  89196. sqlite3_context *context,
  89197. int argc,
  89198. sqlite3_value **argv
  89199. ){
  89200. UNUSED_PARAMETER(argc);
  89201. UNUSED_PARAMETER(context);
  89202. sqlite3_log(sqlite3_value_int(argv[0]), "%s", sqlite3_value_text(argv[1]));
  89203. }
  89204. /*
  89205. ** Implementation of the sqlite_compileoption_used() function.
  89206. ** The result is an integer that identifies if the compiler option
  89207. ** was used to build SQLite.
  89208. */
  89209. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  89210. static void compileoptionusedFunc(
  89211. sqlite3_context *context,
  89212. int argc,
  89213. sqlite3_value **argv
  89214. ){
  89215. const char *zOptName;
  89216. assert( argc==1 );
  89217. UNUSED_PARAMETER(argc);
  89218. /* IMP: R-39564-36305 The sqlite_compileoption_used() SQL
  89219. ** function is a wrapper around the sqlite3_compileoption_used() C/C++
  89220. ** function.
  89221. */
  89222. if( (zOptName = (const char*)sqlite3_value_text(argv[0]))!=0 ){
  89223. sqlite3_result_int(context, sqlite3_compileoption_used(zOptName));
  89224. }
  89225. }
  89226. #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
  89227. /*
  89228. ** Implementation of the sqlite_compileoption_get() function.
  89229. ** The result is a string that identifies the compiler options
  89230. ** used to build SQLite.
  89231. */
  89232. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  89233. static void compileoptiongetFunc(
  89234. sqlite3_context *context,
  89235. int argc,
  89236. sqlite3_value **argv
  89237. ){
  89238. int n;
  89239. assert( argc==1 );
  89240. UNUSED_PARAMETER(argc);
  89241. /* IMP: R-04922-24076 The sqlite_compileoption_get() SQL function
  89242. ** is a wrapper around the sqlite3_compileoption_get() C/C++ function.
  89243. */
  89244. n = sqlite3_value_int(argv[0]);
  89245. sqlite3_result_text(context, sqlite3_compileoption_get(n), -1, SQLITE_STATIC);
  89246. }
  89247. #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
  89248. /* Array for converting from half-bytes (nybbles) into ASCII hex
  89249. ** digits. */
  89250. static const char hexdigits[] = {
  89251. '0', '1', '2', '3', '4', '5', '6', '7',
  89252. '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
  89253. };
  89254. /*
  89255. ** Implementation of the QUOTE() function. This function takes a single
  89256. ** argument. If the argument is numeric, the return value is the same as
  89257. ** the argument. If the argument is NULL, the return value is the string
  89258. ** "NULL". Otherwise, the argument is enclosed in single quotes with
  89259. ** single-quote escapes.
  89260. */
  89261. static void quoteFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
  89262. assert( argc==1 );
  89263. UNUSED_PARAMETER(argc);
  89264. switch( sqlite3_value_type(argv[0]) ){
  89265. case SQLITE_FLOAT: {
  89266. double r1, r2;
  89267. char zBuf[50];
  89268. r1 = sqlite3_value_double(argv[0]);
  89269. sqlite3_snprintf(sizeof(zBuf), zBuf, "%!.15g", r1);
  89270. sqlite3AtoF(zBuf, &r2, 20, SQLITE_UTF8);
  89271. if( r1!=r2 ){
  89272. sqlite3_snprintf(sizeof(zBuf), zBuf, "%!.20e", r1);
  89273. }
  89274. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  89275. break;
  89276. }
  89277. case SQLITE_INTEGER: {
  89278. sqlite3_result_value(context, argv[0]);
  89279. break;
  89280. }
  89281. case SQLITE_BLOB: {
  89282. char *zText = 0;
  89283. char const *zBlob = sqlite3_value_blob(argv[0]);
  89284. int nBlob = sqlite3_value_bytes(argv[0]);
  89285. assert( zBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */
  89286. zText = (char *)contextMalloc(context, (2*(i64)nBlob)+4);
  89287. if( zText ){
  89288. int i;
  89289. for(i=0; i<nBlob; i++){
  89290. zText[(i*2)+2] = hexdigits[(zBlob[i]>>4)&0x0F];
  89291. zText[(i*2)+3] = hexdigits[(zBlob[i])&0x0F];
  89292. }
  89293. zText[(nBlob*2)+2] = '\'';
  89294. zText[(nBlob*2)+3] = '\0';
  89295. zText[0] = 'X';
  89296. zText[1] = '\'';
  89297. sqlite3_result_text(context, zText, -1, SQLITE_TRANSIENT);
  89298. sqlite3_free(zText);
  89299. }
  89300. break;
  89301. }
  89302. case SQLITE_TEXT: {
  89303. int i,j;
  89304. u64 n;
  89305. const unsigned char *zArg = sqlite3_value_text(argv[0]);
  89306. char *z;
  89307. if( zArg==0 ) return;
  89308. for(i=0, n=0; zArg[i]; i++){ if( zArg[i]=='\'' ) n++; }
  89309. z = contextMalloc(context, ((i64)i)+((i64)n)+3);
  89310. if( z ){
  89311. z[0] = '\'';
  89312. for(i=0, j=1; zArg[i]; i++){
  89313. z[j++] = zArg[i];
  89314. if( zArg[i]=='\'' ){
  89315. z[j++] = '\'';
  89316. }
  89317. }
  89318. z[j++] = '\'';
  89319. z[j] = 0;
  89320. sqlite3_result_text(context, z, j, sqlite3_free);
  89321. }
  89322. break;
  89323. }
  89324. default: {
  89325. assert( sqlite3_value_type(argv[0])==SQLITE_NULL );
  89326. sqlite3_result_text(context, "NULL", 4, SQLITE_STATIC);
  89327. break;
  89328. }
  89329. }
  89330. }
  89331. /*
  89332. ** The unicode() function. Return the integer unicode code-point value
  89333. ** for the first character of the input string.
  89334. */
  89335. static void unicodeFunc(
  89336. sqlite3_context *context,
  89337. int argc,
  89338. sqlite3_value **argv
  89339. ){
  89340. const unsigned char *z = sqlite3_value_text(argv[0]);
  89341. (void)argc;
  89342. if( z && z[0] ) sqlite3_result_int(context, sqlite3Utf8Read(&z));
  89343. }
  89344. /*
  89345. ** The char() function takes zero or more arguments, each of which is
  89346. ** an integer. It constructs a string where each character of the string
  89347. ** is the unicode character for the corresponding integer argument.
  89348. */
  89349. static void charFunc(
  89350. sqlite3_context *context,
  89351. int argc,
  89352. sqlite3_value **argv
  89353. ){
  89354. unsigned char *z, *zOut;
  89355. int i;
  89356. zOut = z = sqlite3_malloc( argc*4+1 );
  89357. if( z==0 ){
  89358. sqlite3_result_error_nomem(context);
  89359. return;
  89360. }
  89361. for(i=0; i<argc; i++){
  89362. sqlite3_int64 x;
  89363. unsigned c;
  89364. x = sqlite3_value_int64(argv[i]);
  89365. if( x<0 || x>0x10ffff ) x = 0xfffd;
  89366. c = (unsigned)(x & 0x1fffff);
  89367. if( c<0x00080 ){
  89368. *zOut++ = (u8)(c&0xFF);
  89369. }else if( c<0x00800 ){
  89370. *zOut++ = 0xC0 + (u8)((c>>6)&0x1F);
  89371. *zOut++ = 0x80 + (u8)(c & 0x3F);
  89372. }else if( c<0x10000 ){
  89373. *zOut++ = 0xE0 + (u8)((c>>12)&0x0F);
  89374. *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);
  89375. *zOut++ = 0x80 + (u8)(c & 0x3F);
  89376. }else{
  89377. *zOut++ = 0xF0 + (u8)((c>>18) & 0x07);
  89378. *zOut++ = 0x80 + (u8)((c>>12) & 0x3F);
  89379. *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);
  89380. *zOut++ = 0x80 + (u8)(c & 0x3F);
  89381. } \
  89382. }
  89383. sqlite3_result_text64(context, (char*)z, zOut-z, sqlite3_free, SQLITE_UTF8);
  89384. }
  89385. /*
  89386. ** The hex() function. Interpret the argument as a blob. Return
  89387. ** a hexadecimal rendering as text.
  89388. */
  89389. static void hexFunc(
  89390. sqlite3_context *context,
  89391. int argc,
  89392. sqlite3_value **argv
  89393. ){
  89394. int i, n;
  89395. const unsigned char *pBlob;
  89396. char *zHex, *z;
  89397. assert( argc==1 );
  89398. UNUSED_PARAMETER(argc);
  89399. pBlob = sqlite3_value_blob(argv[0]);
  89400. n = sqlite3_value_bytes(argv[0]);
  89401. assert( pBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */
  89402. z = zHex = contextMalloc(context, ((i64)n)*2 + 1);
  89403. if( zHex ){
  89404. for(i=0; i<n; i++, pBlob++){
  89405. unsigned char c = *pBlob;
  89406. *(z++) = hexdigits[(c>>4)&0xf];
  89407. *(z++) = hexdigits[c&0xf];
  89408. }
  89409. *z = 0;
  89410. sqlite3_result_text(context, zHex, n*2, sqlite3_free);
  89411. }
  89412. }
  89413. /*
  89414. ** The zeroblob(N) function returns a zero-filled blob of size N bytes.
  89415. */
  89416. static void zeroblobFunc(
  89417. sqlite3_context *context,
  89418. int argc,
  89419. sqlite3_value **argv
  89420. ){
  89421. i64 n;
  89422. sqlite3 *db = sqlite3_context_db_handle(context);
  89423. assert( argc==1 );
  89424. UNUSED_PARAMETER(argc);
  89425. n = sqlite3_value_int64(argv[0]);
  89426. testcase( n==db->aLimit[SQLITE_LIMIT_LENGTH] );
  89427. testcase( n==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
  89428. if( n>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  89429. sqlite3_result_error_toobig(context);
  89430. }else{
  89431. sqlite3_result_zeroblob(context, (int)n); /* IMP: R-00293-64994 */
  89432. }
  89433. }
  89434. /*
  89435. ** The replace() function. Three arguments are all strings: call
  89436. ** them A, B, and C. The result is also a string which is derived
  89437. ** from A by replacing every occurrence of B with C. The match
  89438. ** must be exact. Collating sequences are not used.
  89439. */
  89440. static void replaceFunc(
  89441. sqlite3_context *context,
  89442. int argc,
  89443. sqlite3_value **argv
  89444. ){
  89445. const unsigned char *zStr; /* The input string A */
  89446. const unsigned char *zPattern; /* The pattern string B */
  89447. const unsigned char *zRep; /* The replacement string C */
  89448. unsigned char *zOut; /* The output */
  89449. int nStr; /* Size of zStr */
  89450. int nPattern; /* Size of zPattern */
  89451. int nRep; /* Size of zRep */
  89452. i64 nOut; /* Maximum size of zOut */
  89453. int loopLimit; /* Last zStr[] that might match zPattern[] */
  89454. int i, j; /* Loop counters */
  89455. assert( argc==3 );
  89456. UNUSED_PARAMETER(argc);
  89457. zStr = sqlite3_value_text(argv[0]);
  89458. if( zStr==0 ) return;
  89459. nStr = sqlite3_value_bytes(argv[0]);
  89460. assert( zStr==sqlite3_value_text(argv[0]) ); /* No encoding change */
  89461. zPattern = sqlite3_value_text(argv[1]);
  89462. if( zPattern==0 ){
  89463. assert( sqlite3_value_type(argv[1])==SQLITE_NULL
  89464. || sqlite3_context_db_handle(context)->mallocFailed );
  89465. return;
  89466. }
  89467. if( zPattern[0]==0 ){
  89468. assert( sqlite3_value_type(argv[1])!=SQLITE_NULL );
  89469. sqlite3_result_value(context, argv[0]);
  89470. return;
  89471. }
  89472. nPattern = sqlite3_value_bytes(argv[1]);
  89473. assert( zPattern==sqlite3_value_text(argv[1]) ); /* No encoding change */
  89474. zRep = sqlite3_value_text(argv[2]);
  89475. if( zRep==0 ) return;
  89476. nRep = sqlite3_value_bytes(argv[2]);
  89477. assert( zRep==sqlite3_value_text(argv[2]) );
  89478. nOut = nStr + 1;
  89479. assert( nOut<SQLITE_MAX_LENGTH );
  89480. zOut = contextMalloc(context, (i64)nOut);
  89481. if( zOut==0 ){
  89482. return;
  89483. }
  89484. loopLimit = nStr - nPattern;
  89485. for(i=j=0; i<=loopLimit; i++){
  89486. if( zStr[i]!=zPattern[0] || memcmp(&zStr[i], zPattern, nPattern) ){
  89487. zOut[j++] = zStr[i];
  89488. }else{
  89489. u8 *zOld;
  89490. sqlite3 *db = sqlite3_context_db_handle(context);
  89491. nOut += nRep - nPattern;
  89492. testcase( nOut-1==db->aLimit[SQLITE_LIMIT_LENGTH] );
  89493. testcase( nOut-2==db->aLimit[SQLITE_LIMIT_LENGTH] );
  89494. if( nOut-1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  89495. sqlite3_result_error_toobig(context);
  89496. sqlite3_free(zOut);
  89497. return;
  89498. }
  89499. zOld = zOut;
  89500. zOut = sqlite3_realloc(zOut, (int)nOut);
  89501. if( zOut==0 ){
  89502. sqlite3_result_error_nomem(context);
  89503. sqlite3_free(zOld);
  89504. return;
  89505. }
  89506. memcpy(&zOut[j], zRep, nRep);
  89507. j += nRep;
  89508. i += nPattern-1;
  89509. }
  89510. }
  89511. assert( j+nStr-i+1==nOut );
  89512. memcpy(&zOut[j], &zStr[i], nStr-i);
  89513. j += nStr - i;
  89514. assert( j<=nOut );
  89515. zOut[j] = 0;
  89516. sqlite3_result_text(context, (char*)zOut, j, sqlite3_free);
  89517. }
  89518. /*
  89519. ** Implementation of the TRIM(), LTRIM(), and RTRIM() functions.
  89520. ** The userdata is 0x1 for left trim, 0x2 for right trim, 0x3 for both.
  89521. */
  89522. static void trimFunc(
  89523. sqlite3_context *context,
  89524. int argc,
  89525. sqlite3_value **argv
  89526. ){
  89527. const unsigned char *zIn; /* Input string */
  89528. const unsigned char *zCharSet; /* Set of characters to trim */
  89529. int nIn; /* Number of bytes in input */
  89530. int flags; /* 1: trimleft 2: trimright 3: trim */
  89531. int i; /* Loop counter */
  89532. unsigned char *aLen = 0; /* Length of each character in zCharSet */
  89533. unsigned char **azChar = 0; /* Individual characters in zCharSet */
  89534. int nChar; /* Number of characters in zCharSet */
  89535. if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
  89536. return;
  89537. }
  89538. zIn = sqlite3_value_text(argv[0]);
  89539. if( zIn==0 ) return;
  89540. nIn = sqlite3_value_bytes(argv[0]);
  89541. assert( zIn==sqlite3_value_text(argv[0]) );
  89542. if( argc==1 ){
  89543. static const unsigned char lenOne[] = { 1 };
  89544. static unsigned char * const azOne[] = { (u8*)" " };
  89545. nChar = 1;
  89546. aLen = (u8*)lenOne;
  89547. azChar = (unsigned char **)azOne;
  89548. zCharSet = 0;
  89549. }else if( (zCharSet = sqlite3_value_text(argv[1]))==0 ){
  89550. return;
  89551. }else{
  89552. const unsigned char *z;
  89553. for(z=zCharSet, nChar=0; *z; nChar++){
  89554. SQLITE_SKIP_UTF8(z);
  89555. }
  89556. if( nChar>0 ){
  89557. azChar = contextMalloc(context, ((i64)nChar)*(sizeof(char*)+1));
  89558. if( azChar==0 ){
  89559. return;
  89560. }
  89561. aLen = (unsigned char*)&azChar[nChar];
  89562. for(z=zCharSet, nChar=0; *z; nChar++){
  89563. azChar[nChar] = (unsigned char *)z;
  89564. SQLITE_SKIP_UTF8(z);
  89565. aLen[nChar] = (u8)(z - azChar[nChar]);
  89566. }
  89567. }
  89568. }
  89569. if( nChar>0 ){
  89570. flags = SQLITE_PTR_TO_INT(sqlite3_user_data(context));
  89571. if( flags & 1 ){
  89572. while( nIn>0 ){
  89573. int len = 0;
  89574. for(i=0; i<nChar; i++){
  89575. len = aLen[i];
  89576. if( len<=nIn && memcmp(zIn, azChar[i], len)==0 ) break;
  89577. }
  89578. if( i>=nChar ) break;
  89579. zIn += len;
  89580. nIn -= len;
  89581. }
  89582. }
  89583. if( flags & 2 ){
  89584. while( nIn>0 ){
  89585. int len = 0;
  89586. for(i=0; i<nChar; i++){
  89587. len = aLen[i];
  89588. if( len<=nIn && memcmp(&zIn[nIn-len],azChar[i],len)==0 ) break;
  89589. }
  89590. if( i>=nChar ) break;
  89591. nIn -= len;
  89592. }
  89593. }
  89594. if( zCharSet ){
  89595. sqlite3_free(azChar);
  89596. }
  89597. }
  89598. sqlite3_result_text(context, (char*)zIn, nIn, SQLITE_TRANSIENT);
  89599. }
  89600. /* IMP: R-25361-16150 This function is omitted from SQLite by default. It
  89601. ** is only available if the SQLITE_SOUNDEX compile-time option is used
  89602. ** when SQLite is built.
  89603. */
  89604. #ifdef SQLITE_SOUNDEX
  89605. /*
  89606. ** Compute the soundex encoding of a word.
  89607. **
  89608. ** IMP: R-59782-00072 The soundex(X) function returns a string that is the
  89609. ** soundex encoding of the string X.
  89610. */
  89611. static void soundexFunc(
  89612. sqlite3_context *context,
  89613. int argc,
  89614. sqlite3_value **argv
  89615. ){
  89616. char zResult[8];
  89617. const u8 *zIn;
  89618. int i, j;
  89619. static const unsigned char iCode[] = {
  89620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  89621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  89622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  89623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  89624. 0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
  89625. 1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
  89626. 0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
  89627. 1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
  89628. };
  89629. assert( argc==1 );
  89630. zIn = (u8*)sqlite3_value_text(argv[0]);
  89631. if( zIn==0 ) zIn = (u8*)"";
  89632. for(i=0; zIn[i] && !sqlite3Isalpha(zIn[i]); i++){}
  89633. if( zIn[i] ){
  89634. u8 prevcode = iCode[zIn[i]&0x7f];
  89635. zResult[0] = sqlite3Toupper(zIn[i]);
  89636. for(j=1; j<4 && zIn[i]; i++){
  89637. int code = iCode[zIn[i]&0x7f];
  89638. if( code>0 ){
  89639. if( code!=prevcode ){
  89640. prevcode = code;
  89641. zResult[j++] = code + '0';
  89642. }
  89643. }else{
  89644. prevcode = 0;
  89645. }
  89646. }
  89647. while( j<4 ){
  89648. zResult[j++] = '0';
  89649. }
  89650. zResult[j] = 0;
  89651. sqlite3_result_text(context, zResult, 4, SQLITE_TRANSIENT);
  89652. }else{
  89653. /* IMP: R-64894-50321 The string "?000" is returned if the argument
  89654. ** is NULL or contains no ASCII alphabetic characters. */
  89655. sqlite3_result_text(context, "?000", 4, SQLITE_STATIC);
  89656. }
  89657. }
  89658. #endif /* SQLITE_SOUNDEX */
  89659. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  89660. /*
  89661. ** A function that loads a shared-library extension then returns NULL.
  89662. */
  89663. static void loadExt(sqlite3_context *context, int argc, sqlite3_value **argv){
  89664. const char *zFile = (const char *)sqlite3_value_text(argv[0]);
  89665. const char *zProc;
  89666. sqlite3 *db = sqlite3_context_db_handle(context);
  89667. char *zErrMsg = 0;
  89668. if( argc==2 ){
  89669. zProc = (const char *)sqlite3_value_text(argv[1]);
  89670. }else{
  89671. zProc = 0;
  89672. }
  89673. if( zFile && sqlite3_load_extension(db, zFile, zProc, &zErrMsg) ){
  89674. sqlite3_result_error(context, zErrMsg, -1);
  89675. sqlite3_free(zErrMsg);
  89676. }
  89677. }
  89678. #endif
  89679. /*
  89680. ** An instance of the following structure holds the context of a
  89681. ** sum() or avg() aggregate computation.
  89682. */
  89683. typedef struct SumCtx SumCtx;
  89684. struct SumCtx {
  89685. double rSum; /* Floating point sum */
  89686. i64 iSum; /* Integer sum */
  89687. i64 cnt; /* Number of elements summed */
  89688. u8 overflow; /* True if integer overflow seen */
  89689. u8 approx; /* True if non-integer value was input to the sum */
  89690. };
  89691. /*
  89692. ** Routines used to compute the sum, average, and total.
  89693. **
  89694. ** The SUM() function follows the (broken) SQL standard which means
  89695. ** that it returns NULL if it sums over no inputs. TOTAL returns
  89696. ** 0.0 in that case. In addition, TOTAL always returns a float where
  89697. ** SUM might return an integer if it never encounters a floating point
  89698. ** value. TOTAL never fails, but SUM might through an exception if
  89699. ** it overflows an integer.
  89700. */
  89701. static void sumStep(sqlite3_context *context, int argc, sqlite3_value **argv){
  89702. SumCtx *p;
  89703. int type;
  89704. assert( argc==1 );
  89705. UNUSED_PARAMETER(argc);
  89706. p = sqlite3_aggregate_context(context, sizeof(*p));
  89707. type = sqlite3_value_numeric_type(argv[0]);
  89708. if( p && type!=SQLITE_NULL ){
  89709. p->cnt++;
  89710. if( type==SQLITE_INTEGER ){
  89711. i64 v = sqlite3_value_int64(argv[0]);
  89712. p->rSum += v;
  89713. if( (p->approx|p->overflow)==0 && sqlite3AddInt64(&p->iSum, v) ){
  89714. p->overflow = 1;
  89715. }
  89716. }else{
  89717. p->rSum += sqlite3_value_double(argv[0]);
  89718. p->approx = 1;
  89719. }
  89720. }
  89721. }
  89722. static void sumFinalize(sqlite3_context *context){
  89723. SumCtx *p;
  89724. p = sqlite3_aggregate_context(context, 0);
  89725. if( p && p->cnt>0 ){
  89726. if( p->overflow ){
  89727. sqlite3_result_error(context,"integer overflow",-1);
  89728. }else if( p->approx ){
  89729. sqlite3_result_double(context, p->rSum);
  89730. }else{
  89731. sqlite3_result_int64(context, p->iSum);
  89732. }
  89733. }
  89734. }
  89735. static void avgFinalize(sqlite3_context *context){
  89736. SumCtx *p;
  89737. p = sqlite3_aggregate_context(context, 0);
  89738. if( p && p->cnt>0 ){
  89739. sqlite3_result_double(context, p->rSum/(double)p->cnt);
  89740. }
  89741. }
  89742. static void totalFinalize(sqlite3_context *context){
  89743. SumCtx *p;
  89744. p = sqlite3_aggregate_context(context, 0);
  89745. /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
  89746. sqlite3_result_double(context, p ? p->rSum : (double)0);
  89747. }
  89748. /*
  89749. ** The following structure keeps track of state information for the
  89750. ** count() aggregate function.
  89751. */
  89752. typedef struct CountCtx CountCtx;
  89753. struct CountCtx {
  89754. i64 n;
  89755. };
  89756. /*
  89757. ** Routines to implement the count() aggregate function.
  89758. */
  89759. static void countStep(sqlite3_context *context, int argc, sqlite3_value **argv){
  89760. CountCtx *p;
  89761. p = sqlite3_aggregate_context(context, sizeof(*p));
  89762. if( (argc==0 || SQLITE_NULL!=sqlite3_value_type(argv[0])) && p ){
  89763. p->n++;
  89764. }
  89765. #ifndef SQLITE_OMIT_DEPRECATED
  89766. /* The sqlite3_aggregate_count() function is deprecated. But just to make
  89767. ** sure it still operates correctly, verify that its count agrees with our
  89768. ** internal count when using count(*) and when the total count can be
  89769. ** expressed as a 32-bit integer. */
  89770. assert( argc==1 || p==0 || p->n>0x7fffffff
  89771. || p->n==sqlite3_aggregate_count(context) );
  89772. #endif
  89773. }
  89774. static void countFinalize(sqlite3_context *context){
  89775. CountCtx *p;
  89776. p = sqlite3_aggregate_context(context, 0);
  89777. sqlite3_result_int64(context, p ? p->n : 0);
  89778. }
  89779. /*
  89780. ** Routines to implement min() and max() aggregate functions.
  89781. */
  89782. static void minmaxStep(
  89783. sqlite3_context *context,
  89784. int NotUsed,
  89785. sqlite3_value **argv
  89786. ){
  89787. Mem *pArg = (Mem *)argv[0];
  89788. Mem *pBest;
  89789. UNUSED_PARAMETER(NotUsed);
  89790. pBest = (Mem *)sqlite3_aggregate_context(context, sizeof(*pBest));
  89791. if( !pBest ) return;
  89792. if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
  89793. if( pBest->flags ) sqlite3SkipAccumulatorLoad(context);
  89794. }else if( pBest->flags ){
  89795. int max;
  89796. int cmp;
  89797. CollSeq *pColl = sqlite3GetFuncCollSeq(context);
  89798. /* This step function is used for both the min() and max() aggregates,
  89799. ** the only difference between the two being that the sense of the
  89800. ** comparison is inverted. For the max() aggregate, the
  89801. ** sqlite3_user_data() function returns (void *)-1. For min() it
  89802. ** returns (void *)db, where db is the sqlite3* database pointer.
  89803. ** Therefore the next statement sets variable 'max' to 1 for the max()
  89804. ** aggregate, or 0 for min().
  89805. */
  89806. max = sqlite3_user_data(context)!=0;
  89807. cmp = sqlite3MemCompare(pBest, pArg, pColl);
  89808. if( (max && cmp<0) || (!max && cmp>0) ){
  89809. sqlite3VdbeMemCopy(pBest, pArg);
  89810. }else{
  89811. sqlite3SkipAccumulatorLoad(context);
  89812. }
  89813. }else{
  89814. pBest->db = sqlite3_context_db_handle(context);
  89815. sqlite3VdbeMemCopy(pBest, pArg);
  89816. }
  89817. }
  89818. static void minMaxFinalize(sqlite3_context *context){
  89819. sqlite3_value *pRes;
  89820. pRes = (sqlite3_value *)sqlite3_aggregate_context(context, 0);
  89821. if( pRes ){
  89822. if( pRes->flags ){
  89823. sqlite3_result_value(context, pRes);
  89824. }
  89825. sqlite3VdbeMemRelease(pRes);
  89826. }
  89827. }
  89828. /*
  89829. ** group_concat(EXPR, ?SEPARATOR?)
  89830. */
  89831. static void groupConcatStep(
  89832. sqlite3_context *context,
  89833. int argc,
  89834. sqlite3_value **argv
  89835. ){
  89836. const char *zVal;
  89837. StrAccum *pAccum;
  89838. const char *zSep;
  89839. int nVal, nSep;
  89840. assert( argc==1 || argc==2 );
  89841. if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
  89842. pAccum = (StrAccum*)sqlite3_aggregate_context(context, sizeof(*pAccum));
  89843. if( pAccum ){
  89844. sqlite3 *db = sqlite3_context_db_handle(context);
  89845. int firstTerm = pAccum->useMalloc==0;
  89846. pAccum->useMalloc = 2;
  89847. pAccum->mxAlloc = db->aLimit[SQLITE_LIMIT_LENGTH];
  89848. if( !firstTerm ){
  89849. if( argc==2 ){
  89850. zSep = (char*)sqlite3_value_text(argv[1]);
  89851. nSep = sqlite3_value_bytes(argv[1]);
  89852. }else{
  89853. zSep = ",";
  89854. nSep = 1;
  89855. }
  89856. if( nSep ) sqlite3StrAccumAppend(pAccum, zSep, nSep);
  89857. }
  89858. zVal = (char*)sqlite3_value_text(argv[0]);
  89859. nVal = sqlite3_value_bytes(argv[0]);
  89860. if( zVal ) sqlite3StrAccumAppend(pAccum, zVal, nVal);
  89861. }
  89862. }
  89863. static void groupConcatFinalize(sqlite3_context *context){
  89864. StrAccum *pAccum;
  89865. pAccum = sqlite3_aggregate_context(context, 0);
  89866. if( pAccum ){
  89867. if( pAccum->accError==STRACCUM_TOOBIG ){
  89868. sqlite3_result_error_toobig(context);
  89869. }else if( pAccum->accError==STRACCUM_NOMEM ){
  89870. sqlite3_result_error_nomem(context);
  89871. }else{
  89872. sqlite3_result_text(context, sqlite3StrAccumFinish(pAccum), -1,
  89873. sqlite3_free);
  89874. }
  89875. }
  89876. }
  89877. /*
  89878. ** This routine does per-connection function registration. Most
  89879. ** of the built-in functions above are part of the global function set.
  89880. ** This routine only deals with those that are not global.
  89881. */
  89882. SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(sqlite3 *db){
  89883. int rc = sqlite3_overload_function(db, "MATCH", 2);
  89884. assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
  89885. if( rc==SQLITE_NOMEM ){
  89886. db->mallocFailed = 1;
  89887. }
  89888. }
  89889. /*
  89890. ** Set the LIKEOPT flag on the 2-argument function with the given name.
  89891. */
  89892. static void setLikeOptFlag(sqlite3 *db, const char *zName, u8 flagVal){
  89893. FuncDef *pDef;
  89894. pDef = sqlite3FindFunction(db, zName, sqlite3Strlen30(zName),
  89895. 2, SQLITE_UTF8, 0);
  89896. if( ALWAYS(pDef) ){
  89897. pDef->funcFlags |= flagVal;
  89898. }
  89899. }
  89900. /*
  89901. ** Register the built-in LIKE and GLOB functions. The caseSensitive
  89902. ** parameter determines whether or not the LIKE operator is case
  89903. ** sensitive. GLOB is always case sensitive.
  89904. */
  89905. SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3 *db, int caseSensitive){
  89906. struct compareInfo *pInfo;
  89907. if( caseSensitive ){
  89908. pInfo = (struct compareInfo*)&likeInfoAlt;
  89909. }else{
  89910. pInfo = (struct compareInfo*)&likeInfoNorm;
  89911. }
  89912. sqlite3CreateFunc(db, "like", 2, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0);
  89913. sqlite3CreateFunc(db, "like", 3, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0);
  89914. sqlite3CreateFunc(db, "glob", 2, SQLITE_UTF8,
  89915. (struct compareInfo*)&globInfo, likeFunc, 0, 0, 0);
  89916. setLikeOptFlag(db, "glob", SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE);
  89917. setLikeOptFlag(db, "like",
  89918. caseSensitive ? (SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE) : SQLITE_FUNC_LIKE);
  89919. }
  89920. /*
  89921. ** pExpr points to an expression which implements a function. If
  89922. ** it is appropriate to apply the LIKE optimization to that function
  89923. ** then set aWc[0] through aWc[2] to the wildcard characters and
  89924. ** return TRUE. If the function is not a LIKE-style function then
  89925. ** return FALSE.
  89926. */
  89927. SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3 *db, Expr *pExpr, int *pIsNocase, char *aWc){
  89928. FuncDef *pDef;
  89929. if( pExpr->op!=TK_FUNCTION
  89930. || !pExpr->x.pList
  89931. || pExpr->x.pList->nExpr!=2
  89932. ){
  89933. return 0;
  89934. }
  89935. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  89936. pDef = sqlite3FindFunction(db, pExpr->u.zToken,
  89937. sqlite3Strlen30(pExpr->u.zToken),
  89938. 2, SQLITE_UTF8, 0);
  89939. if( NEVER(pDef==0) || (pDef->funcFlags & SQLITE_FUNC_LIKE)==0 ){
  89940. return 0;
  89941. }
  89942. /* The memcpy() statement assumes that the wildcard characters are
  89943. ** the first three statements in the compareInfo structure. The
  89944. ** asserts() that follow verify that assumption
  89945. */
  89946. memcpy(aWc, pDef->pUserData, 3);
  89947. assert( (char*)&likeInfoAlt == (char*)&likeInfoAlt.matchAll );
  89948. assert( &((char*)&likeInfoAlt)[1] == (char*)&likeInfoAlt.matchOne );
  89949. assert( &((char*)&likeInfoAlt)[2] == (char*)&likeInfoAlt.matchSet );
  89950. *pIsNocase = (pDef->funcFlags & SQLITE_FUNC_CASE)==0;
  89951. return 1;
  89952. }
  89953. /*
  89954. ** All of the FuncDef structures in the aBuiltinFunc[] array above
  89955. ** to the global function hash table. This occurs at start-time (as
  89956. ** a consequence of calling sqlite3_initialize()).
  89957. **
  89958. ** After this routine runs
  89959. */
  89960. SQLITE_PRIVATE void sqlite3RegisterGlobalFunctions(void){
  89961. /*
  89962. ** The following array holds FuncDef structures for all of the functions
  89963. ** defined in this file.
  89964. **
  89965. ** The array cannot be constant since changes are made to the
  89966. ** FuncDef.pHash elements at start-time. The elements of this array
  89967. ** are read-only after initialization is complete.
  89968. */
  89969. static SQLITE_WSD FuncDef aBuiltinFunc[] = {
  89970. FUNCTION(ltrim, 1, 1, 0, trimFunc ),
  89971. FUNCTION(ltrim, 2, 1, 0, trimFunc ),
  89972. FUNCTION(rtrim, 1, 2, 0, trimFunc ),
  89973. FUNCTION(rtrim, 2, 2, 0, trimFunc ),
  89974. FUNCTION(trim, 1, 3, 0, trimFunc ),
  89975. FUNCTION(trim, 2, 3, 0, trimFunc ),
  89976. FUNCTION(min, -1, 0, 1, minmaxFunc ),
  89977. FUNCTION(min, 0, 0, 1, 0 ),
  89978. AGGREGATE2(min, 1, 0, 1, minmaxStep, minMaxFinalize,
  89979. SQLITE_FUNC_MINMAX ),
  89980. FUNCTION(max, -1, 1, 1, minmaxFunc ),
  89981. FUNCTION(max, 0, 1, 1, 0 ),
  89982. AGGREGATE2(max, 1, 1, 1, minmaxStep, minMaxFinalize,
  89983. SQLITE_FUNC_MINMAX ),
  89984. FUNCTION2(typeof, 1, 0, 0, typeofFunc, SQLITE_FUNC_TYPEOF),
  89985. FUNCTION2(length, 1, 0, 0, lengthFunc, SQLITE_FUNC_LENGTH),
  89986. FUNCTION(instr, 2, 0, 0, instrFunc ),
  89987. FUNCTION(substr, 2, 0, 0, substrFunc ),
  89988. FUNCTION(substr, 3, 0, 0, substrFunc ),
  89989. FUNCTION(printf, -1, 0, 0, printfFunc ),
  89990. FUNCTION(unicode, 1, 0, 0, unicodeFunc ),
  89991. FUNCTION(char, -1, 0, 0, charFunc ),
  89992. FUNCTION(abs, 1, 0, 0, absFunc ),
  89993. #ifndef SQLITE_OMIT_FLOATING_POINT
  89994. FUNCTION(round, 1, 0, 0, roundFunc ),
  89995. FUNCTION(round, 2, 0, 0, roundFunc ),
  89996. #endif
  89997. FUNCTION(upper, 1, 0, 0, upperFunc ),
  89998. FUNCTION(lower, 1, 0, 0, lowerFunc ),
  89999. FUNCTION(coalesce, 1, 0, 0, 0 ),
  90000. FUNCTION(coalesce, 0, 0, 0, 0 ),
  90001. FUNCTION2(coalesce, -1, 0, 0, noopFunc, SQLITE_FUNC_COALESCE),
  90002. FUNCTION(hex, 1, 0, 0, hexFunc ),
  90003. FUNCTION2(ifnull, 2, 0, 0, noopFunc, SQLITE_FUNC_COALESCE),
  90004. FUNCTION2(unlikely, 1, 0, 0, noopFunc, SQLITE_FUNC_UNLIKELY),
  90005. FUNCTION2(likelihood, 2, 0, 0, noopFunc, SQLITE_FUNC_UNLIKELY),
  90006. FUNCTION2(likely, 1, 0, 0, noopFunc, SQLITE_FUNC_UNLIKELY),
  90007. VFUNCTION(random, 0, 0, 0, randomFunc ),
  90008. VFUNCTION(randomblob, 1, 0, 0, randomBlob ),
  90009. FUNCTION(nullif, 2, 0, 1, nullifFunc ),
  90010. FUNCTION(sqlite_version, 0, 0, 0, versionFunc ),
  90011. FUNCTION(sqlite_source_id, 0, 0, 0, sourceidFunc ),
  90012. FUNCTION(sqlite_log, 2, 0, 0, errlogFunc ),
  90013. #if SQLITE_USER_AUTHENTICATION
  90014. FUNCTION(sqlite_crypt, 2, 0, 0, sqlite3CryptFunc ),
  90015. #endif
  90016. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  90017. FUNCTION(sqlite_compileoption_used,1, 0, 0, compileoptionusedFunc ),
  90018. FUNCTION(sqlite_compileoption_get, 1, 0, 0, compileoptiongetFunc ),
  90019. #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
  90020. FUNCTION(quote, 1, 0, 0, quoteFunc ),
  90021. VFUNCTION(last_insert_rowid, 0, 0, 0, last_insert_rowid),
  90022. VFUNCTION(changes, 0, 0, 0, changes ),
  90023. VFUNCTION(total_changes, 0, 0, 0, total_changes ),
  90024. FUNCTION(replace, 3, 0, 0, replaceFunc ),
  90025. FUNCTION(zeroblob, 1, 0, 0, zeroblobFunc ),
  90026. #ifdef SQLITE_SOUNDEX
  90027. FUNCTION(soundex, 1, 0, 0, soundexFunc ),
  90028. #endif
  90029. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  90030. FUNCTION(load_extension, 1, 0, 0, loadExt ),
  90031. FUNCTION(load_extension, 2, 0, 0, loadExt ),
  90032. #endif
  90033. AGGREGATE(sum, 1, 0, 0, sumStep, sumFinalize ),
  90034. AGGREGATE(total, 1, 0, 0, sumStep, totalFinalize ),
  90035. AGGREGATE(avg, 1, 0, 0, sumStep, avgFinalize ),
  90036. AGGREGATE2(count, 0, 0, 0, countStep, countFinalize,
  90037. SQLITE_FUNC_COUNT ),
  90038. AGGREGATE(count, 1, 0, 0, countStep, countFinalize ),
  90039. AGGREGATE(group_concat, 1, 0, 0, groupConcatStep, groupConcatFinalize),
  90040. AGGREGATE(group_concat, 2, 0, 0, groupConcatStep, groupConcatFinalize),
  90041. LIKEFUNC(glob, 2, &globInfo, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
  90042. #ifdef SQLITE_CASE_SENSITIVE_LIKE
  90043. LIKEFUNC(like, 2, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
  90044. LIKEFUNC(like, 3, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
  90045. #else
  90046. LIKEFUNC(like, 2, &likeInfoNorm, SQLITE_FUNC_LIKE),
  90047. LIKEFUNC(like, 3, &likeInfoNorm, SQLITE_FUNC_LIKE),
  90048. #endif
  90049. };
  90050. int i;
  90051. FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
  90052. FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aBuiltinFunc);
  90053. for(i=0; i<ArraySize(aBuiltinFunc); i++){
  90054. sqlite3FuncDefInsert(pHash, &aFunc[i]);
  90055. }
  90056. sqlite3RegisterDateTimeFunctions();
  90057. #ifndef SQLITE_OMIT_ALTERTABLE
  90058. sqlite3AlterFunctions();
  90059. #endif
  90060. #if defined(SQLITE_ENABLE_STAT3) || defined(SQLITE_ENABLE_STAT4)
  90061. sqlite3AnalyzeFunctions();
  90062. #endif
  90063. }
  90064. /************** End of func.c ************************************************/
  90065. /************** Begin file fkey.c ********************************************/
  90066. /*
  90067. **
  90068. ** The author disclaims copyright to this source code. In place of
  90069. ** a legal notice, here is a blessing:
  90070. **
  90071. ** May you do good and not evil.
  90072. ** May you find forgiveness for yourself and forgive others.
  90073. ** May you share freely, never taking more than you give.
  90074. **
  90075. *************************************************************************
  90076. ** This file contains code used by the compiler to add foreign key
  90077. ** support to compiled SQL statements.
  90078. */
  90079. #ifndef SQLITE_OMIT_FOREIGN_KEY
  90080. #ifndef SQLITE_OMIT_TRIGGER
  90081. /*
  90082. ** Deferred and Immediate FKs
  90083. ** --------------------------
  90084. **
  90085. ** Foreign keys in SQLite come in two flavours: deferred and immediate.
  90086. ** If an immediate foreign key constraint is violated,
  90087. ** SQLITE_CONSTRAINT_FOREIGNKEY is returned and the current
  90088. ** statement transaction rolled back. If a
  90089. ** deferred foreign key constraint is violated, no action is taken
  90090. ** immediately. However if the application attempts to commit the
  90091. ** transaction before fixing the constraint violation, the attempt fails.
  90092. **
  90093. ** Deferred constraints are implemented using a simple counter associated
  90094. ** with the database handle. The counter is set to zero each time a
  90095. ** database transaction is opened. Each time a statement is executed
  90096. ** that causes a foreign key violation, the counter is incremented. Each
  90097. ** time a statement is executed that removes an existing violation from
  90098. ** the database, the counter is decremented. When the transaction is
  90099. ** committed, the commit fails if the current value of the counter is
  90100. ** greater than zero. This scheme has two big drawbacks:
  90101. **
  90102. ** * When a commit fails due to a deferred foreign key constraint,
  90103. ** there is no way to tell which foreign constraint is not satisfied,
  90104. ** or which row it is not satisfied for.
  90105. **
  90106. ** * If the database contains foreign key violations when the
  90107. ** transaction is opened, this may cause the mechanism to malfunction.
  90108. **
  90109. ** Despite these problems, this approach is adopted as it seems simpler
  90110. ** than the alternatives.
  90111. **
  90112. ** INSERT operations:
  90113. **
  90114. ** I.1) For each FK for which the table is the child table, search
  90115. ** the parent table for a match. If none is found increment the
  90116. ** constraint counter.
  90117. **
  90118. ** I.2) For each FK for which the table is the parent table,
  90119. ** search the child table for rows that correspond to the new
  90120. ** row in the parent table. Decrement the counter for each row
  90121. ** found (as the constraint is now satisfied).
  90122. **
  90123. ** DELETE operations:
  90124. **
  90125. ** D.1) For each FK for which the table is the child table,
  90126. ** search the parent table for a row that corresponds to the
  90127. ** deleted row in the child table. If such a row is not found,
  90128. ** decrement the counter.
  90129. **
  90130. ** D.2) For each FK for which the table is the parent table, search
  90131. ** the child table for rows that correspond to the deleted row
  90132. ** in the parent table. For each found increment the counter.
  90133. **
  90134. ** UPDATE operations:
  90135. **
  90136. ** An UPDATE command requires that all 4 steps above are taken, but only
  90137. ** for FK constraints for which the affected columns are actually
  90138. ** modified (values must be compared at runtime).
  90139. **
  90140. ** Note that I.1 and D.1 are very similar operations, as are I.2 and D.2.
  90141. ** This simplifies the implementation a bit.
  90142. **
  90143. ** For the purposes of immediate FK constraints, the OR REPLACE conflict
  90144. ** resolution is considered to delete rows before the new row is inserted.
  90145. ** If a delete caused by OR REPLACE violates an FK constraint, an exception
  90146. ** is thrown, even if the FK constraint would be satisfied after the new
  90147. ** row is inserted.
  90148. **
  90149. ** Immediate constraints are usually handled similarly. The only difference
  90150. ** is that the counter used is stored as part of each individual statement
  90151. ** object (struct Vdbe). If, after the statement has run, its immediate
  90152. ** constraint counter is greater than zero,
  90153. ** it returns SQLITE_CONSTRAINT_FOREIGNKEY
  90154. ** and the statement transaction is rolled back. An exception is an INSERT
  90155. ** statement that inserts a single row only (no triggers). In this case,
  90156. ** instead of using a counter, an exception is thrown immediately if the
  90157. ** INSERT violates a foreign key constraint. This is necessary as such
  90158. ** an INSERT does not open a statement transaction.
  90159. **
  90160. ** TODO: How should dropping a table be handled? How should renaming a
  90161. ** table be handled?
  90162. **
  90163. **
  90164. ** Query API Notes
  90165. ** ---------------
  90166. **
  90167. ** Before coding an UPDATE or DELETE row operation, the code-generator
  90168. ** for those two operations needs to know whether or not the operation
  90169. ** requires any FK processing and, if so, which columns of the original
  90170. ** row are required by the FK processing VDBE code (i.e. if FKs were
  90171. ** implemented using triggers, which of the old.* columns would be
  90172. ** accessed). No information is required by the code-generator before
  90173. ** coding an INSERT operation. The functions used by the UPDATE/DELETE
  90174. ** generation code to query for this information are:
  90175. **
  90176. ** sqlite3FkRequired() - Test to see if FK processing is required.
  90177. ** sqlite3FkOldmask() - Query for the set of required old.* columns.
  90178. **
  90179. **
  90180. ** Externally accessible module functions
  90181. ** --------------------------------------
  90182. **
  90183. ** sqlite3FkCheck() - Check for foreign key violations.
  90184. ** sqlite3FkActions() - Code triggers for ON UPDATE/ON DELETE actions.
  90185. ** sqlite3FkDelete() - Delete an FKey structure.
  90186. */
  90187. /*
  90188. ** VDBE Calling Convention
  90189. ** -----------------------
  90190. **
  90191. ** Example:
  90192. **
  90193. ** For the following INSERT statement:
  90194. **
  90195. ** CREATE TABLE t1(a, b INTEGER PRIMARY KEY, c);
  90196. ** INSERT INTO t1 VALUES(1, 2, 3.1);
  90197. **
  90198. ** Register (x): 2 (type integer)
  90199. ** Register (x+1): 1 (type integer)
  90200. ** Register (x+2): NULL (type NULL)
  90201. ** Register (x+3): 3.1 (type real)
  90202. */
  90203. /*
  90204. ** A foreign key constraint requires that the key columns in the parent
  90205. ** table are collectively subject to a UNIQUE or PRIMARY KEY constraint.
  90206. ** Given that pParent is the parent table for foreign key constraint pFKey,
  90207. ** search the schema for a unique index on the parent key columns.
  90208. **
  90209. ** If successful, zero is returned. If the parent key is an INTEGER PRIMARY
  90210. ** KEY column, then output variable *ppIdx is set to NULL. Otherwise, *ppIdx
  90211. ** is set to point to the unique index.
  90212. **
  90213. ** If the parent key consists of a single column (the foreign key constraint
  90214. ** is not a composite foreign key), output variable *paiCol is set to NULL.
  90215. ** Otherwise, it is set to point to an allocated array of size N, where
  90216. ** N is the number of columns in the parent key. The first element of the
  90217. ** array is the index of the child table column that is mapped by the FK
  90218. ** constraint to the parent table column stored in the left-most column
  90219. ** of index *ppIdx. The second element of the array is the index of the
  90220. ** child table column that corresponds to the second left-most column of
  90221. ** *ppIdx, and so on.
  90222. **
  90223. ** If the required index cannot be found, either because:
  90224. **
  90225. ** 1) The named parent key columns do not exist, or
  90226. **
  90227. ** 2) The named parent key columns do exist, but are not subject to a
  90228. ** UNIQUE or PRIMARY KEY constraint, or
  90229. **
  90230. ** 3) No parent key columns were provided explicitly as part of the
  90231. ** foreign key definition, and the parent table does not have a
  90232. ** PRIMARY KEY, or
  90233. **
  90234. ** 4) No parent key columns were provided explicitly as part of the
  90235. ** foreign key definition, and the PRIMARY KEY of the parent table
  90236. ** consists of a different number of columns to the child key in
  90237. ** the child table.
  90238. **
  90239. ** then non-zero is returned, and a "foreign key mismatch" error loaded
  90240. ** into pParse. If an OOM error occurs, non-zero is returned and the
  90241. ** pParse->db->mallocFailed flag is set.
  90242. */
  90243. SQLITE_PRIVATE int sqlite3FkLocateIndex(
  90244. Parse *pParse, /* Parse context to store any error in */
  90245. Table *pParent, /* Parent table of FK constraint pFKey */
  90246. FKey *pFKey, /* Foreign key to find index for */
  90247. Index **ppIdx, /* OUT: Unique index on parent table */
  90248. int **paiCol /* OUT: Map of index columns in pFKey */
  90249. ){
  90250. Index *pIdx = 0; /* Value to return via *ppIdx */
  90251. int *aiCol = 0; /* Value to return via *paiCol */
  90252. int nCol = pFKey->nCol; /* Number of columns in parent key */
  90253. char *zKey = pFKey->aCol[0].zCol; /* Name of left-most parent key column */
  90254. /* The caller is responsible for zeroing output parameters. */
  90255. assert( ppIdx && *ppIdx==0 );
  90256. assert( !paiCol || *paiCol==0 );
  90257. assert( pParse );
  90258. /* If this is a non-composite (single column) foreign key, check if it
  90259. ** maps to the INTEGER PRIMARY KEY of table pParent. If so, leave *ppIdx
  90260. ** and *paiCol set to zero and return early.
  90261. **
  90262. ** Otherwise, for a composite foreign key (more than one column), allocate
  90263. ** space for the aiCol array (returned via output parameter *paiCol).
  90264. ** Non-composite foreign keys do not require the aiCol array.
  90265. */
  90266. if( nCol==1 ){
  90267. /* The FK maps to the IPK if any of the following are true:
  90268. **
  90269. ** 1) There is an INTEGER PRIMARY KEY column and the FK is implicitly
  90270. ** mapped to the primary key of table pParent, or
  90271. ** 2) The FK is explicitly mapped to a column declared as INTEGER
  90272. ** PRIMARY KEY.
  90273. */
  90274. if( pParent->iPKey>=0 ){
  90275. if( !zKey ) return 0;
  90276. if( !sqlite3StrICmp(pParent->aCol[pParent->iPKey].zName, zKey) ) return 0;
  90277. }
  90278. }else if( paiCol ){
  90279. assert( nCol>1 );
  90280. aiCol = (int *)sqlite3DbMallocRaw(pParse->db, nCol*sizeof(int));
  90281. if( !aiCol ) return 1;
  90282. *paiCol = aiCol;
  90283. }
  90284. for(pIdx=pParent->pIndex; pIdx; pIdx=pIdx->pNext){
  90285. if( pIdx->nKeyCol==nCol && IsUniqueIndex(pIdx) ){
  90286. /* pIdx is a UNIQUE index (or a PRIMARY KEY) and has the right number
  90287. ** of columns. If each indexed column corresponds to a foreign key
  90288. ** column of pFKey, then this index is a winner. */
  90289. if( zKey==0 ){
  90290. /* If zKey is NULL, then this foreign key is implicitly mapped to
  90291. ** the PRIMARY KEY of table pParent. The PRIMARY KEY index may be
  90292. ** identified by the test. */
  90293. if( IsPrimaryKeyIndex(pIdx) ){
  90294. if( aiCol ){
  90295. int i;
  90296. for(i=0; i<nCol; i++) aiCol[i] = pFKey->aCol[i].iFrom;
  90297. }
  90298. break;
  90299. }
  90300. }else{
  90301. /* If zKey is non-NULL, then this foreign key was declared to
  90302. ** map to an explicit list of columns in table pParent. Check if this
  90303. ** index matches those columns. Also, check that the index uses
  90304. ** the default collation sequences for each column. */
  90305. int i, j;
  90306. for(i=0; i<nCol; i++){
  90307. i16 iCol = pIdx->aiColumn[i]; /* Index of column in parent tbl */
  90308. char *zDfltColl; /* Def. collation for column */
  90309. char *zIdxCol; /* Name of indexed column */
  90310. /* If the index uses a collation sequence that is different from
  90311. ** the default collation sequence for the column, this index is
  90312. ** unusable. Bail out early in this case. */
  90313. zDfltColl = pParent->aCol[iCol].zColl;
  90314. if( !zDfltColl ){
  90315. zDfltColl = "BINARY";
  90316. }
  90317. if( sqlite3StrICmp(pIdx->azColl[i], zDfltColl) ) break;
  90318. zIdxCol = pParent->aCol[iCol].zName;
  90319. for(j=0; j<nCol; j++){
  90320. if( sqlite3StrICmp(pFKey->aCol[j].zCol, zIdxCol)==0 ){
  90321. if( aiCol ) aiCol[i] = pFKey->aCol[j].iFrom;
  90322. break;
  90323. }
  90324. }
  90325. if( j==nCol ) break;
  90326. }
  90327. if( i==nCol ) break; /* pIdx is usable */
  90328. }
  90329. }
  90330. }
  90331. if( !pIdx ){
  90332. if( !pParse->disableTriggers ){
  90333. sqlite3ErrorMsg(pParse,
  90334. "foreign key mismatch - \"%w\" referencing \"%w\"",
  90335. pFKey->pFrom->zName, pFKey->zTo);
  90336. }
  90337. sqlite3DbFree(pParse->db, aiCol);
  90338. return 1;
  90339. }
  90340. *ppIdx = pIdx;
  90341. return 0;
  90342. }
  90343. /*
  90344. ** This function is called when a row is inserted into or deleted from the
  90345. ** child table of foreign key constraint pFKey. If an SQL UPDATE is executed
  90346. ** on the child table of pFKey, this function is invoked twice for each row
  90347. ** affected - once to "delete" the old row, and then again to "insert" the
  90348. ** new row.
  90349. **
  90350. ** Each time it is called, this function generates VDBE code to locate the
  90351. ** row in the parent table that corresponds to the row being inserted into
  90352. ** or deleted from the child table. If the parent row can be found, no
  90353. ** special action is taken. Otherwise, if the parent row can *not* be
  90354. ** found in the parent table:
  90355. **
  90356. ** Operation | FK type | Action taken
  90357. ** --------------------------------------------------------------------------
  90358. ** INSERT immediate Increment the "immediate constraint counter".
  90359. **
  90360. ** DELETE immediate Decrement the "immediate constraint counter".
  90361. **
  90362. ** INSERT deferred Increment the "deferred constraint counter".
  90363. **
  90364. ** DELETE deferred Decrement the "deferred constraint counter".
  90365. **
  90366. ** These operations are identified in the comment at the top of this file
  90367. ** (fkey.c) as "I.1" and "D.1".
  90368. */
  90369. static void fkLookupParent(
  90370. Parse *pParse, /* Parse context */
  90371. int iDb, /* Index of database housing pTab */
  90372. Table *pTab, /* Parent table of FK pFKey */
  90373. Index *pIdx, /* Unique index on parent key columns in pTab */
  90374. FKey *pFKey, /* Foreign key constraint */
  90375. int *aiCol, /* Map from parent key columns to child table columns */
  90376. int regData, /* Address of array containing child table row */
  90377. int nIncr, /* Increment constraint counter by this */
  90378. int isIgnore /* If true, pretend pTab contains all NULL values */
  90379. ){
  90380. int i; /* Iterator variable */
  90381. Vdbe *v = sqlite3GetVdbe(pParse); /* Vdbe to add code to */
  90382. int iCur = pParse->nTab - 1; /* Cursor number to use */
  90383. int iOk = sqlite3VdbeMakeLabel(v); /* jump here if parent key found */
  90384. /* If nIncr is less than zero, then check at runtime if there are any
  90385. ** outstanding constraints to resolve. If there are not, there is no need
  90386. ** to check if deleting this row resolves any outstanding violations.
  90387. **
  90388. ** Check if any of the key columns in the child table row are NULL. If
  90389. ** any are, then the constraint is considered satisfied. No need to
  90390. ** search for a matching row in the parent table. */
  90391. if( nIncr<0 ){
  90392. sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, iOk);
  90393. VdbeCoverage(v);
  90394. }
  90395. for(i=0; i<pFKey->nCol; i++){
  90396. int iReg = aiCol[i] + regData + 1;
  90397. sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iOk); VdbeCoverage(v);
  90398. }
  90399. if( isIgnore==0 ){
  90400. if( pIdx==0 ){
  90401. /* If pIdx is NULL, then the parent key is the INTEGER PRIMARY KEY
  90402. ** column of the parent table (table pTab). */
  90403. int iMustBeInt; /* Address of MustBeInt instruction */
  90404. int regTemp = sqlite3GetTempReg(pParse);
  90405. /* Invoke MustBeInt to coerce the child key value to an integer (i.e.
  90406. ** apply the affinity of the parent key). If this fails, then there
  90407. ** is no matching parent key. Before using MustBeInt, make a copy of
  90408. ** the value. Otherwise, the value inserted into the child key column
  90409. ** will have INTEGER affinity applied to it, which may not be correct. */
  90410. sqlite3VdbeAddOp2(v, OP_SCopy, aiCol[0]+1+regData, regTemp);
  90411. iMustBeInt = sqlite3VdbeAddOp2(v, OP_MustBeInt, regTemp, 0);
  90412. VdbeCoverage(v);
  90413. /* If the parent table is the same as the child table, and we are about
  90414. ** to increment the constraint-counter (i.e. this is an INSERT operation),
  90415. ** then check if the row being inserted matches itself. If so, do not
  90416. ** increment the constraint-counter. */
  90417. if( pTab==pFKey->pFrom && nIncr==1 ){
  90418. sqlite3VdbeAddOp3(v, OP_Eq, regData, iOk, regTemp); VdbeCoverage(v);
  90419. sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
  90420. }
  90421. sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenRead);
  90422. sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regTemp); VdbeCoverage(v);
  90423. sqlite3VdbeAddOp2(v, OP_Goto, 0, iOk);
  90424. sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
  90425. sqlite3VdbeJumpHere(v, iMustBeInt);
  90426. sqlite3ReleaseTempReg(pParse, regTemp);
  90427. }else{
  90428. int nCol = pFKey->nCol;
  90429. int regTemp = sqlite3GetTempRange(pParse, nCol);
  90430. int regRec = sqlite3GetTempReg(pParse);
  90431. sqlite3VdbeAddOp3(v, OP_OpenRead, iCur, pIdx->tnum, iDb);
  90432. sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
  90433. for(i=0; i<nCol; i++){
  90434. sqlite3VdbeAddOp2(v, OP_Copy, aiCol[i]+1+regData, regTemp+i);
  90435. }
  90436. /* If the parent table is the same as the child table, and we are about
  90437. ** to increment the constraint-counter (i.e. this is an INSERT operation),
  90438. ** then check if the row being inserted matches itself. If so, do not
  90439. ** increment the constraint-counter.
  90440. **
  90441. ** If any of the parent-key values are NULL, then the row cannot match
  90442. ** itself. So set JUMPIFNULL to make sure we do the OP_Found if any
  90443. ** of the parent-key values are NULL (at this point it is known that
  90444. ** none of the child key values are).
  90445. */
  90446. if( pTab==pFKey->pFrom && nIncr==1 ){
  90447. int iJump = sqlite3VdbeCurrentAddr(v) + nCol + 1;
  90448. for(i=0; i<nCol; i++){
  90449. int iChild = aiCol[i]+1+regData;
  90450. int iParent = pIdx->aiColumn[i]+1+regData;
  90451. assert( aiCol[i]!=pTab->iPKey );
  90452. if( pIdx->aiColumn[i]==pTab->iPKey ){
  90453. /* The parent key is a composite key that includes the IPK column */
  90454. iParent = regData;
  90455. }
  90456. sqlite3VdbeAddOp3(v, OP_Ne, iChild, iJump, iParent); VdbeCoverage(v);
  90457. sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
  90458. }
  90459. sqlite3VdbeAddOp2(v, OP_Goto, 0, iOk);
  90460. }
  90461. sqlite3VdbeAddOp4(v, OP_MakeRecord, regTemp, nCol, regRec,
  90462. sqlite3IndexAffinityStr(v,pIdx), nCol);
  90463. sqlite3VdbeAddOp4Int(v, OP_Found, iCur, iOk, regRec, 0); VdbeCoverage(v);
  90464. sqlite3ReleaseTempReg(pParse, regRec);
  90465. sqlite3ReleaseTempRange(pParse, regTemp, nCol);
  90466. }
  90467. }
  90468. if( !pFKey->isDeferred && !(pParse->db->flags & SQLITE_DeferFKs)
  90469. && !pParse->pToplevel
  90470. && !pParse->isMultiWrite
  90471. ){
  90472. /* Special case: If this is an INSERT statement that will insert exactly
  90473. ** one row into the table, raise a constraint immediately instead of
  90474. ** incrementing a counter. This is necessary as the VM code is being
  90475. ** generated for will not open a statement transaction. */
  90476. assert( nIncr==1 );
  90477. sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_FOREIGNKEY,
  90478. OE_Abort, 0, P4_STATIC, P5_ConstraintFK);
  90479. }else{
  90480. if( nIncr>0 && pFKey->isDeferred==0 ){
  90481. sqlite3ParseToplevel(pParse)->mayAbort = 1;
  90482. }
  90483. sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
  90484. }
  90485. sqlite3VdbeResolveLabel(v, iOk);
  90486. sqlite3VdbeAddOp1(v, OP_Close, iCur);
  90487. }
  90488. /*
  90489. ** Return an Expr object that refers to a memory register corresponding
  90490. ** to column iCol of table pTab.
  90491. **
  90492. ** regBase is the first of an array of register that contains the data
  90493. ** for pTab. regBase itself holds the rowid. regBase+1 holds the first
  90494. ** column. regBase+2 holds the second column, and so forth.
  90495. */
  90496. static Expr *exprTableRegister(
  90497. Parse *pParse, /* Parsing and code generating context */
  90498. Table *pTab, /* The table whose content is at r[regBase]... */
  90499. int regBase, /* Contents of table pTab */
  90500. i16 iCol /* Which column of pTab is desired */
  90501. ){
  90502. Expr *pExpr;
  90503. Column *pCol;
  90504. const char *zColl;
  90505. sqlite3 *db = pParse->db;
  90506. pExpr = sqlite3Expr(db, TK_REGISTER, 0);
  90507. if( pExpr ){
  90508. if( iCol>=0 && iCol!=pTab->iPKey ){
  90509. pCol = &pTab->aCol[iCol];
  90510. pExpr->iTable = regBase + iCol + 1;
  90511. pExpr->affinity = pCol->affinity;
  90512. zColl = pCol->zColl;
  90513. if( zColl==0 ) zColl = db->pDfltColl->zName;
  90514. pExpr = sqlite3ExprAddCollateString(pParse, pExpr, zColl);
  90515. }else{
  90516. pExpr->iTable = regBase;
  90517. pExpr->affinity = SQLITE_AFF_INTEGER;
  90518. }
  90519. }
  90520. return pExpr;
  90521. }
  90522. /*
  90523. ** Return an Expr object that refers to column iCol of table pTab which
  90524. ** has cursor iCur.
  90525. */
  90526. static Expr *exprTableColumn(
  90527. sqlite3 *db, /* The database connection */
  90528. Table *pTab, /* The table whose column is desired */
  90529. int iCursor, /* The open cursor on the table */
  90530. i16 iCol /* The column that is wanted */
  90531. ){
  90532. Expr *pExpr = sqlite3Expr(db, TK_COLUMN, 0);
  90533. if( pExpr ){
  90534. pExpr->pTab = pTab;
  90535. pExpr->iTable = iCursor;
  90536. pExpr->iColumn = iCol;
  90537. }
  90538. return pExpr;
  90539. }
  90540. /*
  90541. ** This function is called to generate code executed when a row is deleted
  90542. ** from the parent table of foreign key constraint pFKey and, if pFKey is
  90543. ** deferred, when a row is inserted into the same table. When generating
  90544. ** code for an SQL UPDATE operation, this function may be called twice -
  90545. ** once to "delete" the old row and once to "insert" the new row.
  90546. **
  90547. ** The code generated by this function scans through the rows in the child
  90548. ** table that correspond to the parent table row being deleted or inserted.
  90549. ** For each child row found, one of the following actions is taken:
  90550. **
  90551. ** Operation | FK type | Action taken
  90552. ** --------------------------------------------------------------------------
  90553. ** DELETE immediate Increment the "immediate constraint counter".
  90554. ** Or, if the ON (UPDATE|DELETE) action is RESTRICT,
  90555. ** throw a "FOREIGN KEY constraint failed" exception.
  90556. **
  90557. ** INSERT immediate Decrement the "immediate constraint counter".
  90558. **
  90559. ** DELETE deferred Increment the "deferred constraint counter".
  90560. ** Or, if the ON (UPDATE|DELETE) action is RESTRICT,
  90561. ** throw a "FOREIGN KEY constraint failed" exception.
  90562. **
  90563. ** INSERT deferred Decrement the "deferred constraint counter".
  90564. **
  90565. ** These operations are identified in the comment at the top of this file
  90566. ** (fkey.c) as "I.2" and "D.2".
  90567. */
  90568. static void fkScanChildren(
  90569. Parse *pParse, /* Parse context */
  90570. SrcList *pSrc, /* The child table to be scanned */
  90571. Table *pTab, /* The parent table */
  90572. Index *pIdx, /* Index on parent covering the foreign key */
  90573. FKey *pFKey, /* The foreign key linking pSrc to pTab */
  90574. int *aiCol, /* Map from pIdx cols to child table cols */
  90575. int regData, /* Parent row data starts here */
  90576. int nIncr /* Amount to increment deferred counter by */
  90577. ){
  90578. sqlite3 *db = pParse->db; /* Database handle */
  90579. int i; /* Iterator variable */
  90580. Expr *pWhere = 0; /* WHERE clause to scan with */
  90581. NameContext sNameContext; /* Context used to resolve WHERE clause */
  90582. WhereInfo *pWInfo; /* Context used by sqlite3WhereXXX() */
  90583. int iFkIfZero = 0; /* Address of OP_FkIfZero */
  90584. Vdbe *v = sqlite3GetVdbe(pParse);
  90585. assert( pIdx==0 || pIdx->pTable==pTab );
  90586. assert( pIdx==0 || pIdx->nKeyCol==pFKey->nCol );
  90587. assert( pIdx!=0 || pFKey->nCol==1 );
  90588. assert( pIdx!=0 || HasRowid(pTab) );
  90589. if( nIncr<0 ){
  90590. iFkIfZero = sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, 0);
  90591. VdbeCoverage(v);
  90592. }
  90593. /* Create an Expr object representing an SQL expression like:
  90594. **
  90595. ** <parent-key1> = <child-key1> AND <parent-key2> = <child-key2> ...
  90596. **
  90597. ** The collation sequence used for the comparison should be that of
  90598. ** the parent key columns. The affinity of the parent key column should
  90599. ** be applied to each child key value before the comparison takes place.
  90600. */
  90601. for(i=0; i<pFKey->nCol; i++){
  90602. Expr *pLeft; /* Value from parent table row */
  90603. Expr *pRight; /* Column ref to child table */
  90604. Expr *pEq; /* Expression (pLeft = pRight) */
  90605. i16 iCol; /* Index of column in child table */
  90606. const char *zCol; /* Name of column in child table */
  90607. iCol = pIdx ? pIdx->aiColumn[i] : -1;
  90608. pLeft = exprTableRegister(pParse, pTab, regData, iCol);
  90609. iCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
  90610. assert( iCol>=0 );
  90611. zCol = pFKey->pFrom->aCol[iCol].zName;
  90612. pRight = sqlite3Expr(db, TK_ID, zCol);
  90613. pEq = sqlite3PExpr(pParse, TK_EQ, pLeft, pRight, 0);
  90614. pWhere = sqlite3ExprAnd(db, pWhere, pEq);
  90615. }
  90616. /* If the child table is the same as the parent table, then add terms
  90617. ** to the WHERE clause that prevent this entry from being scanned.
  90618. ** The added WHERE clause terms are like this:
  90619. **
  90620. ** $current_rowid!=rowid
  90621. ** NOT( $current_a==a AND $current_b==b AND ... )
  90622. **
  90623. ** The first form is used for rowid tables. The second form is used
  90624. ** for WITHOUT ROWID tables. In the second form, the primary key is
  90625. ** (a,b,...)
  90626. */
  90627. if( pTab==pFKey->pFrom && nIncr>0 ){
  90628. Expr *pNe; /* Expression (pLeft != pRight) */
  90629. Expr *pLeft; /* Value from parent table row */
  90630. Expr *pRight; /* Column ref to child table */
  90631. if( HasRowid(pTab) ){
  90632. pLeft = exprTableRegister(pParse, pTab, regData, -1);
  90633. pRight = exprTableColumn(db, pTab, pSrc->a[0].iCursor, -1);
  90634. pNe = sqlite3PExpr(pParse, TK_NE, pLeft, pRight, 0);
  90635. }else{
  90636. Expr *pEq, *pAll = 0;
  90637. Index *pPk = sqlite3PrimaryKeyIndex(pTab);
  90638. assert( pIdx!=0 );
  90639. for(i=0; i<pPk->nKeyCol; i++){
  90640. i16 iCol = pIdx->aiColumn[i];
  90641. pLeft = exprTableRegister(pParse, pTab, regData, iCol);
  90642. pRight = exprTableColumn(db, pTab, pSrc->a[0].iCursor, iCol);
  90643. pEq = sqlite3PExpr(pParse, TK_EQ, pLeft, pRight, 0);
  90644. pAll = sqlite3ExprAnd(db, pAll, pEq);
  90645. }
  90646. pNe = sqlite3PExpr(pParse, TK_NOT, pAll, 0, 0);
  90647. }
  90648. pWhere = sqlite3ExprAnd(db, pWhere, pNe);
  90649. }
  90650. /* Resolve the references in the WHERE clause. */
  90651. memset(&sNameContext, 0, sizeof(NameContext));
  90652. sNameContext.pSrcList = pSrc;
  90653. sNameContext.pParse = pParse;
  90654. sqlite3ResolveExprNames(&sNameContext, pWhere);
  90655. /* Create VDBE to loop through the entries in pSrc that match the WHERE
  90656. ** clause. If the constraint is not deferred, throw an exception for
  90657. ** each row found. Otherwise, for deferred constraints, increment the
  90658. ** deferred constraint counter by nIncr for each row selected. */
  90659. pWInfo = sqlite3WhereBegin(pParse, pSrc, pWhere, 0, 0, 0, 0);
  90660. if( nIncr>0 && pFKey->isDeferred==0 ){
  90661. sqlite3ParseToplevel(pParse)->mayAbort = 1;
  90662. }
  90663. sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
  90664. if( pWInfo ){
  90665. sqlite3WhereEnd(pWInfo);
  90666. }
  90667. /* Clean up the WHERE clause constructed above. */
  90668. sqlite3ExprDelete(db, pWhere);
  90669. if( iFkIfZero ){
  90670. sqlite3VdbeJumpHere(v, iFkIfZero);
  90671. }
  90672. }
  90673. /*
  90674. ** This function returns a linked list of FKey objects (connected by
  90675. ** FKey.pNextTo) holding all children of table pTab. For example,
  90676. ** given the following schema:
  90677. **
  90678. ** CREATE TABLE t1(a PRIMARY KEY);
  90679. ** CREATE TABLE t2(b REFERENCES t1(a);
  90680. **
  90681. ** Calling this function with table "t1" as an argument returns a pointer
  90682. ** to the FKey structure representing the foreign key constraint on table
  90683. ** "t2". Calling this function with "t2" as the argument would return a
  90684. ** NULL pointer (as there are no FK constraints for which t2 is the parent
  90685. ** table).
  90686. */
  90687. SQLITE_PRIVATE FKey *sqlite3FkReferences(Table *pTab){
  90688. return (FKey *)sqlite3HashFind(&pTab->pSchema->fkeyHash, pTab->zName);
  90689. }
  90690. /*
  90691. ** The second argument is a Trigger structure allocated by the
  90692. ** fkActionTrigger() routine. This function deletes the Trigger structure
  90693. ** and all of its sub-components.
  90694. **
  90695. ** The Trigger structure or any of its sub-components may be allocated from
  90696. ** the lookaside buffer belonging to database handle dbMem.
  90697. */
  90698. static void fkTriggerDelete(sqlite3 *dbMem, Trigger *p){
  90699. if( p ){
  90700. TriggerStep *pStep = p->step_list;
  90701. sqlite3ExprDelete(dbMem, pStep->pWhere);
  90702. sqlite3ExprListDelete(dbMem, pStep->pExprList);
  90703. sqlite3SelectDelete(dbMem, pStep->pSelect);
  90704. sqlite3ExprDelete(dbMem, p->pWhen);
  90705. sqlite3DbFree(dbMem, p);
  90706. }
  90707. }
  90708. /*
  90709. ** This function is called to generate code that runs when table pTab is
  90710. ** being dropped from the database. The SrcList passed as the second argument
  90711. ** to this function contains a single entry guaranteed to resolve to
  90712. ** table pTab.
  90713. **
  90714. ** Normally, no code is required. However, if either
  90715. **
  90716. ** (a) The table is the parent table of a FK constraint, or
  90717. ** (b) The table is the child table of a deferred FK constraint and it is
  90718. ** determined at runtime that there are outstanding deferred FK
  90719. ** constraint violations in the database,
  90720. **
  90721. ** then the equivalent of "DELETE FROM <tbl>" is executed before dropping
  90722. ** the table from the database. Triggers are disabled while running this
  90723. ** DELETE, but foreign key actions are not.
  90724. */
  90725. SQLITE_PRIVATE void sqlite3FkDropTable(Parse *pParse, SrcList *pName, Table *pTab){
  90726. sqlite3 *db = pParse->db;
  90727. if( (db->flags&SQLITE_ForeignKeys) && !IsVirtual(pTab) && !pTab->pSelect ){
  90728. int iSkip = 0;
  90729. Vdbe *v = sqlite3GetVdbe(pParse);
  90730. assert( v ); /* VDBE has already been allocated */
  90731. if( sqlite3FkReferences(pTab)==0 ){
  90732. /* Search for a deferred foreign key constraint for which this table
  90733. ** is the child table. If one cannot be found, return without
  90734. ** generating any VDBE code. If one can be found, then jump over
  90735. ** the entire DELETE if there are no outstanding deferred constraints
  90736. ** when this statement is run. */
  90737. FKey *p;
  90738. for(p=pTab->pFKey; p; p=p->pNextFrom){
  90739. if( p->isDeferred || (db->flags & SQLITE_DeferFKs) ) break;
  90740. }
  90741. if( !p ) return;
  90742. iSkip = sqlite3VdbeMakeLabel(v);
  90743. sqlite3VdbeAddOp2(v, OP_FkIfZero, 1, iSkip); VdbeCoverage(v);
  90744. }
  90745. pParse->disableTriggers = 1;
  90746. sqlite3DeleteFrom(pParse, sqlite3SrcListDup(db, pName, 0), 0);
  90747. pParse->disableTriggers = 0;
  90748. /* If the DELETE has generated immediate foreign key constraint
  90749. ** violations, halt the VDBE and return an error at this point, before
  90750. ** any modifications to the schema are made. This is because statement
  90751. ** transactions are not able to rollback schema changes.
  90752. **
  90753. ** If the SQLITE_DeferFKs flag is set, then this is not required, as
  90754. ** the statement transaction will not be rolled back even if FK
  90755. ** constraints are violated.
  90756. */
  90757. if( (db->flags & SQLITE_DeferFKs)==0 ){
  90758. sqlite3VdbeAddOp2(v, OP_FkIfZero, 0, sqlite3VdbeCurrentAddr(v)+2);
  90759. VdbeCoverage(v);
  90760. sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_FOREIGNKEY,
  90761. OE_Abort, 0, P4_STATIC, P5_ConstraintFK);
  90762. }
  90763. if( iSkip ){
  90764. sqlite3VdbeResolveLabel(v, iSkip);
  90765. }
  90766. }
  90767. }
  90768. /*
  90769. ** The second argument points to an FKey object representing a foreign key
  90770. ** for which pTab is the child table. An UPDATE statement against pTab
  90771. ** is currently being processed. For each column of the table that is
  90772. ** actually updated, the corresponding element in the aChange[] array
  90773. ** is zero or greater (if a column is unmodified the corresponding element
  90774. ** is set to -1). If the rowid column is modified by the UPDATE statement
  90775. ** the bChngRowid argument is non-zero.
  90776. **
  90777. ** This function returns true if any of the columns that are part of the
  90778. ** child key for FK constraint *p are modified.
  90779. */
  90780. static int fkChildIsModified(
  90781. Table *pTab, /* Table being updated */
  90782. FKey *p, /* Foreign key for which pTab is the child */
  90783. int *aChange, /* Array indicating modified columns */
  90784. int bChngRowid /* True if rowid is modified by this update */
  90785. ){
  90786. int i;
  90787. for(i=0; i<p->nCol; i++){
  90788. int iChildKey = p->aCol[i].iFrom;
  90789. if( aChange[iChildKey]>=0 ) return 1;
  90790. if( iChildKey==pTab->iPKey && bChngRowid ) return 1;
  90791. }
  90792. return 0;
  90793. }
  90794. /*
  90795. ** The second argument points to an FKey object representing a foreign key
  90796. ** for which pTab is the parent table. An UPDATE statement against pTab
  90797. ** is currently being processed. For each column of the table that is
  90798. ** actually updated, the corresponding element in the aChange[] array
  90799. ** is zero or greater (if a column is unmodified the corresponding element
  90800. ** is set to -1). If the rowid column is modified by the UPDATE statement
  90801. ** the bChngRowid argument is non-zero.
  90802. **
  90803. ** This function returns true if any of the columns that are part of the
  90804. ** parent key for FK constraint *p are modified.
  90805. */
  90806. static int fkParentIsModified(
  90807. Table *pTab,
  90808. FKey *p,
  90809. int *aChange,
  90810. int bChngRowid
  90811. ){
  90812. int i;
  90813. for(i=0; i<p->nCol; i++){
  90814. char *zKey = p->aCol[i].zCol;
  90815. int iKey;
  90816. for(iKey=0; iKey<pTab->nCol; iKey++){
  90817. if( aChange[iKey]>=0 || (iKey==pTab->iPKey && bChngRowid) ){
  90818. Column *pCol = &pTab->aCol[iKey];
  90819. if( zKey ){
  90820. if( 0==sqlite3StrICmp(pCol->zName, zKey) ) return 1;
  90821. }else if( pCol->colFlags & COLFLAG_PRIMKEY ){
  90822. return 1;
  90823. }
  90824. }
  90825. }
  90826. }
  90827. return 0;
  90828. }
  90829. /*
  90830. ** This function is called when inserting, deleting or updating a row of
  90831. ** table pTab to generate VDBE code to perform foreign key constraint
  90832. ** processing for the operation.
  90833. **
  90834. ** For a DELETE operation, parameter regOld is passed the index of the
  90835. ** first register in an array of (pTab->nCol+1) registers containing the
  90836. ** rowid of the row being deleted, followed by each of the column values
  90837. ** of the row being deleted, from left to right. Parameter regNew is passed
  90838. ** zero in this case.
  90839. **
  90840. ** For an INSERT operation, regOld is passed zero and regNew is passed the
  90841. ** first register of an array of (pTab->nCol+1) registers containing the new
  90842. ** row data.
  90843. **
  90844. ** For an UPDATE operation, this function is called twice. Once before
  90845. ** the original record is deleted from the table using the calling convention
  90846. ** described for DELETE. Then again after the original record is deleted
  90847. ** but before the new record is inserted using the INSERT convention.
  90848. */
  90849. SQLITE_PRIVATE void sqlite3FkCheck(
  90850. Parse *pParse, /* Parse context */
  90851. Table *pTab, /* Row is being deleted from this table */
  90852. int regOld, /* Previous row data is stored here */
  90853. int regNew, /* New row data is stored here */
  90854. int *aChange, /* Array indicating UPDATEd columns (or 0) */
  90855. int bChngRowid /* True if rowid is UPDATEd */
  90856. ){
  90857. sqlite3 *db = pParse->db; /* Database handle */
  90858. FKey *pFKey; /* Used to iterate through FKs */
  90859. int iDb; /* Index of database containing pTab */
  90860. const char *zDb; /* Name of database containing pTab */
  90861. int isIgnoreErrors = pParse->disableTriggers;
  90862. /* Exactly one of regOld and regNew should be non-zero. */
  90863. assert( (regOld==0)!=(regNew==0) );
  90864. /* If foreign-keys are disabled, this function is a no-op. */
  90865. if( (db->flags&SQLITE_ForeignKeys)==0 ) return;
  90866. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  90867. zDb = db->aDb[iDb].zName;
  90868. /* Loop through all the foreign key constraints for which pTab is the
  90869. ** child table (the table that the foreign key definition is part of). */
  90870. for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
  90871. Table *pTo; /* Parent table of foreign key pFKey */
  90872. Index *pIdx = 0; /* Index on key columns in pTo */
  90873. int *aiFree = 0;
  90874. int *aiCol;
  90875. int iCol;
  90876. int i;
  90877. int isIgnore = 0;
  90878. if( aChange
  90879. && sqlite3_stricmp(pTab->zName, pFKey->zTo)!=0
  90880. && fkChildIsModified(pTab, pFKey, aChange, bChngRowid)==0
  90881. ){
  90882. continue;
  90883. }
  90884. /* Find the parent table of this foreign key. Also find a unique index
  90885. ** on the parent key columns in the parent table. If either of these
  90886. ** schema items cannot be located, set an error in pParse and return
  90887. ** early. */
  90888. if( pParse->disableTriggers ){
  90889. pTo = sqlite3FindTable(db, pFKey->zTo, zDb);
  90890. }else{
  90891. pTo = sqlite3LocateTable(pParse, 0, pFKey->zTo, zDb);
  90892. }
  90893. if( !pTo || sqlite3FkLocateIndex(pParse, pTo, pFKey, &pIdx, &aiFree) ){
  90894. assert( isIgnoreErrors==0 || (regOld!=0 && regNew==0) );
  90895. if( !isIgnoreErrors || db->mallocFailed ) return;
  90896. if( pTo==0 ){
  90897. /* If isIgnoreErrors is true, then a table is being dropped. In this
  90898. ** case SQLite runs a "DELETE FROM xxx" on the table being dropped
  90899. ** before actually dropping it in order to check FK constraints.
  90900. ** If the parent table of an FK constraint on the current table is
  90901. ** missing, behave as if it is empty. i.e. decrement the relevant
  90902. ** FK counter for each row of the current table with non-NULL keys.
  90903. */
  90904. Vdbe *v = sqlite3GetVdbe(pParse);
  90905. int iJump = sqlite3VdbeCurrentAddr(v) + pFKey->nCol + 1;
  90906. for(i=0; i<pFKey->nCol; i++){
  90907. int iReg = pFKey->aCol[i].iFrom + regOld + 1;
  90908. sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iJump); VdbeCoverage(v);
  90909. }
  90910. sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, -1);
  90911. }
  90912. continue;
  90913. }
  90914. assert( pFKey->nCol==1 || (aiFree && pIdx) );
  90915. if( aiFree ){
  90916. aiCol = aiFree;
  90917. }else{
  90918. iCol = pFKey->aCol[0].iFrom;
  90919. aiCol = &iCol;
  90920. }
  90921. for(i=0; i<pFKey->nCol; i++){
  90922. if( aiCol[i]==pTab->iPKey ){
  90923. aiCol[i] = -1;
  90924. }
  90925. #ifndef SQLITE_OMIT_AUTHORIZATION
  90926. /* Request permission to read the parent key columns. If the
  90927. ** authorization callback returns SQLITE_IGNORE, behave as if any
  90928. ** values read from the parent table are NULL. */
  90929. if( db->xAuth ){
  90930. int rcauth;
  90931. char *zCol = pTo->aCol[pIdx ? pIdx->aiColumn[i] : pTo->iPKey].zName;
  90932. rcauth = sqlite3AuthReadCol(pParse, pTo->zName, zCol, iDb);
  90933. isIgnore = (rcauth==SQLITE_IGNORE);
  90934. }
  90935. #endif
  90936. }
  90937. /* Take a shared-cache advisory read-lock on the parent table. Allocate
  90938. ** a cursor to use to search the unique index on the parent key columns
  90939. ** in the parent table. */
  90940. sqlite3TableLock(pParse, iDb, pTo->tnum, 0, pTo->zName);
  90941. pParse->nTab++;
  90942. if( regOld!=0 ){
  90943. /* A row is being removed from the child table. Search for the parent.
  90944. ** If the parent does not exist, removing the child row resolves an
  90945. ** outstanding foreign key constraint violation. */
  90946. fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regOld, -1,isIgnore);
  90947. }
  90948. if( regNew!=0 ){
  90949. /* A row is being added to the child table. If a parent row cannot
  90950. ** be found, adding the child row has violated the FK constraint. */
  90951. fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regNew, +1,isIgnore);
  90952. }
  90953. sqlite3DbFree(db, aiFree);
  90954. }
  90955. /* Loop through all the foreign key constraints that refer to this table.
  90956. ** (the "child" constraints) */
  90957. for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
  90958. Index *pIdx = 0; /* Foreign key index for pFKey */
  90959. SrcList *pSrc;
  90960. int *aiCol = 0;
  90961. if( aChange && fkParentIsModified(pTab, pFKey, aChange, bChngRowid)==0 ){
  90962. continue;
  90963. }
  90964. if( !pFKey->isDeferred && !(db->flags & SQLITE_DeferFKs)
  90965. && !pParse->pToplevel && !pParse->isMultiWrite
  90966. ){
  90967. assert( regOld==0 && regNew!=0 );
  90968. /* Inserting a single row into a parent table cannot cause an immediate
  90969. ** foreign key violation. So do nothing in this case. */
  90970. continue;
  90971. }
  90972. if( sqlite3FkLocateIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ){
  90973. if( !isIgnoreErrors || db->mallocFailed ) return;
  90974. continue;
  90975. }
  90976. assert( aiCol || pFKey->nCol==1 );
  90977. /* Create a SrcList structure containing the child table. We need the
  90978. ** child table as a SrcList for sqlite3WhereBegin() */
  90979. pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
  90980. if( pSrc ){
  90981. struct SrcList_item *pItem = pSrc->a;
  90982. pItem->pTab = pFKey->pFrom;
  90983. pItem->zName = pFKey->pFrom->zName;
  90984. pItem->pTab->nRef++;
  90985. pItem->iCursor = pParse->nTab++;
  90986. if( regNew!=0 ){
  90987. fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regNew, -1);
  90988. }
  90989. if( regOld!=0 ){
  90990. /* If there is a RESTRICT action configured for the current operation
  90991. ** on the parent table of this FK, then throw an exception
  90992. ** immediately if the FK constraint is violated, even if this is a
  90993. ** deferred trigger. That's what RESTRICT means. To defer checking
  90994. ** the constraint, the FK should specify NO ACTION (represented
  90995. ** using OE_None). NO ACTION is the default. */
  90996. fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regOld, 1);
  90997. }
  90998. pItem->zName = 0;
  90999. sqlite3SrcListDelete(db, pSrc);
  91000. }
  91001. sqlite3DbFree(db, aiCol);
  91002. }
  91003. }
  91004. #define COLUMN_MASK(x) (((x)>31) ? 0xffffffff : ((u32)1<<(x)))
  91005. /*
  91006. ** This function is called before generating code to update or delete a
  91007. ** row contained in table pTab.
  91008. */
  91009. SQLITE_PRIVATE u32 sqlite3FkOldmask(
  91010. Parse *pParse, /* Parse context */
  91011. Table *pTab /* Table being modified */
  91012. ){
  91013. u32 mask = 0;
  91014. if( pParse->db->flags&SQLITE_ForeignKeys ){
  91015. FKey *p;
  91016. int i;
  91017. for(p=pTab->pFKey; p; p=p->pNextFrom){
  91018. for(i=0; i<p->nCol; i++) mask |= COLUMN_MASK(p->aCol[i].iFrom);
  91019. }
  91020. for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
  91021. Index *pIdx = 0;
  91022. sqlite3FkLocateIndex(pParse, pTab, p, &pIdx, 0);
  91023. if( pIdx ){
  91024. for(i=0; i<pIdx->nKeyCol; i++) mask |= COLUMN_MASK(pIdx->aiColumn[i]);
  91025. }
  91026. }
  91027. }
  91028. return mask;
  91029. }
  91030. /*
  91031. ** This function is called before generating code to update or delete a
  91032. ** row contained in table pTab. If the operation is a DELETE, then
  91033. ** parameter aChange is passed a NULL value. For an UPDATE, aChange points
  91034. ** to an array of size N, where N is the number of columns in table pTab.
  91035. ** If the i'th column is not modified by the UPDATE, then the corresponding
  91036. ** entry in the aChange[] array is set to -1. If the column is modified,
  91037. ** the value is 0 or greater. Parameter chngRowid is set to true if the
  91038. ** UPDATE statement modifies the rowid fields of the table.
  91039. **
  91040. ** If any foreign key processing will be required, this function returns
  91041. ** true. If there is no foreign key related processing, this function
  91042. ** returns false.
  91043. */
  91044. SQLITE_PRIVATE int sqlite3FkRequired(
  91045. Parse *pParse, /* Parse context */
  91046. Table *pTab, /* Table being modified */
  91047. int *aChange, /* Non-NULL for UPDATE operations */
  91048. int chngRowid /* True for UPDATE that affects rowid */
  91049. ){
  91050. if( pParse->db->flags&SQLITE_ForeignKeys ){
  91051. if( !aChange ){
  91052. /* A DELETE operation. Foreign key processing is required if the
  91053. ** table in question is either the child or parent table for any
  91054. ** foreign key constraint. */
  91055. return (sqlite3FkReferences(pTab) || pTab->pFKey);
  91056. }else{
  91057. /* This is an UPDATE. Foreign key processing is only required if the
  91058. ** operation modifies one or more child or parent key columns. */
  91059. FKey *p;
  91060. /* Check if any child key columns are being modified. */
  91061. for(p=pTab->pFKey; p; p=p->pNextFrom){
  91062. if( fkChildIsModified(pTab, p, aChange, chngRowid) ) return 1;
  91063. }
  91064. /* Check if any parent key columns are being modified. */
  91065. for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
  91066. if( fkParentIsModified(pTab, p, aChange, chngRowid) ) return 1;
  91067. }
  91068. }
  91069. }
  91070. return 0;
  91071. }
  91072. /*
  91073. ** This function is called when an UPDATE or DELETE operation is being
  91074. ** compiled on table pTab, which is the parent table of foreign-key pFKey.
  91075. ** If the current operation is an UPDATE, then the pChanges parameter is
  91076. ** passed a pointer to the list of columns being modified. If it is a
  91077. ** DELETE, pChanges is passed a NULL pointer.
  91078. **
  91079. ** It returns a pointer to a Trigger structure containing a trigger
  91080. ** equivalent to the ON UPDATE or ON DELETE action specified by pFKey.
  91081. ** If the action is "NO ACTION" or "RESTRICT", then a NULL pointer is
  91082. ** returned (these actions require no special handling by the triggers
  91083. ** sub-system, code for them is created by fkScanChildren()).
  91084. **
  91085. ** For example, if pFKey is the foreign key and pTab is table "p" in
  91086. ** the following schema:
  91087. **
  91088. ** CREATE TABLE p(pk PRIMARY KEY);
  91089. ** CREATE TABLE c(ck REFERENCES p ON DELETE CASCADE);
  91090. **
  91091. ** then the returned trigger structure is equivalent to:
  91092. **
  91093. ** CREATE TRIGGER ... DELETE ON p BEGIN
  91094. ** DELETE FROM c WHERE ck = old.pk;
  91095. ** END;
  91096. **
  91097. ** The returned pointer is cached as part of the foreign key object. It
  91098. ** is eventually freed along with the rest of the foreign key object by
  91099. ** sqlite3FkDelete().
  91100. */
  91101. static Trigger *fkActionTrigger(
  91102. Parse *pParse, /* Parse context */
  91103. Table *pTab, /* Table being updated or deleted from */
  91104. FKey *pFKey, /* Foreign key to get action for */
  91105. ExprList *pChanges /* Change-list for UPDATE, NULL for DELETE */
  91106. ){
  91107. sqlite3 *db = pParse->db; /* Database handle */
  91108. int action; /* One of OE_None, OE_Cascade etc. */
  91109. Trigger *pTrigger; /* Trigger definition to return */
  91110. int iAction = (pChanges!=0); /* 1 for UPDATE, 0 for DELETE */
  91111. action = pFKey->aAction[iAction];
  91112. pTrigger = pFKey->apTrigger[iAction];
  91113. if( action!=OE_None && !pTrigger ){
  91114. u8 enableLookaside; /* Copy of db->lookaside.bEnabled */
  91115. char const *zFrom; /* Name of child table */
  91116. int nFrom; /* Length in bytes of zFrom */
  91117. Index *pIdx = 0; /* Parent key index for this FK */
  91118. int *aiCol = 0; /* child table cols -> parent key cols */
  91119. TriggerStep *pStep = 0; /* First (only) step of trigger program */
  91120. Expr *pWhere = 0; /* WHERE clause of trigger step */
  91121. ExprList *pList = 0; /* Changes list if ON UPDATE CASCADE */
  91122. Select *pSelect = 0; /* If RESTRICT, "SELECT RAISE(...)" */
  91123. int i; /* Iterator variable */
  91124. Expr *pWhen = 0; /* WHEN clause for the trigger */
  91125. if( sqlite3FkLocateIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ) return 0;
  91126. assert( aiCol || pFKey->nCol==1 );
  91127. for(i=0; i<pFKey->nCol; i++){
  91128. Token tOld = { "old", 3 }; /* Literal "old" token */
  91129. Token tNew = { "new", 3 }; /* Literal "new" token */
  91130. Token tFromCol; /* Name of column in child table */
  91131. Token tToCol; /* Name of column in parent table */
  91132. int iFromCol; /* Idx of column in child table */
  91133. Expr *pEq; /* tFromCol = OLD.tToCol */
  91134. iFromCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
  91135. assert( iFromCol>=0 );
  91136. tToCol.z = pIdx ? pTab->aCol[pIdx->aiColumn[i]].zName : "oid";
  91137. tFromCol.z = pFKey->pFrom->aCol[iFromCol].zName;
  91138. tToCol.n = sqlite3Strlen30(tToCol.z);
  91139. tFromCol.n = sqlite3Strlen30(tFromCol.z);
  91140. /* Create the expression "OLD.zToCol = zFromCol". It is important
  91141. ** that the "OLD.zToCol" term is on the LHS of the = operator, so
  91142. ** that the affinity and collation sequence associated with the
  91143. ** parent table are used for the comparison. */
  91144. pEq = sqlite3PExpr(pParse, TK_EQ,
  91145. sqlite3PExpr(pParse, TK_DOT,
  91146. sqlite3PExpr(pParse, TK_ID, 0, 0, &tOld),
  91147. sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol)
  91148. , 0),
  91149. sqlite3PExpr(pParse, TK_ID, 0, 0, &tFromCol)
  91150. , 0);
  91151. pWhere = sqlite3ExprAnd(db, pWhere, pEq);
  91152. /* For ON UPDATE, construct the next term of the WHEN clause.
  91153. ** The final WHEN clause will be like this:
  91154. **
  91155. ** WHEN NOT(old.col1 IS new.col1 AND ... AND old.colN IS new.colN)
  91156. */
  91157. if( pChanges ){
  91158. pEq = sqlite3PExpr(pParse, TK_IS,
  91159. sqlite3PExpr(pParse, TK_DOT,
  91160. sqlite3PExpr(pParse, TK_ID, 0, 0, &tOld),
  91161. sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol),
  91162. 0),
  91163. sqlite3PExpr(pParse, TK_DOT,
  91164. sqlite3PExpr(pParse, TK_ID, 0, 0, &tNew),
  91165. sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol),
  91166. 0),
  91167. 0);
  91168. pWhen = sqlite3ExprAnd(db, pWhen, pEq);
  91169. }
  91170. if( action!=OE_Restrict && (action!=OE_Cascade || pChanges) ){
  91171. Expr *pNew;
  91172. if( action==OE_Cascade ){
  91173. pNew = sqlite3PExpr(pParse, TK_DOT,
  91174. sqlite3PExpr(pParse, TK_ID, 0, 0, &tNew),
  91175. sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol)
  91176. , 0);
  91177. }else if( action==OE_SetDflt ){
  91178. Expr *pDflt = pFKey->pFrom->aCol[iFromCol].pDflt;
  91179. if( pDflt ){
  91180. pNew = sqlite3ExprDup(db, pDflt, 0);
  91181. }else{
  91182. pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
  91183. }
  91184. }else{
  91185. pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
  91186. }
  91187. pList = sqlite3ExprListAppend(pParse, pList, pNew);
  91188. sqlite3ExprListSetName(pParse, pList, &tFromCol, 0);
  91189. }
  91190. }
  91191. sqlite3DbFree(db, aiCol);
  91192. zFrom = pFKey->pFrom->zName;
  91193. nFrom = sqlite3Strlen30(zFrom);
  91194. if( action==OE_Restrict ){
  91195. Token tFrom;
  91196. Expr *pRaise;
  91197. tFrom.z = zFrom;
  91198. tFrom.n = nFrom;
  91199. pRaise = sqlite3Expr(db, TK_RAISE, "FOREIGN KEY constraint failed");
  91200. if( pRaise ){
  91201. pRaise->affinity = OE_Abort;
  91202. }
  91203. pSelect = sqlite3SelectNew(pParse,
  91204. sqlite3ExprListAppend(pParse, 0, pRaise),
  91205. sqlite3SrcListAppend(db, 0, &tFrom, 0),
  91206. pWhere,
  91207. 0, 0, 0, 0, 0, 0
  91208. );
  91209. pWhere = 0;
  91210. }
  91211. /* Disable lookaside memory allocation */
  91212. enableLookaside = db->lookaside.bEnabled;
  91213. db->lookaside.bEnabled = 0;
  91214. pTrigger = (Trigger *)sqlite3DbMallocZero(db,
  91215. sizeof(Trigger) + /* struct Trigger */
  91216. sizeof(TriggerStep) + /* Single step in trigger program */
  91217. nFrom + 1 /* Space for pStep->target.z */
  91218. );
  91219. if( pTrigger ){
  91220. pStep = pTrigger->step_list = (TriggerStep *)&pTrigger[1];
  91221. pStep->target.z = (char *)&pStep[1];
  91222. pStep->target.n = nFrom;
  91223. memcpy((char *)pStep->target.z, zFrom, nFrom);
  91224. pStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
  91225. pStep->pExprList = sqlite3ExprListDup(db, pList, EXPRDUP_REDUCE);
  91226. pStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
  91227. if( pWhen ){
  91228. pWhen = sqlite3PExpr(pParse, TK_NOT, pWhen, 0, 0);
  91229. pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
  91230. }
  91231. }
  91232. /* Re-enable the lookaside buffer, if it was disabled earlier. */
  91233. db->lookaside.bEnabled = enableLookaside;
  91234. sqlite3ExprDelete(db, pWhere);
  91235. sqlite3ExprDelete(db, pWhen);
  91236. sqlite3ExprListDelete(db, pList);
  91237. sqlite3SelectDelete(db, pSelect);
  91238. if( db->mallocFailed==1 ){
  91239. fkTriggerDelete(db, pTrigger);
  91240. return 0;
  91241. }
  91242. assert( pStep!=0 );
  91243. switch( action ){
  91244. case OE_Restrict:
  91245. pStep->op = TK_SELECT;
  91246. break;
  91247. case OE_Cascade:
  91248. if( !pChanges ){
  91249. pStep->op = TK_DELETE;
  91250. break;
  91251. }
  91252. default:
  91253. pStep->op = TK_UPDATE;
  91254. }
  91255. pStep->pTrig = pTrigger;
  91256. pTrigger->pSchema = pTab->pSchema;
  91257. pTrigger->pTabSchema = pTab->pSchema;
  91258. pFKey->apTrigger[iAction] = pTrigger;
  91259. pTrigger->op = (pChanges ? TK_UPDATE : TK_DELETE);
  91260. }
  91261. return pTrigger;
  91262. }
  91263. /*
  91264. ** This function is called when deleting or updating a row to implement
  91265. ** any required CASCADE, SET NULL or SET DEFAULT actions.
  91266. */
  91267. SQLITE_PRIVATE void sqlite3FkActions(
  91268. Parse *pParse, /* Parse context */
  91269. Table *pTab, /* Table being updated or deleted from */
  91270. ExprList *pChanges, /* Change-list for UPDATE, NULL for DELETE */
  91271. int regOld, /* Address of array containing old row */
  91272. int *aChange, /* Array indicating UPDATEd columns (or 0) */
  91273. int bChngRowid /* True if rowid is UPDATEd */
  91274. ){
  91275. /* If foreign-key support is enabled, iterate through all FKs that
  91276. ** refer to table pTab. If there is an action associated with the FK
  91277. ** for this operation (either update or delete), invoke the associated
  91278. ** trigger sub-program. */
  91279. if( pParse->db->flags&SQLITE_ForeignKeys ){
  91280. FKey *pFKey; /* Iterator variable */
  91281. for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
  91282. if( aChange==0 || fkParentIsModified(pTab, pFKey, aChange, bChngRowid) ){
  91283. Trigger *pAct = fkActionTrigger(pParse, pTab, pFKey, pChanges);
  91284. if( pAct ){
  91285. sqlite3CodeRowTriggerDirect(pParse, pAct, pTab, regOld, OE_Abort, 0);
  91286. }
  91287. }
  91288. }
  91289. }
  91290. }
  91291. #endif /* ifndef SQLITE_OMIT_TRIGGER */
  91292. /*
  91293. ** Free all memory associated with foreign key definitions attached to
  91294. ** table pTab. Remove the deleted foreign keys from the Schema.fkeyHash
  91295. ** hash table.
  91296. */
  91297. SQLITE_PRIVATE void sqlite3FkDelete(sqlite3 *db, Table *pTab){
  91298. FKey *pFKey; /* Iterator variable */
  91299. FKey *pNext; /* Copy of pFKey->pNextFrom */
  91300. assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pTab->pSchema) );
  91301. for(pFKey=pTab->pFKey; pFKey; pFKey=pNext){
  91302. /* Remove the FK from the fkeyHash hash table. */
  91303. if( !db || db->pnBytesFreed==0 ){
  91304. if( pFKey->pPrevTo ){
  91305. pFKey->pPrevTo->pNextTo = pFKey->pNextTo;
  91306. }else{
  91307. void *p = (void *)pFKey->pNextTo;
  91308. const char *z = (p ? pFKey->pNextTo->zTo : pFKey->zTo);
  91309. sqlite3HashInsert(&pTab->pSchema->fkeyHash, z, p);
  91310. }
  91311. if( pFKey->pNextTo ){
  91312. pFKey->pNextTo->pPrevTo = pFKey->pPrevTo;
  91313. }
  91314. }
  91315. /* EV: R-30323-21917 Each foreign key constraint in SQLite is
  91316. ** classified as either immediate or deferred.
  91317. */
  91318. assert( pFKey->isDeferred==0 || pFKey->isDeferred==1 );
  91319. /* Delete any triggers created to implement actions for this FK. */
  91320. #ifndef SQLITE_OMIT_TRIGGER
  91321. fkTriggerDelete(db, pFKey->apTrigger[0]);
  91322. fkTriggerDelete(db, pFKey->apTrigger[1]);
  91323. #endif
  91324. pNext = pFKey->pNextFrom;
  91325. sqlite3DbFree(db, pFKey);
  91326. }
  91327. }
  91328. #endif /* ifndef SQLITE_OMIT_FOREIGN_KEY */
  91329. /************** End of fkey.c ************************************************/
  91330. /************** Begin file insert.c ******************************************/
  91331. /*
  91332. ** 2001 September 15
  91333. **
  91334. ** The author disclaims copyright to this source code. In place of
  91335. ** a legal notice, here is a blessing:
  91336. **
  91337. ** May you do good and not evil.
  91338. ** May you find forgiveness for yourself and forgive others.
  91339. ** May you share freely, never taking more than you give.
  91340. **
  91341. *************************************************************************
  91342. ** This file contains C code routines that are called by the parser
  91343. ** to handle INSERT statements in SQLite.
  91344. */
  91345. /*
  91346. ** Generate code that will
  91347. **
  91348. ** (1) acquire a lock for table pTab then
  91349. ** (2) open pTab as cursor iCur.
  91350. **
  91351. ** If pTab is a WITHOUT ROWID table, then it is the PRIMARY KEY index
  91352. ** for that table that is actually opened.
  91353. */
  91354. SQLITE_PRIVATE void sqlite3OpenTable(
  91355. Parse *pParse, /* Generate code into this VDBE */
  91356. int iCur, /* The cursor number of the table */
  91357. int iDb, /* The database index in sqlite3.aDb[] */
  91358. Table *pTab, /* The table to be opened */
  91359. int opcode /* OP_OpenRead or OP_OpenWrite */
  91360. ){
  91361. Vdbe *v;
  91362. assert( !IsVirtual(pTab) );
  91363. v = sqlite3GetVdbe(pParse);
  91364. assert( opcode==OP_OpenWrite || opcode==OP_OpenRead );
  91365. sqlite3TableLock(pParse, iDb, pTab->tnum,
  91366. (opcode==OP_OpenWrite)?1:0, pTab->zName);
  91367. if( HasRowid(pTab) ){
  91368. sqlite3VdbeAddOp4Int(v, opcode, iCur, pTab->tnum, iDb, pTab->nCol);
  91369. VdbeComment((v, "%s", pTab->zName));
  91370. }else{
  91371. Index *pPk = sqlite3PrimaryKeyIndex(pTab);
  91372. assert( pPk!=0 );
  91373. assert( pPk->tnum=pTab->tnum );
  91374. sqlite3VdbeAddOp3(v, opcode, iCur, pPk->tnum, iDb);
  91375. sqlite3VdbeSetP4KeyInfo(pParse, pPk);
  91376. VdbeComment((v, "%s", pTab->zName));
  91377. }
  91378. }
  91379. /*
  91380. ** Return a pointer to the column affinity string associated with index
  91381. ** pIdx. A column affinity string has one character for each column in
  91382. ** the table, according to the affinity of the column:
  91383. **
  91384. ** Character Column affinity
  91385. ** ------------------------------
  91386. ** 'A' NONE
  91387. ** 'B' TEXT
  91388. ** 'C' NUMERIC
  91389. ** 'D' INTEGER
  91390. ** 'F' REAL
  91391. **
  91392. ** An extra 'D' is appended to the end of the string to cover the
  91393. ** rowid that appears as the last column in every index.
  91394. **
  91395. ** Memory for the buffer containing the column index affinity string
  91396. ** is managed along with the rest of the Index structure. It will be
  91397. ** released when sqlite3DeleteIndex() is called.
  91398. */
  91399. SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(Vdbe *v, Index *pIdx){
  91400. if( !pIdx->zColAff ){
  91401. /* The first time a column affinity string for a particular index is
  91402. ** required, it is allocated and populated here. It is then stored as
  91403. ** a member of the Index structure for subsequent use.
  91404. **
  91405. ** The column affinity string will eventually be deleted by
  91406. ** sqliteDeleteIndex() when the Index structure itself is cleaned
  91407. ** up.
  91408. */
  91409. int n;
  91410. Table *pTab = pIdx->pTable;
  91411. sqlite3 *db = sqlite3VdbeDb(v);
  91412. pIdx->zColAff = (char *)sqlite3DbMallocRaw(0, pIdx->nColumn+1);
  91413. if( !pIdx->zColAff ){
  91414. db->mallocFailed = 1;
  91415. return 0;
  91416. }
  91417. for(n=0; n<pIdx->nColumn; n++){
  91418. i16 x = pIdx->aiColumn[n];
  91419. pIdx->zColAff[n] = x<0 ? SQLITE_AFF_INTEGER : pTab->aCol[x].affinity;
  91420. }
  91421. pIdx->zColAff[n] = 0;
  91422. }
  91423. return pIdx->zColAff;
  91424. }
  91425. /*
  91426. ** Compute the affinity string for table pTab, if it has not already been
  91427. ** computed. As an optimization, omit trailing SQLITE_AFF_NONE affinities.
  91428. **
  91429. ** If the affinity exists (if it is no entirely SQLITE_AFF_NONE values) and
  91430. ** if iReg>0 then code an OP_Affinity opcode that will set the affinities
  91431. ** for register iReg and following. Or if affinities exists and iReg==0,
  91432. ** then just set the P4 operand of the previous opcode (which should be
  91433. ** an OP_MakeRecord) to the affinity string.
  91434. **
  91435. ** A column affinity string has one character per column:
  91436. **
  91437. ** Character Column affinity
  91438. ** ------------------------------
  91439. ** 'A' NONE
  91440. ** 'B' TEXT
  91441. ** 'C' NUMERIC
  91442. ** 'D' INTEGER
  91443. ** 'E' REAL
  91444. */
  91445. SQLITE_PRIVATE void sqlite3TableAffinity(Vdbe *v, Table *pTab, int iReg){
  91446. int i;
  91447. char *zColAff = pTab->zColAff;
  91448. if( zColAff==0 ){
  91449. sqlite3 *db = sqlite3VdbeDb(v);
  91450. zColAff = (char *)sqlite3DbMallocRaw(0, pTab->nCol+1);
  91451. if( !zColAff ){
  91452. db->mallocFailed = 1;
  91453. return;
  91454. }
  91455. for(i=0; i<pTab->nCol; i++){
  91456. zColAff[i] = pTab->aCol[i].affinity;
  91457. }
  91458. do{
  91459. zColAff[i--] = 0;
  91460. }while( i>=0 && zColAff[i]==SQLITE_AFF_NONE );
  91461. pTab->zColAff = zColAff;
  91462. }
  91463. i = sqlite3Strlen30(zColAff);
  91464. if( i ){
  91465. if( iReg ){
  91466. sqlite3VdbeAddOp4(v, OP_Affinity, iReg, i, 0, zColAff, i);
  91467. }else{
  91468. sqlite3VdbeChangeP4(v, -1, zColAff, i);
  91469. }
  91470. }
  91471. }
  91472. /*
  91473. ** Return non-zero if the table pTab in database iDb or any of its indices
  91474. ** have been opened at any point in the VDBE program. This is used to see if
  91475. ** a statement of the form "INSERT INTO <iDb, pTab> SELECT ..." can
  91476. ** run without using a temporary table for the results of the SELECT.
  91477. */
  91478. static int readsTable(Parse *p, int iDb, Table *pTab){
  91479. Vdbe *v = sqlite3GetVdbe(p);
  91480. int i;
  91481. int iEnd = sqlite3VdbeCurrentAddr(v);
  91482. #ifndef SQLITE_OMIT_VIRTUALTABLE
  91483. VTable *pVTab = IsVirtual(pTab) ? sqlite3GetVTable(p->db, pTab) : 0;
  91484. #endif
  91485. for(i=1; i<iEnd; i++){
  91486. VdbeOp *pOp = sqlite3VdbeGetOp(v, i);
  91487. assert( pOp!=0 );
  91488. if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){
  91489. Index *pIndex;
  91490. int tnum = pOp->p2;
  91491. if( tnum==pTab->tnum ){
  91492. return 1;
  91493. }
  91494. for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
  91495. if( tnum==pIndex->tnum ){
  91496. return 1;
  91497. }
  91498. }
  91499. }
  91500. #ifndef SQLITE_OMIT_VIRTUALTABLE
  91501. if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pVTab ){
  91502. assert( pOp->p4.pVtab!=0 );
  91503. assert( pOp->p4type==P4_VTAB );
  91504. return 1;
  91505. }
  91506. #endif
  91507. }
  91508. return 0;
  91509. }
  91510. #ifndef SQLITE_OMIT_AUTOINCREMENT
  91511. /*
  91512. ** Locate or create an AutoincInfo structure associated with table pTab
  91513. ** which is in database iDb. Return the register number for the register
  91514. ** that holds the maximum rowid.
  91515. **
  91516. ** There is at most one AutoincInfo structure per table even if the
  91517. ** same table is autoincremented multiple times due to inserts within
  91518. ** triggers. A new AutoincInfo structure is created if this is the
  91519. ** first use of table pTab. On 2nd and subsequent uses, the original
  91520. ** AutoincInfo structure is used.
  91521. **
  91522. ** Three memory locations are allocated:
  91523. **
  91524. ** (1) Register to hold the name of the pTab table.
  91525. ** (2) Register to hold the maximum ROWID of pTab.
  91526. ** (3) Register to hold the rowid in sqlite_sequence of pTab
  91527. **
  91528. ** The 2nd register is the one that is returned. That is all the
  91529. ** insert routine needs to know about.
  91530. */
  91531. static int autoIncBegin(
  91532. Parse *pParse, /* Parsing context */
  91533. int iDb, /* Index of the database holding pTab */
  91534. Table *pTab /* The table we are writing to */
  91535. ){
  91536. int memId = 0; /* Register holding maximum rowid */
  91537. if( pTab->tabFlags & TF_Autoincrement ){
  91538. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  91539. AutoincInfo *pInfo;
  91540. pInfo = pToplevel->pAinc;
  91541. while( pInfo && pInfo->pTab!=pTab ){ pInfo = pInfo->pNext; }
  91542. if( pInfo==0 ){
  91543. pInfo = sqlite3DbMallocRaw(pParse->db, sizeof(*pInfo));
  91544. if( pInfo==0 ) return 0;
  91545. pInfo->pNext = pToplevel->pAinc;
  91546. pToplevel->pAinc = pInfo;
  91547. pInfo->pTab = pTab;
  91548. pInfo->iDb = iDb;
  91549. pToplevel->nMem++; /* Register to hold name of table */
  91550. pInfo->regCtr = ++pToplevel->nMem; /* Max rowid register */
  91551. pToplevel->nMem++; /* Rowid in sqlite_sequence */
  91552. }
  91553. memId = pInfo->regCtr;
  91554. }
  91555. return memId;
  91556. }
  91557. /*
  91558. ** This routine generates code that will initialize all of the
  91559. ** register used by the autoincrement tracker.
  91560. */
  91561. SQLITE_PRIVATE void sqlite3AutoincrementBegin(Parse *pParse){
  91562. AutoincInfo *p; /* Information about an AUTOINCREMENT */
  91563. sqlite3 *db = pParse->db; /* The database connection */
  91564. Db *pDb; /* Database only autoinc table */
  91565. int memId; /* Register holding max rowid */
  91566. int addr; /* A VDBE address */
  91567. Vdbe *v = pParse->pVdbe; /* VDBE under construction */
  91568. /* This routine is never called during trigger-generation. It is
  91569. ** only called from the top-level */
  91570. assert( pParse->pTriggerTab==0 );
  91571. assert( pParse==sqlite3ParseToplevel(pParse) );
  91572. assert( v ); /* We failed long ago if this is not so */
  91573. for(p = pParse->pAinc; p; p = p->pNext){
  91574. pDb = &db->aDb[p->iDb];
  91575. memId = p->regCtr;
  91576. assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
  91577. sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
  91578. sqlite3VdbeAddOp3(v, OP_Null, 0, memId, memId+1);
  91579. addr = sqlite3VdbeCurrentAddr(v);
  91580. sqlite3VdbeAddOp4(v, OP_String8, 0, memId-1, 0, p->pTab->zName, 0);
  91581. sqlite3VdbeAddOp2(v, OP_Rewind, 0, addr+9); VdbeCoverage(v);
  91582. sqlite3VdbeAddOp3(v, OP_Column, 0, 0, memId);
  91583. sqlite3VdbeAddOp3(v, OP_Ne, memId-1, addr+7, memId); VdbeCoverage(v);
  91584. sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
  91585. sqlite3VdbeAddOp2(v, OP_Rowid, 0, memId+1);
  91586. sqlite3VdbeAddOp3(v, OP_Column, 0, 1, memId);
  91587. sqlite3VdbeAddOp2(v, OP_Goto, 0, addr+9);
  91588. sqlite3VdbeAddOp2(v, OP_Next, 0, addr+2); VdbeCoverage(v);
  91589. sqlite3VdbeAddOp2(v, OP_Integer, 0, memId);
  91590. sqlite3VdbeAddOp0(v, OP_Close);
  91591. }
  91592. }
  91593. /*
  91594. ** Update the maximum rowid for an autoincrement calculation.
  91595. **
  91596. ** This routine should be called when the top of the stack holds a
  91597. ** new rowid that is about to be inserted. If that new rowid is
  91598. ** larger than the maximum rowid in the memId memory cell, then the
  91599. ** memory cell is updated. The stack is unchanged.
  91600. */
  91601. static void autoIncStep(Parse *pParse, int memId, int regRowid){
  91602. if( memId>0 ){
  91603. sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid);
  91604. }
  91605. }
  91606. /*
  91607. ** This routine generates the code needed to write autoincrement
  91608. ** maximum rowid values back into the sqlite_sequence register.
  91609. ** Every statement that might do an INSERT into an autoincrement
  91610. ** table (either directly or through triggers) needs to call this
  91611. ** routine just before the "exit" code.
  91612. */
  91613. SQLITE_PRIVATE void sqlite3AutoincrementEnd(Parse *pParse){
  91614. AutoincInfo *p;
  91615. Vdbe *v = pParse->pVdbe;
  91616. sqlite3 *db = pParse->db;
  91617. assert( v );
  91618. for(p = pParse->pAinc; p; p = p->pNext){
  91619. Db *pDb = &db->aDb[p->iDb];
  91620. int j1;
  91621. int iRec;
  91622. int memId = p->regCtr;
  91623. iRec = sqlite3GetTempReg(pParse);
  91624. assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
  91625. sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
  91626. j1 = sqlite3VdbeAddOp1(v, OP_NotNull, memId+1); VdbeCoverage(v);
  91627. sqlite3VdbeAddOp2(v, OP_NewRowid, 0, memId+1);
  91628. sqlite3VdbeJumpHere(v, j1);
  91629. sqlite3VdbeAddOp3(v, OP_MakeRecord, memId-1, 2, iRec);
  91630. sqlite3VdbeAddOp3(v, OP_Insert, 0, iRec, memId+1);
  91631. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  91632. sqlite3VdbeAddOp0(v, OP_Close);
  91633. sqlite3ReleaseTempReg(pParse, iRec);
  91634. }
  91635. }
  91636. #else
  91637. /*
  91638. ** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
  91639. ** above are all no-ops
  91640. */
  91641. # define autoIncBegin(A,B,C) (0)
  91642. # define autoIncStep(A,B,C)
  91643. #endif /* SQLITE_OMIT_AUTOINCREMENT */
  91644. /* Forward declaration */
  91645. static int xferOptimization(
  91646. Parse *pParse, /* Parser context */
  91647. Table *pDest, /* The table we are inserting into */
  91648. Select *pSelect, /* A SELECT statement to use as the data source */
  91649. int onError, /* How to handle constraint errors */
  91650. int iDbDest /* The database of pDest */
  91651. );
  91652. /*
  91653. ** This routine is called to handle SQL of the following forms:
  91654. **
  91655. ** insert into TABLE (IDLIST) values(EXPRLIST)
  91656. ** insert into TABLE (IDLIST) select
  91657. **
  91658. ** The IDLIST following the table name is always optional. If omitted,
  91659. ** then a list of all columns for the table is substituted. The IDLIST
  91660. ** appears in the pColumn parameter. pColumn is NULL if IDLIST is omitted.
  91661. **
  91662. ** The pList parameter holds EXPRLIST in the first form of the INSERT
  91663. ** statement above, and pSelect is NULL. For the second form, pList is
  91664. ** NULL and pSelect is a pointer to the select statement used to generate
  91665. ** data for the insert.
  91666. **
  91667. ** The code generated follows one of four templates. For a simple
  91668. ** insert with data coming from a VALUES clause, the code executes
  91669. ** once straight down through. Pseudo-code follows (we call this
  91670. ** the "1st template"):
  91671. **
  91672. ** open write cursor to <table> and its indices
  91673. ** put VALUES clause expressions into registers
  91674. ** write the resulting record into <table>
  91675. ** cleanup
  91676. **
  91677. ** The three remaining templates assume the statement is of the form
  91678. **
  91679. ** INSERT INTO <table> SELECT ...
  91680. **
  91681. ** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
  91682. ** in other words if the SELECT pulls all columns from a single table
  91683. ** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
  91684. ** if <table2> and <table1> are distinct tables but have identical
  91685. ** schemas, including all the same indices, then a special optimization
  91686. ** is invoked that copies raw records from <table2> over to <table1>.
  91687. ** See the xferOptimization() function for the implementation of this
  91688. ** template. This is the 2nd template.
  91689. **
  91690. ** open a write cursor to <table>
  91691. ** open read cursor on <table2>
  91692. ** transfer all records in <table2> over to <table>
  91693. ** close cursors
  91694. ** foreach index on <table>
  91695. ** open a write cursor on the <table> index
  91696. ** open a read cursor on the corresponding <table2> index
  91697. ** transfer all records from the read to the write cursors
  91698. ** close cursors
  91699. ** end foreach
  91700. **
  91701. ** The 3rd template is for when the second template does not apply
  91702. ** and the SELECT clause does not read from <table> at any time.
  91703. ** The generated code follows this template:
  91704. **
  91705. ** X <- A
  91706. ** goto B
  91707. ** A: setup for the SELECT
  91708. ** loop over the rows in the SELECT
  91709. ** load values into registers R..R+n
  91710. ** yield X
  91711. ** end loop
  91712. ** cleanup after the SELECT
  91713. ** end-coroutine X
  91714. ** B: open write cursor to <table> and its indices
  91715. ** C: yield X, at EOF goto D
  91716. ** insert the select result into <table> from R..R+n
  91717. ** goto C
  91718. ** D: cleanup
  91719. **
  91720. ** The 4th template is used if the insert statement takes its
  91721. ** values from a SELECT but the data is being inserted into a table
  91722. ** that is also read as part of the SELECT. In the third form,
  91723. ** we have to use an intermediate table to store the results of
  91724. ** the select. The template is like this:
  91725. **
  91726. ** X <- A
  91727. ** goto B
  91728. ** A: setup for the SELECT
  91729. ** loop over the tables in the SELECT
  91730. ** load value into register R..R+n
  91731. ** yield X
  91732. ** end loop
  91733. ** cleanup after the SELECT
  91734. ** end co-routine R
  91735. ** B: open temp table
  91736. ** L: yield X, at EOF goto M
  91737. ** insert row from R..R+n into temp table
  91738. ** goto L
  91739. ** M: open write cursor to <table> and its indices
  91740. ** rewind temp table
  91741. ** C: loop over rows of intermediate table
  91742. ** transfer values form intermediate table into <table>
  91743. ** end loop
  91744. ** D: cleanup
  91745. */
  91746. SQLITE_PRIVATE void sqlite3Insert(
  91747. Parse *pParse, /* Parser context */
  91748. SrcList *pTabList, /* Name of table into which we are inserting */
  91749. Select *pSelect, /* A SELECT statement to use as the data source */
  91750. IdList *pColumn, /* Column names corresponding to IDLIST. */
  91751. int onError /* How to handle constraint errors */
  91752. ){
  91753. sqlite3 *db; /* The main database structure */
  91754. Table *pTab; /* The table to insert into. aka TABLE */
  91755. char *zTab; /* Name of the table into which we are inserting */
  91756. const char *zDb; /* Name of the database holding this table */
  91757. int i, j, idx; /* Loop counters */
  91758. Vdbe *v; /* Generate code into this virtual machine */
  91759. Index *pIdx; /* For looping over indices of the table */
  91760. int nColumn; /* Number of columns in the data */
  91761. int nHidden = 0; /* Number of hidden columns if TABLE is virtual */
  91762. int iDataCur = 0; /* VDBE cursor that is the main data repository */
  91763. int iIdxCur = 0; /* First index cursor */
  91764. int ipkColumn = -1; /* Column that is the INTEGER PRIMARY KEY */
  91765. int endOfLoop; /* Label for the end of the insertion loop */
  91766. int srcTab = 0; /* Data comes from this temporary cursor if >=0 */
  91767. int addrInsTop = 0; /* Jump to label "D" */
  91768. int addrCont = 0; /* Top of insert loop. Label "C" in templates 3 and 4 */
  91769. SelectDest dest; /* Destination for SELECT on rhs of INSERT */
  91770. int iDb; /* Index of database holding TABLE */
  91771. Db *pDb; /* The database containing table being inserted into */
  91772. u8 useTempTable = 0; /* Store SELECT results in intermediate table */
  91773. u8 appendFlag = 0; /* True if the insert is likely to be an append */
  91774. u8 withoutRowid; /* 0 for normal table. 1 for WITHOUT ROWID table */
  91775. u8 bIdListInOrder = 1; /* True if IDLIST is in table order */
  91776. ExprList *pList = 0; /* List of VALUES() to be inserted */
  91777. /* Register allocations */
  91778. int regFromSelect = 0;/* Base register for data coming from SELECT */
  91779. int regAutoinc = 0; /* Register holding the AUTOINCREMENT counter */
  91780. int regRowCount = 0; /* Memory cell used for the row counter */
  91781. int regIns; /* Block of regs holding rowid+data being inserted */
  91782. int regRowid; /* registers holding insert rowid */
  91783. int regData; /* register holding first column to insert */
  91784. int *aRegIdx = 0; /* One register allocated to each index */
  91785. #ifndef SQLITE_OMIT_TRIGGER
  91786. int isView; /* True if attempting to insert into a view */
  91787. Trigger *pTrigger; /* List of triggers on pTab, if required */
  91788. int tmask; /* Mask of trigger times */
  91789. #endif
  91790. db = pParse->db;
  91791. memset(&dest, 0, sizeof(dest));
  91792. if( pParse->nErr || db->mallocFailed ){
  91793. goto insert_cleanup;
  91794. }
  91795. /* If the Select object is really just a simple VALUES() list with a
  91796. ** single row values (the common case) then keep that one row of values
  91797. ** and go ahead and discard the Select object
  91798. */
  91799. if( pSelect && (pSelect->selFlags & SF_Values)!=0 && pSelect->pPrior==0 ){
  91800. pList = pSelect->pEList;
  91801. pSelect->pEList = 0;
  91802. sqlite3SelectDelete(db, pSelect);
  91803. pSelect = 0;
  91804. }
  91805. /* Locate the table into which we will be inserting new information.
  91806. */
  91807. assert( pTabList->nSrc==1 );
  91808. zTab = pTabList->a[0].zName;
  91809. if( NEVER(zTab==0) ) goto insert_cleanup;
  91810. pTab = sqlite3SrcListLookup(pParse, pTabList);
  91811. if( pTab==0 ){
  91812. goto insert_cleanup;
  91813. }
  91814. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  91815. assert( iDb<db->nDb );
  91816. pDb = &db->aDb[iDb];
  91817. zDb = pDb->zName;
  91818. if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, zDb) ){
  91819. goto insert_cleanup;
  91820. }
  91821. withoutRowid = !HasRowid(pTab);
  91822. /* Figure out if we have any triggers and if the table being
  91823. ** inserted into is a view
  91824. */
  91825. #ifndef SQLITE_OMIT_TRIGGER
  91826. pTrigger = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0, &tmask);
  91827. isView = pTab->pSelect!=0;
  91828. #else
  91829. # define pTrigger 0
  91830. # define tmask 0
  91831. # define isView 0
  91832. #endif
  91833. #ifdef SQLITE_OMIT_VIEW
  91834. # undef isView
  91835. # define isView 0
  91836. #endif
  91837. assert( (pTrigger && tmask) || (pTrigger==0 && tmask==0) );
  91838. /* If pTab is really a view, make sure it has been initialized.
  91839. ** ViewGetColumnNames() is a no-op if pTab is not a view.
  91840. */
  91841. if( sqlite3ViewGetColumnNames(pParse, pTab) ){
  91842. goto insert_cleanup;
  91843. }
  91844. /* Cannot insert into a read-only table.
  91845. */
  91846. if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
  91847. goto insert_cleanup;
  91848. }
  91849. /* Allocate a VDBE
  91850. */
  91851. v = sqlite3GetVdbe(pParse);
  91852. if( v==0 ) goto insert_cleanup;
  91853. if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
  91854. sqlite3BeginWriteOperation(pParse, pSelect || pTrigger, iDb);
  91855. #ifndef SQLITE_OMIT_XFER_OPT
  91856. /* If the statement is of the form
  91857. **
  91858. ** INSERT INTO <table1> SELECT * FROM <table2>;
  91859. **
  91860. ** Then special optimizations can be applied that make the transfer
  91861. ** very fast and which reduce fragmentation of indices.
  91862. **
  91863. ** This is the 2nd template.
  91864. */
  91865. if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){
  91866. assert( !pTrigger );
  91867. assert( pList==0 );
  91868. goto insert_end;
  91869. }
  91870. #endif /* SQLITE_OMIT_XFER_OPT */
  91871. /* If this is an AUTOINCREMENT table, look up the sequence number in the
  91872. ** sqlite_sequence table and store it in memory cell regAutoinc.
  91873. */
  91874. regAutoinc = autoIncBegin(pParse, iDb, pTab);
  91875. /* Allocate registers for holding the rowid of the new row,
  91876. ** the content of the new row, and the assembled row record.
  91877. */
  91878. regRowid = regIns = pParse->nMem+1;
  91879. pParse->nMem += pTab->nCol + 1;
  91880. if( IsVirtual(pTab) ){
  91881. regRowid++;
  91882. pParse->nMem++;
  91883. }
  91884. regData = regRowid+1;
  91885. /* If the INSERT statement included an IDLIST term, then make sure
  91886. ** all elements of the IDLIST really are columns of the table and
  91887. ** remember the column indices.
  91888. **
  91889. ** If the table has an INTEGER PRIMARY KEY column and that column
  91890. ** is named in the IDLIST, then record in the ipkColumn variable
  91891. ** the index into IDLIST of the primary key column. ipkColumn is
  91892. ** the index of the primary key as it appears in IDLIST, not as
  91893. ** is appears in the original table. (The index of the INTEGER
  91894. ** PRIMARY KEY in the original table is pTab->iPKey.)
  91895. */
  91896. if( pColumn ){
  91897. for(i=0; i<pColumn->nId; i++){
  91898. pColumn->a[i].idx = -1;
  91899. }
  91900. for(i=0; i<pColumn->nId; i++){
  91901. for(j=0; j<pTab->nCol; j++){
  91902. if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
  91903. pColumn->a[i].idx = j;
  91904. if( i!=j ) bIdListInOrder = 0;
  91905. if( j==pTab->iPKey ){
  91906. ipkColumn = i; assert( !withoutRowid );
  91907. }
  91908. break;
  91909. }
  91910. }
  91911. if( j>=pTab->nCol ){
  91912. if( sqlite3IsRowid(pColumn->a[i].zName) && !withoutRowid ){
  91913. ipkColumn = i;
  91914. bIdListInOrder = 0;
  91915. }else{
  91916. sqlite3ErrorMsg(pParse, "table %S has no column named %s",
  91917. pTabList, 0, pColumn->a[i].zName);
  91918. pParse->checkSchema = 1;
  91919. goto insert_cleanup;
  91920. }
  91921. }
  91922. }
  91923. }
  91924. /* Figure out how many columns of data are supplied. If the data
  91925. ** is coming from a SELECT statement, then generate a co-routine that
  91926. ** produces a single row of the SELECT on each invocation. The
  91927. ** co-routine is the common header to the 3rd and 4th templates.
  91928. */
  91929. if( pSelect ){
  91930. /* Data is coming from a SELECT. Generate a co-routine to run the SELECT */
  91931. int regYield; /* Register holding co-routine entry-point */
  91932. int addrTop; /* Top of the co-routine */
  91933. int rc; /* Result code */
  91934. regYield = ++pParse->nMem;
  91935. addrTop = sqlite3VdbeCurrentAddr(v) + 1;
  91936. sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, addrTop);
  91937. sqlite3SelectDestInit(&dest, SRT_Coroutine, regYield);
  91938. dest.iSdst = bIdListInOrder ? regData : 0;
  91939. dest.nSdst = pTab->nCol;
  91940. rc = sqlite3Select(pParse, pSelect, &dest);
  91941. regFromSelect = dest.iSdst;
  91942. assert( pParse->nErr==0 || rc );
  91943. if( rc || db->mallocFailed ) goto insert_cleanup;
  91944. sqlite3VdbeAddOp1(v, OP_EndCoroutine, regYield);
  91945. sqlite3VdbeJumpHere(v, addrTop - 1); /* label B: */
  91946. assert( pSelect->pEList );
  91947. nColumn = pSelect->pEList->nExpr;
  91948. /* Set useTempTable to TRUE if the result of the SELECT statement
  91949. ** should be written into a temporary table (template 4). Set to
  91950. ** FALSE if each output row of the SELECT can be written directly into
  91951. ** the destination table (template 3).
  91952. **
  91953. ** A temp table must be used if the table being updated is also one
  91954. ** of the tables being read by the SELECT statement. Also use a
  91955. ** temp table in the case of row triggers.
  91956. */
  91957. if( pTrigger || readsTable(pParse, iDb, pTab) ){
  91958. useTempTable = 1;
  91959. }
  91960. if( useTempTable ){
  91961. /* Invoke the coroutine to extract information from the SELECT
  91962. ** and add it to a transient table srcTab. The code generated
  91963. ** here is from the 4th template:
  91964. **
  91965. ** B: open temp table
  91966. ** L: yield X, goto M at EOF
  91967. ** insert row from R..R+n into temp table
  91968. ** goto L
  91969. ** M: ...
  91970. */
  91971. int regRec; /* Register to hold packed record */
  91972. int regTempRowid; /* Register to hold temp table ROWID */
  91973. int addrL; /* Label "L" */
  91974. srcTab = pParse->nTab++;
  91975. regRec = sqlite3GetTempReg(pParse);
  91976. regTempRowid = sqlite3GetTempReg(pParse);
  91977. sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn);
  91978. addrL = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm); VdbeCoverage(v);
  91979. sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec);
  91980. sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regTempRowid);
  91981. sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regTempRowid);
  91982. sqlite3VdbeAddOp2(v, OP_Goto, 0, addrL);
  91983. sqlite3VdbeJumpHere(v, addrL);
  91984. sqlite3ReleaseTempReg(pParse, regRec);
  91985. sqlite3ReleaseTempReg(pParse, regTempRowid);
  91986. }
  91987. }else{
  91988. /* This is the case if the data for the INSERT is coming from a VALUES
  91989. ** clause
  91990. */
  91991. NameContext sNC;
  91992. memset(&sNC, 0, sizeof(sNC));
  91993. sNC.pParse = pParse;
  91994. srcTab = -1;
  91995. assert( useTempTable==0 );
  91996. nColumn = pList ? pList->nExpr : 0;
  91997. for(i=0; i<nColumn; i++){
  91998. if( sqlite3ResolveExprNames(&sNC, pList->a[i].pExpr) ){
  91999. goto insert_cleanup;
  92000. }
  92001. }
  92002. }
  92003. /* If there is no IDLIST term but the table has an integer primary
  92004. ** key, the set the ipkColumn variable to the integer primary key
  92005. ** column index in the original table definition.
  92006. */
  92007. if( pColumn==0 && nColumn>0 ){
  92008. ipkColumn = pTab->iPKey;
  92009. }
  92010. /* Make sure the number of columns in the source data matches the number
  92011. ** of columns to be inserted into the table.
  92012. */
  92013. if( IsVirtual(pTab) ){
  92014. for(i=0; i<pTab->nCol; i++){
  92015. nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0);
  92016. }
  92017. }
  92018. if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){
  92019. sqlite3ErrorMsg(pParse,
  92020. "table %S has %d columns but %d values were supplied",
  92021. pTabList, 0, pTab->nCol-nHidden, nColumn);
  92022. goto insert_cleanup;
  92023. }
  92024. if( pColumn!=0 && nColumn!=pColumn->nId ){
  92025. sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
  92026. goto insert_cleanup;
  92027. }
  92028. /* Initialize the count of rows to be inserted
  92029. */
  92030. if( db->flags & SQLITE_CountRows ){
  92031. regRowCount = ++pParse->nMem;
  92032. sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
  92033. }
  92034. /* If this is not a view, open the table and and all indices */
  92035. if( !isView ){
  92036. int nIdx;
  92037. nIdx = sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, -1, 0,
  92038. &iDataCur, &iIdxCur);
  92039. aRegIdx = sqlite3DbMallocRaw(db, sizeof(int)*(nIdx+1));
  92040. if( aRegIdx==0 ){
  92041. goto insert_cleanup;
  92042. }
  92043. for(i=0; i<nIdx; i++){
  92044. aRegIdx[i] = ++pParse->nMem;
  92045. }
  92046. }
  92047. /* This is the top of the main insertion loop */
  92048. if( useTempTable ){
  92049. /* This block codes the top of loop only. The complete loop is the
  92050. ** following pseudocode (template 4):
  92051. **
  92052. ** rewind temp table, if empty goto D
  92053. ** C: loop over rows of intermediate table
  92054. ** transfer values form intermediate table into <table>
  92055. ** end loop
  92056. ** D: ...
  92057. */
  92058. addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab); VdbeCoverage(v);
  92059. addrCont = sqlite3VdbeCurrentAddr(v);
  92060. }else if( pSelect ){
  92061. /* This block codes the top of loop only. The complete loop is the
  92062. ** following pseudocode (template 3):
  92063. **
  92064. ** C: yield X, at EOF goto D
  92065. ** insert the select result into <table> from R..R+n
  92066. ** goto C
  92067. ** D: ...
  92068. */
  92069. addrInsTop = addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
  92070. VdbeCoverage(v);
  92071. }
  92072. /* Run the BEFORE and INSTEAD OF triggers, if there are any
  92073. */
  92074. endOfLoop = sqlite3VdbeMakeLabel(v);
  92075. if( tmask & TRIGGER_BEFORE ){
  92076. int regCols = sqlite3GetTempRange(pParse, pTab->nCol+1);
  92077. /* build the NEW.* reference row. Note that if there is an INTEGER
  92078. ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
  92079. ** translated into a unique ID for the row. But on a BEFORE trigger,
  92080. ** we do not know what the unique ID will be (because the insert has
  92081. ** not happened yet) so we substitute a rowid of -1
  92082. */
  92083. if( ipkColumn<0 ){
  92084. sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
  92085. }else{
  92086. int j1;
  92087. assert( !withoutRowid );
  92088. if( useTempTable ){
  92089. sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regCols);
  92090. }else{
  92091. assert( pSelect==0 ); /* Otherwise useTempTable is true */
  92092. sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regCols);
  92093. }
  92094. j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regCols); VdbeCoverage(v);
  92095. sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
  92096. sqlite3VdbeJumpHere(v, j1);
  92097. sqlite3VdbeAddOp1(v, OP_MustBeInt, regCols); VdbeCoverage(v);
  92098. }
  92099. /* Cannot have triggers on a virtual table. If it were possible,
  92100. ** this block would have to account for hidden column.
  92101. */
  92102. assert( !IsVirtual(pTab) );
  92103. /* Create the new column data
  92104. */
  92105. for(i=0; i<pTab->nCol; i++){
  92106. if( pColumn==0 ){
  92107. j = i;
  92108. }else{
  92109. for(j=0; j<pColumn->nId; j++){
  92110. if( pColumn->a[j].idx==i ) break;
  92111. }
  92112. }
  92113. if( (!useTempTable && !pList) || (pColumn && j>=pColumn->nId) ){
  92114. sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regCols+i+1);
  92115. }else if( useTempTable ){
  92116. sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, regCols+i+1);
  92117. }else{
  92118. assert( pSelect==0 ); /* Otherwise useTempTable is true */
  92119. sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr, regCols+i+1);
  92120. }
  92121. }
  92122. /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
  92123. ** do not attempt any conversions before assembling the record.
  92124. ** If this is a real table, attempt conversions as required by the
  92125. ** table column affinities.
  92126. */
  92127. if( !isView ){
  92128. sqlite3TableAffinity(v, pTab, regCols+1);
  92129. }
  92130. /* Fire BEFORE or INSTEAD OF triggers */
  92131. sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_BEFORE,
  92132. pTab, regCols-pTab->nCol-1, onError, endOfLoop);
  92133. sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol+1);
  92134. }
  92135. /* Compute the content of the next row to insert into a range of
  92136. ** registers beginning at regIns.
  92137. */
  92138. if( !isView ){
  92139. if( IsVirtual(pTab) ){
  92140. /* The row that the VUpdate opcode will delete: none */
  92141. sqlite3VdbeAddOp2(v, OP_Null, 0, regIns);
  92142. }
  92143. if( ipkColumn>=0 ){
  92144. if( useTempTable ){
  92145. sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regRowid);
  92146. }else if( pSelect ){
  92147. sqlite3VdbeAddOp2(v, OP_Copy, regFromSelect+ipkColumn, regRowid);
  92148. }else{
  92149. VdbeOp *pOp;
  92150. sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regRowid);
  92151. pOp = sqlite3VdbeGetOp(v, -1);
  92152. if( ALWAYS(pOp) && pOp->opcode==OP_Null && !IsVirtual(pTab) ){
  92153. appendFlag = 1;
  92154. pOp->opcode = OP_NewRowid;
  92155. pOp->p1 = iDataCur;
  92156. pOp->p2 = regRowid;
  92157. pOp->p3 = regAutoinc;
  92158. }
  92159. }
  92160. /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
  92161. ** to generate a unique primary key value.
  92162. */
  92163. if( !appendFlag ){
  92164. int j1;
  92165. if( !IsVirtual(pTab) ){
  92166. j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid); VdbeCoverage(v);
  92167. sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc);
  92168. sqlite3VdbeJumpHere(v, j1);
  92169. }else{
  92170. j1 = sqlite3VdbeCurrentAddr(v);
  92171. sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, j1+2); VdbeCoverage(v);
  92172. }
  92173. sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid); VdbeCoverage(v);
  92174. }
  92175. }else if( IsVirtual(pTab) || withoutRowid ){
  92176. sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid);
  92177. }else{
  92178. sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc);
  92179. appendFlag = 1;
  92180. }
  92181. autoIncStep(pParse, regAutoinc, regRowid);
  92182. /* Compute data for all columns of the new entry, beginning
  92183. ** with the first column.
  92184. */
  92185. nHidden = 0;
  92186. for(i=0; i<pTab->nCol; i++){
  92187. int iRegStore = regRowid+1+i;
  92188. if( i==pTab->iPKey ){
  92189. /* The value of the INTEGER PRIMARY KEY column is always a NULL.
  92190. ** Whenever this column is read, the rowid will be substituted
  92191. ** in its place. Hence, fill this column with a NULL to avoid
  92192. ** taking up data space with information that will never be used.
  92193. ** As there may be shallow copies of this value, make it a soft-NULL */
  92194. sqlite3VdbeAddOp1(v, OP_SoftNull, iRegStore);
  92195. continue;
  92196. }
  92197. if( pColumn==0 ){
  92198. if( IsHiddenColumn(&pTab->aCol[i]) ){
  92199. assert( IsVirtual(pTab) );
  92200. j = -1;
  92201. nHidden++;
  92202. }else{
  92203. j = i - nHidden;
  92204. }
  92205. }else{
  92206. for(j=0; j<pColumn->nId; j++){
  92207. if( pColumn->a[j].idx==i ) break;
  92208. }
  92209. }
  92210. if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){
  92211. sqlite3ExprCodeFactorable(pParse, pTab->aCol[i].pDflt, iRegStore);
  92212. }else if( useTempTable ){
  92213. sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, iRegStore);
  92214. }else if( pSelect ){
  92215. if( regFromSelect!=regData ){
  92216. sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+j, iRegStore);
  92217. }
  92218. }else{
  92219. sqlite3ExprCode(pParse, pList->a[j].pExpr, iRegStore);
  92220. }
  92221. }
  92222. /* Generate code to check constraints and generate index keys and
  92223. ** do the insertion.
  92224. */
  92225. #ifndef SQLITE_OMIT_VIRTUALTABLE
  92226. if( IsVirtual(pTab) ){
  92227. const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
  92228. sqlite3VtabMakeWritable(pParse, pTab);
  92229. sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns, pVTab, P4_VTAB);
  92230. sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
  92231. sqlite3MayAbort(pParse);
  92232. }else
  92233. #endif
  92234. {
  92235. int isReplace; /* Set to true if constraints may cause a replace */
  92236. sqlite3GenerateConstraintChecks(pParse, pTab, aRegIdx, iDataCur, iIdxCur,
  92237. regIns, 0, ipkColumn>=0, onError, endOfLoop, &isReplace
  92238. );
  92239. sqlite3FkCheck(pParse, pTab, 0, regIns, 0, 0);
  92240. sqlite3CompleteInsertion(pParse, pTab, iDataCur, iIdxCur,
  92241. regIns, aRegIdx, 0, appendFlag, isReplace==0);
  92242. }
  92243. }
  92244. /* Update the count of rows that are inserted
  92245. */
  92246. if( (db->flags & SQLITE_CountRows)!=0 ){
  92247. sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
  92248. }
  92249. if( pTrigger ){
  92250. /* Code AFTER triggers */
  92251. sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_AFTER,
  92252. pTab, regData-2-pTab->nCol, onError, endOfLoop);
  92253. }
  92254. /* The bottom of the main insertion loop, if the data source
  92255. ** is a SELECT statement.
  92256. */
  92257. sqlite3VdbeResolveLabel(v, endOfLoop);
  92258. if( useTempTable ){
  92259. sqlite3VdbeAddOp2(v, OP_Next, srcTab, addrCont); VdbeCoverage(v);
  92260. sqlite3VdbeJumpHere(v, addrInsTop);
  92261. sqlite3VdbeAddOp1(v, OP_Close, srcTab);
  92262. }else if( pSelect ){
  92263. sqlite3VdbeAddOp2(v, OP_Goto, 0, addrCont);
  92264. sqlite3VdbeJumpHere(v, addrInsTop);
  92265. }
  92266. if( !IsVirtual(pTab) && !isView ){
  92267. /* Close all tables opened */
  92268. if( iDataCur<iIdxCur ) sqlite3VdbeAddOp1(v, OP_Close, iDataCur);
  92269. for(idx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
  92270. sqlite3VdbeAddOp1(v, OP_Close, idx+iIdxCur);
  92271. }
  92272. }
  92273. insert_end:
  92274. /* Update the sqlite_sequence table by storing the content of the
  92275. ** maximum rowid counter values recorded while inserting into
  92276. ** autoincrement tables.
  92277. */
  92278. if( pParse->nested==0 && pParse->pTriggerTab==0 ){
  92279. sqlite3AutoincrementEnd(pParse);
  92280. }
  92281. /*
  92282. ** Return the number of rows inserted. If this routine is
  92283. ** generating code because of a call to sqlite3NestedParse(), do not
  92284. ** invoke the callback function.
  92285. */
  92286. if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
  92287. sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
  92288. sqlite3VdbeSetNumCols(v, 1);
  92289. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", SQLITE_STATIC);
  92290. }
  92291. insert_cleanup:
  92292. sqlite3SrcListDelete(db, pTabList);
  92293. sqlite3ExprListDelete(db, pList);
  92294. sqlite3SelectDelete(db, pSelect);
  92295. sqlite3IdListDelete(db, pColumn);
  92296. sqlite3DbFree(db, aRegIdx);
  92297. }
  92298. /* Make sure "isView" and other macros defined above are undefined. Otherwise
  92299. ** they may interfere with compilation of other functions in this file
  92300. ** (or in another file, if this file becomes part of the amalgamation). */
  92301. #ifdef isView
  92302. #undef isView
  92303. #endif
  92304. #ifdef pTrigger
  92305. #undef pTrigger
  92306. #endif
  92307. #ifdef tmask
  92308. #undef tmask
  92309. #endif
  92310. /*
  92311. ** Generate code to do constraint checks prior to an INSERT or an UPDATE
  92312. ** on table pTab.
  92313. **
  92314. ** The regNewData parameter is the first register in a range that contains
  92315. ** the data to be inserted or the data after the update. There will be
  92316. ** pTab->nCol+1 registers in this range. The first register (the one
  92317. ** that regNewData points to) will contain the new rowid, or NULL in the
  92318. ** case of a WITHOUT ROWID table. The second register in the range will
  92319. ** contain the content of the first table column. The third register will
  92320. ** contain the content of the second table column. And so forth.
  92321. **
  92322. ** The regOldData parameter is similar to regNewData except that it contains
  92323. ** the data prior to an UPDATE rather than afterwards. regOldData is zero
  92324. ** for an INSERT. This routine can distinguish between UPDATE and INSERT by
  92325. ** checking regOldData for zero.
  92326. **
  92327. ** For an UPDATE, the pkChng boolean is true if the true primary key (the
  92328. ** rowid for a normal table or the PRIMARY KEY for a WITHOUT ROWID table)
  92329. ** might be modified by the UPDATE. If pkChng is false, then the key of
  92330. ** the iDataCur content table is guaranteed to be unchanged by the UPDATE.
  92331. **
  92332. ** For an INSERT, the pkChng boolean indicates whether or not the rowid
  92333. ** was explicitly specified as part of the INSERT statement. If pkChng
  92334. ** is zero, it means that the either rowid is computed automatically or
  92335. ** that the table is a WITHOUT ROWID table and has no rowid. On an INSERT,
  92336. ** pkChng will only be true if the INSERT statement provides an integer
  92337. ** value for either the rowid column or its INTEGER PRIMARY KEY alias.
  92338. **
  92339. ** The code generated by this routine will store new index entries into
  92340. ** registers identified by aRegIdx[]. No index entry is created for
  92341. ** indices where aRegIdx[i]==0. The order of indices in aRegIdx[] is
  92342. ** the same as the order of indices on the linked list of indices
  92343. ** at pTab->pIndex.
  92344. **
  92345. ** The caller must have already opened writeable cursors on the main
  92346. ** table and all applicable indices (that is to say, all indices for which
  92347. ** aRegIdx[] is not zero). iDataCur is the cursor for the main table when
  92348. ** inserting or updating a rowid table, or the cursor for the PRIMARY KEY
  92349. ** index when operating on a WITHOUT ROWID table. iIdxCur is the cursor
  92350. ** for the first index in the pTab->pIndex list. Cursors for other indices
  92351. ** are at iIdxCur+N for the N-th element of the pTab->pIndex list.
  92352. **
  92353. ** This routine also generates code to check constraints. NOT NULL,
  92354. ** CHECK, and UNIQUE constraints are all checked. If a constraint fails,
  92355. ** then the appropriate action is performed. There are five possible
  92356. ** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
  92357. **
  92358. ** Constraint type Action What Happens
  92359. ** --------------- ---------- ----------------------------------------
  92360. ** any ROLLBACK The current transaction is rolled back and
  92361. ** sqlite3_step() returns immediately with a
  92362. ** return code of SQLITE_CONSTRAINT.
  92363. **
  92364. ** any ABORT Back out changes from the current command
  92365. ** only (do not do a complete rollback) then
  92366. ** cause sqlite3_step() to return immediately
  92367. ** with SQLITE_CONSTRAINT.
  92368. **
  92369. ** any FAIL Sqlite3_step() returns immediately with a
  92370. ** return code of SQLITE_CONSTRAINT. The
  92371. ** transaction is not rolled back and any
  92372. ** changes to prior rows are retained.
  92373. **
  92374. ** any IGNORE The attempt in insert or update the current
  92375. ** row is skipped, without throwing an error.
  92376. ** Processing continues with the next row.
  92377. ** (There is an immediate jump to ignoreDest.)
  92378. **
  92379. ** NOT NULL REPLACE The NULL value is replace by the default
  92380. ** value for that column. If the default value
  92381. ** is NULL, the action is the same as ABORT.
  92382. **
  92383. ** UNIQUE REPLACE The other row that conflicts with the row
  92384. ** being inserted is removed.
  92385. **
  92386. ** CHECK REPLACE Illegal. The results in an exception.
  92387. **
  92388. ** Which action to take is determined by the overrideError parameter.
  92389. ** Or if overrideError==OE_Default, then the pParse->onError parameter
  92390. ** is used. Or if pParse->onError==OE_Default then the onError value
  92391. ** for the constraint is used.
  92392. */
  92393. SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(
  92394. Parse *pParse, /* The parser context */
  92395. Table *pTab, /* The table being inserted or updated */
  92396. int *aRegIdx, /* Use register aRegIdx[i] for index i. 0 for unused */
  92397. int iDataCur, /* Canonical data cursor (main table or PK index) */
  92398. int iIdxCur, /* First index cursor */
  92399. int regNewData, /* First register in a range holding values to insert */
  92400. int regOldData, /* Previous content. 0 for INSERTs */
  92401. u8 pkChng, /* Non-zero if the rowid or PRIMARY KEY changed */
  92402. u8 overrideError, /* Override onError to this if not OE_Default */
  92403. int ignoreDest, /* Jump to this label on an OE_Ignore resolution */
  92404. int *pbMayReplace /* OUT: Set to true if constraint may cause a replace */
  92405. ){
  92406. Vdbe *v; /* VDBE under constrution */
  92407. Index *pIdx; /* Pointer to one of the indices */
  92408. Index *pPk = 0; /* The PRIMARY KEY index */
  92409. sqlite3 *db; /* Database connection */
  92410. int i; /* loop counter */
  92411. int ix; /* Index loop counter */
  92412. int nCol; /* Number of columns */
  92413. int onError; /* Conflict resolution strategy */
  92414. int j1; /* Address of jump instruction */
  92415. int seenReplace = 0; /* True if REPLACE is used to resolve INT PK conflict */
  92416. int nPkField; /* Number of fields in PRIMARY KEY. 1 for ROWID tables */
  92417. int ipkTop = 0; /* Top of the rowid change constraint check */
  92418. int ipkBottom = 0; /* Bottom of the rowid change constraint check */
  92419. u8 isUpdate; /* True if this is an UPDATE operation */
  92420. u8 bAffinityDone = 0; /* True if the OP_Affinity operation has been run */
  92421. int regRowid = -1; /* Register holding ROWID value */
  92422. isUpdate = regOldData!=0;
  92423. db = pParse->db;
  92424. v = sqlite3GetVdbe(pParse);
  92425. assert( v!=0 );
  92426. assert( pTab->pSelect==0 ); /* This table is not a VIEW */
  92427. nCol = pTab->nCol;
  92428. /* pPk is the PRIMARY KEY index for WITHOUT ROWID tables and NULL for
  92429. ** normal rowid tables. nPkField is the number of key fields in the
  92430. ** pPk index or 1 for a rowid table. In other words, nPkField is the
  92431. ** number of fields in the true primary key of the table. */
  92432. if( HasRowid(pTab) ){
  92433. pPk = 0;
  92434. nPkField = 1;
  92435. }else{
  92436. pPk = sqlite3PrimaryKeyIndex(pTab);
  92437. nPkField = pPk->nKeyCol;
  92438. }
  92439. /* Record that this module has started */
  92440. VdbeModuleComment((v, "BEGIN: GenCnstCks(%d,%d,%d,%d,%d)",
  92441. iDataCur, iIdxCur, regNewData, regOldData, pkChng));
  92442. /* Test all NOT NULL constraints.
  92443. */
  92444. for(i=0; i<nCol; i++){
  92445. if( i==pTab->iPKey ){
  92446. continue;
  92447. }
  92448. onError = pTab->aCol[i].notNull;
  92449. if( onError==OE_None ) continue;
  92450. if( overrideError!=OE_Default ){
  92451. onError = overrideError;
  92452. }else if( onError==OE_Default ){
  92453. onError = OE_Abort;
  92454. }
  92455. if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){
  92456. onError = OE_Abort;
  92457. }
  92458. assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
  92459. || onError==OE_Ignore || onError==OE_Replace );
  92460. switch( onError ){
  92461. case OE_Abort:
  92462. sqlite3MayAbort(pParse);
  92463. /* Fall through */
  92464. case OE_Rollback:
  92465. case OE_Fail: {
  92466. char *zMsg = sqlite3MPrintf(db, "%s.%s", pTab->zName,
  92467. pTab->aCol[i].zName);
  92468. sqlite3VdbeAddOp4(v, OP_HaltIfNull, SQLITE_CONSTRAINT_NOTNULL, onError,
  92469. regNewData+1+i, zMsg, P4_DYNAMIC);
  92470. sqlite3VdbeChangeP5(v, P5_ConstraintNotNull);
  92471. VdbeCoverage(v);
  92472. break;
  92473. }
  92474. case OE_Ignore: {
  92475. sqlite3VdbeAddOp2(v, OP_IsNull, regNewData+1+i, ignoreDest);
  92476. VdbeCoverage(v);
  92477. break;
  92478. }
  92479. default: {
  92480. assert( onError==OE_Replace );
  92481. j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regNewData+1+i); VdbeCoverage(v);
  92482. sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regNewData+1+i);
  92483. sqlite3VdbeJumpHere(v, j1);
  92484. break;
  92485. }
  92486. }
  92487. }
  92488. /* Test all CHECK constraints
  92489. */
  92490. #ifndef SQLITE_OMIT_CHECK
  92491. if( pTab->pCheck && (db->flags & SQLITE_IgnoreChecks)==0 ){
  92492. ExprList *pCheck = pTab->pCheck;
  92493. pParse->ckBase = regNewData+1;
  92494. onError = overrideError!=OE_Default ? overrideError : OE_Abort;
  92495. for(i=0; i<pCheck->nExpr; i++){
  92496. int allOk = sqlite3VdbeMakeLabel(v);
  92497. sqlite3ExprIfTrue(pParse, pCheck->a[i].pExpr, allOk, SQLITE_JUMPIFNULL);
  92498. if( onError==OE_Ignore ){
  92499. sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
  92500. }else{
  92501. char *zName = pCheck->a[i].zName;
  92502. if( zName==0 ) zName = pTab->zName;
  92503. if( onError==OE_Replace ) onError = OE_Abort; /* IMP: R-15569-63625 */
  92504. sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_CHECK,
  92505. onError, zName, P4_TRANSIENT,
  92506. P5_ConstraintCheck);
  92507. }
  92508. sqlite3VdbeResolveLabel(v, allOk);
  92509. }
  92510. }
  92511. #endif /* !defined(SQLITE_OMIT_CHECK) */
  92512. /* If rowid is changing, make sure the new rowid does not previously
  92513. ** exist in the table.
  92514. */
  92515. if( pkChng && pPk==0 ){
  92516. int addrRowidOk = sqlite3VdbeMakeLabel(v);
  92517. /* Figure out what action to take in case of a rowid collision */
  92518. onError = pTab->keyConf;
  92519. if( overrideError!=OE_Default ){
  92520. onError = overrideError;
  92521. }else if( onError==OE_Default ){
  92522. onError = OE_Abort;
  92523. }
  92524. if( isUpdate ){
  92525. /* pkChng!=0 does not mean that the rowid has change, only that
  92526. ** it might have changed. Skip the conflict logic below if the rowid
  92527. ** is unchanged. */
  92528. sqlite3VdbeAddOp3(v, OP_Eq, regNewData, addrRowidOk, regOldData);
  92529. sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
  92530. VdbeCoverage(v);
  92531. }
  92532. /* If the response to a rowid conflict is REPLACE but the response
  92533. ** to some other UNIQUE constraint is FAIL or IGNORE, then we need
  92534. ** to defer the running of the rowid conflict checking until after
  92535. ** the UNIQUE constraints have run.
  92536. */
  92537. if( onError==OE_Replace && overrideError!=OE_Replace ){
  92538. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  92539. if( pIdx->onError==OE_Ignore || pIdx->onError==OE_Fail ){
  92540. ipkTop = sqlite3VdbeAddOp0(v, OP_Goto);
  92541. break;
  92542. }
  92543. }
  92544. }
  92545. /* Check to see if the new rowid already exists in the table. Skip
  92546. ** the following conflict logic if it does not. */
  92547. sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, addrRowidOk, regNewData);
  92548. VdbeCoverage(v);
  92549. /* Generate code that deals with a rowid collision */
  92550. switch( onError ){
  92551. default: {
  92552. onError = OE_Abort;
  92553. /* Fall thru into the next case */
  92554. }
  92555. case OE_Rollback:
  92556. case OE_Abort:
  92557. case OE_Fail: {
  92558. sqlite3RowidConstraint(pParse, onError, pTab);
  92559. break;
  92560. }
  92561. case OE_Replace: {
  92562. /* If there are DELETE triggers on this table and the
  92563. ** recursive-triggers flag is set, call GenerateRowDelete() to
  92564. ** remove the conflicting row from the table. This will fire
  92565. ** the triggers and remove both the table and index b-tree entries.
  92566. **
  92567. ** Otherwise, if there are no triggers or the recursive-triggers
  92568. ** flag is not set, but the table has one or more indexes, call
  92569. ** GenerateRowIndexDelete(). This removes the index b-tree entries
  92570. ** only. The table b-tree entry will be replaced by the new entry
  92571. ** when it is inserted.
  92572. **
  92573. ** If either GenerateRowDelete() or GenerateRowIndexDelete() is called,
  92574. ** also invoke MultiWrite() to indicate that this VDBE may require
  92575. ** statement rollback (if the statement is aborted after the delete
  92576. ** takes place). Earlier versions called sqlite3MultiWrite() regardless,
  92577. ** but being more selective here allows statements like:
  92578. **
  92579. ** REPLACE INTO t(rowid) VALUES($newrowid)
  92580. **
  92581. ** to run without a statement journal if there are no indexes on the
  92582. ** table.
  92583. */
  92584. Trigger *pTrigger = 0;
  92585. if( db->flags&SQLITE_RecTriggers ){
  92586. pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
  92587. }
  92588. if( pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0) ){
  92589. sqlite3MultiWrite(pParse);
  92590. sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
  92591. regNewData, 1, 0, OE_Replace, 1);
  92592. }else if( pTab->pIndex ){
  92593. sqlite3MultiWrite(pParse);
  92594. sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur, 0);
  92595. }
  92596. seenReplace = 1;
  92597. break;
  92598. }
  92599. case OE_Ignore: {
  92600. /*assert( seenReplace==0 );*/
  92601. sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
  92602. break;
  92603. }
  92604. }
  92605. sqlite3VdbeResolveLabel(v, addrRowidOk);
  92606. if( ipkTop ){
  92607. ipkBottom = sqlite3VdbeAddOp0(v, OP_Goto);
  92608. sqlite3VdbeJumpHere(v, ipkTop);
  92609. }
  92610. }
  92611. /* Test all UNIQUE constraints by creating entries for each UNIQUE
  92612. ** index and making sure that duplicate entries do not already exist.
  92613. ** Compute the revised record entries for indices as we go.
  92614. **
  92615. ** This loop also handles the case of the PRIMARY KEY index for a
  92616. ** WITHOUT ROWID table.
  92617. */
  92618. for(ix=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, ix++){
  92619. int regIdx; /* Range of registers hold conent for pIdx */
  92620. int regR; /* Range of registers holding conflicting PK */
  92621. int iThisCur; /* Cursor for this UNIQUE index */
  92622. int addrUniqueOk; /* Jump here if the UNIQUE constraint is satisfied */
  92623. if( aRegIdx[ix]==0 ) continue; /* Skip indices that do not change */
  92624. if( bAffinityDone==0 ){
  92625. sqlite3TableAffinity(v, pTab, regNewData+1);
  92626. bAffinityDone = 1;
  92627. }
  92628. iThisCur = iIdxCur+ix;
  92629. addrUniqueOk = sqlite3VdbeMakeLabel(v);
  92630. /* Skip partial indices for which the WHERE clause is not true */
  92631. if( pIdx->pPartIdxWhere ){
  92632. sqlite3VdbeAddOp2(v, OP_Null, 0, aRegIdx[ix]);
  92633. pParse->ckBase = regNewData+1;
  92634. sqlite3ExprIfFalse(pParse, pIdx->pPartIdxWhere, addrUniqueOk,
  92635. SQLITE_JUMPIFNULL);
  92636. pParse->ckBase = 0;
  92637. }
  92638. /* Create a record for this index entry as it should appear after
  92639. ** the insert or update. Store that record in the aRegIdx[ix] register
  92640. */
  92641. regIdx = sqlite3GetTempRange(pParse, pIdx->nColumn);
  92642. for(i=0; i<pIdx->nColumn; i++){
  92643. int iField = pIdx->aiColumn[i];
  92644. int x;
  92645. if( iField<0 || iField==pTab->iPKey ){
  92646. if( regRowid==regIdx+i ) continue; /* ROWID already in regIdx+i */
  92647. x = regNewData;
  92648. regRowid = pIdx->pPartIdxWhere ? -1 : regIdx+i;
  92649. }else{
  92650. x = iField + regNewData + 1;
  92651. }
  92652. sqlite3VdbeAddOp2(v, OP_SCopy, x, regIdx+i);
  92653. VdbeComment((v, "%s", iField<0 ? "rowid" : pTab->aCol[iField].zName));
  92654. }
  92655. sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn, aRegIdx[ix]);
  92656. VdbeComment((v, "for %s", pIdx->zName));
  92657. sqlite3ExprCacheAffinityChange(pParse, regIdx, pIdx->nColumn);
  92658. /* In an UPDATE operation, if this index is the PRIMARY KEY index
  92659. ** of a WITHOUT ROWID table and there has been no change the
  92660. ** primary key, then no collision is possible. The collision detection
  92661. ** logic below can all be skipped. */
  92662. if( isUpdate && pPk==pIdx && pkChng==0 ){
  92663. sqlite3VdbeResolveLabel(v, addrUniqueOk);
  92664. continue;
  92665. }
  92666. /* Find out what action to take in case there is a uniqueness conflict */
  92667. onError = pIdx->onError;
  92668. if( onError==OE_None ){
  92669. sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn);
  92670. sqlite3VdbeResolveLabel(v, addrUniqueOk);
  92671. continue; /* pIdx is not a UNIQUE index */
  92672. }
  92673. if( overrideError!=OE_Default ){
  92674. onError = overrideError;
  92675. }else if( onError==OE_Default ){
  92676. onError = OE_Abort;
  92677. }
  92678. /* Check to see if the new index entry will be unique */
  92679. sqlite3VdbeAddOp4Int(v, OP_NoConflict, iThisCur, addrUniqueOk,
  92680. regIdx, pIdx->nKeyCol); VdbeCoverage(v);
  92681. /* Generate code to handle collisions */
  92682. regR = (pIdx==pPk) ? regIdx : sqlite3GetTempRange(pParse, nPkField);
  92683. if( isUpdate || onError==OE_Replace ){
  92684. if( HasRowid(pTab) ){
  92685. sqlite3VdbeAddOp2(v, OP_IdxRowid, iThisCur, regR);
  92686. /* Conflict only if the rowid of the existing index entry
  92687. ** is different from old-rowid */
  92688. if( isUpdate ){
  92689. sqlite3VdbeAddOp3(v, OP_Eq, regR, addrUniqueOk, regOldData);
  92690. sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
  92691. VdbeCoverage(v);
  92692. }
  92693. }else{
  92694. int x;
  92695. /* Extract the PRIMARY KEY from the end of the index entry and
  92696. ** store it in registers regR..regR+nPk-1 */
  92697. if( pIdx!=pPk ){
  92698. for(i=0; i<pPk->nKeyCol; i++){
  92699. x = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[i]);
  92700. sqlite3VdbeAddOp3(v, OP_Column, iThisCur, x, regR+i);
  92701. VdbeComment((v, "%s.%s", pTab->zName,
  92702. pTab->aCol[pPk->aiColumn[i]].zName));
  92703. }
  92704. }
  92705. if( isUpdate ){
  92706. /* If currently processing the PRIMARY KEY of a WITHOUT ROWID
  92707. ** table, only conflict if the new PRIMARY KEY values are actually
  92708. ** different from the old.
  92709. **
  92710. ** For a UNIQUE index, only conflict if the PRIMARY KEY values
  92711. ** of the matched index row are different from the original PRIMARY
  92712. ** KEY values of this row before the update. */
  92713. int addrJump = sqlite3VdbeCurrentAddr(v)+pPk->nKeyCol;
  92714. int op = OP_Ne;
  92715. int regCmp = (IsPrimaryKeyIndex(pIdx) ? regIdx : regR);
  92716. for(i=0; i<pPk->nKeyCol; i++){
  92717. char *p4 = (char*)sqlite3LocateCollSeq(pParse, pPk->azColl[i]);
  92718. x = pPk->aiColumn[i];
  92719. if( i==(pPk->nKeyCol-1) ){
  92720. addrJump = addrUniqueOk;
  92721. op = OP_Eq;
  92722. }
  92723. sqlite3VdbeAddOp4(v, op,
  92724. regOldData+1+x, addrJump, regCmp+i, p4, P4_COLLSEQ
  92725. );
  92726. sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
  92727. VdbeCoverageIf(v, op==OP_Eq);
  92728. VdbeCoverageIf(v, op==OP_Ne);
  92729. }
  92730. }
  92731. }
  92732. }
  92733. /* Generate code that executes if the new index entry is not unique */
  92734. assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
  92735. || onError==OE_Ignore || onError==OE_Replace );
  92736. switch( onError ){
  92737. case OE_Rollback:
  92738. case OE_Abort:
  92739. case OE_Fail: {
  92740. sqlite3UniqueConstraint(pParse, onError, pIdx);
  92741. break;
  92742. }
  92743. case OE_Ignore: {
  92744. sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
  92745. break;
  92746. }
  92747. default: {
  92748. Trigger *pTrigger = 0;
  92749. assert( onError==OE_Replace );
  92750. sqlite3MultiWrite(pParse);
  92751. if( db->flags&SQLITE_RecTriggers ){
  92752. pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
  92753. }
  92754. sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
  92755. regR, nPkField, 0, OE_Replace, pIdx==pPk);
  92756. seenReplace = 1;
  92757. break;
  92758. }
  92759. }
  92760. sqlite3VdbeResolveLabel(v, addrUniqueOk);
  92761. sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn);
  92762. if( regR!=regIdx ) sqlite3ReleaseTempRange(pParse, regR, nPkField);
  92763. }
  92764. if( ipkTop ){
  92765. sqlite3VdbeAddOp2(v, OP_Goto, 0, ipkTop+1);
  92766. sqlite3VdbeJumpHere(v, ipkBottom);
  92767. }
  92768. *pbMayReplace = seenReplace;
  92769. VdbeModuleComment((v, "END: GenCnstCks(%d)", seenReplace));
  92770. }
  92771. /*
  92772. ** This routine generates code to finish the INSERT or UPDATE operation
  92773. ** that was started by a prior call to sqlite3GenerateConstraintChecks.
  92774. ** A consecutive range of registers starting at regNewData contains the
  92775. ** rowid and the content to be inserted.
  92776. **
  92777. ** The arguments to this routine should be the same as the first six
  92778. ** arguments to sqlite3GenerateConstraintChecks.
  92779. */
  92780. SQLITE_PRIVATE void sqlite3CompleteInsertion(
  92781. Parse *pParse, /* The parser context */
  92782. Table *pTab, /* the table into which we are inserting */
  92783. int iDataCur, /* Cursor of the canonical data source */
  92784. int iIdxCur, /* First index cursor */
  92785. int regNewData, /* Range of content */
  92786. int *aRegIdx, /* Register used by each index. 0 for unused indices */
  92787. int isUpdate, /* True for UPDATE, False for INSERT */
  92788. int appendBias, /* True if this is likely to be an append */
  92789. int useSeekResult /* True to set the USESEEKRESULT flag on OP_[Idx]Insert */
  92790. ){
  92791. Vdbe *v; /* Prepared statements under construction */
  92792. Index *pIdx; /* An index being inserted or updated */
  92793. u8 pik_flags; /* flag values passed to the btree insert */
  92794. int regData; /* Content registers (after the rowid) */
  92795. int regRec; /* Register holding assembled record for the table */
  92796. int i; /* Loop counter */
  92797. u8 bAffinityDone = 0; /* True if OP_Affinity has been run already */
  92798. v = sqlite3GetVdbe(pParse);
  92799. assert( v!=0 );
  92800. assert( pTab->pSelect==0 ); /* This table is not a VIEW */
  92801. for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
  92802. if( aRegIdx[i]==0 ) continue;
  92803. bAffinityDone = 1;
  92804. if( pIdx->pPartIdxWhere ){
  92805. sqlite3VdbeAddOp2(v, OP_IsNull, aRegIdx[i], sqlite3VdbeCurrentAddr(v)+2);
  92806. VdbeCoverage(v);
  92807. }
  92808. sqlite3VdbeAddOp2(v, OP_IdxInsert, iIdxCur+i, aRegIdx[i]);
  92809. pik_flags = 0;
  92810. if( useSeekResult ) pik_flags = OPFLAG_USESEEKRESULT;
  92811. if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) ){
  92812. assert( pParse->nested==0 );
  92813. pik_flags |= OPFLAG_NCHANGE;
  92814. }
  92815. if( pik_flags ) sqlite3VdbeChangeP5(v, pik_flags);
  92816. }
  92817. if( !HasRowid(pTab) ) return;
  92818. regData = regNewData + 1;
  92819. regRec = sqlite3GetTempReg(pParse);
  92820. sqlite3VdbeAddOp3(v, OP_MakeRecord, regData, pTab->nCol, regRec);
  92821. if( !bAffinityDone ) sqlite3TableAffinity(v, pTab, 0);
  92822. sqlite3ExprCacheAffinityChange(pParse, regData, pTab->nCol);
  92823. if( pParse->nested ){
  92824. pik_flags = 0;
  92825. }else{
  92826. pik_flags = OPFLAG_NCHANGE;
  92827. pik_flags |= (isUpdate?OPFLAG_ISUPDATE:OPFLAG_LASTROWID);
  92828. }
  92829. if( appendBias ){
  92830. pik_flags |= OPFLAG_APPEND;
  92831. }
  92832. if( useSeekResult ){
  92833. pik_flags |= OPFLAG_USESEEKRESULT;
  92834. }
  92835. sqlite3VdbeAddOp3(v, OP_Insert, iDataCur, regRec, regNewData);
  92836. if( !pParse->nested ){
  92837. sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_TRANSIENT);
  92838. }
  92839. sqlite3VdbeChangeP5(v, pik_flags);
  92840. }
  92841. /*
  92842. ** Allocate cursors for the pTab table and all its indices and generate
  92843. ** code to open and initialized those cursors.
  92844. **
  92845. ** The cursor for the object that contains the complete data (normally
  92846. ** the table itself, but the PRIMARY KEY index in the case of a WITHOUT
  92847. ** ROWID table) is returned in *piDataCur. The first index cursor is
  92848. ** returned in *piIdxCur. The number of indices is returned.
  92849. **
  92850. ** Use iBase as the first cursor (either the *piDataCur for rowid tables
  92851. ** or the first index for WITHOUT ROWID tables) if it is non-negative.
  92852. ** If iBase is negative, then allocate the next available cursor.
  92853. **
  92854. ** For a rowid table, *piDataCur will be exactly one less than *piIdxCur.
  92855. ** For a WITHOUT ROWID table, *piDataCur will be somewhere in the range
  92856. ** of *piIdxCurs, depending on where the PRIMARY KEY index appears on the
  92857. ** pTab->pIndex list.
  92858. **
  92859. ** If pTab is a virtual table, then this routine is a no-op and the
  92860. ** *piDataCur and *piIdxCur values are left uninitialized.
  92861. */
  92862. SQLITE_PRIVATE int sqlite3OpenTableAndIndices(
  92863. Parse *pParse, /* Parsing context */
  92864. Table *pTab, /* Table to be opened */
  92865. int op, /* OP_OpenRead or OP_OpenWrite */
  92866. int iBase, /* Use this for the table cursor, if there is one */
  92867. u8 *aToOpen, /* If not NULL: boolean for each table and index */
  92868. int *piDataCur, /* Write the database source cursor number here */
  92869. int *piIdxCur /* Write the first index cursor number here */
  92870. ){
  92871. int i;
  92872. int iDb;
  92873. int iDataCur;
  92874. Index *pIdx;
  92875. Vdbe *v;
  92876. assert( op==OP_OpenRead || op==OP_OpenWrite );
  92877. if( IsVirtual(pTab) ){
  92878. /* This routine is a no-op for virtual tables. Leave the output
  92879. ** variables *piDataCur and *piIdxCur uninitialized so that valgrind
  92880. ** can detect if they are used by mistake in the caller. */
  92881. return 0;
  92882. }
  92883. iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  92884. v = sqlite3GetVdbe(pParse);
  92885. assert( v!=0 );
  92886. if( iBase<0 ) iBase = pParse->nTab;
  92887. iDataCur = iBase++;
  92888. if( piDataCur ) *piDataCur = iDataCur;
  92889. if( HasRowid(pTab) && (aToOpen==0 || aToOpen[0]) ){
  92890. sqlite3OpenTable(pParse, iDataCur, iDb, pTab, op);
  92891. }else{
  92892. sqlite3TableLock(pParse, iDb, pTab->tnum, op==OP_OpenWrite, pTab->zName);
  92893. }
  92894. if( piIdxCur ) *piIdxCur = iBase;
  92895. for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
  92896. int iIdxCur = iBase++;
  92897. assert( pIdx->pSchema==pTab->pSchema );
  92898. if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) && piDataCur ){
  92899. *piDataCur = iIdxCur;
  92900. }
  92901. if( aToOpen==0 || aToOpen[i+1] ){
  92902. sqlite3VdbeAddOp3(v, op, iIdxCur, pIdx->tnum, iDb);
  92903. sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
  92904. VdbeComment((v, "%s", pIdx->zName));
  92905. }
  92906. }
  92907. if( iBase>pParse->nTab ) pParse->nTab = iBase;
  92908. return i;
  92909. }
  92910. #ifdef SQLITE_TEST
  92911. /*
  92912. ** The following global variable is incremented whenever the
  92913. ** transfer optimization is used. This is used for testing
  92914. ** purposes only - to make sure the transfer optimization really
  92915. ** is happening when it is supposed to.
  92916. */
  92917. SQLITE_API int sqlite3_xferopt_count;
  92918. #endif /* SQLITE_TEST */
  92919. #ifndef SQLITE_OMIT_XFER_OPT
  92920. /*
  92921. ** Check to collation names to see if they are compatible.
  92922. */
  92923. static int xferCompatibleCollation(const char *z1, const char *z2){
  92924. if( z1==0 ){
  92925. return z2==0;
  92926. }
  92927. if( z2==0 ){
  92928. return 0;
  92929. }
  92930. return sqlite3StrICmp(z1, z2)==0;
  92931. }
  92932. /*
  92933. ** Check to see if index pSrc is compatible as a source of data
  92934. ** for index pDest in an insert transfer optimization. The rules
  92935. ** for a compatible index:
  92936. **
  92937. ** * The index is over the same set of columns
  92938. ** * The same DESC and ASC markings occurs on all columns
  92939. ** * The same onError processing (OE_Abort, OE_Ignore, etc)
  92940. ** * The same collating sequence on each column
  92941. ** * The index has the exact same WHERE clause
  92942. */
  92943. static int xferCompatibleIndex(Index *pDest, Index *pSrc){
  92944. int i;
  92945. assert( pDest && pSrc );
  92946. assert( pDest->pTable!=pSrc->pTable );
  92947. if( pDest->nKeyCol!=pSrc->nKeyCol ){
  92948. return 0; /* Different number of columns */
  92949. }
  92950. if( pDest->onError!=pSrc->onError ){
  92951. return 0; /* Different conflict resolution strategies */
  92952. }
  92953. for(i=0; i<pSrc->nKeyCol; i++){
  92954. if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
  92955. return 0; /* Different columns indexed */
  92956. }
  92957. if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
  92958. return 0; /* Different sort orders */
  92959. }
  92960. if( !xferCompatibleCollation(pSrc->azColl[i],pDest->azColl[i]) ){
  92961. return 0; /* Different collating sequences */
  92962. }
  92963. }
  92964. if( sqlite3ExprCompare(pSrc->pPartIdxWhere, pDest->pPartIdxWhere, -1) ){
  92965. return 0; /* Different WHERE clauses */
  92966. }
  92967. /* If no test above fails then the indices must be compatible */
  92968. return 1;
  92969. }
  92970. /*
  92971. ** Attempt the transfer optimization on INSERTs of the form
  92972. **
  92973. ** INSERT INTO tab1 SELECT * FROM tab2;
  92974. **
  92975. ** The xfer optimization transfers raw records from tab2 over to tab1.
  92976. ** Columns are not decoded and reassembled, which greatly improves
  92977. ** performance. Raw index records are transferred in the same way.
  92978. **
  92979. ** The xfer optimization is only attempted if tab1 and tab2 are compatible.
  92980. ** There are lots of rules for determining compatibility - see comments
  92981. ** embedded in the code for details.
  92982. **
  92983. ** This routine returns TRUE if the optimization is guaranteed to be used.
  92984. ** Sometimes the xfer optimization will only work if the destination table
  92985. ** is empty - a factor that can only be determined at run-time. In that
  92986. ** case, this routine generates code for the xfer optimization but also
  92987. ** does a test to see if the destination table is empty and jumps over the
  92988. ** xfer optimization code if the test fails. In that case, this routine
  92989. ** returns FALSE so that the caller will know to go ahead and generate
  92990. ** an unoptimized transfer. This routine also returns FALSE if there
  92991. ** is no chance that the xfer optimization can be applied.
  92992. **
  92993. ** This optimization is particularly useful at making VACUUM run faster.
  92994. */
  92995. static int xferOptimization(
  92996. Parse *pParse, /* Parser context */
  92997. Table *pDest, /* The table we are inserting into */
  92998. Select *pSelect, /* A SELECT statement to use as the data source */
  92999. int onError, /* How to handle constraint errors */
  93000. int iDbDest /* The database of pDest */
  93001. ){
  93002. ExprList *pEList; /* The result set of the SELECT */
  93003. Table *pSrc; /* The table in the FROM clause of SELECT */
  93004. Index *pSrcIdx, *pDestIdx; /* Source and destination indices */
  93005. struct SrcList_item *pItem; /* An element of pSelect->pSrc */
  93006. int i; /* Loop counter */
  93007. int iDbSrc; /* The database of pSrc */
  93008. int iSrc, iDest; /* Cursors from source and destination */
  93009. int addr1, addr2; /* Loop addresses */
  93010. int emptyDestTest = 0; /* Address of test for empty pDest */
  93011. int emptySrcTest = 0; /* Address of test for empty pSrc */
  93012. Vdbe *v; /* The VDBE we are building */
  93013. int regAutoinc; /* Memory register used by AUTOINC */
  93014. int destHasUniqueIdx = 0; /* True if pDest has a UNIQUE index */
  93015. int regData, regRowid; /* Registers holding data and rowid */
  93016. if( pSelect==0 ){
  93017. return 0; /* Must be of the form INSERT INTO ... SELECT ... */
  93018. }
  93019. if( pParse->pWith || pSelect->pWith ){
  93020. /* Do not attempt to process this query if there are an WITH clauses
  93021. ** attached to it. Proceeding may generate a false "no such table: xxx"
  93022. ** error if pSelect reads from a CTE named "xxx". */
  93023. return 0;
  93024. }
  93025. if( sqlite3TriggerList(pParse, pDest) ){
  93026. return 0; /* tab1 must not have triggers */
  93027. }
  93028. #ifndef SQLITE_OMIT_VIRTUALTABLE
  93029. if( pDest->tabFlags & TF_Virtual ){
  93030. return 0; /* tab1 must not be a virtual table */
  93031. }
  93032. #endif
  93033. if( onError==OE_Default ){
  93034. if( pDest->iPKey>=0 ) onError = pDest->keyConf;
  93035. if( onError==OE_Default ) onError = OE_Abort;
  93036. }
  93037. assert(pSelect->pSrc); /* allocated even if there is no FROM clause */
  93038. if( pSelect->pSrc->nSrc!=1 ){
  93039. return 0; /* FROM clause must have exactly one term */
  93040. }
  93041. if( pSelect->pSrc->a[0].pSelect ){
  93042. return 0; /* FROM clause cannot contain a subquery */
  93043. }
  93044. if( pSelect->pWhere ){
  93045. return 0; /* SELECT may not have a WHERE clause */
  93046. }
  93047. if( pSelect->pOrderBy ){
  93048. return 0; /* SELECT may not have an ORDER BY clause */
  93049. }
  93050. /* Do not need to test for a HAVING clause. If HAVING is present but
  93051. ** there is no ORDER BY, we will get an error. */
  93052. if( pSelect->pGroupBy ){
  93053. return 0; /* SELECT may not have a GROUP BY clause */
  93054. }
  93055. if( pSelect->pLimit ){
  93056. return 0; /* SELECT may not have a LIMIT clause */
  93057. }
  93058. assert( pSelect->pOffset==0 ); /* Must be so if pLimit==0 */
  93059. if( pSelect->pPrior ){
  93060. return 0; /* SELECT may not be a compound query */
  93061. }
  93062. if( pSelect->selFlags & SF_Distinct ){
  93063. return 0; /* SELECT may not be DISTINCT */
  93064. }
  93065. pEList = pSelect->pEList;
  93066. assert( pEList!=0 );
  93067. if( pEList->nExpr!=1 ){
  93068. return 0; /* The result set must have exactly one column */
  93069. }
  93070. assert( pEList->a[0].pExpr );
  93071. if( pEList->a[0].pExpr->op!=TK_ALL ){
  93072. return 0; /* The result set must be the special operator "*" */
  93073. }
  93074. /* At this point we have established that the statement is of the
  93075. ** correct syntactic form to participate in this optimization. Now
  93076. ** we have to check the semantics.
  93077. */
  93078. pItem = pSelect->pSrc->a;
  93079. pSrc = sqlite3LocateTableItem(pParse, 0, pItem);
  93080. if( pSrc==0 ){
  93081. return 0; /* FROM clause does not contain a real table */
  93082. }
  93083. if( pSrc==pDest ){
  93084. return 0; /* tab1 and tab2 may not be the same table */
  93085. }
  93086. if( HasRowid(pDest)!=HasRowid(pSrc) ){
  93087. return 0; /* source and destination must both be WITHOUT ROWID or not */
  93088. }
  93089. #ifndef SQLITE_OMIT_VIRTUALTABLE
  93090. if( pSrc->tabFlags & TF_Virtual ){
  93091. return 0; /* tab2 must not be a virtual table */
  93092. }
  93093. #endif
  93094. if( pSrc->pSelect ){
  93095. return 0; /* tab2 may not be a view */
  93096. }
  93097. if( pDest->nCol!=pSrc->nCol ){
  93098. return 0; /* Number of columns must be the same in tab1 and tab2 */
  93099. }
  93100. if( pDest->iPKey!=pSrc->iPKey ){
  93101. return 0; /* Both tables must have the same INTEGER PRIMARY KEY */
  93102. }
  93103. for(i=0; i<pDest->nCol; i++){
  93104. Column *pDestCol = &pDest->aCol[i];
  93105. Column *pSrcCol = &pSrc->aCol[i];
  93106. if( pDestCol->affinity!=pSrcCol->affinity ){
  93107. return 0; /* Affinity must be the same on all columns */
  93108. }
  93109. if( !xferCompatibleCollation(pDestCol->zColl, pSrcCol->zColl) ){
  93110. return 0; /* Collating sequence must be the same on all columns */
  93111. }
  93112. if( pDestCol->notNull && !pSrcCol->notNull ){
  93113. return 0; /* tab2 must be NOT NULL if tab1 is */
  93114. }
  93115. /* Default values for second and subsequent columns need to match. */
  93116. if( i>0
  93117. && ((pDestCol->zDflt==0)!=(pSrcCol->zDflt==0)
  93118. || (pDestCol->zDflt && strcmp(pDestCol->zDflt, pSrcCol->zDflt)!=0))
  93119. ){
  93120. return 0; /* Default values must be the same for all columns */
  93121. }
  93122. }
  93123. for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
  93124. if( IsUniqueIndex(pDestIdx) ){
  93125. destHasUniqueIdx = 1;
  93126. }
  93127. for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
  93128. if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
  93129. }
  93130. if( pSrcIdx==0 ){
  93131. return 0; /* pDestIdx has no corresponding index in pSrc */
  93132. }
  93133. }
  93134. #ifndef SQLITE_OMIT_CHECK
  93135. if( pDest->pCheck && sqlite3ExprListCompare(pSrc->pCheck,pDest->pCheck,-1) ){
  93136. return 0; /* Tables have different CHECK constraints. Ticket #2252 */
  93137. }
  93138. #endif
  93139. #ifndef SQLITE_OMIT_FOREIGN_KEY
  93140. /* Disallow the transfer optimization if the destination table constains
  93141. ** any foreign key constraints. This is more restrictive than necessary.
  93142. ** But the main beneficiary of the transfer optimization is the VACUUM
  93143. ** command, and the VACUUM command disables foreign key constraints. So
  93144. ** the extra complication to make this rule less restrictive is probably
  93145. ** not worth the effort. Ticket [6284df89debdfa61db8073e062908af0c9b6118e]
  93146. */
  93147. if( (pParse->db->flags & SQLITE_ForeignKeys)!=0 && pDest->pFKey!=0 ){
  93148. return 0;
  93149. }
  93150. #endif
  93151. if( (pParse->db->flags & SQLITE_CountRows)!=0 ){
  93152. return 0; /* xfer opt does not play well with PRAGMA count_changes */
  93153. }
  93154. /* If we get this far, it means that the xfer optimization is at
  93155. ** least a possibility, though it might only work if the destination
  93156. ** table (tab1) is initially empty.
  93157. */
  93158. #ifdef SQLITE_TEST
  93159. sqlite3_xferopt_count++;
  93160. #endif
  93161. iDbSrc = sqlite3SchemaToIndex(pParse->db, pSrc->pSchema);
  93162. v = sqlite3GetVdbe(pParse);
  93163. sqlite3CodeVerifySchema(pParse, iDbSrc);
  93164. iSrc = pParse->nTab++;
  93165. iDest = pParse->nTab++;
  93166. regAutoinc = autoIncBegin(pParse, iDbDest, pDest);
  93167. regData = sqlite3GetTempReg(pParse);
  93168. regRowid = sqlite3GetTempReg(pParse);
  93169. sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
  93170. assert( HasRowid(pDest) || destHasUniqueIdx );
  93171. if( (pDest->iPKey<0 && pDest->pIndex!=0) /* (1) */
  93172. || destHasUniqueIdx /* (2) */
  93173. || (onError!=OE_Abort && onError!=OE_Rollback) /* (3) */
  93174. ){
  93175. /* In some circumstances, we are able to run the xfer optimization
  93176. ** only if the destination table is initially empty. This code makes
  93177. ** that determination. Conditions under which the destination must
  93178. ** be empty:
  93179. **
  93180. ** (1) There is no INTEGER PRIMARY KEY but there are indices.
  93181. ** (If the destination is not initially empty, the rowid fields
  93182. ** of index entries might need to change.)
  93183. **
  93184. ** (2) The destination has a unique index. (The xfer optimization
  93185. ** is unable to test uniqueness.)
  93186. **
  93187. ** (3) onError is something other than OE_Abort and OE_Rollback.
  93188. */
  93189. addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0); VdbeCoverage(v);
  93190. emptyDestTest = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
  93191. sqlite3VdbeJumpHere(v, addr1);
  93192. }
  93193. if( HasRowid(pSrc) ){
  93194. sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
  93195. emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v);
  93196. if( pDest->iPKey>=0 ){
  93197. addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
  93198. addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid);
  93199. VdbeCoverage(v);
  93200. sqlite3RowidConstraint(pParse, onError, pDest);
  93201. sqlite3VdbeJumpHere(v, addr2);
  93202. autoIncStep(pParse, regAutoinc, regRowid);
  93203. }else if( pDest->pIndex==0 ){
  93204. addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid);
  93205. }else{
  93206. addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
  93207. assert( (pDest->tabFlags & TF_Autoincrement)==0 );
  93208. }
  93209. sqlite3VdbeAddOp2(v, OP_RowData, iSrc, regData);
  93210. sqlite3VdbeAddOp3(v, OP_Insert, iDest, regData, regRowid);
  93211. sqlite3VdbeChangeP5(v, OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND);
  93212. sqlite3VdbeChangeP4(v, -1, pDest->zName, 0);
  93213. sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1); VdbeCoverage(v);
  93214. sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
  93215. sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
  93216. }else{
  93217. sqlite3TableLock(pParse, iDbDest, pDest->tnum, 1, pDest->zName);
  93218. sqlite3TableLock(pParse, iDbSrc, pSrc->tnum, 0, pSrc->zName);
  93219. }
  93220. for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
  93221. for(pSrcIdx=pSrc->pIndex; ALWAYS(pSrcIdx); pSrcIdx=pSrcIdx->pNext){
  93222. if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
  93223. }
  93224. assert( pSrcIdx );
  93225. sqlite3VdbeAddOp3(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc);
  93226. sqlite3VdbeSetP4KeyInfo(pParse, pSrcIdx);
  93227. VdbeComment((v, "%s", pSrcIdx->zName));
  93228. sqlite3VdbeAddOp3(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest);
  93229. sqlite3VdbeSetP4KeyInfo(pParse, pDestIdx);
  93230. sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR);
  93231. VdbeComment((v, "%s", pDestIdx->zName));
  93232. addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v);
  93233. sqlite3VdbeAddOp2(v, OP_RowKey, iSrc, regData);
  93234. sqlite3VdbeAddOp3(v, OP_IdxInsert, iDest, regData, 1);
  93235. sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1); VdbeCoverage(v);
  93236. sqlite3VdbeJumpHere(v, addr1);
  93237. sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
  93238. sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
  93239. }
  93240. if( emptySrcTest ) sqlite3VdbeJumpHere(v, emptySrcTest);
  93241. sqlite3ReleaseTempReg(pParse, regRowid);
  93242. sqlite3ReleaseTempReg(pParse, regData);
  93243. if( emptyDestTest ){
  93244. sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0);
  93245. sqlite3VdbeJumpHere(v, emptyDestTest);
  93246. sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
  93247. return 0;
  93248. }else{
  93249. return 1;
  93250. }
  93251. }
  93252. #endif /* SQLITE_OMIT_XFER_OPT */
  93253. /************** End of insert.c **********************************************/
  93254. /************** Begin file legacy.c ******************************************/
  93255. /*
  93256. ** 2001 September 15
  93257. **
  93258. ** The author disclaims copyright to this source code. In place of
  93259. ** a legal notice, here is a blessing:
  93260. **
  93261. ** May you do good and not evil.
  93262. ** May you find forgiveness for yourself and forgive others.
  93263. ** May you share freely, never taking more than you give.
  93264. **
  93265. *************************************************************************
  93266. ** Main file for the SQLite library. The routines in this file
  93267. ** implement the programmer interface to the library. Routines in
  93268. ** other files are for internal use by SQLite and should not be
  93269. ** accessed by users of the library.
  93270. */
  93271. /*
  93272. ** Execute SQL code. Return one of the SQLITE_ success/failure
  93273. ** codes. Also write an error message into memory obtained from
  93274. ** malloc() and make *pzErrMsg point to that message.
  93275. **
  93276. ** If the SQL is a query, then for each row in the query result
  93277. ** the xCallback() function is called. pArg becomes the first
  93278. ** argument to xCallback(). If xCallback=NULL then no callback
  93279. ** is invoked, even for queries.
  93280. */
  93281. SQLITE_API int sqlite3_exec(
  93282. sqlite3 *db, /* The database on which the SQL executes */
  93283. const char *zSql, /* The SQL to be executed */
  93284. sqlite3_callback xCallback, /* Invoke this callback routine */
  93285. void *pArg, /* First argument to xCallback() */
  93286. char **pzErrMsg /* Write error messages here */
  93287. ){
  93288. int rc = SQLITE_OK; /* Return code */
  93289. const char *zLeftover; /* Tail of unprocessed SQL */
  93290. sqlite3_stmt *pStmt = 0; /* The current SQL statement */
  93291. char **azCols = 0; /* Names of result columns */
  93292. int callbackIsInit; /* True if callback data is initialized */
  93293. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  93294. if( zSql==0 ) zSql = "";
  93295. sqlite3_mutex_enter(db->mutex);
  93296. sqlite3Error(db, SQLITE_OK);
  93297. while( rc==SQLITE_OK && zSql[0] ){
  93298. int nCol;
  93299. char **azVals = 0;
  93300. pStmt = 0;
  93301. rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover);
  93302. assert( rc==SQLITE_OK || pStmt==0 );
  93303. if( rc!=SQLITE_OK ){
  93304. continue;
  93305. }
  93306. if( !pStmt ){
  93307. /* this happens for a comment or white-space */
  93308. zSql = zLeftover;
  93309. continue;
  93310. }
  93311. callbackIsInit = 0;
  93312. nCol = sqlite3_column_count(pStmt);
  93313. while( 1 ){
  93314. int i;
  93315. rc = sqlite3_step(pStmt);
  93316. /* Invoke the callback function if required */
  93317. if( xCallback && (SQLITE_ROW==rc ||
  93318. (SQLITE_DONE==rc && !callbackIsInit
  93319. && db->flags&SQLITE_NullCallback)) ){
  93320. if( !callbackIsInit ){
  93321. azCols = sqlite3DbMallocZero(db, 2*nCol*sizeof(const char*) + 1);
  93322. if( azCols==0 ){
  93323. goto exec_out;
  93324. }
  93325. for(i=0; i<nCol; i++){
  93326. azCols[i] = (char *)sqlite3_column_name(pStmt, i);
  93327. /* sqlite3VdbeSetColName() installs column names as UTF8
  93328. ** strings so there is no way for sqlite3_column_name() to fail. */
  93329. assert( azCols[i]!=0 );
  93330. }
  93331. callbackIsInit = 1;
  93332. }
  93333. if( rc==SQLITE_ROW ){
  93334. azVals = &azCols[nCol];
  93335. for(i=0; i<nCol; i++){
  93336. azVals[i] = (char *)sqlite3_column_text(pStmt, i);
  93337. if( !azVals[i] && sqlite3_column_type(pStmt, i)!=SQLITE_NULL ){
  93338. db->mallocFailed = 1;
  93339. goto exec_out;
  93340. }
  93341. }
  93342. }
  93343. if( xCallback(pArg, nCol, azVals, azCols) ){
  93344. /* EVIDENCE-OF: R-38229-40159 If the callback function to
  93345. ** sqlite3_exec() returns non-zero, then sqlite3_exec() will
  93346. ** return SQLITE_ABORT. */
  93347. rc = SQLITE_ABORT;
  93348. sqlite3VdbeFinalize((Vdbe *)pStmt);
  93349. pStmt = 0;
  93350. sqlite3Error(db, SQLITE_ABORT);
  93351. goto exec_out;
  93352. }
  93353. }
  93354. if( rc!=SQLITE_ROW ){
  93355. rc = sqlite3VdbeFinalize((Vdbe *)pStmt);
  93356. pStmt = 0;
  93357. zSql = zLeftover;
  93358. while( sqlite3Isspace(zSql[0]) ) zSql++;
  93359. break;
  93360. }
  93361. }
  93362. sqlite3DbFree(db, azCols);
  93363. azCols = 0;
  93364. }
  93365. exec_out:
  93366. if( pStmt ) sqlite3VdbeFinalize((Vdbe *)pStmt);
  93367. sqlite3DbFree(db, azCols);
  93368. rc = sqlite3ApiExit(db, rc);
  93369. if( rc!=SQLITE_OK && pzErrMsg ){
  93370. int nErrMsg = 1 + sqlite3Strlen30(sqlite3_errmsg(db));
  93371. *pzErrMsg = sqlite3Malloc(nErrMsg);
  93372. if( *pzErrMsg ){
  93373. memcpy(*pzErrMsg, sqlite3_errmsg(db), nErrMsg);
  93374. }else{
  93375. rc = SQLITE_NOMEM;
  93376. sqlite3Error(db, SQLITE_NOMEM);
  93377. }
  93378. }else if( pzErrMsg ){
  93379. *pzErrMsg = 0;
  93380. }
  93381. assert( (rc&db->errMask)==rc );
  93382. sqlite3_mutex_leave(db->mutex);
  93383. return rc;
  93384. }
  93385. /************** End of legacy.c **********************************************/
  93386. /************** Begin file loadext.c *****************************************/
  93387. /*
  93388. ** 2006 June 7
  93389. **
  93390. ** The author disclaims copyright to this source code. In place of
  93391. ** a legal notice, here is a blessing:
  93392. **
  93393. ** May you do good and not evil.
  93394. ** May you find forgiveness for yourself and forgive others.
  93395. ** May you share freely, never taking more than you give.
  93396. **
  93397. *************************************************************************
  93398. ** This file contains code used to dynamically load extensions into
  93399. ** the SQLite library.
  93400. */
  93401. #ifndef SQLITE_CORE
  93402. #define SQLITE_CORE 1 /* Disable the API redefinition in sqlite3ext.h */
  93403. #endif
  93404. /************** Include sqlite3ext.h in the middle of loadext.c **************/
  93405. /************** Begin file sqlite3ext.h **************************************/
  93406. /*
  93407. ** 2006 June 7
  93408. **
  93409. ** The author disclaims copyright to this source code. In place of
  93410. ** a legal notice, here is a blessing:
  93411. **
  93412. ** May you do good and not evil.
  93413. ** May you find forgiveness for yourself and forgive others.
  93414. ** May you share freely, never taking more than you give.
  93415. **
  93416. *************************************************************************
  93417. ** This header file defines the SQLite interface for use by
  93418. ** shared libraries that want to be imported as extensions into
  93419. ** an SQLite instance. Shared libraries that intend to be loaded
  93420. ** as extensions by SQLite should #include this file instead of
  93421. ** sqlite3.h.
  93422. */
  93423. #ifndef _SQLITE3EXT_H_
  93424. #define _SQLITE3EXT_H_
  93425. typedef struct sqlite3_api_routines sqlite3_api_routines;
  93426. /*
  93427. ** The following structure holds pointers to all of the SQLite API
  93428. ** routines.
  93429. **
  93430. ** WARNING: In order to maintain backwards compatibility, add new
  93431. ** interfaces to the end of this structure only. If you insert new
  93432. ** interfaces in the middle of this structure, then older different
  93433. ** versions of SQLite will not be able to load each other's shared
  93434. ** libraries!
  93435. */
  93436. struct sqlite3_api_routines {
  93437. void * (*aggregate_context)(sqlite3_context*,int nBytes);
  93438. int (*aggregate_count)(sqlite3_context*);
  93439. int (*bind_blob)(sqlite3_stmt*,int,const void*,int n,void(*)(void*));
  93440. int (*bind_double)(sqlite3_stmt*,int,double);
  93441. int (*bind_int)(sqlite3_stmt*,int,int);
  93442. int (*bind_int64)(sqlite3_stmt*,int,sqlite_int64);
  93443. int (*bind_null)(sqlite3_stmt*,int);
  93444. int (*bind_parameter_count)(sqlite3_stmt*);
  93445. int (*bind_parameter_index)(sqlite3_stmt*,const char*zName);
  93446. const char * (*bind_parameter_name)(sqlite3_stmt*,int);
  93447. int (*bind_text)(sqlite3_stmt*,int,const char*,int n,void(*)(void*));
  93448. int (*bind_text16)(sqlite3_stmt*,int,const void*,int,void(*)(void*));
  93449. int (*bind_value)(sqlite3_stmt*,int,const sqlite3_value*);
  93450. int (*busy_handler)(sqlite3*,int(*)(void*,int),void*);
  93451. int (*busy_timeout)(sqlite3*,int ms);
  93452. int (*changes)(sqlite3*);
  93453. int (*close)(sqlite3*);
  93454. int (*collation_needed)(sqlite3*,void*,void(*)(void*,sqlite3*,
  93455. int eTextRep,const char*));
  93456. int (*collation_needed16)(sqlite3*,void*,void(*)(void*,sqlite3*,
  93457. int eTextRep,const void*));
  93458. const void * (*column_blob)(sqlite3_stmt*,int iCol);
  93459. int (*column_bytes)(sqlite3_stmt*,int iCol);
  93460. int (*column_bytes16)(sqlite3_stmt*,int iCol);
  93461. int (*column_count)(sqlite3_stmt*pStmt);
  93462. const char * (*column_database_name)(sqlite3_stmt*,int);
  93463. const void * (*column_database_name16)(sqlite3_stmt*,int);
  93464. const char * (*column_decltype)(sqlite3_stmt*,int i);
  93465. const void * (*column_decltype16)(sqlite3_stmt*,int);
  93466. double (*column_double)(sqlite3_stmt*,int iCol);
  93467. int (*column_int)(sqlite3_stmt*,int iCol);
  93468. sqlite_int64 (*column_int64)(sqlite3_stmt*,int iCol);
  93469. const char * (*column_name)(sqlite3_stmt*,int);
  93470. const void * (*column_name16)(sqlite3_stmt*,int);
  93471. const char * (*column_origin_name)(sqlite3_stmt*,int);
  93472. const void * (*column_origin_name16)(sqlite3_stmt*,int);
  93473. const char * (*column_table_name)(sqlite3_stmt*,int);
  93474. const void * (*column_table_name16)(sqlite3_stmt*,int);
  93475. const unsigned char * (*column_text)(sqlite3_stmt*,int iCol);
  93476. const void * (*column_text16)(sqlite3_stmt*,int iCol);
  93477. int (*column_type)(sqlite3_stmt*,int iCol);
  93478. sqlite3_value* (*column_value)(sqlite3_stmt*,int iCol);
  93479. void * (*commit_hook)(sqlite3*,int(*)(void*),void*);
  93480. int (*complete)(const char*sql);
  93481. int (*complete16)(const void*sql);
  93482. int (*create_collation)(sqlite3*,const char*,int,void*,
  93483. int(*)(void*,int,const void*,int,const void*));
  93484. int (*create_collation16)(sqlite3*,const void*,int,void*,
  93485. int(*)(void*,int,const void*,int,const void*));
  93486. int (*create_function)(sqlite3*,const char*,int,int,void*,
  93487. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  93488. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  93489. void (*xFinal)(sqlite3_context*));
  93490. int (*create_function16)(sqlite3*,const void*,int,int,void*,
  93491. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  93492. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  93493. void (*xFinal)(sqlite3_context*));
  93494. int (*create_module)(sqlite3*,const char*,const sqlite3_module*,void*);
  93495. int (*data_count)(sqlite3_stmt*pStmt);
  93496. sqlite3 * (*db_handle)(sqlite3_stmt*);
  93497. int (*declare_vtab)(sqlite3*,const char*);
  93498. int (*enable_shared_cache)(int);
  93499. int (*errcode)(sqlite3*db);
  93500. const char * (*errmsg)(sqlite3*);
  93501. const void * (*errmsg16)(sqlite3*);
  93502. int (*exec)(sqlite3*,const char*,sqlite3_callback,void*,char**);
  93503. int (*expired)(sqlite3_stmt*);
  93504. int (*finalize)(sqlite3_stmt*pStmt);
  93505. void (*free)(void*);
  93506. void (*free_table)(char**result);
  93507. int (*get_autocommit)(sqlite3*);
  93508. void * (*get_auxdata)(sqlite3_context*,int);
  93509. int (*get_table)(sqlite3*,const char*,char***,int*,int*,char**);
  93510. int (*global_recover)(void);
  93511. void (*interruptx)(sqlite3*);
  93512. sqlite_int64 (*last_insert_rowid)(sqlite3*);
  93513. const char * (*libversion)(void);
  93514. int (*libversion_number)(void);
  93515. void *(*malloc)(int);
  93516. char * (*mprintf)(const char*,...);
  93517. int (*open)(const char*,sqlite3**);
  93518. int (*open16)(const void*,sqlite3**);
  93519. int (*prepare)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
  93520. int (*prepare16)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
  93521. void * (*profile)(sqlite3*,void(*)(void*,const char*,sqlite_uint64),void*);
  93522. void (*progress_handler)(sqlite3*,int,int(*)(void*),void*);
  93523. void *(*realloc)(void*,int);
  93524. int (*reset)(sqlite3_stmt*pStmt);
  93525. void (*result_blob)(sqlite3_context*,const void*,int,void(*)(void*));
  93526. void (*result_double)(sqlite3_context*,double);
  93527. void (*result_error)(sqlite3_context*,const char*,int);
  93528. void (*result_error16)(sqlite3_context*,const void*,int);
  93529. void (*result_int)(sqlite3_context*,int);
  93530. void (*result_int64)(sqlite3_context*,sqlite_int64);
  93531. void (*result_null)(sqlite3_context*);
  93532. void (*result_text)(sqlite3_context*,const char*,int,void(*)(void*));
  93533. void (*result_text16)(sqlite3_context*,const void*,int,void(*)(void*));
  93534. void (*result_text16be)(sqlite3_context*,const void*,int,void(*)(void*));
  93535. void (*result_text16le)(sqlite3_context*,const void*,int,void(*)(void*));
  93536. void (*result_value)(sqlite3_context*,sqlite3_value*);
  93537. void * (*rollback_hook)(sqlite3*,void(*)(void*),void*);
  93538. int (*set_authorizer)(sqlite3*,int(*)(void*,int,const char*,const char*,
  93539. const char*,const char*),void*);
  93540. void (*set_auxdata)(sqlite3_context*,int,void*,void (*)(void*));
  93541. char * (*snprintf)(int,char*,const char*,...);
  93542. int (*step)(sqlite3_stmt*);
  93543. int (*table_column_metadata)(sqlite3*,const char*,const char*,const char*,
  93544. char const**,char const**,int*,int*,int*);
  93545. void (*thread_cleanup)(void);
  93546. int (*total_changes)(sqlite3*);
  93547. void * (*trace)(sqlite3*,void(*xTrace)(void*,const char*),void*);
  93548. int (*transfer_bindings)(sqlite3_stmt*,sqlite3_stmt*);
  93549. void * (*update_hook)(sqlite3*,void(*)(void*,int ,char const*,char const*,
  93550. sqlite_int64),void*);
  93551. void * (*user_data)(sqlite3_context*);
  93552. const void * (*value_blob)(sqlite3_value*);
  93553. int (*value_bytes)(sqlite3_value*);
  93554. int (*value_bytes16)(sqlite3_value*);
  93555. double (*value_double)(sqlite3_value*);
  93556. int (*value_int)(sqlite3_value*);
  93557. sqlite_int64 (*value_int64)(sqlite3_value*);
  93558. int (*value_numeric_type)(sqlite3_value*);
  93559. const unsigned char * (*value_text)(sqlite3_value*);
  93560. const void * (*value_text16)(sqlite3_value*);
  93561. const void * (*value_text16be)(sqlite3_value*);
  93562. const void * (*value_text16le)(sqlite3_value*);
  93563. int (*value_type)(sqlite3_value*);
  93564. char *(*vmprintf)(const char*,va_list);
  93565. /* Added ??? */
  93566. int (*overload_function)(sqlite3*, const char *zFuncName, int nArg);
  93567. /* Added by 3.3.13 */
  93568. int (*prepare_v2)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
  93569. int (*prepare16_v2)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
  93570. int (*clear_bindings)(sqlite3_stmt*);
  93571. /* Added by 3.4.1 */
  93572. int (*create_module_v2)(sqlite3*,const char*,const sqlite3_module*,void*,
  93573. void (*xDestroy)(void *));
  93574. /* Added by 3.5.0 */
  93575. int (*bind_zeroblob)(sqlite3_stmt*,int,int);
  93576. int (*blob_bytes)(sqlite3_blob*);
  93577. int (*blob_close)(sqlite3_blob*);
  93578. int (*blob_open)(sqlite3*,const char*,const char*,const char*,sqlite3_int64,
  93579. int,sqlite3_blob**);
  93580. int (*blob_read)(sqlite3_blob*,void*,int,int);
  93581. int (*blob_write)(sqlite3_blob*,const void*,int,int);
  93582. int (*create_collation_v2)(sqlite3*,const char*,int,void*,
  93583. int(*)(void*,int,const void*,int,const void*),
  93584. void(*)(void*));
  93585. int (*file_control)(sqlite3*,const char*,int,void*);
  93586. sqlite3_int64 (*memory_highwater)(int);
  93587. sqlite3_int64 (*memory_used)(void);
  93588. sqlite3_mutex *(*mutex_alloc)(int);
  93589. void (*mutex_enter)(sqlite3_mutex*);
  93590. void (*mutex_free)(sqlite3_mutex*);
  93591. void (*mutex_leave)(sqlite3_mutex*);
  93592. int (*mutex_try)(sqlite3_mutex*);
  93593. int (*open_v2)(const char*,sqlite3**,int,const char*);
  93594. int (*release_memory)(int);
  93595. void (*result_error_nomem)(sqlite3_context*);
  93596. void (*result_error_toobig)(sqlite3_context*);
  93597. int (*sleep)(int);
  93598. void (*soft_heap_limit)(int);
  93599. sqlite3_vfs *(*vfs_find)(const char*);
  93600. int (*vfs_register)(sqlite3_vfs*,int);
  93601. int (*vfs_unregister)(sqlite3_vfs*);
  93602. int (*xthreadsafe)(void);
  93603. void (*result_zeroblob)(sqlite3_context*,int);
  93604. void (*result_error_code)(sqlite3_context*,int);
  93605. int (*test_control)(int, ...);
  93606. void (*randomness)(int,void*);
  93607. sqlite3 *(*context_db_handle)(sqlite3_context*);
  93608. int (*extended_result_codes)(sqlite3*,int);
  93609. int (*limit)(sqlite3*,int,int);
  93610. sqlite3_stmt *(*next_stmt)(sqlite3*,sqlite3_stmt*);
  93611. const char *(*sql)(sqlite3_stmt*);
  93612. int (*status)(int,int*,int*,int);
  93613. int (*backup_finish)(sqlite3_backup*);
  93614. sqlite3_backup *(*backup_init)(sqlite3*,const char*,sqlite3*,const char*);
  93615. int (*backup_pagecount)(sqlite3_backup*);
  93616. int (*backup_remaining)(sqlite3_backup*);
  93617. int (*backup_step)(sqlite3_backup*,int);
  93618. const char *(*compileoption_get)(int);
  93619. int (*compileoption_used)(const char*);
  93620. int (*create_function_v2)(sqlite3*,const char*,int,int,void*,
  93621. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  93622. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  93623. void (*xFinal)(sqlite3_context*),
  93624. void(*xDestroy)(void*));
  93625. int (*db_config)(sqlite3*,int,...);
  93626. sqlite3_mutex *(*db_mutex)(sqlite3*);
  93627. int (*db_status)(sqlite3*,int,int*,int*,int);
  93628. int (*extended_errcode)(sqlite3*);
  93629. void (*log)(int,const char*,...);
  93630. sqlite3_int64 (*soft_heap_limit64)(sqlite3_int64);
  93631. const char *(*sourceid)(void);
  93632. int (*stmt_status)(sqlite3_stmt*,int,int);
  93633. int (*strnicmp)(const char*,const char*,int);
  93634. int (*unlock_notify)(sqlite3*,void(*)(void**,int),void*);
  93635. int (*wal_autocheckpoint)(sqlite3*,int);
  93636. int (*wal_checkpoint)(sqlite3*,const char*);
  93637. void *(*wal_hook)(sqlite3*,int(*)(void*,sqlite3*,const char*,int),void*);
  93638. int (*blob_reopen)(sqlite3_blob*,sqlite3_int64);
  93639. int (*vtab_config)(sqlite3*,int op,...);
  93640. int (*vtab_on_conflict)(sqlite3*);
  93641. /* Version 3.7.16 and later */
  93642. int (*close_v2)(sqlite3*);
  93643. const char *(*db_filename)(sqlite3*,const char*);
  93644. int (*db_readonly)(sqlite3*,const char*);
  93645. int (*db_release_memory)(sqlite3*);
  93646. const char *(*errstr)(int);
  93647. int (*stmt_busy)(sqlite3_stmt*);
  93648. int (*stmt_readonly)(sqlite3_stmt*);
  93649. int (*stricmp)(const char*,const char*);
  93650. int (*uri_boolean)(const char*,const char*,int);
  93651. sqlite3_int64 (*uri_int64)(const char*,const char*,sqlite3_int64);
  93652. const char *(*uri_parameter)(const char*,const char*);
  93653. char *(*vsnprintf)(int,char*,const char*,va_list);
  93654. int (*wal_checkpoint_v2)(sqlite3*,const char*,int,int*,int*);
  93655. /* Version 3.8.7 and later */
  93656. int (*auto_extension)(void(*)(void));
  93657. int (*bind_blob64)(sqlite3_stmt*,int,const void*,sqlite3_uint64,
  93658. void(*)(void*));
  93659. int (*bind_text64)(sqlite3_stmt*,int,const char*,sqlite3_uint64,
  93660. void(*)(void*),unsigned char);
  93661. int (*cancel_auto_extension)(void(*)(void));
  93662. int (*load_extension)(sqlite3*,const char*,const char*,char**);
  93663. void *(*malloc64)(sqlite3_uint64);
  93664. sqlite3_uint64 (*msize)(void*);
  93665. void *(*realloc64)(void*,sqlite3_uint64);
  93666. void (*reset_auto_extension)(void);
  93667. void (*result_blob64)(sqlite3_context*,const void*,sqlite3_uint64,
  93668. void(*)(void*));
  93669. void (*result_text64)(sqlite3_context*,const char*,sqlite3_uint64,
  93670. void(*)(void*), unsigned char);
  93671. int (*strglob)(const char*,const char*);
  93672. };
  93673. /*
  93674. ** The following macros redefine the API routines so that they are
  93675. ** redirected through the global sqlite3_api structure.
  93676. **
  93677. ** This header file is also used by the loadext.c source file
  93678. ** (part of the main SQLite library - not an extension) so that
  93679. ** it can get access to the sqlite3_api_routines structure
  93680. ** definition. But the main library does not want to redefine
  93681. ** the API. So the redefinition macros are only valid if the
  93682. ** SQLITE_CORE macros is undefined.
  93683. */
  93684. #ifndef SQLITE_CORE
  93685. #define sqlite3_aggregate_context sqlite3_api->aggregate_context
  93686. #ifndef SQLITE_OMIT_DEPRECATED
  93687. #define sqlite3_aggregate_count sqlite3_api->aggregate_count
  93688. #endif
  93689. #define sqlite3_bind_blob sqlite3_api->bind_blob
  93690. #define sqlite3_bind_double sqlite3_api->bind_double
  93691. #define sqlite3_bind_int sqlite3_api->bind_int
  93692. #define sqlite3_bind_int64 sqlite3_api->bind_int64
  93693. #define sqlite3_bind_null sqlite3_api->bind_null
  93694. #define sqlite3_bind_parameter_count sqlite3_api->bind_parameter_count
  93695. #define sqlite3_bind_parameter_index sqlite3_api->bind_parameter_index
  93696. #define sqlite3_bind_parameter_name sqlite3_api->bind_parameter_name
  93697. #define sqlite3_bind_text sqlite3_api->bind_text
  93698. #define sqlite3_bind_text16 sqlite3_api->bind_text16
  93699. #define sqlite3_bind_value sqlite3_api->bind_value
  93700. #define sqlite3_busy_handler sqlite3_api->busy_handler
  93701. #define sqlite3_busy_timeout sqlite3_api->busy_timeout
  93702. #define sqlite3_changes sqlite3_api->changes
  93703. #define sqlite3_close sqlite3_api->close
  93704. #define sqlite3_collation_needed sqlite3_api->collation_needed
  93705. #define sqlite3_collation_needed16 sqlite3_api->collation_needed16
  93706. #define sqlite3_column_blob sqlite3_api->column_blob
  93707. #define sqlite3_column_bytes sqlite3_api->column_bytes
  93708. #define sqlite3_column_bytes16 sqlite3_api->column_bytes16
  93709. #define sqlite3_column_count sqlite3_api->column_count
  93710. #define sqlite3_column_database_name sqlite3_api->column_database_name
  93711. #define sqlite3_column_database_name16 sqlite3_api->column_database_name16
  93712. #define sqlite3_column_decltype sqlite3_api->column_decltype
  93713. #define sqlite3_column_decltype16 sqlite3_api->column_decltype16
  93714. #define sqlite3_column_double sqlite3_api->column_double
  93715. #define sqlite3_column_int sqlite3_api->column_int
  93716. #define sqlite3_column_int64 sqlite3_api->column_int64
  93717. #define sqlite3_column_name sqlite3_api->column_name
  93718. #define sqlite3_column_name16 sqlite3_api->column_name16
  93719. #define sqlite3_column_origin_name sqlite3_api->column_origin_name
  93720. #define sqlite3_column_origin_name16 sqlite3_api->column_origin_name16
  93721. #define sqlite3_column_table_name sqlite3_api->column_table_name
  93722. #define sqlite3_column_table_name16 sqlite3_api->column_table_name16
  93723. #define sqlite3_column_text sqlite3_api->column_text
  93724. #define sqlite3_column_text16 sqlite3_api->column_text16
  93725. #define sqlite3_column_type sqlite3_api->column_type
  93726. #define sqlite3_column_value sqlite3_api->column_value
  93727. #define sqlite3_commit_hook sqlite3_api->commit_hook
  93728. #define sqlite3_complete sqlite3_api->complete
  93729. #define sqlite3_complete16 sqlite3_api->complete16
  93730. #define sqlite3_create_collation sqlite3_api->create_collation
  93731. #define sqlite3_create_collation16 sqlite3_api->create_collation16
  93732. #define sqlite3_create_function sqlite3_api->create_function
  93733. #define sqlite3_create_function16 sqlite3_api->create_function16
  93734. #define sqlite3_create_module sqlite3_api->create_module
  93735. #define sqlite3_create_module_v2 sqlite3_api->create_module_v2
  93736. #define sqlite3_data_count sqlite3_api->data_count
  93737. #define sqlite3_db_handle sqlite3_api->db_handle
  93738. #define sqlite3_declare_vtab sqlite3_api->declare_vtab
  93739. #define sqlite3_enable_shared_cache sqlite3_api->enable_shared_cache
  93740. #define sqlite3_errcode sqlite3_api->errcode
  93741. #define sqlite3_errmsg sqlite3_api->errmsg
  93742. #define sqlite3_errmsg16 sqlite3_api->errmsg16
  93743. #define sqlite3_exec sqlite3_api->exec
  93744. #ifndef SQLITE_OMIT_DEPRECATED
  93745. #define sqlite3_expired sqlite3_api->expired
  93746. #endif
  93747. #define sqlite3_finalize sqlite3_api->finalize
  93748. #define sqlite3_free sqlite3_api->free
  93749. #define sqlite3_free_table sqlite3_api->free_table
  93750. #define sqlite3_get_autocommit sqlite3_api->get_autocommit
  93751. #define sqlite3_get_auxdata sqlite3_api->get_auxdata
  93752. #define sqlite3_get_table sqlite3_api->get_table
  93753. #ifndef SQLITE_OMIT_DEPRECATED
  93754. #define sqlite3_global_recover sqlite3_api->global_recover
  93755. #endif
  93756. #define sqlite3_interrupt sqlite3_api->interruptx
  93757. #define sqlite3_last_insert_rowid sqlite3_api->last_insert_rowid
  93758. #define sqlite3_libversion sqlite3_api->libversion
  93759. #define sqlite3_libversion_number sqlite3_api->libversion_number
  93760. #define sqlite3_malloc sqlite3_api->malloc
  93761. #define sqlite3_mprintf sqlite3_api->mprintf
  93762. #define sqlite3_open sqlite3_api->open
  93763. #define sqlite3_open16 sqlite3_api->open16
  93764. #define sqlite3_prepare sqlite3_api->prepare
  93765. #define sqlite3_prepare16 sqlite3_api->prepare16
  93766. #define sqlite3_prepare_v2 sqlite3_api->prepare_v2
  93767. #define sqlite3_prepare16_v2 sqlite3_api->prepare16_v2
  93768. #define sqlite3_profile sqlite3_api->profile
  93769. #define sqlite3_progress_handler sqlite3_api->progress_handler
  93770. #define sqlite3_realloc sqlite3_api->realloc
  93771. #define sqlite3_reset sqlite3_api->reset
  93772. #define sqlite3_result_blob sqlite3_api->result_blob
  93773. #define sqlite3_result_double sqlite3_api->result_double
  93774. #define sqlite3_result_error sqlite3_api->result_error
  93775. #define sqlite3_result_error16 sqlite3_api->result_error16
  93776. #define sqlite3_result_int sqlite3_api->result_int
  93777. #define sqlite3_result_int64 sqlite3_api->result_int64
  93778. #define sqlite3_result_null sqlite3_api->result_null
  93779. #define sqlite3_result_text sqlite3_api->result_text
  93780. #define sqlite3_result_text16 sqlite3_api->result_text16
  93781. #define sqlite3_result_text16be sqlite3_api->result_text16be
  93782. #define sqlite3_result_text16le sqlite3_api->result_text16le
  93783. #define sqlite3_result_value sqlite3_api->result_value
  93784. #define sqlite3_rollback_hook sqlite3_api->rollback_hook
  93785. #define sqlite3_set_authorizer sqlite3_api->set_authorizer
  93786. #define sqlite3_set_auxdata sqlite3_api->set_auxdata
  93787. #define sqlite3_snprintf sqlite3_api->snprintf
  93788. #define sqlite3_step sqlite3_api->step
  93789. #define sqlite3_table_column_metadata sqlite3_api->table_column_metadata
  93790. #define sqlite3_thread_cleanup sqlite3_api->thread_cleanup
  93791. #define sqlite3_total_changes sqlite3_api->total_changes
  93792. #define sqlite3_trace sqlite3_api->trace
  93793. #ifndef SQLITE_OMIT_DEPRECATED
  93794. #define sqlite3_transfer_bindings sqlite3_api->transfer_bindings
  93795. #endif
  93796. #define sqlite3_update_hook sqlite3_api->update_hook
  93797. #define sqlite3_user_data sqlite3_api->user_data
  93798. #define sqlite3_value_blob sqlite3_api->value_blob
  93799. #define sqlite3_value_bytes sqlite3_api->value_bytes
  93800. #define sqlite3_value_bytes16 sqlite3_api->value_bytes16
  93801. #define sqlite3_value_double sqlite3_api->value_double
  93802. #define sqlite3_value_int sqlite3_api->value_int
  93803. #define sqlite3_value_int64 sqlite3_api->value_int64
  93804. #define sqlite3_value_numeric_type sqlite3_api->value_numeric_type
  93805. #define sqlite3_value_text sqlite3_api->value_text
  93806. #define sqlite3_value_text16 sqlite3_api->value_text16
  93807. #define sqlite3_value_text16be sqlite3_api->value_text16be
  93808. #define sqlite3_value_text16le sqlite3_api->value_text16le
  93809. #define sqlite3_value_type sqlite3_api->value_type
  93810. #define sqlite3_vmprintf sqlite3_api->vmprintf
  93811. #define sqlite3_overload_function sqlite3_api->overload_function
  93812. #define sqlite3_prepare_v2 sqlite3_api->prepare_v2
  93813. #define sqlite3_prepare16_v2 sqlite3_api->prepare16_v2
  93814. #define sqlite3_clear_bindings sqlite3_api->clear_bindings
  93815. #define sqlite3_bind_zeroblob sqlite3_api->bind_zeroblob
  93816. #define sqlite3_blob_bytes sqlite3_api->blob_bytes
  93817. #define sqlite3_blob_close sqlite3_api->blob_close
  93818. #define sqlite3_blob_open sqlite3_api->blob_open
  93819. #define sqlite3_blob_read sqlite3_api->blob_read
  93820. #define sqlite3_blob_write sqlite3_api->blob_write
  93821. #define sqlite3_create_collation_v2 sqlite3_api->create_collation_v2
  93822. #define sqlite3_file_control sqlite3_api->file_control
  93823. #define sqlite3_memory_highwater sqlite3_api->memory_highwater
  93824. #define sqlite3_memory_used sqlite3_api->memory_used
  93825. #define sqlite3_mutex_alloc sqlite3_api->mutex_alloc
  93826. #define sqlite3_mutex_enter sqlite3_api->mutex_enter
  93827. #define sqlite3_mutex_free sqlite3_api->mutex_free
  93828. #define sqlite3_mutex_leave sqlite3_api->mutex_leave
  93829. #define sqlite3_mutex_try sqlite3_api->mutex_try
  93830. #define sqlite3_open_v2 sqlite3_api->open_v2
  93831. #define sqlite3_release_memory sqlite3_api->release_memory
  93832. #define sqlite3_result_error_nomem sqlite3_api->result_error_nomem
  93833. #define sqlite3_result_error_toobig sqlite3_api->result_error_toobig
  93834. #define sqlite3_sleep sqlite3_api->sleep
  93835. #define sqlite3_soft_heap_limit sqlite3_api->soft_heap_limit
  93836. #define sqlite3_vfs_find sqlite3_api->vfs_find
  93837. #define sqlite3_vfs_register sqlite3_api->vfs_register
  93838. #define sqlite3_vfs_unregister sqlite3_api->vfs_unregister
  93839. #define sqlite3_threadsafe sqlite3_api->xthreadsafe
  93840. #define sqlite3_result_zeroblob sqlite3_api->result_zeroblob
  93841. #define sqlite3_result_error_code sqlite3_api->result_error_code
  93842. #define sqlite3_test_control sqlite3_api->test_control
  93843. #define sqlite3_randomness sqlite3_api->randomness
  93844. #define sqlite3_context_db_handle sqlite3_api->context_db_handle
  93845. #define sqlite3_extended_result_codes sqlite3_api->extended_result_codes
  93846. #define sqlite3_limit sqlite3_api->limit
  93847. #define sqlite3_next_stmt sqlite3_api->next_stmt
  93848. #define sqlite3_sql sqlite3_api->sql
  93849. #define sqlite3_status sqlite3_api->status
  93850. #define sqlite3_backup_finish sqlite3_api->backup_finish
  93851. #define sqlite3_backup_init sqlite3_api->backup_init
  93852. #define sqlite3_backup_pagecount sqlite3_api->backup_pagecount
  93853. #define sqlite3_backup_remaining sqlite3_api->backup_remaining
  93854. #define sqlite3_backup_step sqlite3_api->backup_step
  93855. #define sqlite3_compileoption_get sqlite3_api->compileoption_get
  93856. #define sqlite3_compileoption_used sqlite3_api->compileoption_used
  93857. #define sqlite3_create_function_v2 sqlite3_api->create_function_v2
  93858. #define sqlite3_db_config sqlite3_api->db_config
  93859. #define sqlite3_db_mutex sqlite3_api->db_mutex
  93860. #define sqlite3_db_status sqlite3_api->db_status
  93861. #define sqlite3_extended_errcode sqlite3_api->extended_errcode
  93862. #define sqlite3_log sqlite3_api->log
  93863. #define sqlite3_soft_heap_limit64 sqlite3_api->soft_heap_limit64
  93864. #define sqlite3_sourceid sqlite3_api->sourceid
  93865. #define sqlite3_stmt_status sqlite3_api->stmt_status
  93866. #define sqlite3_strnicmp sqlite3_api->strnicmp
  93867. #define sqlite3_unlock_notify sqlite3_api->unlock_notify
  93868. #define sqlite3_wal_autocheckpoint sqlite3_api->wal_autocheckpoint
  93869. #define sqlite3_wal_checkpoint sqlite3_api->wal_checkpoint
  93870. #define sqlite3_wal_hook sqlite3_api->wal_hook
  93871. #define sqlite3_blob_reopen sqlite3_api->blob_reopen
  93872. #define sqlite3_vtab_config sqlite3_api->vtab_config
  93873. #define sqlite3_vtab_on_conflict sqlite3_api->vtab_on_conflict
  93874. /* Version 3.7.16 and later */
  93875. #define sqlite3_close_v2 sqlite3_api->close_v2
  93876. #define sqlite3_db_filename sqlite3_api->db_filename
  93877. #define sqlite3_db_readonly sqlite3_api->db_readonly
  93878. #define sqlite3_db_release_memory sqlite3_api->db_release_memory
  93879. #define sqlite3_errstr sqlite3_api->errstr
  93880. #define sqlite3_stmt_busy sqlite3_api->stmt_busy
  93881. #define sqlite3_stmt_readonly sqlite3_api->stmt_readonly
  93882. #define sqlite3_stricmp sqlite3_api->stricmp
  93883. #define sqlite3_uri_boolean sqlite3_api->uri_boolean
  93884. #define sqlite3_uri_int64 sqlite3_api->uri_int64
  93885. #define sqlite3_uri_parameter sqlite3_api->uri_parameter
  93886. #define sqlite3_uri_vsnprintf sqlite3_api->vsnprintf
  93887. #define sqlite3_wal_checkpoint_v2 sqlite3_api->wal_checkpoint_v2
  93888. /* Version 3.8.7 and later */
  93889. #define sqlite3_auto_extension sqlite3_api->auto_extension
  93890. #define sqlite3_bind_blob64 sqlite3_api->bind_blob64
  93891. #define sqlite3_bind_text64 sqlite3_api->bind_text64
  93892. #define sqlite3_cancel_auto_extension sqlite3_api->cancel_auto_extension
  93893. #define sqlite3_load_extension sqlite3_api->load_extension
  93894. #define sqlite3_malloc64 sqlite3_api->malloc64
  93895. #define sqlite3_msize sqlite3_api->msize
  93896. #define sqlite3_realloc64 sqlite3_api->realloc64
  93897. #define sqlite3_reset_auto_extension sqlite3_api->reset_auto_extension
  93898. #define sqlite3_result_blob64 sqlite3_api->result_blob64
  93899. #define sqlite3_result_text64 sqlite3_api->result_text64
  93900. #define sqlite3_strglob sqlite3_api->strglob
  93901. #endif /* SQLITE_CORE */
  93902. #ifndef SQLITE_CORE
  93903. /* This case when the file really is being compiled as a loadable
  93904. ** extension */
  93905. # define SQLITE_EXTENSION_INIT1 const sqlite3_api_routines *sqlite3_api=0;
  93906. # define SQLITE_EXTENSION_INIT2(v) sqlite3_api=v;
  93907. # define SQLITE_EXTENSION_INIT3 \
  93908. extern const sqlite3_api_routines *sqlite3_api;
  93909. #else
  93910. /* This case when the file is being statically linked into the
  93911. ** application */
  93912. # define SQLITE_EXTENSION_INIT1 /*no-op*/
  93913. # define SQLITE_EXTENSION_INIT2(v) (void)v; /* unused parameter */
  93914. # define SQLITE_EXTENSION_INIT3 /*no-op*/
  93915. #endif
  93916. #endif /* _SQLITE3EXT_H_ */
  93917. /************** End of sqlite3ext.h ******************************************/
  93918. /************** Continuing where we left off in loadext.c ********************/
  93919. /* #include <string.h> */
  93920. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  93921. /*
  93922. ** Some API routines are omitted when various features are
  93923. ** excluded from a build of SQLite. Substitute a NULL pointer
  93924. ** for any missing APIs.
  93925. */
  93926. #ifndef SQLITE_ENABLE_COLUMN_METADATA
  93927. # define sqlite3_column_database_name 0
  93928. # define sqlite3_column_database_name16 0
  93929. # define sqlite3_column_table_name 0
  93930. # define sqlite3_column_table_name16 0
  93931. # define sqlite3_column_origin_name 0
  93932. # define sqlite3_column_origin_name16 0
  93933. # define sqlite3_table_column_metadata 0
  93934. #endif
  93935. #ifdef SQLITE_OMIT_AUTHORIZATION
  93936. # define sqlite3_set_authorizer 0
  93937. #endif
  93938. #ifdef SQLITE_OMIT_UTF16
  93939. # define sqlite3_bind_text16 0
  93940. # define sqlite3_collation_needed16 0
  93941. # define sqlite3_column_decltype16 0
  93942. # define sqlite3_column_name16 0
  93943. # define sqlite3_column_text16 0
  93944. # define sqlite3_complete16 0
  93945. # define sqlite3_create_collation16 0
  93946. # define sqlite3_create_function16 0
  93947. # define sqlite3_errmsg16 0
  93948. # define sqlite3_open16 0
  93949. # define sqlite3_prepare16 0
  93950. # define sqlite3_prepare16_v2 0
  93951. # define sqlite3_result_error16 0
  93952. # define sqlite3_result_text16 0
  93953. # define sqlite3_result_text16be 0
  93954. # define sqlite3_result_text16le 0
  93955. # define sqlite3_value_text16 0
  93956. # define sqlite3_value_text16be 0
  93957. # define sqlite3_value_text16le 0
  93958. # define sqlite3_column_database_name16 0
  93959. # define sqlite3_column_table_name16 0
  93960. # define sqlite3_column_origin_name16 0
  93961. #endif
  93962. #ifdef SQLITE_OMIT_COMPLETE
  93963. # define sqlite3_complete 0
  93964. # define sqlite3_complete16 0
  93965. #endif
  93966. #ifdef SQLITE_OMIT_DECLTYPE
  93967. # define sqlite3_column_decltype16 0
  93968. # define sqlite3_column_decltype 0
  93969. #endif
  93970. #ifdef SQLITE_OMIT_PROGRESS_CALLBACK
  93971. # define sqlite3_progress_handler 0
  93972. #endif
  93973. #ifdef SQLITE_OMIT_VIRTUALTABLE
  93974. # define sqlite3_create_module 0
  93975. # define sqlite3_create_module_v2 0
  93976. # define sqlite3_declare_vtab 0
  93977. # define sqlite3_vtab_config 0
  93978. # define sqlite3_vtab_on_conflict 0
  93979. #endif
  93980. #ifdef SQLITE_OMIT_SHARED_CACHE
  93981. # define sqlite3_enable_shared_cache 0
  93982. #endif
  93983. #ifdef SQLITE_OMIT_TRACE
  93984. # define sqlite3_profile 0
  93985. # define sqlite3_trace 0
  93986. #endif
  93987. #ifdef SQLITE_OMIT_GET_TABLE
  93988. # define sqlite3_free_table 0
  93989. # define sqlite3_get_table 0
  93990. #endif
  93991. #ifdef SQLITE_OMIT_INCRBLOB
  93992. #define sqlite3_bind_zeroblob 0
  93993. #define sqlite3_blob_bytes 0
  93994. #define sqlite3_blob_close 0
  93995. #define sqlite3_blob_open 0
  93996. #define sqlite3_blob_read 0
  93997. #define sqlite3_blob_write 0
  93998. #define sqlite3_blob_reopen 0
  93999. #endif
  94000. /*
  94001. ** The following structure contains pointers to all SQLite API routines.
  94002. ** A pointer to this structure is passed into extensions when they are
  94003. ** loaded so that the extension can make calls back into the SQLite
  94004. ** library.
  94005. **
  94006. ** When adding new APIs, add them to the bottom of this structure
  94007. ** in order to preserve backwards compatibility.
  94008. **
  94009. ** Extensions that use newer APIs should first call the
  94010. ** sqlite3_libversion_number() to make sure that the API they
  94011. ** intend to use is supported by the library. Extensions should
  94012. ** also check to make sure that the pointer to the function is
  94013. ** not NULL before calling it.
  94014. */
  94015. static const sqlite3_api_routines sqlite3Apis = {
  94016. sqlite3_aggregate_context,
  94017. #ifndef SQLITE_OMIT_DEPRECATED
  94018. sqlite3_aggregate_count,
  94019. #else
  94020. 0,
  94021. #endif
  94022. sqlite3_bind_blob,
  94023. sqlite3_bind_double,
  94024. sqlite3_bind_int,
  94025. sqlite3_bind_int64,
  94026. sqlite3_bind_null,
  94027. sqlite3_bind_parameter_count,
  94028. sqlite3_bind_parameter_index,
  94029. sqlite3_bind_parameter_name,
  94030. sqlite3_bind_text,
  94031. sqlite3_bind_text16,
  94032. sqlite3_bind_value,
  94033. sqlite3_busy_handler,
  94034. sqlite3_busy_timeout,
  94035. sqlite3_changes,
  94036. sqlite3_close,
  94037. sqlite3_collation_needed,
  94038. sqlite3_collation_needed16,
  94039. sqlite3_column_blob,
  94040. sqlite3_column_bytes,
  94041. sqlite3_column_bytes16,
  94042. sqlite3_column_count,
  94043. sqlite3_column_database_name,
  94044. sqlite3_column_database_name16,
  94045. sqlite3_column_decltype,
  94046. sqlite3_column_decltype16,
  94047. sqlite3_column_double,
  94048. sqlite3_column_int,
  94049. sqlite3_column_int64,
  94050. sqlite3_column_name,
  94051. sqlite3_column_name16,
  94052. sqlite3_column_origin_name,
  94053. sqlite3_column_origin_name16,
  94054. sqlite3_column_table_name,
  94055. sqlite3_column_table_name16,
  94056. sqlite3_column_text,
  94057. sqlite3_column_text16,
  94058. sqlite3_column_type,
  94059. sqlite3_column_value,
  94060. sqlite3_commit_hook,
  94061. sqlite3_complete,
  94062. sqlite3_complete16,
  94063. sqlite3_create_collation,
  94064. sqlite3_create_collation16,
  94065. sqlite3_create_function,
  94066. sqlite3_create_function16,
  94067. sqlite3_create_module,
  94068. sqlite3_data_count,
  94069. sqlite3_db_handle,
  94070. sqlite3_declare_vtab,
  94071. sqlite3_enable_shared_cache,
  94072. sqlite3_errcode,
  94073. sqlite3_errmsg,
  94074. sqlite3_errmsg16,
  94075. sqlite3_exec,
  94076. #ifndef SQLITE_OMIT_DEPRECATED
  94077. sqlite3_expired,
  94078. #else
  94079. 0,
  94080. #endif
  94081. sqlite3_finalize,
  94082. sqlite3_free,
  94083. sqlite3_free_table,
  94084. sqlite3_get_autocommit,
  94085. sqlite3_get_auxdata,
  94086. sqlite3_get_table,
  94087. 0, /* Was sqlite3_global_recover(), but that function is deprecated */
  94088. sqlite3_interrupt,
  94089. sqlite3_last_insert_rowid,
  94090. sqlite3_libversion,
  94091. sqlite3_libversion_number,
  94092. sqlite3_malloc,
  94093. sqlite3_mprintf,
  94094. sqlite3_open,
  94095. sqlite3_open16,
  94096. sqlite3_prepare,
  94097. sqlite3_prepare16,
  94098. sqlite3_profile,
  94099. sqlite3_progress_handler,
  94100. sqlite3_realloc,
  94101. sqlite3_reset,
  94102. sqlite3_result_blob,
  94103. sqlite3_result_double,
  94104. sqlite3_result_error,
  94105. sqlite3_result_error16,
  94106. sqlite3_result_int,
  94107. sqlite3_result_int64,
  94108. sqlite3_result_null,
  94109. sqlite3_result_text,
  94110. sqlite3_result_text16,
  94111. sqlite3_result_text16be,
  94112. sqlite3_result_text16le,
  94113. sqlite3_result_value,
  94114. sqlite3_rollback_hook,
  94115. sqlite3_set_authorizer,
  94116. sqlite3_set_auxdata,
  94117. sqlite3_snprintf,
  94118. sqlite3_step,
  94119. sqlite3_table_column_metadata,
  94120. #ifndef SQLITE_OMIT_DEPRECATED
  94121. sqlite3_thread_cleanup,
  94122. #else
  94123. 0,
  94124. #endif
  94125. sqlite3_total_changes,
  94126. sqlite3_trace,
  94127. #ifndef SQLITE_OMIT_DEPRECATED
  94128. sqlite3_transfer_bindings,
  94129. #else
  94130. 0,
  94131. #endif
  94132. sqlite3_update_hook,
  94133. sqlite3_user_data,
  94134. sqlite3_value_blob,
  94135. sqlite3_value_bytes,
  94136. sqlite3_value_bytes16,
  94137. sqlite3_value_double,
  94138. sqlite3_value_int,
  94139. sqlite3_value_int64,
  94140. sqlite3_value_numeric_type,
  94141. sqlite3_value_text,
  94142. sqlite3_value_text16,
  94143. sqlite3_value_text16be,
  94144. sqlite3_value_text16le,
  94145. sqlite3_value_type,
  94146. sqlite3_vmprintf,
  94147. /*
  94148. ** The original API set ends here. All extensions can call any
  94149. ** of the APIs above provided that the pointer is not NULL. But
  94150. ** before calling APIs that follow, extension should check the
  94151. ** sqlite3_libversion_number() to make sure they are dealing with
  94152. ** a library that is new enough to support that API.
  94153. *************************************************************************
  94154. */
  94155. sqlite3_overload_function,
  94156. /*
  94157. ** Added after 3.3.13
  94158. */
  94159. sqlite3_prepare_v2,
  94160. sqlite3_prepare16_v2,
  94161. sqlite3_clear_bindings,
  94162. /*
  94163. ** Added for 3.4.1
  94164. */
  94165. sqlite3_create_module_v2,
  94166. /*
  94167. ** Added for 3.5.0
  94168. */
  94169. sqlite3_bind_zeroblob,
  94170. sqlite3_blob_bytes,
  94171. sqlite3_blob_close,
  94172. sqlite3_blob_open,
  94173. sqlite3_blob_read,
  94174. sqlite3_blob_write,
  94175. sqlite3_create_collation_v2,
  94176. sqlite3_file_control,
  94177. sqlite3_memory_highwater,
  94178. sqlite3_memory_used,
  94179. #ifdef SQLITE_MUTEX_OMIT
  94180. 0,
  94181. 0,
  94182. 0,
  94183. 0,
  94184. 0,
  94185. #else
  94186. sqlite3_mutex_alloc,
  94187. sqlite3_mutex_enter,
  94188. sqlite3_mutex_free,
  94189. sqlite3_mutex_leave,
  94190. sqlite3_mutex_try,
  94191. #endif
  94192. sqlite3_open_v2,
  94193. sqlite3_release_memory,
  94194. sqlite3_result_error_nomem,
  94195. sqlite3_result_error_toobig,
  94196. sqlite3_sleep,
  94197. sqlite3_soft_heap_limit,
  94198. sqlite3_vfs_find,
  94199. sqlite3_vfs_register,
  94200. sqlite3_vfs_unregister,
  94201. /*
  94202. ** Added for 3.5.8
  94203. */
  94204. sqlite3_threadsafe,
  94205. sqlite3_result_zeroblob,
  94206. sqlite3_result_error_code,
  94207. sqlite3_test_control,
  94208. sqlite3_randomness,
  94209. sqlite3_context_db_handle,
  94210. /*
  94211. ** Added for 3.6.0
  94212. */
  94213. sqlite3_extended_result_codes,
  94214. sqlite3_limit,
  94215. sqlite3_next_stmt,
  94216. sqlite3_sql,
  94217. sqlite3_status,
  94218. /*
  94219. ** Added for 3.7.4
  94220. */
  94221. sqlite3_backup_finish,
  94222. sqlite3_backup_init,
  94223. sqlite3_backup_pagecount,
  94224. sqlite3_backup_remaining,
  94225. sqlite3_backup_step,
  94226. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  94227. sqlite3_compileoption_get,
  94228. sqlite3_compileoption_used,
  94229. #else
  94230. 0,
  94231. 0,
  94232. #endif
  94233. sqlite3_create_function_v2,
  94234. sqlite3_db_config,
  94235. sqlite3_db_mutex,
  94236. sqlite3_db_status,
  94237. sqlite3_extended_errcode,
  94238. sqlite3_log,
  94239. sqlite3_soft_heap_limit64,
  94240. sqlite3_sourceid,
  94241. sqlite3_stmt_status,
  94242. sqlite3_strnicmp,
  94243. #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
  94244. sqlite3_unlock_notify,
  94245. #else
  94246. 0,
  94247. #endif
  94248. #ifndef SQLITE_OMIT_WAL
  94249. sqlite3_wal_autocheckpoint,
  94250. sqlite3_wal_checkpoint,
  94251. sqlite3_wal_hook,
  94252. #else
  94253. 0,
  94254. 0,
  94255. 0,
  94256. #endif
  94257. sqlite3_blob_reopen,
  94258. sqlite3_vtab_config,
  94259. sqlite3_vtab_on_conflict,
  94260. sqlite3_close_v2,
  94261. sqlite3_db_filename,
  94262. sqlite3_db_readonly,
  94263. sqlite3_db_release_memory,
  94264. sqlite3_errstr,
  94265. sqlite3_stmt_busy,
  94266. sqlite3_stmt_readonly,
  94267. sqlite3_stricmp,
  94268. sqlite3_uri_boolean,
  94269. sqlite3_uri_int64,
  94270. sqlite3_uri_parameter,
  94271. sqlite3_vsnprintf,
  94272. sqlite3_wal_checkpoint_v2,
  94273. /* Version 3.8.7 and later */
  94274. sqlite3_auto_extension,
  94275. sqlite3_bind_blob64,
  94276. sqlite3_bind_text64,
  94277. sqlite3_cancel_auto_extension,
  94278. sqlite3_load_extension,
  94279. sqlite3_malloc64,
  94280. sqlite3_msize,
  94281. sqlite3_realloc64,
  94282. sqlite3_reset_auto_extension,
  94283. sqlite3_result_blob64,
  94284. sqlite3_result_text64,
  94285. sqlite3_strglob
  94286. };
  94287. /*
  94288. ** Attempt to load an SQLite extension library contained in the file
  94289. ** zFile. The entry point is zProc. zProc may be 0 in which case a
  94290. ** default entry point name (sqlite3_extension_init) is used. Use
  94291. ** of the default name is recommended.
  94292. **
  94293. ** Return SQLITE_OK on success and SQLITE_ERROR if something goes wrong.
  94294. **
  94295. ** If an error occurs and pzErrMsg is not 0, then fill *pzErrMsg with
  94296. ** error message text. The calling function should free this memory
  94297. ** by calling sqlite3DbFree(db, ).
  94298. */
  94299. static int sqlite3LoadExtension(
  94300. sqlite3 *db, /* Load the extension into this database connection */
  94301. const char *zFile, /* Name of the shared library containing extension */
  94302. const char *zProc, /* Entry point. Use "sqlite3_extension_init" if 0 */
  94303. char **pzErrMsg /* Put error message here if not 0 */
  94304. ){
  94305. sqlite3_vfs *pVfs = db->pVfs;
  94306. void *handle;
  94307. int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*);
  94308. char *zErrmsg = 0;
  94309. const char *zEntry;
  94310. char *zAltEntry = 0;
  94311. void **aHandle;
  94312. int nMsg = 300 + sqlite3Strlen30(zFile);
  94313. int ii;
  94314. /* Shared library endings to try if zFile cannot be loaded as written */
  94315. static const char *azEndings[] = {
  94316. #if SQLITE_OS_WIN
  94317. "dll"
  94318. #elif defined(__APPLE__)
  94319. "dylib"
  94320. #else
  94321. "so"
  94322. #endif
  94323. };
  94324. if( pzErrMsg ) *pzErrMsg = 0;
  94325. /* Ticket #1863. To avoid a creating security problems for older
  94326. ** applications that relink against newer versions of SQLite, the
  94327. ** ability to run load_extension is turned off by default. One
  94328. ** must call sqlite3_enable_load_extension() to turn on extension
  94329. ** loading. Otherwise you get the following error.
  94330. */
  94331. if( (db->flags & SQLITE_LoadExtension)==0 ){
  94332. if( pzErrMsg ){
  94333. *pzErrMsg = sqlite3_mprintf("not authorized");
  94334. }
  94335. return SQLITE_ERROR;
  94336. }
  94337. zEntry = zProc ? zProc : "sqlite3_extension_init";
  94338. handle = sqlite3OsDlOpen(pVfs, zFile);
  94339. #if SQLITE_OS_UNIX || SQLITE_OS_WIN
  94340. for(ii=0; ii<ArraySize(azEndings) && handle==0; ii++){
  94341. char *zAltFile = sqlite3_mprintf("%s.%s", zFile, azEndings[ii]);
  94342. if( zAltFile==0 ) return SQLITE_NOMEM;
  94343. handle = sqlite3OsDlOpen(pVfs, zAltFile);
  94344. sqlite3_free(zAltFile);
  94345. }
  94346. #endif
  94347. if( handle==0 ){
  94348. if( pzErrMsg ){
  94349. *pzErrMsg = zErrmsg = sqlite3_malloc(nMsg);
  94350. if( zErrmsg ){
  94351. sqlite3_snprintf(nMsg, zErrmsg,
  94352. "unable to open shared library [%s]", zFile);
  94353. sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
  94354. }
  94355. }
  94356. return SQLITE_ERROR;
  94357. }
  94358. xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
  94359. sqlite3OsDlSym(pVfs, handle, zEntry);
  94360. /* If no entry point was specified and the default legacy
  94361. ** entry point name "sqlite3_extension_init" was not found, then
  94362. ** construct an entry point name "sqlite3_X_init" where the X is
  94363. ** replaced by the lowercase value of every ASCII alphabetic
  94364. ** character in the filename after the last "/" upto the first ".",
  94365. ** and eliding the first three characters if they are "lib".
  94366. ** Examples:
  94367. **
  94368. ** /usr/local/lib/libExample5.4.3.so ==> sqlite3_example_init
  94369. ** C:/lib/mathfuncs.dll ==> sqlite3_mathfuncs_init
  94370. */
  94371. if( xInit==0 && zProc==0 ){
  94372. int iFile, iEntry, c;
  94373. int ncFile = sqlite3Strlen30(zFile);
  94374. zAltEntry = sqlite3_malloc(ncFile+30);
  94375. if( zAltEntry==0 ){
  94376. sqlite3OsDlClose(pVfs, handle);
  94377. return SQLITE_NOMEM;
  94378. }
  94379. memcpy(zAltEntry, "sqlite3_", 8);
  94380. for(iFile=ncFile-1; iFile>=0 && zFile[iFile]!='/'; iFile--){}
  94381. iFile++;
  94382. if( sqlite3_strnicmp(zFile+iFile, "lib", 3)==0 ) iFile += 3;
  94383. for(iEntry=8; (c = zFile[iFile])!=0 && c!='.'; iFile++){
  94384. if( sqlite3Isalpha(c) ){
  94385. zAltEntry[iEntry++] = (char)sqlite3UpperToLower[(unsigned)c];
  94386. }
  94387. }
  94388. memcpy(zAltEntry+iEntry, "_init", 6);
  94389. zEntry = zAltEntry;
  94390. xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
  94391. sqlite3OsDlSym(pVfs, handle, zEntry);
  94392. }
  94393. if( xInit==0 ){
  94394. if( pzErrMsg ){
  94395. nMsg += sqlite3Strlen30(zEntry);
  94396. *pzErrMsg = zErrmsg = sqlite3_malloc(nMsg);
  94397. if( zErrmsg ){
  94398. sqlite3_snprintf(nMsg, zErrmsg,
  94399. "no entry point [%s] in shared library [%s]", zEntry, zFile);
  94400. sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
  94401. }
  94402. }
  94403. sqlite3OsDlClose(pVfs, handle);
  94404. sqlite3_free(zAltEntry);
  94405. return SQLITE_ERROR;
  94406. }
  94407. sqlite3_free(zAltEntry);
  94408. if( xInit(db, &zErrmsg, &sqlite3Apis) ){
  94409. if( pzErrMsg ){
  94410. *pzErrMsg = sqlite3_mprintf("error during initialization: %s", zErrmsg);
  94411. }
  94412. sqlite3_free(zErrmsg);
  94413. sqlite3OsDlClose(pVfs, handle);
  94414. return SQLITE_ERROR;
  94415. }
  94416. /* Append the new shared library handle to the db->aExtension array. */
  94417. aHandle = sqlite3DbMallocZero(db, sizeof(handle)*(db->nExtension+1));
  94418. if( aHandle==0 ){
  94419. return SQLITE_NOMEM;
  94420. }
  94421. if( db->nExtension>0 ){
  94422. memcpy(aHandle, db->aExtension, sizeof(handle)*db->nExtension);
  94423. }
  94424. sqlite3DbFree(db, db->aExtension);
  94425. db->aExtension = aHandle;
  94426. db->aExtension[db->nExtension++] = handle;
  94427. return SQLITE_OK;
  94428. }
  94429. SQLITE_API int sqlite3_load_extension(
  94430. sqlite3 *db, /* Load the extension into this database connection */
  94431. const char *zFile, /* Name of the shared library containing extension */
  94432. const char *zProc, /* Entry point. Use "sqlite3_extension_init" if 0 */
  94433. char **pzErrMsg /* Put error message here if not 0 */
  94434. ){
  94435. int rc;
  94436. sqlite3_mutex_enter(db->mutex);
  94437. rc = sqlite3LoadExtension(db, zFile, zProc, pzErrMsg);
  94438. rc = sqlite3ApiExit(db, rc);
  94439. sqlite3_mutex_leave(db->mutex);
  94440. return rc;
  94441. }
  94442. /*
  94443. ** Call this routine when the database connection is closing in order
  94444. ** to clean up loaded extensions
  94445. */
  94446. SQLITE_PRIVATE void sqlite3CloseExtensions(sqlite3 *db){
  94447. int i;
  94448. assert( sqlite3_mutex_held(db->mutex) );
  94449. for(i=0; i<db->nExtension; i++){
  94450. sqlite3OsDlClose(db->pVfs, db->aExtension[i]);
  94451. }
  94452. sqlite3DbFree(db, db->aExtension);
  94453. }
  94454. /*
  94455. ** Enable or disable extension loading. Extension loading is disabled by
  94456. ** default so as not to open security holes in older applications.
  94457. */
  94458. SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff){
  94459. sqlite3_mutex_enter(db->mutex);
  94460. if( onoff ){
  94461. db->flags |= SQLITE_LoadExtension;
  94462. }else{
  94463. db->flags &= ~SQLITE_LoadExtension;
  94464. }
  94465. sqlite3_mutex_leave(db->mutex);
  94466. return SQLITE_OK;
  94467. }
  94468. #endif /* SQLITE_OMIT_LOAD_EXTENSION */
  94469. /*
  94470. ** The auto-extension code added regardless of whether or not extension
  94471. ** loading is supported. We need a dummy sqlite3Apis pointer for that
  94472. ** code if regular extension loading is not available. This is that
  94473. ** dummy pointer.
  94474. */
  94475. #ifdef SQLITE_OMIT_LOAD_EXTENSION
  94476. static const sqlite3_api_routines sqlite3Apis = { 0 };
  94477. #endif
  94478. /*
  94479. ** The following object holds the list of automatically loaded
  94480. ** extensions.
  94481. **
  94482. ** This list is shared across threads. The SQLITE_MUTEX_STATIC_MASTER
  94483. ** mutex must be held while accessing this list.
  94484. */
  94485. typedef struct sqlite3AutoExtList sqlite3AutoExtList;
  94486. static SQLITE_WSD struct sqlite3AutoExtList {
  94487. int nExt; /* Number of entries in aExt[] */
  94488. void (**aExt)(void); /* Pointers to the extension init functions */
  94489. } sqlite3Autoext = { 0, 0 };
  94490. /* The "wsdAutoext" macro will resolve to the autoextension
  94491. ** state vector. If writable static data is unsupported on the target,
  94492. ** we have to locate the state vector at run-time. In the more common
  94493. ** case where writable static data is supported, wsdStat can refer directly
  94494. ** to the "sqlite3Autoext" state vector declared above.
  94495. */
  94496. #ifdef SQLITE_OMIT_WSD
  94497. # define wsdAutoextInit \
  94498. sqlite3AutoExtList *x = &GLOBAL(sqlite3AutoExtList,sqlite3Autoext)
  94499. # define wsdAutoext x[0]
  94500. #else
  94501. # define wsdAutoextInit
  94502. # define wsdAutoext sqlite3Autoext
  94503. #endif
  94504. /*
  94505. ** Register a statically linked extension that is automatically
  94506. ** loaded by every new database connection.
  94507. */
  94508. SQLITE_API int sqlite3_auto_extension(void (*xInit)(void)){
  94509. int rc = SQLITE_OK;
  94510. #ifndef SQLITE_OMIT_AUTOINIT
  94511. rc = sqlite3_initialize();
  94512. if( rc ){
  94513. return rc;
  94514. }else
  94515. #endif
  94516. {
  94517. int i;
  94518. #if SQLITE_THREADSAFE
  94519. sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  94520. #endif
  94521. wsdAutoextInit;
  94522. sqlite3_mutex_enter(mutex);
  94523. for(i=0; i<wsdAutoext.nExt; i++){
  94524. if( wsdAutoext.aExt[i]==xInit ) break;
  94525. }
  94526. if( i==wsdAutoext.nExt ){
  94527. int nByte = (wsdAutoext.nExt+1)*sizeof(wsdAutoext.aExt[0]);
  94528. void (**aNew)(void);
  94529. aNew = sqlite3_realloc(wsdAutoext.aExt, nByte);
  94530. if( aNew==0 ){
  94531. rc = SQLITE_NOMEM;
  94532. }else{
  94533. wsdAutoext.aExt = aNew;
  94534. wsdAutoext.aExt[wsdAutoext.nExt] = xInit;
  94535. wsdAutoext.nExt++;
  94536. }
  94537. }
  94538. sqlite3_mutex_leave(mutex);
  94539. assert( (rc&0xff)==rc );
  94540. return rc;
  94541. }
  94542. }
  94543. /*
  94544. ** Cancel a prior call to sqlite3_auto_extension. Remove xInit from the
  94545. ** set of routines that is invoked for each new database connection, if it
  94546. ** is currently on the list. If xInit is not on the list, then this
  94547. ** routine is a no-op.
  94548. **
  94549. ** Return 1 if xInit was found on the list and removed. Return 0 if xInit
  94550. ** was not on the list.
  94551. */
  94552. SQLITE_API int sqlite3_cancel_auto_extension(void (*xInit)(void)){
  94553. #if SQLITE_THREADSAFE
  94554. sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  94555. #endif
  94556. int i;
  94557. int n = 0;
  94558. wsdAutoextInit;
  94559. sqlite3_mutex_enter(mutex);
  94560. for(i=wsdAutoext.nExt-1; i>=0; i--){
  94561. if( wsdAutoext.aExt[i]==xInit ){
  94562. wsdAutoext.nExt--;
  94563. wsdAutoext.aExt[i] = wsdAutoext.aExt[wsdAutoext.nExt];
  94564. n++;
  94565. break;
  94566. }
  94567. }
  94568. sqlite3_mutex_leave(mutex);
  94569. return n;
  94570. }
  94571. /*
  94572. ** Reset the automatic extension loading mechanism.
  94573. */
  94574. SQLITE_API void sqlite3_reset_auto_extension(void){
  94575. #ifndef SQLITE_OMIT_AUTOINIT
  94576. if( sqlite3_initialize()==SQLITE_OK )
  94577. #endif
  94578. {
  94579. #if SQLITE_THREADSAFE
  94580. sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  94581. #endif
  94582. wsdAutoextInit;
  94583. sqlite3_mutex_enter(mutex);
  94584. sqlite3_free(wsdAutoext.aExt);
  94585. wsdAutoext.aExt = 0;
  94586. wsdAutoext.nExt = 0;
  94587. sqlite3_mutex_leave(mutex);
  94588. }
  94589. }
  94590. /*
  94591. ** Load all automatic extensions.
  94592. **
  94593. ** If anything goes wrong, set an error in the database connection.
  94594. */
  94595. SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3 *db){
  94596. int i;
  94597. int go = 1;
  94598. int rc;
  94599. int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*);
  94600. wsdAutoextInit;
  94601. if( wsdAutoext.nExt==0 ){
  94602. /* Common case: early out without every having to acquire a mutex */
  94603. return;
  94604. }
  94605. for(i=0; go; i++){
  94606. char *zErrmsg;
  94607. #if SQLITE_THREADSAFE
  94608. sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  94609. #endif
  94610. sqlite3_mutex_enter(mutex);
  94611. if( i>=wsdAutoext.nExt ){
  94612. xInit = 0;
  94613. go = 0;
  94614. }else{
  94615. xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
  94616. wsdAutoext.aExt[i];
  94617. }
  94618. sqlite3_mutex_leave(mutex);
  94619. zErrmsg = 0;
  94620. if( xInit && (rc = xInit(db, &zErrmsg, &sqlite3Apis))!=0 ){
  94621. sqlite3ErrorWithMsg(db, rc,
  94622. "automatic extension loading failed: %s", zErrmsg);
  94623. go = 0;
  94624. }
  94625. sqlite3_free(zErrmsg);
  94626. }
  94627. }
  94628. /************** End of loadext.c *********************************************/
  94629. /************** Begin file pragma.c ******************************************/
  94630. /*
  94631. ** 2003 April 6
  94632. **
  94633. ** The author disclaims copyright to this source code. In place of
  94634. ** a legal notice, here is a blessing:
  94635. **
  94636. ** May you do good and not evil.
  94637. ** May you find forgiveness for yourself and forgive others.
  94638. ** May you share freely, never taking more than you give.
  94639. **
  94640. *************************************************************************
  94641. ** This file contains code used to implement the PRAGMA command.
  94642. */
  94643. #if !defined(SQLITE_ENABLE_LOCKING_STYLE)
  94644. # if defined(__APPLE__)
  94645. # define SQLITE_ENABLE_LOCKING_STYLE 1
  94646. # else
  94647. # define SQLITE_ENABLE_LOCKING_STYLE 0
  94648. # endif
  94649. #endif
  94650. /***************************************************************************
  94651. ** The next block of code, including the PragTyp_XXXX macro definitions and
  94652. ** the aPragmaName[] object is composed of generated code. DO NOT EDIT.
  94653. **
  94654. ** To add new pragmas, edit the code in ../tool/mkpragmatab.tcl and rerun
  94655. ** that script. Then copy/paste the output in place of the following:
  94656. */
  94657. #define PragTyp_HEADER_VALUE 0
  94658. #define PragTyp_AUTO_VACUUM 1
  94659. #define PragTyp_FLAG 2
  94660. #define PragTyp_BUSY_TIMEOUT 3
  94661. #define PragTyp_CACHE_SIZE 4
  94662. #define PragTyp_CASE_SENSITIVE_LIKE 5
  94663. #define PragTyp_COLLATION_LIST 6
  94664. #define PragTyp_COMPILE_OPTIONS 7
  94665. #define PragTyp_DATA_STORE_DIRECTORY 8
  94666. #define PragTyp_DATABASE_LIST 9
  94667. #define PragTyp_DEFAULT_CACHE_SIZE 10
  94668. #define PragTyp_ENCODING 11
  94669. #define PragTyp_FOREIGN_KEY_CHECK 12
  94670. #define PragTyp_FOREIGN_KEY_LIST 13
  94671. #define PragTyp_INCREMENTAL_VACUUM 14
  94672. #define PragTyp_INDEX_INFO 15
  94673. #define PragTyp_INDEX_LIST 16
  94674. #define PragTyp_INTEGRITY_CHECK 17
  94675. #define PragTyp_JOURNAL_MODE 18
  94676. #define PragTyp_JOURNAL_SIZE_LIMIT 19
  94677. #define PragTyp_LOCK_PROXY_FILE 20
  94678. #define PragTyp_LOCKING_MODE 21
  94679. #define PragTyp_PAGE_COUNT 22
  94680. #define PragTyp_MMAP_SIZE 23
  94681. #define PragTyp_PAGE_SIZE 24
  94682. #define PragTyp_SECURE_DELETE 25
  94683. #define PragTyp_SHRINK_MEMORY 26
  94684. #define PragTyp_SOFT_HEAP_LIMIT 27
  94685. #define PragTyp_STATS 28
  94686. #define PragTyp_SYNCHRONOUS 29
  94687. #define PragTyp_TABLE_INFO 30
  94688. #define PragTyp_TEMP_STORE 31
  94689. #define PragTyp_TEMP_STORE_DIRECTORY 32
  94690. #define PragTyp_THREADS 33
  94691. #define PragTyp_WAL_AUTOCHECKPOINT 34
  94692. #define PragTyp_WAL_CHECKPOINT 35
  94693. #define PragTyp_ACTIVATE_EXTENSIONS 36
  94694. #define PragTyp_HEXKEY 37
  94695. #define PragTyp_KEY 38
  94696. #define PragTyp_REKEY 39
  94697. #define PragTyp_LOCK_STATUS 40
  94698. #define PragTyp_PARSER_TRACE 41
  94699. #define PragFlag_NeedSchema 0x01
  94700. static const struct sPragmaNames {
  94701. const char *const zName; /* Name of pragma */
  94702. u8 ePragTyp; /* PragTyp_XXX value */
  94703. u8 mPragFlag; /* Zero or more PragFlag_XXX values */
  94704. u32 iArg; /* Extra argument */
  94705. } aPragmaNames[] = {
  94706. #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_ENABLE_CEROD)
  94707. { /* zName: */ "activate_extensions",
  94708. /* ePragTyp: */ PragTyp_ACTIVATE_EXTENSIONS,
  94709. /* ePragFlag: */ 0,
  94710. /* iArg: */ 0 },
  94711. #endif
  94712. #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
  94713. { /* zName: */ "application_id",
  94714. /* ePragTyp: */ PragTyp_HEADER_VALUE,
  94715. /* ePragFlag: */ 0,
  94716. /* iArg: */ 0 },
  94717. #endif
  94718. #if !defined(SQLITE_OMIT_AUTOVACUUM)
  94719. { /* zName: */ "auto_vacuum",
  94720. /* ePragTyp: */ PragTyp_AUTO_VACUUM,
  94721. /* ePragFlag: */ PragFlag_NeedSchema,
  94722. /* iArg: */ 0 },
  94723. #endif
  94724. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  94725. #if !defined(SQLITE_OMIT_AUTOMATIC_INDEX)
  94726. { /* zName: */ "automatic_index",
  94727. /* ePragTyp: */ PragTyp_FLAG,
  94728. /* ePragFlag: */ 0,
  94729. /* iArg: */ SQLITE_AutoIndex },
  94730. #endif
  94731. #endif
  94732. { /* zName: */ "busy_timeout",
  94733. /* ePragTyp: */ PragTyp_BUSY_TIMEOUT,
  94734. /* ePragFlag: */ 0,
  94735. /* iArg: */ 0 },
  94736. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  94737. { /* zName: */ "cache_size",
  94738. /* ePragTyp: */ PragTyp_CACHE_SIZE,
  94739. /* ePragFlag: */ PragFlag_NeedSchema,
  94740. /* iArg: */ 0 },
  94741. #endif
  94742. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  94743. { /* zName: */ "cache_spill",
  94744. /* ePragTyp: */ PragTyp_FLAG,
  94745. /* ePragFlag: */ 0,
  94746. /* iArg: */ SQLITE_CacheSpill },
  94747. #endif
  94748. { /* zName: */ "case_sensitive_like",
  94749. /* ePragTyp: */ PragTyp_CASE_SENSITIVE_LIKE,
  94750. /* ePragFlag: */ 0,
  94751. /* iArg: */ 0 },
  94752. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  94753. { /* zName: */ "checkpoint_fullfsync",
  94754. /* ePragTyp: */ PragTyp_FLAG,
  94755. /* ePragFlag: */ 0,
  94756. /* iArg: */ SQLITE_CkptFullFSync },
  94757. #endif
  94758. #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
  94759. { /* zName: */ "collation_list",
  94760. /* ePragTyp: */ PragTyp_COLLATION_LIST,
  94761. /* ePragFlag: */ 0,
  94762. /* iArg: */ 0 },
  94763. #endif
  94764. #if !defined(SQLITE_OMIT_COMPILEOPTION_DIAGS)
  94765. { /* zName: */ "compile_options",
  94766. /* ePragTyp: */ PragTyp_COMPILE_OPTIONS,
  94767. /* ePragFlag: */ 0,
  94768. /* iArg: */ 0 },
  94769. #endif
  94770. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  94771. { /* zName: */ "count_changes",
  94772. /* ePragTyp: */ PragTyp_FLAG,
  94773. /* ePragFlag: */ 0,
  94774. /* iArg: */ SQLITE_CountRows },
  94775. #endif
  94776. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && SQLITE_OS_WIN
  94777. { /* zName: */ "data_store_directory",
  94778. /* ePragTyp: */ PragTyp_DATA_STORE_DIRECTORY,
  94779. /* ePragFlag: */ 0,
  94780. /* iArg: */ 0 },
  94781. #endif
  94782. #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
  94783. { /* zName: */ "database_list",
  94784. /* ePragTyp: */ PragTyp_DATABASE_LIST,
  94785. /* ePragFlag: */ PragFlag_NeedSchema,
  94786. /* iArg: */ 0 },
  94787. #endif
  94788. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && !defined(SQLITE_OMIT_DEPRECATED)
  94789. { /* zName: */ "default_cache_size",
  94790. /* ePragTyp: */ PragTyp_DEFAULT_CACHE_SIZE,
  94791. /* ePragFlag: */ PragFlag_NeedSchema,
  94792. /* iArg: */ 0 },
  94793. #endif
  94794. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  94795. #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
  94796. { /* zName: */ "defer_foreign_keys",
  94797. /* ePragTyp: */ PragTyp_FLAG,
  94798. /* ePragFlag: */ 0,
  94799. /* iArg: */ SQLITE_DeferFKs },
  94800. #endif
  94801. #endif
  94802. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  94803. { /* zName: */ "empty_result_callbacks",
  94804. /* ePragTyp: */ PragTyp_FLAG,
  94805. /* ePragFlag: */ 0,
  94806. /* iArg: */ SQLITE_NullCallback },
  94807. #endif
  94808. #if !defined(SQLITE_OMIT_UTF16)
  94809. { /* zName: */ "encoding",
  94810. /* ePragTyp: */ PragTyp_ENCODING,
  94811. /* ePragFlag: */ 0,
  94812. /* iArg: */ 0 },
  94813. #endif
  94814. #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
  94815. { /* zName: */ "foreign_key_check",
  94816. /* ePragTyp: */ PragTyp_FOREIGN_KEY_CHECK,
  94817. /* ePragFlag: */ PragFlag_NeedSchema,
  94818. /* iArg: */ 0 },
  94819. #endif
  94820. #if !defined(SQLITE_OMIT_FOREIGN_KEY)
  94821. { /* zName: */ "foreign_key_list",
  94822. /* ePragTyp: */ PragTyp_FOREIGN_KEY_LIST,
  94823. /* ePragFlag: */ PragFlag_NeedSchema,
  94824. /* iArg: */ 0 },
  94825. #endif
  94826. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  94827. #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
  94828. { /* zName: */ "foreign_keys",
  94829. /* ePragTyp: */ PragTyp_FLAG,
  94830. /* ePragFlag: */ 0,
  94831. /* iArg: */ SQLITE_ForeignKeys },
  94832. #endif
  94833. #endif
  94834. #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
  94835. { /* zName: */ "freelist_count",
  94836. /* ePragTyp: */ PragTyp_HEADER_VALUE,
  94837. /* ePragFlag: */ 0,
  94838. /* iArg: */ 0 },
  94839. #endif
  94840. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  94841. { /* zName: */ "full_column_names",
  94842. /* ePragTyp: */ PragTyp_FLAG,
  94843. /* ePragFlag: */ 0,
  94844. /* iArg: */ SQLITE_FullColNames },
  94845. { /* zName: */ "fullfsync",
  94846. /* ePragTyp: */ PragTyp_FLAG,
  94847. /* ePragFlag: */ 0,
  94848. /* iArg: */ SQLITE_FullFSync },
  94849. #endif
  94850. #if defined(SQLITE_HAS_CODEC)
  94851. { /* zName: */ "hexkey",
  94852. /* ePragTyp: */ PragTyp_HEXKEY,
  94853. /* ePragFlag: */ 0,
  94854. /* iArg: */ 0 },
  94855. { /* zName: */ "hexrekey",
  94856. /* ePragTyp: */ PragTyp_HEXKEY,
  94857. /* ePragFlag: */ 0,
  94858. /* iArg: */ 0 },
  94859. #endif
  94860. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  94861. #if !defined(SQLITE_OMIT_CHECK)
  94862. { /* zName: */ "ignore_check_constraints",
  94863. /* ePragTyp: */ PragTyp_FLAG,
  94864. /* ePragFlag: */ 0,
  94865. /* iArg: */ SQLITE_IgnoreChecks },
  94866. #endif
  94867. #endif
  94868. #if !defined(SQLITE_OMIT_AUTOVACUUM)
  94869. { /* zName: */ "incremental_vacuum",
  94870. /* ePragTyp: */ PragTyp_INCREMENTAL_VACUUM,
  94871. /* ePragFlag: */ PragFlag_NeedSchema,
  94872. /* iArg: */ 0 },
  94873. #endif
  94874. #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
  94875. { /* zName: */ "index_info",
  94876. /* ePragTyp: */ PragTyp_INDEX_INFO,
  94877. /* ePragFlag: */ PragFlag_NeedSchema,
  94878. /* iArg: */ 0 },
  94879. { /* zName: */ "index_list",
  94880. /* ePragTyp: */ PragTyp_INDEX_LIST,
  94881. /* ePragFlag: */ PragFlag_NeedSchema,
  94882. /* iArg: */ 0 },
  94883. #endif
  94884. #if !defined(SQLITE_OMIT_INTEGRITY_CHECK)
  94885. { /* zName: */ "integrity_check",
  94886. /* ePragTyp: */ PragTyp_INTEGRITY_CHECK,
  94887. /* ePragFlag: */ PragFlag_NeedSchema,
  94888. /* iArg: */ 0 },
  94889. #endif
  94890. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  94891. { /* zName: */ "journal_mode",
  94892. /* ePragTyp: */ PragTyp_JOURNAL_MODE,
  94893. /* ePragFlag: */ PragFlag_NeedSchema,
  94894. /* iArg: */ 0 },
  94895. { /* zName: */ "journal_size_limit",
  94896. /* ePragTyp: */ PragTyp_JOURNAL_SIZE_LIMIT,
  94897. /* ePragFlag: */ 0,
  94898. /* iArg: */ 0 },
  94899. #endif
  94900. #if defined(SQLITE_HAS_CODEC)
  94901. { /* zName: */ "key",
  94902. /* ePragTyp: */ PragTyp_KEY,
  94903. /* ePragFlag: */ 0,
  94904. /* iArg: */ 0 },
  94905. #endif
  94906. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  94907. { /* zName: */ "legacy_file_format",
  94908. /* ePragTyp: */ PragTyp_FLAG,
  94909. /* ePragFlag: */ 0,
  94910. /* iArg: */ SQLITE_LegacyFileFmt },
  94911. #endif
  94912. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && SQLITE_ENABLE_LOCKING_STYLE
  94913. { /* zName: */ "lock_proxy_file",
  94914. /* ePragTyp: */ PragTyp_LOCK_PROXY_FILE,
  94915. /* ePragFlag: */ 0,
  94916. /* iArg: */ 0 },
  94917. #endif
  94918. #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
  94919. { /* zName: */ "lock_status",
  94920. /* ePragTyp: */ PragTyp_LOCK_STATUS,
  94921. /* ePragFlag: */ 0,
  94922. /* iArg: */ 0 },
  94923. #endif
  94924. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  94925. { /* zName: */ "locking_mode",
  94926. /* ePragTyp: */ PragTyp_LOCKING_MODE,
  94927. /* ePragFlag: */ 0,
  94928. /* iArg: */ 0 },
  94929. { /* zName: */ "max_page_count",
  94930. /* ePragTyp: */ PragTyp_PAGE_COUNT,
  94931. /* ePragFlag: */ PragFlag_NeedSchema,
  94932. /* iArg: */ 0 },
  94933. { /* zName: */ "mmap_size",
  94934. /* ePragTyp: */ PragTyp_MMAP_SIZE,
  94935. /* ePragFlag: */ 0,
  94936. /* iArg: */ 0 },
  94937. { /* zName: */ "page_count",
  94938. /* ePragTyp: */ PragTyp_PAGE_COUNT,
  94939. /* ePragFlag: */ PragFlag_NeedSchema,
  94940. /* iArg: */ 0 },
  94941. { /* zName: */ "page_size",
  94942. /* ePragTyp: */ PragTyp_PAGE_SIZE,
  94943. /* ePragFlag: */ 0,
  94944. /* iArg: */ 0 },
  94945. #endif
  94946. #if defined(SQLITE_DEBUG)
  94947. { /* zName: */ "parser_trace",
  94948. /* ePragTyp: */ PragTyp_PARSER_TRACE,
  94949. /* ePragFlag: */ 0,
  94950. /* iArg: */ 0 },
  94951. #endif
  94952. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  94953. { /* zName: */ "query_only",
  94954. /* ePragTyp: */ PragTyp_FLAG,
  94955. /* ePragFlag: */ 0,
  94956. /* iArg: */ SQLITE_QueryOnly },
  94957. #endif
  94958. #if !defined(SQLITE_OMIT_INTEGRITY_CHECK)
  94959. { /* zName: */ "quick_check",
  94960. /* ePragTyp: */ PragTyp_INTEGRITY_CHECK,
  94961. /* ePragFlag: */ PragFlag_NeedSchema,
  94962. /* iArg: */ 0 },
  94963. #endif
  94964. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  94965. { /* zName: */ "read_uncommitted",
  94966. /* ePragTyp: */ PragTyp_FLAG,
  94967. /* ePragFlag: */ 0,
  94968. /* iArg: */ SQLITE_ReadUncommitted },
  94969. { /* zName: */ "recursive_triggers",
  94970. /* ePragTyp: */ PragTyp_FLAG,
  94971. /* ePragFlag: */ 0,
  94972. /* iArg: */ SQLITE_RecTriggers },
  94973. #endif
  94974. #if defined(SQLITE_HAS_CODEC)
  94975. { /* zName: */ "rekey",
  94976. /* ePragTyp: */ PragTyp_REKEY,
  94977. /* ePragFlag: */ 0,
  94978. /* iArg: */ 0 },
  94979. #endif
  94980. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  94981. { /* zName: */ "reverse_unordered_selects",
  94982. /* ePragTyp: */ PragTyp_FLAG,
  94983. /* ePragFlag: */ 0,
  94984. /* iArg: */ SQLITE_ReverseOrder },
  94985. #endif
  94986. #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
  94987. { /* zName: */ "schema_version",
  94988. /* ePragTyp: */ PragTyp_HEADER_VALUE,
  94989. /* ePragFlag: */ 0,
  94990. /* iArg: */ 0 },
  94991. #endif
  94992. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  94993. { /* zName: */ "secure_delete",
  94994. /* ePragTyp: */ PragTyp_SECURE_DELETE,
  94995. /* ePragFlag: */ 0,
  94996. /* iArg: */ 0 },
  94997. #endif
  94998. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  94999. { /* zName: */ "short_column_names",
  95000. /* ePragTyp: */ PragTyp_FLAG,
  95001. /* ePragFlag: */ 0,
  95002. /* iArg: */ SQLITE_ShortColNames },
  95003. #endif
  95004. { /* zName: */ "shrink_memory",
  95005. /* ePragTyp: */ PragTyp_SHRINK_MEMORY,
  95006. /* ePragFlag: */ 0,
  95007. /* iArg: */ 0 },
  95008. { /* zName: */ "soft_heap_limit",
  95009. /* ePragTyp: */ PragTyp_SOFT_HEAP_LIMIT,
  95010. /* ePragFlag: */ 0,
  95011. /* iArg: */ 0 },
  95012. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  95013. #if defined(SQLITE_DEBUG)
  95014. { /* zName: */ "sql_trace",
  95015. /* ePragTyp: */ PragTyp_FLAG,
  95016. /* ePragFlag: */ 0,
  95017. /* iArg: */ SQLITE_SqlTrace },
  95018. #endif
  95019. #endif
  95020. #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
  95021. { /* zName: */ "stats",
  95022. /* ePragTyp: */ PragTyp_STATS,
  95023. /* ePragFlag: */ PragFlag_NeedSchema,
  95024. /* iArg: */ 0 },
  95025. #endif
  95026. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  95027. { /* zName: */ "synchronous",
  95028. /* ePragTyp: */ PragTyp_SYNCHRONOUS,
  95029. /* ePragFlag: */ PragFlag_NeedSchema,
  95030. /* iArg: */ 0 },
  95031. #endif
  95032. #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
  95033. { /* zName: */ "table_info",
  95034. /* ePragTyp: */ PragTyp_TABLE_INFO,
  95035. /* ePragFlag: */ PragFlag_NeedSchema,
  95036. /* iArg: */ 0 },
  95037. #endif
  95038. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  95039. { /* zName: */ "temp_store",
  95040. /* ePragTyp: */ PragTyp_TEMP_STORE,
  95041. /* ePragFlag: */ 0,
  95042. /* iArg: */ 0 },
  95043. { /* zName: */ "temp_store_directory",
  95044. /* ePragTyp: */ PragTyp_TEMP_STORE_DIRECTORY,
  95045. /* ePragFlag: */ 0,
  95046. /* iArg: */ 0 },
  95047. #endif
  95048. { /* zName: */ "threads",
  95049. /* ePragTyp: */ PragTyp_THREADS,
  95050. /* ePragFlag: */ 0,
  95051. /* iArg: */ 0 },
  95052. #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
  95053. { /* zName: */ "user_version",
  95054. /* ePragTyp: */ PragTyp_HEADER_VALUE,
  95055. /* ePragFlag: */ 0,
  95056. /* iArg: */ 0 },
  95057. #endif
  95058. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  95059. #if defined(SQLITE_DEBUG)
  95060. { /* zName: */ "vdbe_addoptrace",
  95061. /* ePragTyp: */ PragTyp_FLAG,
  95062. /* ePragFlag: */ 0,
  95063. /* iArg: */ SQLITE_VdbeAddopTrace },
  95064. { /* zName: */ "vdbe_debug",
  95065. /* ePragTyp: */ PragTyp_FLAG,
  95066. /* ePragFlag: */ 0,
  95067. /* iArg: */ SQLITE_SqlTrace|SQLITE_VdbeListing|SQLITE_VdbeTrace },
  95068. { /* zName: */ "vdbe_eqp",
  95069. /* ePragTyp: */ PragTyp_FLAG,
  95070. /* ePragFlag: */ 0,
  95071. /* iArg: */ SQLITE_VdbeEQP },
  95072. { /* zName: */ "vdbe_listing",
  95073. /* ePragTyp: */ PragTyp_FLAG,
  95074. /* ePragFlag: */ 0,
  95075. /* iArg: */ SQLITE_VdbeListing },
  95076. { /* zName: */ "vdbe_trace",
  95077. /* ePragTyp: */ PragTyp_FLAG,
  95078. /* ePragFlag: */ 0,
  95079. /* iArg: */ SQLITE_VdbeTrace },
  95080. #endif
  95081. #endif
  95082. #if !defined(SQLITE_OMIT_WAL)
  95083. { /* zName: */ "wal_autocheckpoint",
  95084. /* ePragTyp: */ PragTyp_WAL_AUTOCHECKPOINT,
  95085. /* ePragFlag: */ 0,
  95086. /* iArg: */ 0 },
  95087. { /* zName: */ "wal_checkpoint",
  95088. /* ePragTyp: */ PragTyp_WAL_CHECKPOINT,
  95089. /* ePragFlag: */ PragFlag_NeedSchema,
  95090. /* iArg: */ 0 },
  95091. #endif
  95092. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  95093. { /* zName: */ "writable_schema",
  95094. /* ePragTyp: */ PragTyp_FLAG,
  95095. /* ePragFlag: */ 0,
  95096. /* iArg: */ SQLITE_WriteSchema|SQLITE_RecoveryMode },
  95097. #endif
  95098. };
  95099. /* Number of pragmas: 57 on by default, 70 total. */
  95100. /* End of the automatically generated pragma table.
  95101. ***************************************************************************/
  95102. /*
  95103. ** Interpret the given string as a safety level. Return 0 for OFF,
  95104. ** 1 for ON or NORMAL and 2 for FULL. Return 1 for an empty or
  95105. ** unrecognized string argument. The FULL option is disallowed
  95106. ** if the omitFull parameter it 1.
  95107. **
  95108. ** Note that the values returned are one less that the values that
  95109. ** should be passed into sqlite3BtreeSetSafetyLevel(). The is done
  95110. ** to support legacy SQL code. The safety level used to be boolean
  95111. ** and older scripts may have used numbers 0 for OFF and 1 for ON.
  95112. */
  95113. static u8 getSafetyLevel(const char *z, int omitFull, u8 dflt){
  95114. /* 123456789 123456789 */
  95115. static const char zText[] = "onoffalseyestruefull";
  95116. static const u8 iOffset[] = {0, 1, 2, 4, 9, 12, 16};
  95117. static const u8 iLength[] = {2, 2, 3, 5, 3, 4, 4};
  95118. static const u8 iValue[] = {1, 0, 0, 0, 1, 1, 2};
  95119. int i, n;
  95120. if( sqlite3Isdigit(*z) ){
  95121. return (u8)sqlite3Atoi(z);
  95122. }
  95123. n = sqlite3Strlen30(z);
  95124. for(i=0; i<ArraySize(iLength)-omitFull; i++){
  95125. if( iLength[i]==n && sqlite3StrNICmp(&zText[iOffset[i]],z,n)==0 ){
  95126. return iValue[i];
  95127. }
  95128. }
  95129. return dflt;
  95130. }
  95131. /*
  95132. ** Interpret the given string as a boolean value.
  95133. */
  95134. SQLITE_PRIVATE u8 sqlite3GetBoolean(const char *z, u8 dflt){
  95135. return getSafetyLevel(z,1,dflt)!=0;
  95136. }
  95137. /* The sqlite3GetBoolean() function is used by other modules but the
  95138. ** remainder of this file is specific to PRAGMA processing. So omit
  95139. ** the rest of the file if PRAGMAs are omitted from the build.
  95140. */
  95141. #if !defined(SQLITE_OMIT_PRAGMA)
  95142. /*
  95143. ** Interpret the given string as a locking mode value.
  95144. */
  95145. static int getLockingMode(const char *z){
  95146. if( z ){
  95147. if( 0==sqlite3StrICmp(z, "exclusive") ) return PAGER_LOCKINGMODE_EXCLUSIVE;
  95148. if( 0==sqlite3StrICmp(z, "normal") ) return PAGER_LOCKINGMODE_NORMAL;
  95149. }
  95150. return PAGER_LOCKINGMODE_QUERY;
  95151. }
  95152. #ifndef SQLITE_OMIT_AUTOVACUUM
  95153. /*
  95154. ** Interpret the given string as an auto-vacuum mode value.
  95155. **
  95156. ** The following strings, "none", "full" and "incremental" are
  95157. ** acceptable, as are their numeric equivalents: 0, 1 and 2 respectively.
  95158. */
  95159. static int getAutoVacuum(const char *z){
  95160. int i;
  95161. if( 0==sqlite3StrICmp(z, "none") ) return BTREE_AUTOVACUUM_NONE;
  95162. if( 0==sqlite3StrICmp(z, "full") ) return BTREE_AUTOVACUUM_FULL;
  95163. if( 0==sqlite3StrICmp(z, "incremental") ) return BTREE_AUTOVACUUM_INCR;
  95164. i = sqlite3Atoi(z);
  95165. return (u8)((i>=0&&i<=2)?i:0);
  95166. }
  95167. #endif /* ifndef SQLITE_OMIT_AUTOVACUUM */
  95168. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  95169. /*
  95170. ** Interpret the given string as a temp db location. Return 1 for file
  95171. ** backed temporary databases, 2 for the Red-Black tree in memory database
  95172. ** and 0 to use the compile-time default.
  95173. */
  95174. static int getTempStore(const char *z){
  95175. if( z[0]>='0' && z[0]<='2' ){
  95176. return z[0] - '0';
  95177. }else if( sqlite3StrICmp(z, "file")==0 ){
  95178. return 1;
  95179. }else if( sqlite3StrICmp(z, "memory")==0 ){
  95180. return 2;
  95181. }else{
  95182. return 0;
  95183. }
  95184. }
  95185. #endif /* SQLITE_PAGER_PRAGMAS */
  95186. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  95187. /*
  95188. ** Invalidate temp storage, either when the temp storage is changed
  95189. ** from default, or when 'file' and the temp_store_directory has changed
  95190. */
  95191. static int invalidateTempStorage(Parse *pParse){
  95192. sqlite3 *db = pParse->db;
  95193. if( db->aDb[1].pBt!=0 ){
  95194. if( !db->autoCommit || sqlite3BtreeIsInReadTrans(db->aDb[1].pBt) ){
  95195. sqlite3ErrorMsg(pParse, "temporary storage cannot be changed "
  95196. "from within a transaction");
  95197. return SQLITE_ERROR;
  95198. }
  95199. sqlite3BtreeClose(db->aDb[1].pBt);
  95200. db->aDb[1].pBt = 0;
  95201. sqlite3ResetAllSchemasOfConnection(db);
  95202. }
  95203. return SQLITE_OK;
  95204. }
  95205. #endif /* SQLITE_PAGER_PRAGMAS */
  95206. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  95207. /*
  95208. ** If the TEMP database is open, close it and mark the database schema
  95209. ** as needing reloading. This must be done when using the SQLITE_TEMP_STORE
  95210. ** or DEFAULT_TEMP_STORE pragmas.
  95211. */
  95212. static int changeTempStorage(Parse *pParse, const char *zStorageType){
  95213. int ts = getTempStore(zStorageType);
  95214. sqlite3 *db = pParse->db;
  95215. if( db->temp_store==ts ) return SQLITE_OK;
  95216. if( invalidateTempStorage( pParse ) != SQLITE_OK ){
  95217. return SQLITE_ERROR;
  95218. }
  95219. db->temp_store = (u8)ts;
  95220. return SQLITE_OK;
  95221. }
  95222. #endif /* SQLITE_PAGER_PRAGMAS */
  95223. /*
  95224. ** Generate code to return a single integer value.
  95225. */
  95226. static void returnSingleInt(Parse *pParse, const char *zLabel, i64 value){
  95227. Vdbe *v = sqlite3GetVdbe(pParse);
  95228. int mem = ++pParse->nMem;
  95229. i64 *pI64 = sqlite3DbMallocRaw(pParse->db, sizeof(value));
  95230. if( pI64 ){
  95231. memcpy(pI64, &value, sizeof(value));
  95232. }
  95233. sqlite3VdbeAddOp4(v, OP_Int64, 0, mem, 0, (char*)pI64, P4_INT64);
  95234. sqlite3VdbeSetNumCols(v, 1);
  95235. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLabel, SQLITE_STATIC);
  95236. sqlite3VdbeAddOp2(v, OP_ResultRow, mem, 1);
  95237. }
  95238. /*
  95239. ** Set the safety_level and pager flags for pager iDb. Or if iDb<0
  95240. ** set these values for all pagers.
  95241. */
  95242. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  95243. static void setAllPagerFlags(sqlite3 *db){
  95244. if( db->autoCommit ){
  95245. Db *pDb = db->aDb;
  95246. int n = db->nDb;
  95247. assert( SQLITE_FullFSync==PAGER_FULLFSYNC );
  95248. assert( SQLITE_CkptFullFSync==PAGER_CKPT_FULLFSYNC );
  95249. assert( SQLITE_CacheSpill==PAGER_CACHESPILL );
  95250. assert( (PAGER_FULLFSYNC | PAGER_CKPT_FULLFSYNC | PAGER_CACHESPILL)
  95251. == PAGER_FLAGS_MASK );
  95252. assert( (pDb->safety_level & PAGER_SYNCHRONOUS_MASK)==pDb->safety_level );
  95253. while( (n--) > 0 ){
  95254. if( pDb->pBt ){
  95255. sqlite3BtreeSetPagerFlags(pDb->pBt,
  95256. pDb->safety_level | (db->flags & PAGER_FLAGS_MASK) );
  95257. }
  95258. pDb++;
  95259. }
  95260. }
  95261. }
  95262. #else
  95263. # define setAllPagerFlags(X) /* no-op */
  95264. #endif
  95265. /*
  95266. ** Return a human-readable name for a constraint resolution action.
  95267. */
  95268. #ifndef SQLITE_OMIT_FOREIGN_KEY
  95269. static const char *actionName(u8 action){
  95270. const char *zName;
  95271. switch( action ){
  95272. case OE_SetNull: zName = "SET NULL"; break;
  95273. case OE_SetDflt: zName = "SET DEFAULT"; break;
  95274. case OE_Cascade: zName = "CASCADE"; break;
  95275. case OE_Restrict: zName = "RESTRICT"; break;
  95276. default: zName = "NO ACTION";
  95277. assert( action==OE_None ); break;
  95278. }
  95279. return zName;
  95280. }
  95281. #endif
  95282. /*
  95283. ** Parameter eMode must be one of the PAGER_JOURNALMODE_XXX constants
  95284. ** defined in pager.h. This function returns the associated lowercase
  95285. ** journal-mode name.
  95286. */
  95287. SQLITE_PRIVATE const char *sqlite3JournalModename(int eMode){
  95288. static char * const azModeName[] = {
  95289. "delete", "persist", "off", "truncate", "memory"
  95290. #ifndef SQLITE_OMIT_WAL
  95291. , "wal"
  95292. #endif
  95293. };
  95294. assert( PAGER_JOURNALMODE_DELETE==0 );
  95295. assert( PAGER_JOURNALMODE_PERSIST==1 );
  95296. assert( PAGER_JOURNALMODE_OFF==2 );
  95297. assert( PAGER_JOURNALMODE_TRUNCATE==3 );
  95298. assert( PAGER_JOURNALMODE_MEMORY==4 );
  95299. assert( PAGER_JOURNALMODE_WAL==5 );
  95300. assert( eMode>=0 && eMode<=ArraySize(azModeName) );
  95301. if( eMode==ArraySize(azModeName) ) return 0;
  95302. return azModeName[eMode];
  95303. }
  95304. /*
  95305. ** Process a pragma statement.
  95306. **
  95307. ** Pragmas are of this form:
  95308. **
  95309. ** PRAGMA [database.]id [= value]
  95310. **
  95311. ** The identifier might also be a string. The value is a string, and
  95312. ** identifier, or a number. If minusFlag is true, then the value is
  95313. ** a number that was preceded by a minus sign.
  95314. **
  95315. ** If the left side is "database.id" then pId1 is the database name
  95316. ** and pId2 is the id. If the left side is just "id" then pId1 is the
  95317. ** id and pId2 is any empty string.
  95318. */
  95319. SQLITE_PRIVATE void sqlite3Pragma(
  95320. Parse *pParse,
  95321. Token *pId1, /* First part of [database.]id field */
  95322. Token *pId2, /* Second part of [database.]id field, or NULL */
  95323. Token *pValue, /* Token for <value>, or NULL */
  95324. int minusFlag /* True if a '-' sign preceded <value> */
  95325. ){
  95326. char *zLeft = 0; /* Nul-terminated UTF-8 string <id> */
  95327. char *zRight = 0; /* Nul-terminated UTF-8 string <value>, or NULL */
  95328. const char *zDb = 0; /* The database name */
  95329. Token *pId; /* Pointer to <id> token */
  95330. char *aFcntl[4]; /* Argument to SQLITE_FCNTL_PRAGMA */
  95331. int iDb; /* Database index for <database> */
  95332. int lwr, upr, mid; /* Binary search bounds */
  95333. int rc; /* return value form SQLITE_FCNTL_PRAGMA */
  95334. sqlite3 *db = pParse->db; /* The database connection */
  95335. Db *pDb; /* The specific database being pragmaed */
  95336. Vdbe *v = sqlite3GetVdbe(pParse); /* Prepared statement */
  95337. if( v==0 ) return;
  95338. sqlite3VdbeRunOnlyOnce(v);
  95339. pParse->nMem = 2;
  95340. /* Interpret the [database.] part of the pragma statement. iDb is the
  95341. ** index of the database this pragma is being applied to in db.aDb[]. */
  95342. iDb = sqlite3TwoPartName(pParse, pId1, pId2, &pId);
  95343. if( iDb<0 ) return;
  95344. pDb = &db->aDb[iDb];
  95345. /* If the temp database has been explicitly named as part of the
  95346. ** pragma, make sure it is open.
  95347. */
  95348. if( iDb==1 && sqlite3OpenTempDatabase(pParse) ){
  95349. return;
  95350. }
  95351. zLeft = sqlite3NameFromToken(db, pId);
  95352. if( !zLeft ) return;
  95353. if( minusFlag ){
  95354. zRight = sqlite3MPrintf(db, "-%T", pValue);
  95355. }else{
  95356. zRight = sqlite3NameFromToken(db, pValue);
  95357. }
  95358. assert( pId2 );
  95359. zDb = pId2->n>0 ? pDb->zName : 0;
  95360. if( sqlite3AuthCheck(pParse, SQLITE_PRAGMA, zLeft, zRight, zDb) ){
  95361. goto pragma_out;
  95362. }
  95363. /* Send an SQLITE_FCNTL_PRAGMA file-control to the underlying VFS
  95364. ** connection. If it returns SQLITE_OK, then assume that the VFS
  95365. ** handled the pragma and generate a no-op prepared statement.
  95366. */
  95367. aFcntl[0] = 0;
  95368. aFcntl[1] = zLeft;
  95369. aFcntl[2] = zRight;
  95370. aFcntl[3] = 0;
  95371. db->busyHandler.nBusy = 0;
  95372. rc = sqlite3_file_control(db, zDb, SQLITE_FCNTL_PRAGMA, (void*)aFcntl);
  95373. if( rc==SQLITE_OK ){
  95374. if( aFcntl[0] ){
  95375. int mem = ++pParse->nMem;
  95376. sqlite3VdbeAddOp4(v, OP_String8, 0, mem, 0, aFcntl[0], 0);
  95377. sqlite3VdbeSetNumCols(v, 1);
  95378. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "result", SQLITE_STATIC);
  95379. sqlite3VdbeAddOp2(v, OP_ResultRow, mem, 1);
  95380. sqlite3_free(aFcntl[0]);
  95381. }
  95382. goto pragma_out;
  95383. }
  95384. if( rc!=SQLITE_NOTFOUND ){
  95385. if( aFcntl[0] ){
  95386. sqlite3ErrorMsg(pParse, "%s", aFcntl[0]);
  95387. sqlite3_free(aFcntl[0]);
  95388. }
  95389. pParse->nErr++;
  95390. pParse->rc = rc;
  95391. goto pragma_out;
  95392. }
  95393. /* Locate the pragma in the lookup table */
  95394. lwr = 0;
  95395. upr = ArraySize(aPragmaNames)-1;
  95396. while( lwr<=upr ){
  95397. mid = (lwr+upr)/2;
  95398. rc = sqlite3_stricmp(zLeft, aPragmaNames[mid].zName);
  95399. if( rc==0 ) break;
  95400. if( rc<0 ){
  95401. upr = mid - 1;
  95402. }else{
  95403. lwr = mid + 1;
  95404. }
  95405. }
  95406. if( lwr>upr ) goto pragma_out;
  95407. /* Make sure the database schema is loaded if the pragma requires that */
  95408. if( (aPragmaNames[mid].mPragFlag & PragFlag_NeedSchema)!=0 ){
  95409. if( sqlite3ReadSchema(pParse) ) goto pragma_out;
  95410. }
  95411. /* Jump to the appropriate pragma handler */
  95412. switch( aPragmaNames[mid].ePragTyp ){
  95413. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && !defined(SQLITE_OMIT_DEPRECATED)
  95414. /*
  95415. ** PRAGMA [database.]default_cache_size
  95416. ** PRAGMA [database.]default_cache_size=N
  95417. **
  95418. ** The first form reports the current persistent setting for the
  95419. ** page cache size. The value returned is the maximum number of
  95420. ** pages in the page cache. The second form sets both the current
  95421. ** page cache size value and the persistent page cache size value
  95422. ** stored in the database file.
  95423. **
  95424. ** Older versions of SQLite would set the default cache size to a
  95425. ** negative number to indicate synchronous=OFF. These days, synchronous
  95426. ** is always on by default regardless of the sign of the default cache
  95427. ** size. But continue to take the absolute value of the default cache
  95428. ** size of historical compatibility.
  95429. */
  95430. case PragTyp_DEFAULT_CACHE_SIZE: {
  95431. static const int iLn = VDBE_OFFSET_LINENO(2);
  95432. static const VdbeOpList getCacheSize[] = {
  95433. { OP_Transaction, 0, 0, 0}, /* 0 */
  95434. { OP_ReadCookie, 0, 1, BTREE_DEFAULT_CACHE_SIZE}, /* 1 */
  95435. { OP_IfPos, 1, 8, 0},
  95436. { OP_Integer, 0, 2, 0},
  95437. { OP_Subtract, 1, 2, 1},
  95438. { OP_IfPos, 1, 8, 0},
  95439. { OP_Integer, 0, 1, 0}, /* 6 */
  95440. { OP_Noop, 0, 0, 0},
  95441. { OP_ResultRow, 1, 1, 0},
  95442. };
  95443. int addr;
  95444. sqlite3VdbeUsesBtree(v, iDb);
  95445. if( !zRight ){
  95446. sqlite3VdbeSetNumCols(v, 1);
  95447. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "cache_size", SQLITE_STATIC);
  95448. pParse->nMem += 2;
  95449. addr = sqlite3VdbeAddOpList(v, ArraySize(getCacheSize), getCacheSize,iLn);
  95450. sqlite3VdbeChangeP1(v, addr, iDb);
  95451. sqlite3VdbeChangeP1(v, addr+1, iDb);
  95452. sqlite3VdbeChangeP1(v, addr+6, SQLITE_DEFAULT_CACHE_SIZE);
  95453. }else{
  95454. int size = sqlite3AbsInt32(sqlite3Atoi(zRight));
  95455. sqlite3BeginWriteOperation(pParse, 0, iDb);
  95456. sqlite3VdbeAddOp2(v, OP_Integer, size, 1);
  95457. sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_DEFAULT_CACHE_SIZE, 1);
  95458. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  95459. pDb->pSchema->cache_size = size;
  95460. sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
  95461. }
  95462. break;
  95463. }
  95464. #endif /* !SQLITE_OMIT_PAGER_PRAGMAS && !SQLITE_OMIT_DEPRECATED */
  95465. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  95466. /*
  95467. ** PRAGMA [database.]page_size
  95468. ** PRAGMA [database.]page_size=N
  95469. **
  95470. ** The first form reports the current setting for the
  95471. ** database page size in bytes. The second form sets the
  95472. ** database page size value. The value can only be set if
  95473. ** the database has not yet been created.
  95474. */
  95475. case PragTyp_PAGE_SIZE: {
  95476. Btree *pBt = pDb->pBt;
  95477. assert( pBt!=0 );
  95478. if( !zRight ){
  95479. int size = ALWAYS(pBt) ? sqlite3BtreeGetPageSize(pBt) : 0;
  95480. returnSingleInt(pParse, "page_size", size);
  95481. }else{
  95482. /* Malloc may fail when setting the page-size, as there is an internal
  95483. ** buffer that the pager module resizes using sqlite3_realloc().
  95484. */
  95485. db->nextPagesize = sqlite3Atoi(zRight);
  95486. if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize,-1,0) ){
  95487. db->mallocFailed = 1;
  95488. }
  95489. }
  95490. break;
  95491. }
  95492. /*
  95493. ** PRAGMA [database.]secure_delete
  95494. ** PRAGMA [database.]secure_delete=ON/OFF
  95495. **
  95496. ** The first form reports the current setting for the
  95497. ** secure_delete flag. The second form changes the secure_delete
  95498. ** flag setting and reports thenew value.
  95499. */
  95500. case PragTyp_SECURE_DELETE: {
  95501. Btree *pBt = pDb->pBt;
  95502. int b = -1;
  95503. assert( pBt!=0 );
  95504. if( zRight ){
  95505. b = sqlite3GetBoolean(zRight, 0);
  95506. }
  95507. if( pId2->n==0 && b>=0 ){
  95508. int ii;
  95509. for(ii=0; ii<db->nDb; ii++){
  95510. sqlite3BtreeSecureDelete(db->aDb[ii].pBt, b);
  95511. }
  95512. }
  95513. b = sqlite3BtreeSecureDelete(pBt, b);
  95514. returnSingleInt(pParse, "secure_delete", b);
  95515. break;
  95516. }
  95517. /*
  95518. ** PRAGMA [database.]max_page_count
  95519. ** PRAGMA [database.]max_page_count=N
  95520. **
  95521. ** The first form reports the current setting for the
  95522. ** maximum number of pages in the database file. The
  95523. ** second form attempts to change this setting. Both
  95524. ** forms return the current setting.
  95525. **
  95526. ** The absolute value of N is used. This is undocumented and might
  95527. ** change. The only purpose is to provide an easy way to test
  95528. ** the sqlite3AbsInt32() function.
  95529. **
  95530. ** PRAGMA [database.]page_count
  95531. **
  95532. ** Return the number of pages in the specified database.
  95533. */
  95534. case PragTyp_PAGE_COUNT: {
  95535. int iReg;
  95536. sqlite3CodeVerifySchema(pParse, iDb);
  95537. iReg = ++pParse->nMem;
  95538. if( sqlite3Tolower(zLeft[0])=='p' ){
  95539. sqlite3VdbeAddOp2(v, OP_Pagecount, iDb, iReg);
  95540. }else{
  95541. sqlite3VdbeAddOp3(v, OP_MaxPgcnt, iDb, iReg,
  95542. sqlite3AbsInt32(sqlite3Atoi(zRight)));
  95543. }
  95544. sqlite3VdbeAddOp2(v, OP_ResultRow, iReg, 1);
  95545. sqlite3VdbeSetNumCols(v, 1);
  95546. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, SQLITE_TRANSIENT);
  95547. break;
  95548. }
  95549. /*
  95550. ** PRAGMA [database.]locking_mode
  95551. ** PRAGMA [database.]locking_mode = (normal|exclusive)
  95552. */
  95553. case PragTyp_LOCKING_MODE: {
  95554. const char *zRet = "normal";
  95555. int eMode = getLockingMode(zRight);
  95556. if( pId2->n==0 && eMode==PAGER_LOCKINGMODE_QUERY ){
  95557. /* Simple "PRAGMA locking_mode;" statement. This is a query for
  95558. ** the current default locking mode (which may be different to
  95559. ** the locking-mode of the main database).
  95560. */
  95561. eMode = db->dfltLockMode;
  95562. }else{
  95563. Pager *pPager;
  95564. if( pId2->n==0 ){
  95565. /* This indicates that no database name was specified as part
  95566. ** of the PRAGMA command. In this case the locking-mode must be
  95567. ** set on all attached databases, as well as the main db file.
  95568. **
  95569. ** Also, the sqlite3.dfltLockMode variable is set so that
  95570. ** any subsequently attached databases also use the specified
  95571. ** locking mode.
  95572. */
  95573. int ii;
  95574. assert(pDb==&db->aDb[0]);
  95575. for(ii=2; ii<db->nDb; ii++){
  95576. pPager = sqlite3BtreePager(db->aDb[ii].pBt);
  95577. sqlite3PagerLockingMode(pPager, eMode);
  95578. }
  95579. db->dfltLockMode = (u8)eMode;
  95580. }
  95581. pPager = sqlite3BtreePager(pDb->pBt);
  95582. eMode = sqlite3PagerLockingMode(pPager, eMode);
  95583. }
  95584. assert( eMode==PAGER_LOCKINGMODE_NORMAL
  95585. || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
  95586. if( eMode==PAGER_LOCKINGMODE_EXCLUSIVE ){
  95587. zRet = "exclusive";
  95588. }
  95589. sqlite3VdbeSetNumCols(v, 1);
  95590. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "locking_mode", SQLITE_STATIC);
  95591. sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, zRet, 0);
  95592. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
  95593. break;
  95594. }
  95595. /*
  95596. ** PRAGMA [database.]journal_mode
  95597. ** PRAGMA [database.]journal_mode =
  95598. ** (delete|persist|off|truncate|memory|wal|off)
  95599. */
  95600. case PragTyp_JOURNAL_MODE: {
  95601. int eMode; /* One of the PAGER_JOURNALMODE_XXX symbols */
  95602. int ii; /* Loop counter */
  95603. sqlite3VdbeSetNumCols(v, 1);
  95604. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "journal_mode", SQLITE_STATIC);
  95605. if( zRight==0 ){
  95606. /* If there is no "=MODE" part of the pragma, do a query for the
  95607. ** current mode */
  95608. eMode = PAGER_JOURNALMODE_QUERY;
  95609. }else{
  95610. const char *zMode;
  95611. int n = sqlite3Strlen30(zRight);
  95612. for(eMode=0; (zMode = sqlite3JournalModename(eMode))!=0; eMode++){
  95613. if( sqlite3StrNICmp(zRight, zMode, n)==0 ) break;
  95614. }
  95615. if( !zMode ){
  95616. /* If the "=MODE" part does not match any known journal mode,
  95617. ** then do a query */
  95618. eMode = PAGER_JOURNALMODE_QUERY;
  95619. }
  95620. }
  95621. if( eMode==PAGER_JOURNALMODE_QUERY && pId2->n==0 ){
  95622. /* Convert "PRAGMA journal_mode" into "PRAGMA main.journal_mode" */
  95623. iDb = 0;
  95624. pId2->n = 1;
  95625. }
  95626. for(ii=db->nDb-1; ii>=0; ii--){
  95627. if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){
  95628. sqlite3VdbeUsesBtree(v, ii);
  95629. sqlite3VdbeAddOp3(v, OP_JournalMode, ii, 1, eMode);
  95630. }
  95631. }
  95632. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
  95633. break;
  95634. }
  95635. /*
  95636. ** PRAGMA [database.]journal_size_limit
  95637. ** PRAGMA [database.]journal_size_limit=N
  95638. **
  95639. ** Get or set the size limit on rollback journal files.
  95640. */
  95641. case PragTyp_JOURNAL_SIZE_LIMIT: {
  95642. Pager *pPager = sqlite3BtreePager(pDb->pBt);
  95643. i64 iLimit = -2;
  95644. if( zRight ){
  95645. sqlite3DecOrHexToI64(zRight, &iLimit);
  95646. if( iLimit<-1 ) iLimit = -1;
  95647. }
  95648. iLimit = sqlite3PagerJournalSizeLimit(pPager, iLimit);
  95649. returnSingleInt(pParse, "journal_size_limit", iLimit);
  95650. break;
  95651. }
  95652. #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
  95653. /*
  95654. ** PRAGMA [database.]auto_vacuum
  95655. ** PRAGMA [database.]auto_vacuum=N
  95656. **
  95657. ** Get or set the value of the database 'auto-vacuum' parameter.
  95658. ** The value is one of: 0 NONE 1 FULL 2 INCREMENTAL
  95659. */
  95660. #ifndef SQLITE_OMIT_AUTOVACUUM
  95661. case PragTyp_AUTO_VACUUM: {
  95662. Btree *pBt = pDb->pBt;
  95663. assert( pBt!=0 );
  95664. if( !zRight ){
  95665. returnSingleInt(pParse, "auto_vacuum", sqlite3BtreeGetAutoVacuum(pBt));
  95666. }else{
  95667. int eAuto = getAutoVacuum(zRight);
  95668. assert( eAuto>=0 && eAuto<=2 );
  95669. db->nextAutovac = (u8)eAuto;
  95670. /* Call SetAutoVacuum() to set initialize the internal auto and
  95671. ** incr-vacuum flags. This is required in case this connection
  95672. ** creates the database file. It is important that it is created
  95673. ** as an auto-vacuum capable db.
  95674. */
  95675. rc = sqlite3BtreeSetAutoVacuum(pBt, eAuto);
  95676. if( rc==SQLITE_OK && (eAuto==1 || eAuto==2) ){
  95677. /* When setting the auto_vacuum mode to either "full" or
  95678. ** "incremental", write the value of meta[6] in the database
  95679. ** file. Before writing to meta[6], check that meta[3] indicates
  95680. ** that this really is an auto-vacuum capable database.
  95681. */
  95682. static const int iLn = VDBE_OFFSET_LINENO(2);
  95683. static const VdbeOpList setMeta6[] = {
  95684. { OP_Transaction, 0, 1, 0}, /* 0 */
  95685. { OP_ReadCookie, 0, 1, BTREE_LARGEST_ROOT_PAGE},
  95686. { OP_If, 1, 0, 0}, /* 2 */
  95687. { OP_Halt, SQLITE_OK, OE_Abort, 0}, /* 3 */
  95688. { OP_Integer, 0, 1, 0}, /* 4 */
  95689. { OP_SetCookie, 0, BTREE_INCR_VACUUM, 1}, /* 5 */
  95690. };
  95691. int iAddr;
  95692. iAddr = sqlite3VdbeAddOpList(v, ArraySize(setMeta6), setMeta6, iLn);
  95693. sqlite3VdbeChangeP1(v, iAddr, iDb);
  95694. sqlite3VdbeChangeP1(v, iAddr+1, iDb);
  95695. sqlite3VdbeChangeP2(v, iAddr+2, iAddr+4);
  95696. sqlite3VdbeChangeP1(v, iAddr+4, eAuto-1);
  95697. sqlite3VdbeChangeP1(v, iAddr+5, iDb);
  95698. sqlite3VdbeUsesBtree(v, iDb);
  95699. }
  95700. }
  95701. break;
  95702. }
  95703. #endif
  95704. /*
  95705. ** PRAGMA [database.]incremental_vacuum(N)
  95706. **
  95707. ** Do N steps of incremental vacuuming on a database.
  95708. */
  95709. #ifndef SQLITE_OMIT_AUTOVACUUM
  95710. case PragTyp_INCREMENTAL_VACUUM: {
  95711. int iLimit, addr;
  95712. if( zRight==0 || !sqlite3GetInt32(zRight, &iLimit) || iLimit<=0 ){
  95713. iLimit = 0x7fffffff;
  95714. }
  95715. sqlite3BeginWriteOperation(pParse, 0, iDb);
  95716. sqlite3VdbeAddOp2(v, OP_Integer, iLimit, 1);
  95717. addr = sqlite3VdbeAddOp1(v, OP_IncrVacuum, iDb); VdbeCoverage(v);
  95718. sqlite3VdbeAddOp1(v, OP_ResultRow, 1);
  95719. sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1);
  95720. sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr); VdbeCoverage(v);
  95721. sqlite3VdbeJumpHere(v, addr);
  95722. break;
  95723. }
  95724. #endif
  95725. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  95726. /*
  95727. ** PRAGMA [database.]cache_size
  95728. ** PRAGMA [database.]cache_size=N
  95729. **
  95730. ** The first form reports the current local setting for the
  95731. ** page cache size. The second form sets the local
  95732. ** page cache size value. If N is positive then that is the
  95733. ** number of pages in the cache. If N is negative, then the
  95734. ** number of pages is adjusted so that the cache uses -N kibibytes
  95735. ** of memory.
  95736. */
  95737. case PragTyp_CACHE_SIZE: {
  95738. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  95739. if( !zRight ){
  95740. returnSingleInt(pParse, "cache_size", pDb->pSchema->cache_size);
  95741. }else{
  95742. int size = sqlite3Atoi(zRight);
  95743. pDb->pSchema->cache_size = size;
  95744. sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
  95745. }
  95746. break;
  95747. }
  95748. /*
  95749. ** PRAGMA [database.]mmap_size(N)
  95750. **
  95751. ** Used to set mapping size limit. The mapping size limit is
  95752. ** used to limit the aggregate size of all memory mapped regions of the
  95753. ** database file. If this parameter is set to zero, then memory mapping
  95754. ** is not used at all. If N is negative, then the default memory map
  95755. ** limit determined by sqlite3_config(SQLITE_CONFIG_MMAP_SIZE) is set.
  95756. ** The parameter N is measured in bytes.
  95757. **
  95758. ** This value is advisory. The underlying VFS is free to memory map
  95759. ** as little or as much as it wants. Except, if N is set to 0 then the
  95760. ** upper layers will never invoke the xFetch interfaces to the VFS.
  95761. */
  95762. case PragTyp_MMAP_SIZE: {
  95763. sqlite3_int64 sz;
  95764. #if SQLITE_MAX_MMAP_SIZE>0
  95765. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  95766. if( zRight ){
  95767. int ii;
  95768. sqlite3DecOrHexToI64(zRight, &sz);
  95769. if( sz<0 ) sz = sqlite3GlobalConfig.szMmap;
  95770. if( pId2->n==0 ) db->szMmap = sz;
  95771. for(ii=db->nDb-1; ii>=0; ii--){
  95772. if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){
  95773. sqlite3BtreeSetMmapLimit(db->aDb[ii].pBt, sz);
  95774. }
  95775. }
  95776. }
  95777. sz = -1;
  95778. rc = sqlite3_file_control(db, zDb, SQLITE_FCNTL_MMAP_SIZE, &sz);
  95779. #else
  95780. sz = 0;
  95781. rc = SQLITE_OK;
  95782. #endif
  95783. if( rc==SQLITE_OK ){
  95784. returnSingleInt(pParse, "mmap_size", sz);
  95785. }else if( rc!=SQLITE_NOTFOUND ){
  95786. pParse->nErr++;
  95787. pParse->rc = rc;
  95788. }
  95789. break;
  95790. }
  95791. /*
  95792. ** PRAGMA temp_store
  95793. ** PRAGMA temp_store = "default"|"memory"|"file"
  95794. **
  95795. ** Return or set the local value of the temp_store flag. Changing
  95796. ** the local value does not make changes to the disk file and the default
  95797. ** value will be restored the next time the database is opened.
  95798. **
  95799. ** Note that it is possible for the library compile-time options to
  95800. ** override this setting
  95801. */
  95802. case PragTyp_TEMP_STORE: {
  95803. if( !zRight ){
  95804. returnSingleInt(pParse, "temp_store", db->temp_store);
  95805. }else{
  95806. changeTempStorage(pParse, zRight);
  95807. }
  95808. break;
  95809. }
  95810. /*
  95811. ** PRAGMA temp_store_directory
  95812. ** PRAGMA temp_store_directory = ""|"directory_name"
  95813. **
  95814. ** Return or set the local value of the temp_store_directory flag. Changing
  95815. ** the value sets a specific directory to be used for temporary files.
  95816. ** Setting to a null string reverts to the default temporary directory search.
  95817. ** If temporary directory is changed, then invalidateTempStorage.
  95818. **
  95819. */
  95820. case PragTyp_TEMP_STORE_DIRECTORY: {
  95821. if( !zRight ){
  95822. if( sqlite3_temp_directory ){
  95823. sqlite3VdbeSetNumCols(v, 1);
  95824. sqlite3VdbeSetColName(v, 0, COLNAME_NAME,
  95825. "temp_store_directory", SQLITE_STATIC);
  95826. sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, sqlite3_temp_directory, 0);
  95827. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
  95828. }
  95829. }else{
  95830. #ifndef SQLITE_OMIT_WSD
  95831. if( zRight[0] ){
  95832. int res;
  95833. rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
  95834. if( rc!=SQLITE_OK || res==0 ){
  95835. sqlite3ErrorMsg(pParse, "not a writable directory");
  95836. goto pragma_out;
  95837. }
  95838. }
  95839. if( SQLITE_TEMP_STORE==0
  95840. || (SQLITE_TEMP_STORE==1 && db->temp_store<=1)
  95841. || (SQLITE_TEMP_STORE==2 && db->temp_store==1)
  95842. ){
  95843. invalidateTempStorage(pParse);
  95844. }
  95845. sqlite3_free(sqlite3_temp_directory);
  95846. if( zRight[0] ){
  95847. sqlite3_temp_directory = sqlite3_mprintf("%s", zRight);
  95848. }else{
  95849. sqlite3_temp_directory = 0;
  95850. }
  95851. #endif /* SQLITE_OMIT_WSD */
  95852. }
  95853. break;
  95854. }
  95855. #if SQLITE_OS_WIN
  95856. /*
  95857. ** PRAGMA data_store_directory
  95858. ** PRAGMA data_store_directory = ""|"directory_name"
  95859. **
  95860. ** Return or set the local value of the data_store_directory flag. Changing
  95861. ** the value sets a specific directory to be used for database files that
  95862. ** were specified with a relative pathname. Setting to a null string reverts
  95863. ** to the default database directory, which for database files specified with
  95864. ** a relative path will probably be based on the current directory for the
  95865. ** process. Database file specified with an absolute path are not impacted
  95866. ** by this setting, regardless of its value.
  95867. **
  95868. */
  95869. case PragTyp_DATA_STORE_DIRECTORY: {
  95870. if( !zRight ){
  95871. if( sqlite3_data_directory ){
  95872. sqlite3VdbeSetNumCols(v, 1);
  95873. sqlite3VdbeSetColName(v, 0, COLNAME_NAME,
  95874. "data_store_directory", SQLITE_STATIC);
  95875. sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, sqlite3_data_directory, 0);
  95876. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
  95877. }
  95878. }else{
  95879. #ifndef SQLITE_OMIT_WSD
  95880. if( zRight[0] ){
  95881. int res;
  95882. rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
  95883. if( rc!=SQLITE_OK || res==0 ){
  95884. sqlite3ErrorMsg(pParse, "not a writable directory");
  95885. goto pragma_out;
  95886. }
  95887. }
  95888. sqlite3_free(sqlite3_data_directory);
  95889. if( zRight[0] ){
  95890. sqlite3_data_directory = sqlite3_mprintf("%s", zRight);
  95891. }else{
  95892. sqlite3_data_directory = 0;
  95893. }
  95894. #endif /* SQLITE_OMIT_WSD */
  95895. }
  95896. break;
  95897. }
  95898. #endif
  95899. #if SQLITE_ENABLE_LOCKING_STYLE
  95900. /*
  95901. ** PRAGMA [database.]lock_proxy_file
  95902. ** PRAGMA [database.]lock_proxy_file = ":auto:"|"lock_file_path"
  95903. **
  95904. ** Return or set the value of the lock_proxy_file flag. Changing
  95905. ** the value sets a specific file to be used for database access locks.
  95906. **
  95907. */
  95908. case PragTyp_LOCK_PROXY_FILE: {
  95909. if( !zRight ){
  95910. Pager *pPager = sqlite3BtreePager(pDb->pBt);
  95911. char *proxy_file_path = NULL;
  95912. sqlite3_file *pFile = sqlite3PagerFile(pPager);
  95913. sqlite3OsFileControlHint(pFile, SQLITE_GET_LOCKPROXYFILE,
  95914. &proxy_file_path);
  95915. if( proxy_file_path ){
  95916. sqlite3VdbeSetNumCols(v, 1);
  95917. sqlite3VdbeSetColName(v, 0, COLNAME_NAME,
  95918. "lock_proxy_file", SQLITE_STATIC);
  95919. sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, proxy_file_path, 0);
  95920. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
  95921. }
  95922. }else{
  95923. Pager *pPager = sqlite3BtreePager(pDb->pBt);
  95924. sqlite3_file *pFile = sqlite3PagerFile(pPager);
  95925. int res;
  95926. if( zRight[0] ){
  95927. res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE,
  95928. zRight);
  95929. } else {
  95930. res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE,
  95931. NULL);
  95932. }
  95933. if( res!=SQLITE_OK ){
  95934. sqlite3ErrorMsg(pParse, "failed to set lock proxy file");
  95935. goto pragma_out;
  95936. }
  95937. }
  95938. break;
  95939. }
  95940. #endif /* SQLITE_ENABLE_LOCKING_STYLE */
  95941. /*
  95942. ** PRAGMA [database.]synchronous
  95943. ** PRAGMA [database.]synchronous=OFF|ON|NORMAL|FULL
  95944. **
  95945. ** Return or set the local value of the synchronous flag. Changing
  95946. ** the local value does not make changes to the disk file and the
  95947. ** default value will be restored the next time the database is
  95948. ** opened.
  95949. */
  95950. case PragTyp_SYNCHRONOUS: {
  95951. if( !zRight ){
  95952. returnSingleInt(pParse, "synchronous", pDb->safety_level-1);
  95953. }else{
  95954. if( !db->autoCommit ){
  95955. sqlite3ErrorMsg(pParse,
  95956. "Safety level may not be changed inside a transaction");
  95957. }else{
  95958. pDb->safety_level = getSafetyLevel(zRight,0,1)+1;
  95959. setAllPagerFlags(db);
  95960. }
  95961. }
  95962. break;
  95963. }
  95964. #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
  95965. #ifndef SQLITE_OMIT_FLAG_PRAGMAS
  95966. case PragTyp_FLAG: {
  95967. if( zRight==0 ){
  95968. returnSingleInt(pParse, aPragmaNames[mid].zName,
  95969. (db->flags & aPragmaNames[mid].iArg)!=0 );
  95970. }else{
  95971. int mask = aPragmaNames[mid].iArg; /* Mask of bits to set or clear. */
  95972. if( db->autoCommit==0 ){
  95973. /* Foreign key support may not be enabled or disabled while not
  95974. ** in auto-commit mode. */
  95975. mask &= ~(SQLITE_ForeignKeys);
  95976. }
  95977. #if SQLITE_USER_AUTHENTICATION
  95978. if( db->auth.authLevel==UAUTH_User ){
  95979. /* Do not allow non-admin users to modify the schema arbitrarily */
  95980. mask &= ~(SQLITE_WriteSchema);
  95981. }
  95982. #endif
  95983. if( sqlite3GetBoolean(zRight, 0) ){
  95984. db->flags |= mask;
  95985. }else{
  95986. db->flags &= ~mask;
  95987. if( mask==SQLITE_DeferFKs ) db->nDeferredImmCons = 0;
  95988. }
  95989. /* Many of the flag-pragmas modify the code generated by the SQL
  95990. ** compiler (eg. count_changes). So add an opcode to expire all
  95991. ** compiled SQL statements after modifying a pragma value.
  95992. */
  95993. sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);
  95994. setAllPagerFlags(db);
  95995. }
  95996. break;
  95997. }
  95998. #endif /* SQLITE_OMIT_FLAG_PRAGMAS */
  95999. #ifndef SQLITE_OMIT_SCHEMA_PRAGMAS
  96000. /*
  96001. ** PRAGMA table_info(<table>)
  96002. **
  96003. ** Return a single row for each column of the named table. The columns of
  96004. ** the returned data set are:
  96005. **
  96006. ** cid: Column id (numbered from left to right, starting at 0)
  96007. ** name: Column name
  96008. ** type: Column declaration type.
  96009. ** notnull: True if 'NOT NULL' is part of column declaration
  96010. ** dflt_value: The default value for the column, if any.
  96011. */
  96012. case PragTyp_TABLE_INFO: if( zRight ){
  96013. Table *pTab;
  96014. pTab = sqlite3FindTable(db, zRight, zDb);
  96015. if( pTab ){
  96016. int i, k;
  96017. int nHidden = 0;
  96018. Column *pCol;
  96019. Index *pPk = sqlite3PrimaryKeyIndex(pTab);
  96020. sqlite3VdbeSetNumCols(v, 6);
  96021. pParse->nMem = 6;
  96022. sqlite3CodeVerifySchema(pParse, iDb);
  96023. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "cid", SQLITE_STATIC);
  96024. sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
  96025. sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "type", SQLITE_STATIC);
  96026. sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "notnull", SQLITE_STATIC);
  96027. sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "dflt_value", SQLITE_STATIC);
  96028. sqlite3VdbeSetColName(v, 5, COLNAME_NAME, "pk", SQLITE_STATIC);
  96029. sqlite3ViewGetColumnNames(pParse, pTab);
  96030. for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
  96031. if( IsHiddenColumn(pCol) ){
  96032. nHidden++;
  96033. continue;
  96034. }
  96035. sqlite3VdbeAddOp2(v, OP_Integer, i-nHidden, 1);
  96036. sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pCol->zName, 0);
  96037. sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
  96038. pCol->zType ? pCol->zType : "", 0);
  96039. sqlite3VdbeAddOp2(v, OP_Integer, (pCol->notNull ? 1 : 0), 4);
  96040. if( pCol->zDflt ){
  96041. sqlite3VdbeAddOp4(v, OP_String8, 0, 5, 0, (char*)pCol->zDflt, 0);
  96042. }else{
  96043. sqlite3VdbeAddOp2(v, OP_Null, 0, 5);
  96044. }
  96045. if( (pCol->colFlags & COLFLAG_PRIMKEY)==0 ){
  96046. k = 0;
  96047. }else if( pPk==0 ){
  96048. k = 1;
  96049. }else{
  96050. for(k=1; ALWAYS(k<=pTab->nCol) && pPk->aiColumn[k-1]!=i; k++){}
  96051. }
  96052. sqlite3VdbeAddOp2(v, OP_Integer, k, 6);
  96053. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 6);
  96054. }
  96055. }
  96056. }
  96057. break;
  96058. case PragTyp_STATS: {
  96059. Index *pIdx;
  96060. HashElem *i;
  96061. v = sqlite3GetVdbe(pParse);
  96062. sqlite3VdbeSetNumCols(v, 4);
  96063. pParse->nMem = 4;
  96064. sqlite3CodeVerifySchema(pParse, iDb);
  96065. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "table", SQLITE_STATIC);
  96066. sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "index", SQLITE_STATIC);
  96067. sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "width", SQLITE_STATIC);
  96068. sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "height", SQLITE_STATIC);
  96069. for(i=sqliteHashFirst(&pDb->pSchema->tblHash); i; i=sqliteHashNext(i)){
  96070. Table *pTab = sqliteHashData(i);
  96071. sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, pTab->zName, 0);
  96072. sqlite3VdbeAddOp2(v, OP_Null, 0, 2);
  96073. sqlite3VdbeAddOp2(v, OP_Integer,
  96074. (int)sqlite3LogEstToInt(pTab->szTabRow), 3);
  96075. sqlite3VdbeAddOp2(v, OP_Integer,
  96076. (int)sqlite3LogEstToInt(pTab->nRowLogEst), 4);
  96077. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 4);
  96078. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  96079. sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pIdx->zName, 0);
  96080. sqlite3VdbeAddOp2(v, OP_Integer,
  96081. (int)sqlite3LogEstToInt(pIdx->szIdxRow), 3);
  96082. sqlite3VdbeAddOp2(v, OP_Integer,
  96083. (int)sqlite3LogEstToInt(pIdx->aiRowLogEst[0]), 4);
  96084. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 4);
  96085. }
  96086. }
  96087. }
  96088. break;
  96089. case PragTyp_INDEX_INFO: if( zRight ){
  96090. Index *pIdx;
  96091. Table *pTab;
  96092. pIdx = sqlite3FindIndex(db, zRight, zDb);
  96093. if( pIdx ){
  96094. int i;
  96095. pTab = pIdx->pTable;
  96096. sqlite3VdbeSetNumCols(v, 3);
  96097. pParse->nMem = 3;
  96098. sqlite3CodeVerifySchema(pParse, iDb);
  96099. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seqno", SQLITE_STATIC);
  96100. sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "cid", SQLITE_STATIC);
  96101. sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "name", SQLITE_STATIC);
  96102. for(i=0; i<pIdx->nKeyCol; i++){
  96103. i16 cnum = pIdx->aiColumn[i];
  96104. sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
  96105. sqlite3VdbeAddOp2(v, OP_Integer, cnum, 2);
  96106. assert( pTab->nCol>cnum );
  96107. sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pTab->aCol[cnum].zName, 0);
  96108. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
  96109. }
  96110. }
  96111. }
  96112. break;
  96113. case PragTyp_INDEX_LIST: if( zRight ){
  96114. Index *pIdx;
  96115. Table *pTab;
  96116. int i;
  96117. pTab = sqlite3FindTable(db, zRight, zDb);
  96118. if( pTab ){
  96119. v = sqlite3GetVdbe(pParse);
  96120. sqlite3VdbeSetNumCols(v, 3);
  96121. pParse->nMem = 3;
  96122. sqlite3CodeVerifySchema(pParse, iDb);
  96123. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
  96124. sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
  96125. sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "unique", SQLITE_STATIC);
  96126. for(pIdx=pTab->pIndex, i=0; pIdx; pIdx=pIdx->pNext, i++){
  96127. sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
  96128. sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pIdx->zName, 0);
  96129. sqlite3VdbeAddOp2(v, OP_Integer, IsUniqueIndex(pIdx), 3);
  96130. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
  96131. }
  96132. }
  96133. }
  96134. break;
  96135. case PragTyp_DATABASE_LIST: {
  96136. int i;
  96137. sqlite3VdbeSetNumCols(v, 3);
  96138. pParse->nMem = 3;
  96139. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
  96140. sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
  96141. sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "file", SQLITE_STATIC);
  96142. for(i=0; i<db->nDb; i++){
  96143. if( db->aDb[i].pBt==0 ) continue;
  96144. assert( db->aDb[i].zName!=0 );
  96145. sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
  96146. sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, db->aDb[i].zName, 0);
  96147. sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
  96148. sqlite3BtreeGetFilename(db->aDb[i].pBt), 0);
  96149. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
  96150. }
  96151. }
  96152. break;
  96153. case PragTyp_COLLATION_LIST: {
  96154. int i = 0;
  96155. HashElem *p;
  96156. sqlite3VdbeSetNumCols(v, 2);
  96157. pParse->nMem = 2;
  96158. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
  96159. sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
  96160. for(p=sqliteHashFirst(&db->aCollSeq); p; p=sqliteHashNext(p)){
  96161. CollSeq *pColl = (CollSeq *)sqliteHashData(p);
  96162. sqlite3VdbeAddOp2(v, OP_Integer, i++, 1);
  96163. sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pColl->zName, 0);
  96164. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
  96165. }
  96166. }
  96167. break;
  96168. #endif /* SQLITE_OMIT_SCHEMA_PRAGMAS */
  96169. #ifndef SQLITE_OMIT_FOREIGN_KEY
  96170. case PragTyp_FOREIGN_KEY_LIST: if( zRight ){
  96171. FKey *pFK;
  96172. Table *pTab;
  96173. pTab = sqlite3FindTable(db, zRight, zDb);
  96174. if( pTab ){
  96175. v = sqlite3GetVdbe(pParse);
  96176. pFK = pTab->pFKey;
  96177. if( pFK ){
  96178. int i = 0;
  96179. sqlite3VdbeSetNumCols(v, 8);
  96180. pParse->nMem = 8;
  96181. sqlite3CodeVerifySchema(pParse, iDb);
  96182. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "id", SQLITE_STATIC);
  96183. sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "seq", SQLITE_STATIC);
  96184. sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "table", SQLITE_STATIC);
  96185. sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "from", SQLITE_STATIC);
  96186. sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "to", SQLITE_STATIC);
  96187. sqlite3VdbeSetColName(v, 5, COLNAME_NAME, "on_update", SQLITE_STATIC);
  96188. sqlite3VdbeSetColName(v, 6, COLNAME_NAME, "on_delete", SQLITE_STATIC);
  96189. sqlite3VdbeSetColName(v, 7, COLNAME_NAME, "match", SQLITE_STATIC);
  96190. while(pFK){
  96191. int j;
  96192. for(j=0; j<pFK->nCol; j++){
  96193. char *zCol = pFK->aCol[j].zCol;
  96194. char *zOnDelete = (char *)actionName(pFK->aAction[0]);
  96195. char *zOnUpdate = (char *)actionName(pFK->aAction[1]);
  96196. sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
  96197. sqlite3VdbeAddOp2(v, OP_Integer, j, 2);
  96198. sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pFK->zTo, 0);
  96199. sqlite3VdbeAddOp4(v, OP_String8, 0, 4, 0,
  96200. pTab->aCol[pFK->aCol[j].iFrom].zName, 0);
  96201. sqlite3VdbeAddOp4(v, zCol ? OP_String8 : OP_Null, 0, 5, 0, zCol, 0);
  96202. sqlite3VdbeAddOp4(v, OP_String8, 0, 6, 0, zOnUpdate, 0);
  96203. sqlite3VdbeAddOp4(v, OP_String8, 0, 7, 0, zOnDelete, 0);
  96204. sqlite3VdbeAddOp4(v, OP_String8, 0, 8, 0, "NONE", 0);
  96205. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 8);
  96206. }
  96207. ++i;
  96208. pFK = pFK->pNextFrom;
  96209. }
  96210. }
  96211. }
  96212. }
  96213. break;
  96214. #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
  96215. #ifndef SQLITE_OMIT_FOREIGN_KEY
  96216. #ifndef SQLITE_OMIT_TRIGGER
  96217. case PragTyp_FOREIGN_KEY_CHECK: {
  96218. FKey *pFK; /* A foreign key constraint */
  96219. Table *pTab; /* Child table contain "REFERENCES" keyword */
  96220. Table *pParent; /* Parent table that child points to */
  96221. Index *pIdx; /* Index in the parent table */
  96222. int i; /* Loop counter: Foreign key number for pTab */
  96223. int j; /* Loop counter: Field of the foreign key */
  96224. HashElem *k; /* Loop counter: Next table in schema */
  96225. int x; /* result variable */
  96226. int regResult; /* 3 registers to hold a result row */
  96227. int regKey; /* Register to hold key for checking the FK */
  96228. int regRow; /* Registers to hold a row from pTab */
  96229. int addrTop; /* Top of a loop checking foreign keys */
  96230. int addrOk; /* Jump here if the key is OK */
  96231. int *aiCols; /* child to parent column mapping */
  96232. regResult = pParse->nMem+1;
  96233. pParse->nMem += 4;
  96234. regKey = ++pParse->nMem;
  96235. regRow = ++pParse->nMem;
  96236. v = sqlite3GetVdbe(pParse);
  96237. sqlite3VdbeSetNumCols(v, 4);
  96238. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "table", SQLITE_STATIC);
  96239. sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "rowid", SQLITE_STATIC);
  96240. sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "parent", SQLITE_STATIC);
  96241. sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "fkid", SQLITE_STATIC);
  96242. sqlite3CodeVerifySchema(pParse, iDb);
  96243. k = sqliteHashFirst(&db->aDb[iDb].pSchema->tblHash);
  96244. while( k ){
  96245. if( zRight ){
  96246. pTab = sqlite3LocateTable(pParse, 0, zRight, zDb);
  96247. k = 0;
  96248. }else{
  96249. pTab = (Table*)sqliteHashData(k);
  96250. k = sqliteHashNext(k);
  96251. }
  96252. if( pTab==0 || pTab->pFKey==0 ) continue;
  96253. sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
  96254. if( pTab->nCol+regRow>pParse->nMem ) pParse->nMem = pTab->nCol + regRow;
  96255. sqlite3OpenTable(pParse, 0, iDb, pTab, OP_OpenRead);
  96256. sqlite3VdbeAddOp4(v, OP_String8, 0, regResult, 0, pTab->zName,
  96257. P4_TRANSIENT);
  96258. for(i=1, pFK=pTab->pFKey; pFK; i++, pFK=pFK->pNextFrom){
  96259. pParent = sqlite3FindTable(db, pFK->zTo, zDb);
  96260. if( pParent==0 ) continue;
  96261. pIdx = 0;
  96262. sqlite3TableLock(pParse, iDb, pParent->tnum, 0, pParent->zName);
  96263. x = sqlite3FkLocateIndex(pParse, pParent, pFK, &pIdx, 0);
  96264. if( x==0 ){
  96265. if( pIdx==0 ){
  96266. sqlite3OpenTable(pParse, i, iDb, pParent, OP_OpenRead);
  96267. }else{
  96268. sqlite3VdbeAddOp3(v, OP_OpenRead, i, pIdx->tnum, iDb);
  96269. sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
  96270. }
  96271. }else{
  96272. k = 0;
  96273. break;
  96274. }
  96275. }
  96276. assert( pParse->nErr>0 || pFK==0 );
  96277. if( pFK ) break;
  96278. if( pParse->nTab<i ) pParse->nTab = i;
  96279. addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, 0); VdbeCoverage(v);
  96280. for(i=1, pFK=pTab->pFKey; pFK; i++, pFK=pFK->pNextFrom){
  96281. pParent = sqlite3FindTable(db, pFK->zTo, zDb);
  96282. pIdx = 0;
  96283. aiCols = 0;
  96284. if( pParent ){
  96285. x = sqlite3FkLocateIndex(pParse, pParent, pFK, &pIdx, &aiCols);
  96286. assert( x==0 );
  96287. }
  96288. addrOk = sqlite3VdbeMakeLabel(v);
  96289. if( pParent && pIdx==0 ){
  96290. int iKey = pFK->aCol[0].iFrom;
  96291. assert( iKey>=0 && iKey<pTab->nCol );
  96292. if( iKey!=pTab->iPKey ){
  96293. sqlite3VdbeAddOp3(v, OP_Column, 0, iKey, regRow);
  96294. sqlite3ColumnDefault(v, pTab, iKey, regRow);
  96295. sqlite3VdbeAddOp2(v, OP_IsNull, regRow, addrOk); VdbeCoverage(v);
  96296. sqlite3VdbeAddOp2(v, OP_MustBeInt, regRow,
  96297. sqlite3VdbeCurrentAddr(v)+3); VdbeCoverage(v);
  96298. }else{
  96299. sqlite3VdbeAddOp2(v, OP_Rowid, 0, regRow);
  96300. }
  96301. sqlite3VdbeAddOp3(v, OP_NotExists, i, 0, regRow); VdbeCoverage(v);
  96302. sqlite3VdbeAddOp2(v, OP_Goto, 0, addrOk);
  96303. sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
  96304. }else{
  96305. for(j=0; j<pFK->nCol; j++){
  96306. sqlite3ExprCodeGetColumnOfTable(v, pTab, 0,
  96307. aiCols ? aiCols[j] : pFK->aCol[j].iFrom, regRow+j);
  96308. sqlite3VdbeAddOp2(v, OP_IsNull, regRow+j, addrOk); VdbeCoverage(v);
  96309. }
  96310. if( pParent ){
  96311. sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, pFK->nCol, regKey,
  96312. sqlite3IndexAffinityStr(v,pIdx), pFK->nCol);
  96313. sqlite3VdbeAddOp4Int(v, OP_Found, i, addrOk, regKey, 0);
  96314. VdbeCoverage(v);
  96315. }
  96316. }
  96317. sqlite3VdbeAddOp2(v, OP_Rowid, 0, regResult+1);
  96318. sqlite3VdbeAddOp4(v, OP_String8, 0, regResult+2, 0,
  96319. pFK->zTo, P4_TRANSIENT);
  96320. sqlite3VdbeAddOp2(v, OP_Integer, i-1, regResult+3);
  96321. sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, 4);
  96322. sqlite3VdbeResolveLabel(v, addrOk);
  96323. sqlite3DbFree(db, aiCols);
  96324. }
  96325. sqlite3VdbeAddOp2(v, OP_Next, 0, addrTop+1); VdbeCoverage(v);
  96326. sqlite3VdbeJumpHere(v, addrTop);
  96327. }
  96328. }
  96329. break;
  96330. #endif /* !defined(SQLITE_OMIT_TRIGGER) */
  96331. #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
  96332. #ifndef NDEBUG
  96333. case PragTyp_PARSER_TRACE: {
  96334. if( zRight ){
  96335. if( sqlite3GetBoolean(zRight, 0) ){
  96336. sqlite3ParserTrace(stderr, "parser: ");
  96337. }else{
  96338. sqlite3ParserTrace(0, 0);
  96339. }
  96340. }
  96341. }
  96342. break;
  96343. #endif
  96344. /* Reinstall the LIKE and GLOB functions. The variant of LIKE
  96345. ** used will be case sensitive or not depending on the RHS.
  96346. */
  96347. case PragTyp_CASE_SENSITIVE_LIKE: {
  96348. if( zRight ){
  96349. sqlite3RegisterLikeFunctions(db, sqlite3GetBoolean(zRight, 0));
  96350. }
  96351. }
  96352. break;
  96353. #ifndef SQLITE_INTEGRITY_CHECK_ERROR_MAX
  96354. # define SQLITE_INTEGRITY_CHECK_ERROR_MAX 100
  96355. #endif
  96356. #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  96357. /* Pragma "quick_check" is reduced version of
  96358. ** integrity_check designed to detect most database corruption
  96359. ** without most of the overhead of a full integrity-check.
  96360. */
  96361. case PragTyp_INTEGRITY_CHECK: {
  96362. int i, j, addr, mxErr;
  96363. /* Code that appears at the end of the integrity check. If no error
  96364. ** messages have been generated, output OK. Otherwise output the
  96365. ** error message
  96366. */
  96367. static const int iLn = VDBE_OFFSET_LINENO(2);
  96368. static const VdbeOpList endCode[] = {
  96369. { OP_IfNeg, 1, 0, 0}, /* 0 */
  96370. { OP_String8, 0, 3, 0}, /* 1 */
  96371. { OP_ResultRow, 3, 1, 0},
  96372. };
  96373. int isQuick = (sqlite3Tolower(zLeft[0])=='q');
  96374. /* If the PRAGMA command was of the form "PRAGMA <db>.integrity_check",
  96375. ** then iDb is set to the index of the database identified by <db>.
  96376. ** In this case, the integrity of database iDb only is verified by
  96377. ** the VDBE created below.
  96378. **
  96379. ** Otherwise, if the command was simply "PRAGMA integrity_check" (or
  96380. ** "PRAGMA quick_check"), then iDb is set to 0. In this case, set iDb
  96381. ** to -1 here, to indicate that the VDBE should verify the integrity
  96382. ** of all attached databases. */
  96383. assert( iDb>=0 );
  96384. assert( iDb==0 || pId2->z );
  96385. if( pId2->z==0 ) iDb = -1;
  96386. /* Initialize the VDBE program */
  96387. pParse->nMem = 6;
  96388. sqlite3VdbeSetNumCols(v, 1);
  96389. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "integrity_check", SQLITE_STATIC);
  96390. /* Set the maximum error count */
  96391. mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
  96392. if( zRight ){
  96393. sqlite3GetInt32(zRight, &mxErr);
  96394. if( mxErr<=0 ){
  96395. mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
  96396. }
  96397. }
  96398. sqlite3VdbeAddOp2(v, OP_Integer, mxErr, 1); /* reg[1] holds errors left */
  96399. /* Do an integrity check on each database file */
  96400. for(i=0; i<db->nDb; i++){
  96401. HashElem *x;
  96402. Hash *pTbls;
  96403. int cnt = 0;
  96404. if( OMIT_TEMPDB && i==1 ) continue;
  96405. if( iDb>=0 && i!=iDb ) continue;
  96406. sqlite3CodeVerifySchema(pParse, i);
  96407. addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1); /* Halt if out of errors */
  96408. VdbeCoverage(v);
  96409. sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
  96410. sqlite3VdbeJumpHere(v, addr);
  96411. /* Do an integrity check of the B-Tree
  96412. **
  96413. ** Begin by filling registers 2, 3, ... with the root pages numbers
  96414. ** for all tables and indices in the database.
  96415. */
  96416. assert( sqlite3SchemaMutexHeld(db, i, 0) );
  96417. pTbls = &db->aDb[i].pSchema->tblHash;
  96418. for(x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
  96419. Table *pTab = sqliteHashData(x);
  96420. Index *pIdx;
  96421. if( HasRowid(pTab) ){
  96422. sqlite3VdbeAddOp2(v, OP_Integer, pTab->tnum, 2+cnt);
  96423. VdbeComment((v, "%s", pTab->zName));
  96424. cnt++;
  96425. }
  96426. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  96427. sqlite3VdbeAddOp2(v, OP_Integer, pIdx->tnum, 2+cnt);
  96428. VdbeComment((v, "%s", pIdx->zName));
  96429. cnt++;
  96430. }
  96431. }
  96432. /* Make sure sufficient number of registers have been allocated */
  96433. pParse->nMem = MAX( pParse->nMem, cnt+8 );
  96434. /* Do the b-tree integrity checks */
  96435. sqlite3VdbeAddOp3(v, OP_IntegrityCk, 2, cnt, 1);
  96436. sqlite3VdbeChangeP5(v, (u8)i);
  96437. addr = sqlite3VdbeAddOp1(v, OP_IsNull, 2); VdbeCoverage(v);
  96438. sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
  96439. sqlite3MPrintf(db, "*** in database %s ***\n", db->aDb[i].zName),
  96440. P4_DYNAMIC);
  96441. sqlite3VdbeAddOp3(v, OP_Move, 2, 4, 1);
  96442. sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 2);
  96443. sqlite3VdbeAddOp2(v, OP_ResultRow, 2, 1);
  96444. sqlite3VdbeJumpHere(v, addr);
  96445. /* Make sure all the indices are constructed correctly.
  96446. */
  96447. for(x=sqliteHashFirst(pTbls); x && !isQuick; x=sqliteHashNext(x)){
  96448. Table *pTab = sqliteHashData(x);
  96449. Index *pIdx, *pPk;
  96450. Index *pPrior = 0;
  96451. int loopTop;
  96452. int iDataCur, iIdxCur;
  96453. int r1 = -1;
  96454. if( pTab->pIndex==0 ) continue;
  96455. pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab);
  96456. addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1); /* Stop if out of errors */
  96457. VdbeCoverage(v);
  96458. sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
  96459. sqlite3VdbeJumpHere(v, addr);
  96460. sqlite3ExprCacheClear(pParse);
  96461. sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenRead,
  96462. 1, 0, &iDataCur, &iIdxCur);
  96463. sqlite3VdbeAddOp2(v, OP_Integer, 0, 7);
  96464. for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
  96465. sqlite3VdbeAddOp2(v, OP_Integer, 0, 8+j); /* index entries counter */
  96466. }
  96467. pParse->nMem = MAX(pParse->nMem, 8+j);
  96468. sqlite3VdbeAddOp2(v, OP_Rewind, iDataCur, 0); VdbeCoverage(v);
  96469. loopTop = sqlite3VdbeAddOp2(v, OP_AddImm, 7, 1);
  96470. /* Verify that all NOT NULL columns really are NOT NULL */
  96471. for(j=0; j<pTab->nCol; j++){
  96472. char *zErr;
  96473. int jmp2, jmp3;
  96474. if( j==pTab->iPKey ) continue;
  96475. if( pTab->aCol[j].notNull==0 ) continue;
  96476. sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, j, 3);
  96477. sqlite3VdbeChangeP5(v, OPFLAG_TYPEOFARG);
  96478. jmp2 = sqlite3VdbeAddOp1(v, OP_NotNull, 3); VdbeCoverage(v);
  96479. sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1); /* Decrement error limit */
  96480. zErr = sqlite3MPrintf(db, "NULL value in %s.%s", pTab->zName,
  96481. pTab->aCol[j].zName);
  96482. sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, zErr, P4_DYNAMIC);
  96483. sqlite3VdbeAddOp2(v, OP_ResultRow, 3, 1);
  96484. jmp3 = sqlite3VdbeAddOp1(v, OP_IfPos, 1); VdbeCoverage(v);
  96485. sqlite3VdbeAddOp0(v, OP_Halt);
  96486. sqlite3VdbeJumpHere(v, jmp2);
  96487. sqlite3VdbeJumpHere(v, jmp3);
  96488. }
  96489. /* Validate index entries for the current row */
  96490. for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
  96491. int jmp2, jmp3, jmp4, jmp5;
  96492. int ckUniq = sqlite3VdbeMakeLabel(v);
  96493. if( pPk==pIdx ) continue;
  96494. r1 = sqlite3GenerateIndexKey(pParse, pIdx, iDataCur, 0, 0, &jmp3,
  96495. pPrior, r1);
  96496. pPrior = pIdx;
  96497. sqlite3VdbeAddOp2(v, OP_AddImm, 8+j, 1); /* increment entry count */
  96498. /* Verify that an index entry exists for the current table row */
  96499. jmp2 = sqlite3VdbeAddOp4Int(v, OP_Found, iIdxCur+j, ckUniq, r1,
  96500. pIdx->nColumn); VdbeCoverage(v);
  96501. sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1); /* Decrement error limit */
  96502. sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, "row ", P4_STATIC);
  96503. sqlite3VdbeAddOp3(v, OP_Concat, 7, 3, 3);
  96504. sqlite3VdbeAddOp4(v, OP_String8, 0, 4, 0,
  96505. " missing from index ", P4_STATIC);
  96506. sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 3);
  96507. jmp5 = sqlite3VdbeAddOp4(v, OP_String8, 0, 4, 0,
  96508. pIdx->zName, P4_TRANSIENT);
  96509. sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 3);
  96510. sqlite3VdbeAddOp2(v, OP_ResultRow, 3, 1);
  96511. jmp4 = sqlite3VdbeAddOp1(v, OP_IfPos, 1); VdbeCoverage(v);
  96512. sqlite3VdbeAddOp0(v, OP_Halt);
  96513. sqlite3VdbeJumpHere(v, jmp2);
  96514. /* For UNIQUE indexes, verify that only one entry exists with the
  96515. ** current key. The entry is unique if (1) any column is NULL
  96516. ** or (2) the next entry has a different key */
  96517. if( IsUniqueIndex(pIdx) ){
  96518. int uniqOk = sqlite3VdbeMakeLabel(v);
  96519. int jmp6;
  96520. int kk;
  96521. for(kk=0; kk<pIdx->nKeyCol; kk++){
  96522. int iCol = pIdx->aiColumn[kk];
  96523. assert( iCol>=0 && iCol<pTab->nCol );
  96524. if( pTab->aCol[iCol].notNull ) continue;
  96525. sqlite3VdbeAddOp2(v, OP_IsNull, r1+kk, uniqOk);
  96526. VdbeCoverage(v);
  96527. }
  96528. jmp6 = sqlite3VdbeAddOp1(v, OP_Next, iIdxCur+j); VdbeCoverage(v);
  96529. sqlite3VdbeAddOp2(v, OP_Goto, 0, uniqOk);
  96530. sqlite3VdbeJumpHere(v, jmp6);
  96531. sqlite3VdbeAddOp4Int(v, OP_IdxGT, iIdxCur+j, uniqOk, r1,
  96532. pIdx->nKeyCol); VdbeCoverage(v);
  96533. sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1); /* Decrement error limit */
  96534. sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
  96535. "non-unique entry in index ", P4_STATIC);
  96536. sqlite3VdbeAddOp2(v, OP_Goto, 0, jmp5);
  96537. sqlite3VdbeResolveLabel(v, uniqOk);
  96538. }
  96539. sqlite3VdbeJumpHere(v, jmp4);
  96540. sqlite3ResolvePartIdxLabel(pParse, jmp3);
  96541. }
  96542. sqlite3VdbeAddOp2(v, OP_Next, iDataCur, loopTop); VdbeCoverage(v);
  96543. sqlite3VdbeJumpHere(v, loopTop-1);
  96544. #ifndef SQLITE_OMIT_BTREECOUNT
  96545. sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0,
  96546. "wrong # of entries in index ", P4_STATIC);
  96547. for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
  96548. if( pPk==pIdx ) continue;
  96549. addr = sqlite3VdbeCurrentAddr(v);
  96550. sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr+2); VdbeCoverage(v);
  96551. sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
  96552. sqlite3VdbeAddOp2(v, OP_Count, iIdxCur+j, 3);
  96553. sqlite3VdbeAddOp3(v, OP_Eq, 8+j, addr+8, 3); VdbeCoverage(v);
  96554. sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
  96555. sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1);
  96556. sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pIdx->zName, P4_TRANSIENT);
  96557. sqlite3VdbeAddOp3(v, OP_Concat, 3, 2, 7);
  96558. sqlite3VdbeAddOp2(v, OP_ResultRow, 7, 1);
  96559. }
  96560. #endif /* SQLITE_OMIT_BTREECOUNT */
  96561. }
  96562. }
  96563. addr = sqlite3VdbeAddOpList(v, ArraySize(endCode), endCode, iLn);
  96564. sqlite3VdbeChangeP3(v, addr, -mxErr);
  96565. sqlite3VdbeJumpHere(v, addr);
  96566. sqlite3VdbeChangeP4(v, addr+1, "ok", P4_STATIC);
  96567. }
  96568. break;
  96569. #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  96570. #ifndef SQLITE_OMIT_UTF16
  96571. /*
  96572. ** PRAGMA encoding
  96573. ** PRAGMA encoding = "utf-8"|"utf-16"|"utf-16le"|"utf-16be"
  96574. **
  96575. ** In its first form, this pragma returns the encoding of the main
  96576. ** database. If the database is not initialized, it is initialized now.
  96577. **
  96578. ** The second form of this pragma is a no-op if the main database file
  96579. ** has not already been initialized. In this case it sets the default
  96580. ** encoding that will be used for the main database file if a new file
  96581. ** is created. If an existing main database file is opened, then the
  96582. ** default text encoding for the existing database is used.
  96583. **
  96584. ** In all cases new databases created using the ATTACH command are
  96585. ** created to use the same default text encoding as the main database. If
  96586. ** the main database has not been initialized and/or created when ATTACH
  96587. ** is executed, this is done before the ATTACH operation.
  96588. **
  96589. ** In the second form this pragma sets the text encoding to be used in
  96590. ** new database files created using this database handle. It is only
  96591. ** useful if invoked immediately after the main database i
  96592. */
  96593. case PragTyp_ENCODING: {
  96594. static const struct EncName {
  96595. char *zName;
  96596. u8 enc;
  96597. } encnames[] = {
  96598. { "UTF8", SQLITE_UTF8 },
  96599. { "UTF-8", SQLITE_UTF8 }, /* Must be element [1] */
  96600. { "UTF-16le", SQLITE_UTF16LE }, /* Must be element [2] */
  96601. { "UTF-16be", SQLITE_UTF16BE }, /* Must be element [3] */
  96602. { "UTF16le", SQLITE_UTF16LE },
  96603. { "UTF16be", SQLITE_UTF16BE },
  96604. { "UTF-16", 0 }, /* SQLITE_UTF16NATIVE */
  96605. { "UTF16", 0 }, /* SQLITE_UTF16NATIVE */
  96606. { 0, 0 }
  96607. };
  96608. const struct EncName *pEnc;
  96609. if( !zRight ){ /* "PRAGMA encoding" */
  96610. if( sqlite3ReadSchema(pParse) ) goto pragma_out;
  96611. sqlite3VdbeSetNumCols(v, 1);
  96612. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "encoding", SQLITE_STATIC);
  96613. sqlite3VdbeAddOp2(v, OP_String8, 0, 1);
  96614. assert( encnames[SQLITE_UTF8].enc==SQLITE_UTF8 );
  96615. assert( encnames[SQLITE_UTF16LE].enc==SQLITE_UTF16LE );
  96616. assert( encnames[SQLITE_UTF16BE].enc==SQLITE_UTF16BE );
  96617. sqlite3VdbeChangeP4(v, -1, encnames[ENC(pParse->db)].zName, P4_STATIC);
  96618. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
  96619. }else{ /* "PRAGMA encoding = XXX" */
  96620. /* Only change the value of sqlite.enc if the database handle is not
  96621. ** initialized. If the main database exists, the new sqlite.enc value
  96622. ** will be overwritten when the schema is next loaded. If it does not
  96623. ** already exists, it will be created to use the new encoding value.
  96624. */
  96625. if(
  96626. !(DbHasProperty(db, 0, DB_SchemaLoaded)) ||
  96627. DbHasProperty(db, 0, DB_Empty)
  96628. ){
  96629. for(pEnc=&encnames[0]; pEnc->zName; pEnc++){
  96630. if( 0==sqlite3StrICmp(zRight, pEnc->zName) ){
  96631. ENC(pParse->db) = pEnc->enc ? pEnc->enc : SQLITE_UTF16NATIVE;
  96632. break;
  96633. }
  96634. }
  96635. if( !pEnc->zName ){
  96636. sqlite3ErrorMsg(pParse, "unsupported encoding: %s", zRight);
  96637. }
  96638. }
  96639. }
  96640. }
  96641. break;
  96642. #endif /* SQLITE_OMIT_UTF16 */
  96643. #ifndef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
  96644. /*
  96645. ** PRAGMA [database.]schema_version
  96646. ** PRAGMA [database.]schema_version = <integer>
  96647. **
  96648. ** PRAGMA [database.]user_version
  96649. ** PRAGMA [database.]user_version = <integer>
  96650. **
  96651. ** PRAGMA [database.]freelist_count = <integer>
  96652. **
  96653. ** PRAGMA [database.]application_id
  96654. ** PRAGMA [database.]application_id = <integer>
  96655. **
  96656. ** The pragma's schema_version and user_version are used to set or get
  96657. ** the value of the schema-version and user-version, respectively. Both
  96658. ** the schema-version and the user-version are 32-bit signed integers
  96659. ** stored in the database header.
  96660. **
  96661. ** The schema-cookie is usually only manipulated internally by SQLite. It
  96662. ** is incremented by SQLite whenever the database schema is modified (by
  96663. ** creating or dropping a table or index). The schema version is used by
  96664. ** SQLite each time a query is executed to ensure that the internal cache
  96665. ** of the schema used when compiling the SQL query matches the schema of
  96666. ** the database against which the compiled query is actually executed.
  96667. ** Subverting this mechanism by using "PRAGMA schema_version" to modify
  96668. ** the schema-version is potentially dangerous and may lead to program
  96669. ** crashes or database corruption. Use with caution!
  96670. **
  96671. ** The user-version is not used internally by SQLite. It may be used by
  96672. ** applications for any purpose.
  96673. */
  96674. case PragTyp_HEADER_VALUE: {
  96675. int iCookie; /* Cookie index. 1 for schema-cookie, 6 for user-cookie. */
  96676. sqlite3VdbeUsesBtree(v, iDb);
  96677. switch( zLeft[0] ){
  96678. case 'a': case 'A':
  96679. iCookie = BTREE_APPLICATION_ID;
  96680. break;
  96681. case 'f': case 'F':
  96682. iCookie = BTREE_FREE_PAGE_COUNT;
  96683. break;
  96684. case 's': case 'S':
  96685. iCookie = BTREE_SCHEMA_VERSION;
  96686. break;
  96687. default:
  96688. iCookie = BTREE_USER_VERSION;
  96689. break;
  96690. }
  96691. if( zRight && iCookie!=BTREE_FREE_PAGE_COUNT ){
  96692. /* Write the specified cookie value */
  96693. static const VdbeOpList setCookie[] = {
  96694. { OP_Transaction, 0, 1, 0}, /* 0 */
  96695. { OP_Integer, 0, 1, 0}, /* 1 */
  96696. { OP_SetCookie, 0, 0, 1}, /* 2 */
  96697. };
  96698. int addr = sqlite3VdbeAddOpList(v, ArraySize(setCookie), setCookie, 0);
  96699. sqlite3VdbeChangeP1(v, addr, iDb);
  96700. sqlite3VdbeChangeP1(v, addr+1, sqlite3Atoi(zRight));
  96701. sqlite3VdbeChangeP1(v, addr+2, iDb);
  96702. sqlite3VdbeChangeP2(v, addr+2, iCookie);
  96703. }else{
  96704. /* Read the specified cookie value */
  96705. static const VdbeOpList readCookie[] = {
  96706. { OP_Transaction, 0, 0, 0}, /* 0 */
  96707. { OP_ReadCookie, 0, 1, 0}, /* 1 */
  96708. { OP_ResultRow, 1, 1, 0}
  96709. };
  96710. int addr = sqlite3VdbeAddOpList(v, ArraySize(readCookie), readCookie, 0);
  96711. sqlite3VdbeChangeP1(v, addr, iDb);
  96712. sqlite3VdbeChangeP1(v, addr+1, iDb);
  96713. sqlite3VdbeChangeP3(v, addr+1, iCookie);
  96714. sqlite3VdbeSetNumCols(v, 1);
  96715. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, SQLITE_TRANSIENT);
  96716. }
  96717. }
  96718. break;
  96719. #endif /* SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS */
  96720. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  96721. /*
  96722. ** PRAGMA compile_options
  96723. **
  96724. ** Return the names of all compile-time options used in this build,
  96725. ** one option per row.
  96726. */
  96727. case PragTyp_COMPILE_OPTIONS: {
  96728. int i = 0;
  96729. const char *zOpt;
  96730. sqlite3VdbeSetNumCols(v, 1);
  96731. pParse->nMem = 1;
  96732. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "compile_option", SQLITE_STATIC);
  96733. while( (zOpt = sqlite3_compileoption_get(i++))!=0 ){
  96734. sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, zOpt, 0);
  96735. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
  96736. }
  96737. }
  96738. break;
  96739. #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
  96740. #ifndef SQLITE_OMIT_WAL
  96741. /*
  96742. ** PRAGMA [database.]wal_checkpoint = passive|full|restart
  96743. **
  96744. ** Checkpoint the database.
  96745. */
  96746. case PragTyp_WAL_CHECKPOINT: {
  96747. int iBt = (pId2->z?iDb:SQLITE_MAX_ATTACHED);
  96748. int eMode = SQLITE_CHECKPOINT_PASSIVE;
  96749. if( zRight ){
  96750. if( sqlite3StrICmp(zRight, "full")==0 ){
  96751. eMode = SQLITE_CHECKPOINT_FULL;
  96752. }else if( sqlite3StrICmp(zRight, "restart")==0 ){
  96753. eMode = SQLITE_CHECKPOINT_RESTART;
  96754. }
  96755. }
  96756. sqlite3VdbeSetNumCols(v, 3);
  96757. pParse->nMem = 3;
  96758. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "busy", SQLITE_STATIC);
  96759. sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "log", SQLITE_STATIC);
  96760. sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "checkpointed", SQLITE_STATIC);
  96761. sqlite3VdbeAddOp3(v, OP_Checkpoint, iBt, eMode, 1);
  96762. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
  96763. }
  96764. break;
  96765. /*
  96766. ** PRAGMA wal_autocheckpoint
  96767. ** PRAGMA wal_autocheckpoint = N
  96768. **
  96769. ** Configure a database connection to automatically checkpoint a database
  96770. ** after accumulating N frames in the log. Or query for the current value
  96771. ** of N.
  96772. */
  96773. case PragTyp_WAL_AUTOCHECKPOINT: {
  96774. if( zRight ){
  96775. sqlite3_wal_autocheckpoint(db, sqlite3Atoi(zRight));
  96776. }
  96777. returnSingleInt(pParse, "wal_autocheckpoint",
  96778. db->xWalCallback==sqlite3WalDefaultHook ?
  96779. SQLITE_PTR_TO_INT(db->pWalArg) : 0);
  96780. }
  96781. break;
  96782. #endif
  96783. /*
  96784. ** PRAGMA shrink_memory
  96785. **
  96786. ** This pragma attempts to free as much memory as possible from the
  96787. ** current database connection.
  96788. */
  96789. case PragTyp_SHRINK_MEMORY: {
  96790. sqlite3_db_release_memory(db);
  96791. break;
  96792. }
  96793. /*
  96794. ** PRAGMA busy_timeout
  96795. ** PRAGMA busy_timeout = N
  96796. **
  96797. ** Call sqlite3_busy_timeout(db, N). Return the current timeout value
  96798. ** if one is set. If no busy handler or a different busy handler is set
  96799. ** then 0 is returned. Setting the busy_timeout to 0 or negative
  96800. ** disables the timeout.
  96801. */
  96802. /*case PragTyp_BUSY_TIMEOUT*/ default: {
  96803. assert( aPragmaNames[mid].ePragTyp==PragTyp_BUSY_TIMEOUT );
  96804. if( zRight ){
  96805. sqlite3_busy_timeout(db, sqlite3Atoi(zRight));
  96806. }
  96807. returnSingleInt(pParse, "timeout", db->busyTimeout);
  96808. break;
  96809. }
  96810. /*
  96811. ** PRAGMA soft_heap_limit
  96812. ** PRAGMA soft_heap_limit = N
  96813. **
  96814. ** Call sqlite3_soft_heap_limit64(N). Return the result. If N is omitted,
  96815. ** use -1.
  96816. */
  96817. case PragTyp_SOFT_HEAP_LIMIT: {
  96818. sqlite3_int64 N;
  96819. if( zRight && sqlite3DecOrHexToI64(zRight, &N)==SQLITE_OK ){
  96820. sqlite3_soft_heap_limit64(N);
  96821. }
  96822. returnSingleInt(pParse, "soft_heap_limit", sqlite3_soft_heap_limit64(-1));
  96823. break;
  96824. }
  96825. /*
  96826. ** PRAGMA threads
  96827. ** PRAGMA threads = N
  96828. **
  96829. ** Configure the maximum number of worker threads. Return the new
  96830. ** maximum, which might be less than requested.
  96831. */
  96832. case PragTyp_THREADS: {
  96833. sqlite3_int64 N;
  96834. if( zRight
  96835. && sqlite3DecOrHexToI64(zRight, &N)==SQLITE_OK
  96836. && N>=0
  96837. ){
  96838. sqlite3_limit(db, SQLITE_LIMIT_WORKER_THREADS, (int)(N&0x7fffffff));
  96839. }
  96840. returnSingleInt(pParse, "threads",
  96841. sqlite3_limit(db, SQLITE_LIMIT_WORKER_THREADS, -1));
  96842. break;
  96843. }
  96844. #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
  96845. /*
  96846. ** Report the current state of file logs for all databases
  96847. */
  96848. case PragTyp_LOCK_STATUS: {
  96849. static const char *const azLockName[] = {
  96850. "unlocked", "shared", "reserved", "pending", "exclusive"
  96851. };
  96852. int i;
  96853. sqlite3VdbeSetNumCols(v, 2);
  96854. pParse->nMem = 2;
  96855. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "database", SQLITE_STATIC);
  96856. sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "status", SQLITE_STATIC);
  96857. for(i=0; i<db->nDb; i++){
  96858. Btree *pBt;
  96859. const char *zState = "unknown";
  96860. int j;
  96861. if( db->aDb[i].zName==0 ) continue;
  96862. sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, db->aDb[i].zName, P4_STATIC);
  96863. pBt = db->aDb[i].pBt;
  96864. if( pBt==0 || sqlite3BtreePager(pBt)==0 ){
  96865. zState = "closed";
  96866. }else if( sqlite3_file_control(db, i ? db->aDb[i].zName : 0,
  96867. SQLITE_FCNTL_LOCKSTATE, &j)==SQLITE_OK ){
  96868. zState = azLockName[j];
  96869. }
  96870. sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, zState, P4_STATIC);
  96871. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
  96872. }
  96873. break;
  96874. }
  96875. #endif
  96876. #ifdef SQLITE_HAS_CODEC
  96877. case PragTyp_KEY: {
  96878. if( zRight ) sqlite3_key_v2(db, zDb, zRight, sqlite3Strlen30(zRight));
  96879. break;
  96880. }
  96881. case PragTyp_REKEY: {
  96882. if( zRight ) sqlite3_rekey_v2(db, zDb, zRight, sqlite3Strlen30(zRight));
  96883. break;
  96884. }
  96885. case PragTyp_HEXKEY: {
  96886. if( zRight ){
  96887. u8 iByte;
  96888. int i;
  96889. char zKey[40];
  96890. for(i=0, iByte=0; i<sizeof(zKey)*2 && sqlite3Isxdigit(zRight[i]); i++){
  96891. iByte = (iByte<<4) + sqlite3HexToInt(zRight[i]);
  96892. if( (i&1)!=0 ) zKey[i/2] = iByte;
  96893. }
  96894. if( (zLeft[3] & 0xf)==0xb ){
  96895. sqlite3_key_v2(db, zDb, zKey, i/2);
  96896. }else{
  96897. sqlite3_rekey_v2(db, zDb, zKey, i/2);
  96898. }
  96899. }
  96900. break;
  96901. }
  96902. #endif
  96903. #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_ENABLE_CEROD)
  96904. case PragTyp_ACTIVATE_EXTENSIONS: if( zRight ){
  96905. #ifdef SQLITE_HAS_CODEC
  96906. if( sqlite3StrNICmp(zRight, "see-", 4)==0 ){
  96907. sqlite3_activate_see(&zRight[4]);
  96908. }
  96909. #endif
  96910. #ifdef SQLITE_ENABLE_CEROD
  96911. if( sqlite3StrNICmp(zRight, "cerod-", 6)==0 ){
  96912. sqlite3_activate_cerod(&zRight[6]);
  96913. }
  96914. #endif
  96915. }
  96916. break;
  96917. #endif
  96918. } /* End of the PRAGMA switch */
  96919. pragma_out:
  96920. sqlite3DbFree(db, zLeft);
  96921. sqlite3DbFree(db, zRight);
  96922. }
  96923. #endif /* SQLITE_OMIT_PRAGMA */
  96924. /************** End of pragma.c **********************************************/
  96925. /************** Begin file prepare.c *****************************************/
  96926. /*
  96927. ** 2005 May 25
  96928. **
  96929. ** The author disclaims copyright to this source code. In place of
  96930. ** a legal notice, here is a blessing:
  96931. **
  96932. ** May you do good and not evil.
  96933. ** May you find forgiveness for yourself and forgive others.
  96934. ** May you share freely, never taking more than you give.
  96935. **
  96936. *************************************************************************
  96937. ** This file contains the implementation of the sqlite3_prepare()
  96938. ** interface, and routines that contribute to loading the database schema
  96939. ** from disk.
  96940. */
  96941. /*
  96942. ** Fill the InitData structure with an error message that indicates
  96943. ** that the database is corrupt.
  96944. */
  96945. static void corruptSchema(
  96946. InitData *pData, /* Initialization context */
  96947. const char *zObj, /* Object being parsed at the point of error */
  96948. const char *zExtra /* Error information */
  96949. ){
  96950. sqlite3 *db = pData->db;
  96951. if( !db->mallocFailed && (db->flags & SQLITE_RecoveryMode)==0 ){
  96952. if( zObj==0 ) zObj = "?";
  96953. sqlite3SetString(pData->pzErrMsg, db,
  96954. "malformed database schema (%s)", zObj);
  96955. if( zExtra ){
  96956. *pData->pzErrMsg = sqlite3MAppendf(db, *pData->pzErrMsg,
  96957. "%s - %s", *pData->pzErrMsg, zExtra);
  96958. }
  96959. }
  96960. pData->rc = db->mallocFailed ? SQLITE_NOMEM : SQLITE_CORRUPT_BKPT;
  96961. }
  96962. /*
  96963. ** This is the callback routine for the code that initializes the
  96964. ** database. See sqlite3Init() below for additional information.
  96965. ** This routine is also called from the OP_ParseSchema opcode of the VDBE.
  96966. **
  96967. ** Each callback contains the following information:
  96968. **
  96969. ** argv[0] = name of thing being created
  96970. ** argv[1] = root page number for table or index. 0 for trigger or view.
  96971. ** argv[2] = SQL text for the CREATE statement.
  96972. **
  96973. */
  96974. SQLITE_PRIVATE int sqlite3InitCallback(void *pInit, int argc, char **argv, char **NotUsed){
  96975. InitData *pData = (InitData*)pInit;
  96976. sqlite3 *db = pData->db;
  96977. int iDb = pData->iDb;
  96978. assert( argc==3 );
  96979. UNUSED_PARAMETER2(NotUsed, argc);
  96980. assert( sqlite3_mutex_held(db->mutex) );
  96981. DbClearProperty(db, iDb, DB_Empty);
  96982. if( db->mallocFailed ){
  96983. corruptSchema(pData, argv[0], 0);
  96984. return 1;
  96985. }
  96986. assert( iDb>=0 && iDb<db->nDb );
  96987. if( argv==0 ) return 0; /* Might happen if EMPTY_RESULT_CALLBACKS are on */
  96988. if( argv[1]==0 ){
  96989. corruptSchema(pData, argv[0], 0);
  96990. }else if( argv[2] && argv[2][0] ){
  96991. /* Call the parser to process a CREATE TABLE, INDEX or VIEW.
  96992. ** But because db->init.busy is set to 1, no VDBE code is generated
  96993. ** or executed. All the parser does is build the internal data
  96994. ** structures that describe the table, index, or view.
  96995. */
  96996. int rc;
  96997. sqlite3_stmt *pStmt;
  96998. TESTONLY(int rcp); /* Return code from sqlite3_prepare() */
  96999. assert( db->init.busy );
  97000. db->init.iDb = iDb;
  97001. db->init.newTnum = sqlite3Atoi(argv[1]);
  97002. db->init.orphanTrigger = 0;
  97003. TESTONLY(rcp = ) sqlite3_prepare(db, argv[2], -1, &pStmt, 0);
  97004. rc = db->errCode;
  97005. assert( (rc&0xFF)==(rcp&0xFF) );
  97006. db->init.iDb = 0;
  97007. if( SQLITE_OK!=rc ){
  97008. if( db->init.orphanTrigger ){
  97009. assert( iDb==1 );
  97010. }else{
  97011. pData->rc = rc;
  97012. if( rc==SQLITE_NOMEM ){
  97013. db->mallocFailed = 1;
  97014. }else if( rc!=SQLITE_INTERRUPT && (rc&0xFF)!=SQLITE_LOCKED ){
  97015. corruptSchema(pData, argv[0], sqlite3_errmsg(db));
  97016. }
  97017. }
  97018. }
  97019. sqlite3_finalize(pStmt);
  97020. }else if( argv[0]==0 ){
  97021. corruptSchema(pData, 0, 0);
  97022. }else{
  97023. /* If the SQL column is blank it means this is an index that
  97024. ** was created to be the PRIMARY KEY or to fulfill a UNIQUE
  97025. ** constraint for a CREATE TABLE. The index should have already
  97026. ** been created when we processed the CREATE TABLE. All we have
  97027. ** to do here is record the root page number for that index.
  97028. */
  97029. Index *pIndex;
  97030. pIndex = sqlite3FindIndex(db, argv[0], db->aDb[iDb].zName);
  97031. if( pIndex==0 ){
  97032. /* This can occur if there exists an index on a TEMP table which
  97033. ** has the same name as another index on a permanent index. Since
  97034. ** the permanent table is hidden by the TEMP table, we can also
  97035. ** safely ignore the index on the permanent table.
  97036. */
  97037. /* Do Nothing */;
  97038. }else if( sqlite3GetInt32(argv[1], &pIndex->tnum)==0 ){
  97039. corruptSchema(pData, argv[0], "invalid rootpage");
  97040. }
  97041. }
  97042. return 0;
  97043. }
  97044. /*
  97045. ** Attempt to read the database schema and initialize internal
  97046. ** data structures for a single database file. The index of the
  97047. ** database file is given by iDb. iDb==0 is used for the main
  97048. ** database. iDb==1 should never be used. iDb>=2 is used for
  97049. ** auxiliary databases. Return one of the SQLITE_ error codes to
  97050. ** indicate success or failure.
  97051. */
  97052. static int sqlite3InitOne(sqlite3 *db, int iDb, char **pzErrMsg){
  97053. int rc;
  97054. int i;
  97055. #ifndef SQLITE_OMIT_DEPRECATED
  97056. int size;
  97057. #endif
  97058. Table *pTab;
  97059. Db *pDb;
  97060. char const *azArg[4];
  97061. int meta[5];
  97062. InitData initData;
  97063. char const *zMasterSchema;
  97064. char const *zMasterName;
  97065. int openedTransaction = 0;
  97066. /*
  97067. ** The master database table has a structure like this
  97068. */
  97069. static const char master_schema[] =
  97070. "CREATE TABLE sqlite_master(\n"
  97071. " type text,\n"
  97072. " name text,\n"
  97073. " tbl_name text,\n"
  97074. " rootpage integer,\n"
  97075. " sql text\n"
  97076. ")"
  97077. ;
  97078. #ifndef SQLITE_OMIT_TEMPDB
  97079. static const char temp_master_schema[] =
  97080. "CREATE TEMP TABLE sqlite_temp_master(\n"
  97081. " type text,\n"
  97082. " name text,\n"
  97083. " tbl_name text,\n"
  97084. " rootpage integer,\n"
  97085. " sql text\n"
  97086. ")"
  97087. ;
  97088. #else
  97089. #define temp_master_schema 0
  97090. #endif
  97091. assert( iDb>=0 && iDb<db->nDb );
  97092. assert( db->aDb[iDb].pSchema );
  97093. assert( sqlite3_mutex_held(db->mutex) );
  97094. assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
  97095. /* zMasterSchema and zInitScript are set to point at the master schema
  97096. ** and initialisation script appropriate for the database being
  97097. ** initialized. zMasterName is the name of the master table.
  97098. */
  97099. if( !OMIT_TEMPDB && iDb==1 ){
  97100. zMasterSchema = temp_master_schema;
  97101. }else{
  97102. zMasterSchema = master_schema;
  97103. }
  97104. zMasterName = SCHEMA_TABLE(iDb);
  97105. /* Construct the schema tables. */
  97106. azArg[0] = zMasterName;
  97107. azArg[1] = "1";
  97108. azArg[2] = zMasterSchema;
  97109. azArg[3] = 0;
  97110. initData.db = db;
  97111. initData.iDb = iDb;
  97112. initData.rc = SQLITE_OK;
  97113. initData.pzErrMsg = pzErrMsg;
  97114. sqlite3InitCallback(&initData, 3, (char **)azArg, 0);
  97115. if( initData.rc ){
  97116. rc = initData.rc;
  97117. goto error_out;
  97118. }
  97119. pTab = sqlite3FindTable(db, zMasterName, db->aDb[iDb].zName);
  97120. if( ALWAYS(pTab) ){
  97121. pTab->tabFlags |= TF_Readonly;
  97122. }
  97123. /* Create a cursor to hold the database open
  97124. */
  97125. pDb = &db->aDb[iDb];
  97126. if( pDb->pBt==0 ){
  97127. if( !OMIT_TEMPDB && ALWAYS(iDb==1) ){
  97128. DbSetProperty(db, 1, DB_SchemaLoaded);
  97129. }
  97130. return SQLITE_OK;
  97131. }
  97132. /* If there is not already a read-only (or read-write) transaction opened
  97133. ** on the b-tree database, open one now. If a transaction is opened, it
  97134. ** will be closed before this function returns. */
  97135. sqlite3BtreeEnter(pDb->pBt);
  97136. if( !sqlite3BtreeIsInReadTrans(pDb->pBt) ){
  97137. rc = sqlite3BtreeBeginTrans(pDb->pBt, 0);
  97138. if( rc!=SQLITE_OK ){
  97139. sqlite3SetString(pzErrMsg, db, "%s", sqlite3ErrStr(rc));
  97140. goto initone_error_out;
  97141. }
  97142. openedTransaction = 1;
  97143. }
  97144. /* Get the database meta information.
  97145. **
  97146. ** Meta values are as follows:
  97147. ** meta[0] Schema cookie. Changes with each schema change.
  97148. ** meta[1] File format of schema layer.
  97149. ** meta[2] Size of the page cache.
  97150. ** meta[3] Largest rootpage (auto/incr_vacuum mode)
  97151. ** meta[4] Db text encoding. 1:UTF-8 2:UTF-16LE 3:UTF-16BE
  97152. ** meta[5] User version
  97153. ** meta[6] Incremental vacuum mode
  97154. ** meta[7] unused
  97155. ** meta[8] unused
  97156. ** meta[9] unused
  97157. **
  97158. ** Note: The #defined SQLITE_UTF* symbols in sqliteInt.h correspond to
  97159. ** the possible values of meta[4].
  97160. */
  97161. for(i=0; i<ArraySize(meta); i++){
  97162. sqlite3BtreeGetMeta(pDb->pBt, i+1, (u32 *)&meta[i]);
  97163. }
  97164. pDb->pSchema->schema_cookie = meta[BTREE_SCHEMA_VERSION-1];
  97165. /* If opening a non-empty database, check the text encoding. For the
  97166. ** main database, set sqlite3.enc to the encoding of the main database.
  97167. ** For an attached db, it is an error if the encoding is not the same
  97168. ** as sqlite3.enc.
  97169. */
  97170. if( meta[BTREE_TEXT_ENCODING-1] ){ /* text encoding */
  97171. if( iDb==0 ){
  97172. #ifndef SQLITE_OMIT_UTF16
  97173. u8 encoding;
  97174. /* If opening the main database, set ENC(db). */
  97175. encoding = (u8)meta[BTREE_TEXT_ENCODING-1] & 3;
  97176. if( encoding==0 ) encoding = SQLITE_UTF8;
  97177. ENC(db) = encoding;
  97178. #else
  97179. ENC(db) = SQLITE_UTF8;
  97180. #endif
  97181. }else{
  97182. /* If opening an attached database, the encoding much match ENC(db) */
  97183. if( meta[BTREE_TEXT_ENCODING-1]!=ENC(db) ){
  97184. sqlite3SetString(pzErrMsg, db, "attached databases must use the same"
  97185. " text encoding as main database");
  97186. rc = SQLITE_ERROR;
  97187. goto initone_error_out;
  97188. }
  97189. }
  97190. }else{
  97191. DbSetProperty(db, iDb, DB_Empty);
  97192. }
  97193. pDb->pSchema->enc = ENC(db);
  97194. if( pDb->pSchema->cache_size==0 ){
  97195. #ifndef SQLITE_OMIT_DEPRECATED
  97196. size = sqlite3AbsInt32(meta[BTREE_DEFAULT_CACHE_SIZE-1]);
  97197. if( size==0 ){ size = SQLITE_DEFAULT_CACHE_SIZE; }
  97198. pDb->pSchema->cache_size = size;
  97199. #else
  97200. pDb->pSchema->cache_size = SQLITE_DEFAULT_CACHE_SIZE;
  97201. #endif
  97202. sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
  97203. }
  97204. /*
  97205. ** file_format==1 Version 3.0.0.
  97206. ** file_format==2 Version 3.1.3. // ALTER TABLE ADD COLUMN
  97207. ** file_format==3 Version 3.1.4. // ditto but with non-NULL defaults
  97208. ** file_format==4 Version 3.3.0. // DESC indices. Boolean constants
  97209. */
  97210. pDb->pSchema->file_format = (u8)meta[BTREE_FILE_FORMAT-1];
  97211. if( pDb->pSchema->file_format==0 ){
  97212. pDb->pSchema->file_format = 1;
  97213. }
  97214. if( pDb->pSchema->file_format>SQLITE_MAX_FILE_FORMAT ){
  97215. sqlite3SetString(pzErrMsg, db, "unsupported file format");
  97216. rc = SQLITE_ERROR;
  97217. goto initone_error_out;
  97218. }
  97219. /* Ticket #2804: When we open a database in the newer file format,
  97220. ** clear the legacy_file_format pragma flag so that a VACUUM will
  97221. ** not downgrade the database and thus invalidate any descending
  97222. ** indices that the user might have created.
  97223. */
  97224. if( iDb==0 && meta[BTREE_FILE_FORMAT-1]>=4 ){
  97225. db->flags &= ~SQLITE_LegacyFileFmt;
  97226. }
  97227. /* Read the schema information out of the schema tables
  97228. */
  97229. assert( db->init.busy );
  97230. {
  97231. char *zSql;
  97232. zSql = sqlite3MPrintf(db,
  97233. "SELECT name, rootpage, sql FROM '%q'.%s ORDER BY rowid",
  97234. db->aDb[iDb].zName, zMasterName);
  97235. #ifndef SQLITE_OMIT_AUTHORIZATION
  97236. {
  97237. sqlite3_xauth xAuth;
  97238. xAuth = db->xAuth;
  97239. db->xAuth = 0;
  97240. #endif
  97241. rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
  97242. #ifndef SQLITE_OMIT_AUTHORIZATION
  97243. db->xAuth = xAuth;
  97244. }
  97245. #endif
  97246. if( rc==SQLITE_OK ) rc = initData.rc;
  97247. sqlite3DbFree(db, zSql);
  97248. #ifndef SQLITE_OMIT_ANALYZE
  97249. if( rc==SQLITE_OK ){
  97250. sqlite3AnalysisLoad(db, iDb);
  97251. }
  97252. #endif
  97253. }
  97254. if( db->mallocFailed ){
  97255. rc = SQLITE_NOMEM;
  97256. sqlite3ResetAllSchemasOfConnection(db);
  97257. }
  97258. if( rc==SQLITE_OK || (db->flags&SQLITE_RecoveryMode)){
  97259. /* Black magic: If the SQLITE_RecoveryMode flag is set, then consider
  97260. ** the schema loaded, even if errors occurred. In this situation the
  97261. ** current sqlite3_prepare() operation will fail, but the following one
  97262. ** will attempt to compile the supplied statement against whatever subset
  97263. ** of the schema was loaded before the error occurred. The primary
  97264. ** purpose of this is to allow access to the sqlite_master table
  97265. ** even when its contents have been corrupted.
  97266. */
  97267. DbSetProperty(db, iDb, DB_SchemaLoaded);
  97268. rc = SQLITE_OK;
  97269. }
  97270. /* Jump here for an error that occurs after successfully allocating
  97271. ** curMain and calling sqlite3BtreeEnter(). For an error that occurs
  97272. ** before that point, jump to error_out.
  97273. */
  97274. initone_error_out:
  97275. if( openedTransaction ){
  97276. sqlite3BtreeCommit(pDb->pBt);
  97277. }
  97278. sqlite3BtreeLeave(pDb->pBt);
  97279. error_out:
  97280. if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
  97281. db->mallocFailed = 1;
  97282. }
  97283. return rc;
  97284. }
  97285. /*
  97286. ** Initialize all database files - the main database file, the file
  97287. ** used to store temporary tables, and any additional database files
  97288. ** created using ATTACH statements. Return a success code. If an
  97289. ** error occurs, write an error message into *pzErrMsg.
  97290. **
  97291. ** After a database is initialized, the DB_SchemaLoaded bit is set
  97292. ** bit is set in the flags field of the Db structure. If the database
  97293. ** file was of zero-length, then the DB_Empty flag is also set.
  97294. */
  97295. SQLITE_PRIVATE int sqlite3Init(sqlite3 *db, char **pzErrMsg){
  97296. int i, rc;
  97297. int commit_internal = !(db->flags&SQLITE_InternChanges);
  97298. assert( sqlite3_mutex_held(db->mutex) );
  97299. assert( db->init.busy==0 );
  97300. rc = SQLITE_OK;
  97301. db->init.busy = 1;
  97302. for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
  97303. if( DbHasProperty(db, i, DB_SchemaLoaded) || i==1 ) continue;
  97304. rc = sqlite3InitOne(db, i, pzErrMsg);
  97305. if( rc ){
  97306. sqlite3ResetOneSchema(db, i);
  97307. }
  97308. }
  97309. /* Once all the other databases have been initialized, load the schema
  97310. ** for the TEMP database. This is loaded last, as the TEMP database
  97311. ** schema may contain references to objects in other databases.
  97312. */
  97313. #ifndef SQLITE_OMIT_TEMPDB
  97314. assert( db->nDb>1 );
  97315. if( rc==SQLITE_OK && !DbHasProperty(db, 1, DB_SchemaLoaded) ){
  97316. rc = sqlite3InitOne(db, 1, pzErrMsg);
  97317. if( rc ){
  97318. sqlite3ResetOneSchema(db, 1);
  97319. }
  97320. }
  97321. #endif
  97322. db->init.busy = 0;
  97323. if( rc==SQLITE_OK && commit_internal ){
  97324. sqlite3CommitInternalChanges(db);
  97325. }
  97326. return rc;
  97327. }
  97328. /*
  97329. ** This routine is a no-op if the database schema is already initialized.
  97330. ** Otherwise, the schema is loaded. An error code is returned.
  97331. */
  97332. SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse){
  97333. int rc = SQLITE_OK;
  97334. sqlite3 *db = pParse->db;
  97335. assert( sqlite3_mutex_held(db->mutex) );
  97336. if( !db->init.busy ){
  97337. rc = sqlite3Init(db, &pParse->zErrMsg);
  97338. }
  97339. if( rc!=SQLITE_OK ){
  97340. pParse->rc = rc;
  97341. pParse->nErr++;
  97342. }
  97343. return rc;
  97344. }
  97345. /*
  97346. ** Check schema cookies in all databases. If any cookie is out
  97347. ** of date set pParse->rc to SQLITE_SCHEMA. If all schema cookies
  97348. ** make no changes to pParse->rc.
  97349. */
  97350. static void schemaIsValid(Parse *pParse){
  97351. sqlite3 *db = pParse->db;
  97352. int iDb;
  97353. int rc;
  97354. int cookie;
  97355. assert( pParse->checkSchema );
  97356. assert( sqlite3_mutex_held(db->mutex) );
  97357. for(iDb=0; iDb<db->nDb; iDb++){
  97358. int openedTransaction = 0; /* True if a transaction is opened */
  97359. Btree *pBt = db->aDb[iDb].pBt; /* Btree database to read cookie from */
  97360. if( pBt==0 ) continue;
  97361. /* If there is not already a read-only (or read-write) transaction opened
  97362. ** on the b-tree database, open one now. If a transaction is opened, it
  97363. ** will be closed immediately after reading the meta-value. */
  97364. if( !sqlite3BtreeIsInReadTrans(pBt) ){
  97365. rc = sqlite3BtreeBeginTrans(pBt, 0);
  97366. if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
  97367. db->mallocFailed = 1;
  97368. }
  97369. if( rc!=SQLITE_OK ) return;
  97370. openedTransaction = 1;
  97371. }
  97372. /* Read the schema cookie from the database. If it does not match the
  97373. ** value stored as part of the in-memory schema representation,
  97374. ** set Parse.rc to SQLITE_SCHEMA. */
  97375. sqlite3BtreeGetMeta(pBt, BTREE_SCHEMA_VERSION, (u32 *)&cookie);
  97376. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  97377. if( cookie!=db->aDb[iDb].pSchema->schema_cookie ){
  97378. sqlite3ResetOneSchema(db, iDb);
  97379. pParse->rc = SQLITE_SCHEMA;
  97380. }
  97381. /* Close the transaction, if one was opened. */
  97382. if( openedTransaction ){
  97383. sqlite3BtreeCommit(pBt);
  97384. }
  97385. }
  97386. }
  97387. /*
  97388. ** Convert a schema pointer into the iDb index that indicates
  97389. ** which database file in db->aDb[] the schema refers to.
  97390. **
  97391. ** If the same database is attached more than once, the first
  97392. ** attached database is returned.
  97393. */
  97394. SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *pSchema){
  97395. int i = -1000000;
  97396. /* If pSchema is NULL, then return -1000000. This happens when code in
  97397. ** expr.c is trying to resolve a reference to a transient table (i.e. one
  97398. ** created by a sub-select). In this case the return value of this
  97399. ** function should never be used.
  97400. **
  97401. ** We return -1000000 instead of the more usual -1 simply because using
  97402. ** -1000000 as the incorrect index into db->aDb[] is much
  97403. ** more likely to cause a segfault than -1 (of course there are assert()
  97404. ** statements too, but it never hurts to play the odds).
  97405. */
  97406. assert( sqlite3_mutex_held(db->mutex) );
  97407. if( pSchema ){
  97408. for(i=0; ALWAYS(i<db->nDb); i++){
  97409. if( db->aDb[i].pSchema==pSchema ){
  97410. break;
  97411. }
  97412. }
  97413. assert( i>=0 && i<db->nDb );
  97414. }
  97415. return i;
  97416. }
  97417. /*
  97418. ** Free all memory allocations in the pParse object
  97419. */
  97420. SQLITE_PRIVATE void sqlite3ParserReset(Parse *pParse){
  97421. if( pParse ){
  97422. sqlite3 *db = pParse->db;
  97423. sqlite3DbFree(db, pParse->aLabel);
  97424. sqlite3ExprListDelete(db, pParse->pConstExpr);
  97425. }
  97426. }
  97427. /*
  97428. ** Compile the UTF-8 encoded SQL statement zSql into a statement handle.
  97429. */
  97430. static int sqlite3Prepare(
  97431. sqlite3 *db, /* Database handle. */
  97432. const char *zSql, /* UTF-8 encoded SQL statement. */
  97433. int nBytes, /* Length of zSql in bytes. */
  97434. int saveSqlFlag, /* True to copy SQL text into the sqlite3_stmt */
  97435. Vdbe *pReprepare, /* VM being reprepared */
  97436. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  97437. const char **pzTail /* OUT: End of parsed string */
  97438. ){
  97439. Parse *pParse; /* Parsing context */
  97440. char *zErrMsg = 0; /* Error message */
  97441. int rc = SQLITE_OK; /* Result code */
  97442. int i; /* Loop counter */
  97443. /* Allocate the parsing context */
  97444. pParse = sqlite3StackAllocZero(db, sizeof(*pParse));
  97445. if( pParse==0 ){
  97446. rc = SQLITE_NOMEM;
  97447. goto end_prepare;
  97448. }
  97449. pParse->pReprepare = pReprepare;
  97450. assert( ppStmt && *ppStmt==0 );
  97451. assert( !db->mallocFailed );
  97452. assert( sqlite3_mutex_held(db->mutex) );
  97453. /* Check to verify that it is possible to get a read lock on all
  97454. ** database schemas. The inability to get a read lock indicates that
  97455. ** some other database connection is holding a write-lock, which in
  97456. ** turn means that the other connection has made uncommitted changes
  97457. ** to the schema.
  97458. **
  97459. ** Were we to proceed and prepare the statement against the uncommitted
  97460. ** schema changes and if those schema changes are subsequently rolled
  97461. ** back and different changes are made in their place, then when this
  97462. ** prepared statement goes to run the schema cookie would fail to detect
  97463. ** the schema change. Disaster would follow.
  97464. **
  97465. ** This thread is currently holding mutexes on all Btrees (because
  97466. ** of the sqlite3BtreeEnterAll() in sqlite3LockAndPrepare()) so it
  97467. ** is not possible for another thread to start a new schema change
  97468. ** while this routine is running. Hence, we do not need to hold
  97469. ** locks on the schema, we just need to make sure nobody else is
  97470. ** holding them.
  97471. **
  97472. ** Note that setting READ_UNCOMMITTED overrides most lock detection,
  97473. ** but it does *not* override schema lock detection, so this all still
  97474. ** works even if READ_UNCOMMITTED is set.
  97475. */
  97476. for(i=0; i<db->nDb; i++) {
  97477. Btree *pBt = db->aDb[i].pBt;
  97478. if( pBt ){
  97479. assert( sqlite3BtreeHoldsMutex(pBt) );
  97480. rc = sqlite3BtreeSchemaLocked(pBt);
  97481. if( rc ){
  97482. const char *zDb = db->aDb[i].zName;
  97483. sqlite3ErrorWithMsg(db, rc, "database schema is locked: %s", zDb);
  97484. testcase( db->flags & SQLITE_ReadUncommitted );
  97485. goto end_prepare;
  97486. }
  97487. }
  97488. }
  97489. sqlite3VtabUnlockList(db);
  97490. pParse->db = db;
  97491. pParse->nQueryLoop = 0; /* Logarithmic, so 0 really means 1 */
  97492. if( nBytes>=0 && (nBytes==0 || zSql[nBytes-1]!=0) ){
  97493. char *zSqlCopy;
  97494. int mxLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
  97495. testcase( nBytes==mxLen );
  97496. testcase( nBytes==mxLen+1 );
  97497. if( nBytes>mxLen ){
  97498. sqlite3ErrorWithMsg(db, SQLITE_TOOBIG, "statement too long");
  97499. rc = sqlite3ApiExit(db, SQLITE_TOOBIG);
  97500. goto end_prepare;
  97501. }
  97502. zSqlCopy = sqlite3DbStrNDup(db, zSql, nBytes);
  97503. if( zSqlCopy ){
  97504. sqlite3RunParser(pParse, zSqlCopy, &zErrMsg);
  97505. sqlite3DbFree(db, zSqlCopy);
  97506. pParse->zTail = &zSql[pParse->zTail-zSqlCopy];
  97507. }else{
  97508. pParse->zTail = &zSql[nBytes];
  97509. }
  97510. }else{
  97511. sqlite3RunParser(pParse, zSql, &zErrMsg);
  97512. }
  97513. assert( 0==pParse->nQueryLoop );
  97514. if( db->mallocFailed ){
  97515. pParse->rc = SQLITE_NOMEM;
  97516. }
  97517. if( pParse->rc==SQLITE_DONE ) pParse->rc = SQLITE_OK;
  97518. if( pParse->checkSchema ){
  97519. schemaIsValid(pParse);
  97520. }
  97521. if( db->mallocFailed ){
  97522. pParse->rc = SQLITE_NOMEM;
  97523. }
  97524. if( pzTail ){
  97525. *pzTail = pParse->zTail;
  97526. }
  97527. rc = pParse->rc;
  97528. #ifndef SQLITE_OMIT_EXPLAIN
  97529. if( rc==SQLITE_OK && pParse->pVdbe && pParse->explain ){
  97530. static const char * const azColName[] = {
  97531. "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment",
  97532. "selectid", "order", "from", "detail"
  97533. };
  97534. int iFirst, mx;
  97535. if( pParse->explain==2 ){
  97536. sqlite3VdbeSetNumCols(pParse->pVdbe, 4);
  97537. iFirst = 8;
  97538. mx = 12;
  97539. }else{
  97540. sqlite3VdbeSetNumCols(pParse->pVdbe, 8);
  97541. iFirst = 0;
  97542. mx = 8;
  97543. }
  97544. for(i=iFirst; i<mx; i++){
  97545. sqlite3VdbeSetColName(pParse->pVdbe, i-iFirst, COLNAME_NAME,
  97546. azColName[i], SQLITE_STATIC);
  97547. }
  97548. }
  97549. #endif
  97550. if( db->init.busy==0 ){
  97551. Vdbe *pVdbe = pParse->pVdbe;
  97552. sqlite3VdbeSetSql(pVdbe, zSql, (int)(pParse->zTail-zSql), saveSqlFlag);
  97553. }
  97554. if( pParse->pVdbe && (rc!=SQLITE_OK || db->mallocFailed) ){
  97555. sqlite3VdbeFinalize(pParse->pVdbe);
  97556. assert(!(*ppStmt));
  97557. }else{
  97558. *ppStmt = (sqlite3_stmt*)pParse->pVdbe;
  97559. }
  97560. if( zErrMsg ){
  97561. sqlite3ErrorWithMsg(db, rc, "%s", zErrMsg);
  97562. sqlite3DbFree(db, zErrMsg);
  97563. }else{
  97564. sqlite3Error(db, rc);
  97565. }
  97566. /* Delete any TriggerPrg structures allocated while parsing this statement. */
  97567. while( pParse->pTriggerPrg ){
  97568. TriggerPrg *pT = pParse->pTriggerPrg;
  97569. pParse->pTriggerPrg = pT->pNext;
  97570. sqlite3DbFree(db, pT);
  97571. }
  97572. end_prepare:
  97573. sqlite3ParserReset(pParse);
  97574. sqlite3StackFree(db, pParse);
  97575. rc = sqlite3ApiExit(db, rc);
  97576. assert( (rc&db->errMask)==rc );
  97577. return rc;
  97578. }
  97579. static int sqlite3LockAndPrepare(
  97580. sqlite3 *db, /* Database handle. */
  97581. const char *zSql, /* UTF-8 encoded SQL statement. */
  97582. int nBytes, /* Length of zSql in bytes. */
  97583. int saveSqlFlag, /* True to copy SQL text into the sqlite3_stmt */
  97584. Vdbe *pOld, /* VM being reprepared */
  97585. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  97586. const char **pzTail /* OUT: End of parsed string */
  97587. ){
  97588. int rc;
  97589. #ifdef SQLITE_ENABLE_API_ARMOR
  97590. if( ppStmt==0 ) return SQLITE_MISUSE_BKPT;
  97591. #endif
  97592. *ppStmt = 0;
  97593. if( !sqlite3SafetyCheckOk(db)||zSql==0 ){
  97594. return SQLITE_MISUSE_BKPT;
  97595. }
  97596. sqlite3_mutex_enter(db->mutex);
  97597. sqlite3BtreeEnterAll(db);
  97598. rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail);
  97599. if( rc==SQLITE_SCHEMA ){
  97600. sqlite3_finalize(*ppStmt);
  97601. rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail);
  97602. }
  97603. sqlite3BtreeLeaveAll(db);
  97604. sqlite3_mutex_leave(db->mutex);
  97605. assert( rc==SQLITE_OK || *ppStmt==0 );
  97606. return rc;
  97607. }
  97608. /*
  97609. ** Rerun the compilation of a statement after a schema change.
  97610. **
  97611. ** If the statement is successfully recompiled, return SQLITE_OK. Otherwise,
  97612. ** if the statement cannot be recompiled because another connection has
  97613. ** locked the sqlite3_master table, return SQLITE_LOCKED. If any other error
  97614. ** occurs, return SQLITE_SCHEMA.
  97615. */
  97616. SQLITE_PRIVATE int sqlite3Reprepare(Vdbe *p){
  97617. int rc;
  97618. sqlite3_stmt *pNew;
  97619. const char *zSql;
  97620. sqlite3 *db;
  97621. assert( sqlite3_mutex_held(sqlite3VdbeDb(p)->mutex) );
  97622. zSql = sqlite3_sql((sqlite3_stmt *)p);
  97623. assert( zSql!=0 ); /* Reprepare only called for prepare_v2() statements */
  97624. db = sqlite3VdbeDb(p);
  97625. assert( sqlite3_mutex_held(db->mutex) );
  97626. rc = sqlite3LockAndPrepare(db, zSql, -1, 0, p, &pNew, 0);
  97627. if( rc ){
  97628. if( rc==SQLITE_NOMEM ){
  97629. db->mallocFailed = 1;
  97630. }
  97631. assert( pNew==0 );
  97632. return rc;
  97633. }else{
  97634. assert( pNew!=0 );
  97635. }
  97636. sqlite3VdbeSwap((Vdbe*)pNew, p);
  97637. sqlite3TransferBindings(pNew, (sqlite3_stmt*)p);
  97638. sqlite3VdbeResetStepResult((Vdbe*)pNew);
  97639. sqlite3VdbeFinalize((Vdbe*)pNew);
  97640. return SQLITE_OK;
  97641. }
  97642. /*
  97643. ** Two versions of the official API. Legacy and new use. In the legacy
  97644. ** version, the original SQL text is not saved in the prepared statement
  97645. ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
  97646. ** sqlite3_step(). In the new version, the original SQL text is retained
  97647. ** and the statement is automatically recompiled if an schema change
  97648. ** occurs.
  97649. */
  97650. SQLITE_API int sqlite3_prepare(
  97651. sqlite3 *db, /* Database handle. */
  97652. const char *zSql, /* UTF-8 encoded SQL statement. */
  97653. int nBytes, /* Length of zSql in bytes. */
  97654. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  97655. const char **pzTail /* OUT: End of parsed string */
  97656. ){
  97657. int rc;
  97658. rc = sqlite3LockAndPrepare(db,zSql,nBytes,0,0,ppStmt,pzTail);
  97659. assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
  97660. return rc;
  97661. }
  97662. SQLITE_API int sqlite3_prepare_v2(
  97663. sqlite3 *db, /* Database handle. */
  97664. const char *zSql, /* UTF-8 encoded SQL statement. */
  97665. int nBytes, /* Length of zSql in bytes. */
  97666. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  97667. const char **pzTail /* OUT: End of parsed string */
  97668. ){
  97669. int rc;
  97670. rc = sqlite3LockAndPrepare(db,zSql,nBytes,1,0,ppStmt,pzTail);
  97671. assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
  97672. return rc;
  97673. }
  97674. #ifndef SQLITE_OMIT_UTF16
  97675. /*
  97676. ** Compile the UTF-16 encoded SQL statement zSql into a statement handle.
  97677. */
  97678. static int sqlite3Prepare16(
  97679. sqlite3 *db, /* Database handle. */
  97680. const void *zSql, /* UTF-16 encoded SQL statement. */
  97681. int nBytes, /* Length of zSql in bytes. */
  97682. int saveSqlFlag, /* True to save SQL text into the sqlite3_stmt */
  97683. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  97684. const void **pzTail /* OUT: End of parsed string */
  97685. ){
  97686. /* This function currently works by first transforming the UTF-16
  97687. ** encoded string to UTF-8, then invoking sqlite3_prepare(). The
  97688. ** tricky bit is figuring out the pointer to return in *pzTail.
  97689. */
  97690. char *zSql8;
  97691. const char *zTail8 = 0;
  97692. int rc = SQLITE_OK;
  97693. #ifdef SQLITE_ENABLE_API_ARMOR
  97694. if( ppStmt==0 ) return SQLITE_MISUSE_BKPT;
  97695. #endif
  97696. *ppStmt = 0;
  97697. if( !sqlite3SafetyCheckOk(db)||zSql==0 ){
  97698. return SQLITE_MISUSE_BKPT;
  97699. }
  97700. if( nBytes>=0 ){
  97701. int sz;
  97702. const char *z = (const char*)zSql;
  97703. for(sz=0; sz<nBytes && (z[sz]!=0 || z[sz+1]!=0); sz += 2){}
  97704. nBytes = sz;
  97705. }
  97706. sqlite3_mutex_enter(db->mutex);
  97707. zSql8 = sqlite3Utf16to8(db, zSql, nBytes, SQLITE_UTF16NATIVE);
  97708. if( zSql8 ){
  97709. rc = sqlite3LockAndPrepare(db, zSql8, -1, saveSqlFlag, 0, ppStmt, &zTail8);
  97710. }
  97711. if( zTail8 && pzTail ){
  97712. /* If sqlite3_prepare returns a tail pointer, we calculate the
  97713. ** equivalent pointer into the UTF-16 string by counting the unicode
  97714. ** characters between zSql8 and zTail8, and then returning a pointer
  97715. ** the same number of characters into the UTF-16 string.
  97716. */
  97717. int chars_parsed = sqlite3Utf8CharLen(zSql8, (int)(zTail8-zSql8));
  97718. *pzTail = (u8 *)zSql + sqlite3Utf16ByteLen(zSql, chars_parsed);
  97719. }
  97720. sqlite3DbFree(db, zSql8);
  97721. rc = sqlite3ApiExit(db, rc);
  97722. sqlite3_mutex_leave(db->mutex);
  97723. return rc;
  97724. }
  97725. /*
  97726. ** Two versions of the official API. Legacy and new use. In the legacy
  97727. ** version, the original SQL text is not saved in the prepared statement
  97728. ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
  97729. ** sqlite3_step(). In the new version, the original SQL text is retained
  97730. ** and the statement is automatically recompiled if an schema change
  97731. ** occurs.
  97732. */
  97733. SQLITE_API int sqlite3_prepare16(
  97734. sqlite3 *db, /* Database handle. */
  97735. const void *zSql, /* UTF-16 encoded SQL statement. */
  97736. int nBytes, /* Length of zSql in bytes. */
  97737. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  97738. const void **pzTail /* OUT: End of parsed string */
  97739. ){
  97740. int rc;
  97741. rc = sqlite3Prepare16(db,zSql,nBytes,0,ppStmt,pzTail);
  97742. assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
  97743. return rc;
  97744. }
  97745. SQLITE_API int sqlite3_prepare16_v2(
  97746. sqlite3 *db, /* Database handle. */
  97747. const void *zSql, /* UTF-16 encoded SQL statement. */
  97748. int nBytes, /* Length of zSql in bytes. */
  97749. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  97750. const void **pzTail /* OUT: End of parsed string */
  97751. ){
  97752. int rc;
  97753. rc = sqlite3Prepare16(db,zSql,nBytes,1,ppStmt,pzTail);
  97754. assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
  97755. return rc;
  97756. }
  97757. #endif /* SQLITE_OMIT_UTF16 */
  97758. /************** End of prepare.c *********************************************/
  97759. /************** Begin file select.c ******************************************/
  97760. /*
  97761. ** 2001 September 15
  97762. **
  97763. ** The author disclaims copyright to this source code. In place of
  97764. ** a legal notice, here is a blessing:
  97765. **
  97766. ** May you do good and not evil.
  97767. ** May you find forgiveness for yourself and forgive others.
  97768. ** May you share freely, never taking more than you give.
  97769. **
  97770. *************************************************************************
  97771. ** This file contains C code routines that are called by the parser
  97772. ** to handle SELECT statements in SQLite.
  97773. */
  97774. /*
  97775. ** Trace output macros
  97776. */
  97777. #if SELECTTRACE_ENABLED
  97778. /***/ int sqlite3SelectTrace = 0;
  97779. # define SELECTTRACE(K,P,S,X) \
  97780. if(sqlite3SelectTrace&(K)) \
  97781. sqlite3DebugPrintf("%*s%s.%p: ",(P)->nSelectIndent*2-2,"",(S)->zSelName,(S)),\
  97782. sqlite3DebugPrintf X
  97783. #else
  97784. # define SELECTTRACE(K,P,S,X)
  97785. #endif
  97786. /*
  97787. ** An instance of the following object is used to record information about
  97788. ** how to process the DISTINCT keyword, to simplify passing that information
  97789. ** into the selectInnerLoop() routine.
  97790. */
  97791. typedef struct DistinctCtx DistinctCtx;
  97792. struct DistinctCtx {
  97793. u8 isTnct; /* True if the DISTINCT keyword is present */
  97794. u8 eTnctType; /* One of the WHERE_DISTINCT_* operators */
  97795. int tabTnct; /* Ephemeral table used for DISTINCT processing */
  97796. int addrTnct; /* Address of OP_OpenEphemeral opcode for tabTnct */
  97797. };
  97798. /*
  97799. ** An instance of the following object is used to record information about
  97800. ** the ORDER BY (or GROUP BY) clause of query is being coded.
  97801. */
  97802. typedef struct SortCtx SortCtx;
  97803. struct SortCtx {
  97804. ExprList *pOrderBy; /* The ORDER BY (or GROUP BY clause) */
  97805. int nOBSat; /* Number of ORDER BY terms satisfied by indices */
  97806. int iECursor; /* Cursor number for the sorter */
  97807. int regReturn; /* Register holding block-output return address */
  97808. int labelBkOut; /* Start label for the block-output subroutine */
  97809. int addrSortIndex; /* Address of the OP_SorterOpen or OP_OpenEphemeral */
  97810. u8 sortFlags; /* Zero or more SORTFLAG_* bits */
  97811. };
  97812. #define SORTFLAG_UseSorter 0x01 /* Use SorterOpen instead of OpenEphemeral */
  97813. /*
  97814. ** Delete all the content of a Select structure but do not deallocate
  97815. ** the select structure itself.
  97816. */
  97817. static void clearSelect(sqlite3 *db, Select *p){
  97818. sqlite3ExprListDelete(db, p->pEList);
  97819. sqlite3SrcListDelete(db, p->pSrc);
  97820. sqlite3ExprDelete(db, p->pWhere);
  97821. sqlite3ExprListDelete(db, p->pGroupBy);
  97822. sqlite3ExprDelete(db, p->pHaving);
  97823. sqlite3ExprListDelete(db, p->pOrderBy);
  97824. sqlite3SelectDelete(db, p->pPrior);
  97825. sqlite3ExprDelete(db, p->pLimit);
  97826. sqlite3ExprDelete(db, p->pOffset);
  97827. sqlite3WithDelete(db, p->pWith);
  97828. }
  97829. /*
  97830. ** Initialize a SelectDest structure.
  97831. */
  97832. SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest *pDest, int eDest, int iParm){
  97833. pDest->eDest = (u8)eDest;
  97834. pDest->iSDParm = iParm;
  97835. pDest->affSdst = 0;
  97836. pDest->iSdst = 0;
  97837. pDest->nSdst = 0;
  97838. }
  97839. /*
  97840. ** Allocate a new Select structure and return a pointer to that
  97841. ** structure.
  97842. */
  97843. SQLITE_PRIVATE Select *sqlite3SelectNew(
  97844. Parse *pParse, /* Parsing context */
  97845. ExprList *pEList, /* which columns to include in the result */
  97846. SrcList *pSrc, /* the FROM clause -- which tables to scan */
  97847. Expr *pWhere, /* the WHERE clause */
  97848. ExprList *pGroupBy, /* the GROUP BY clause */
  97849. Expr *pHaving, /* the HAVING clause */
  97850. ExprList *pOrderBy, /* the ORDER BY clause */
  97851. u16 selFlags, /* Flag parameters, such as SF_Distinct */
  97852. Expr *pLimit, /* LIMIT value. NULL means not used */
  97853. Expr *pOffset /* OFFSET value. NULL means no offset */
  97854. ){
  97855. Select *pNew;
  97856. Select standin;
  97857. sqlite3 *db = pParse->db;
  97858. pNew = sqlite3DbMallocZero(db, sizeof(*pNew) );
  97859. assert( db->mallocFailed || !pOffset || pLimit ); /* OFFSET implies LIMIT */
  97860. if( pNew==0 ){
  97861. assert( db->mallocFailed );
  97862. pNew = &standin;
  97863. memset(pNew, 0, sizeof(*pNew));
  97864. }
  97865. if( pEList==0 ){
  97866. pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db,TK_ALL,0));
  97867. }
  97868. pNew->pEList = pEList;
  97869. if( pSrc==0 ) pSrc = sqlite3DbMallocZero(db, sizeof(*pSrc));
  97870. pNew->pSrc = pSrc;
  97871. pNew->pWhere = pWhere;
  97872. pNew->pGroupBy = pGroupBy;
  97873. pNew->pHaving = pHaving;
  97874. pNew->pOrderBy = pOrderBy;
  97875. pNew->selFlags = selFlags;
  97876. pNew->op = TK_SELECT;
  97877. pNew->pLimit = pLimit;
  97878. pNew->pOffset = pOffset;
  97879. assert( pOffset==0 || pLimit!=0 );
  97880. pNew->addrOpenEphm[0] = -1;
  97881. pNew->addrOpenEphm[1] = -1;
  97882. if( db->mallocFailed ) {
  97883. clearSelect(db, pNew);
  97884. if( pNew!=&standin ) sqlite3DbFree(db, pNew);
  97885. pNew = 0;
  97886. }else{
  97887. assert( pNew->pSrc!=0 || pParse->nErr>0 );
  97888. }
  97889. assert( pNew!=&standin );
  97890. return pNew;
  97891. }
  97892. #if SELECTTRACE_ENABLED
  97893. /*
  97894. ** Set the name of a Select object
  97895. */
  97896. SQLITE_PRIVATE void sqlite3SelectSetName(Select *p, const char *zName){
  97897. if( p && zName ){
  97898. sqlite3_snprintf(sizeof(p->zSelName), p->zSelName, "%s", zName);
  97899. }
  97900. }
  97901. #endif
  97902. /*
  97903. ** Delete the given Select structure and all of its substructures.
  97904. */
  97905. SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3 *db, Select *p){
  97906. if( p ){
  97907. clearSelect(db, p);
  97908. sqlite3DbFree(db, p);
  97909. }
  97910. }
  97911. /*
  97912. ** Return a pointer to the right-most SELECT statement in a compound.
  97913. */
  97914. static Select *findRightmost(Select *p){
  97915. while( p->pNext ) p = p->pNext;
  97916. return p;
  97917. }
  97918. /*
  97919. ** Given 1 to 3 identifiers preceding the JOIN keyword, determine the
  97920. ** type of join. Return an integer constant that expresses that type
  97921. ** in terms of the following bit values:
  97922. **
  97923. ** JT_INNER
  97924. ** JT_CROSS
  97925. ** JT_OUTER
  97926. ** JT_NATURAL
  97927. ** JT_LEFT
  97928. ** JT_RIGHT
  97929. **
  97930. ** A full outer join is the combination of JT_LEFT and JT_RIGHT.
  97931. **
  97932. ** If an illegal or unsupported join type is seen, then still return
  97933. ** a join type, but put an error in the pParse structure.
  97934. */
  97935. SQLITE_PRIVATE int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){
  97936. int jointype = 0;
  97937. Token *apAll[3];
  97938. Token *p;
  97939. /* 0123456789 123456789 123456789 123 */
  97940. static const char zKeyText[] = "naturaleftouterightfullinnercross";
  97941. static const struct {
  97942. u8 i; /* Beginning of keyword text in zKeyText[] */
  97943. u8 nChar; /* Length of the keyword in characters */
  97944. u8 code; /* Join type mask */
  97945. } aKeyword[] = {
  97946. /* natural */ { 0, 7, JT_NATURAL },
  97947. /* left */ { 6, 4, JT_LEFT|JT_OUTER },
  97948. /* outer */ { 10, 5, JT_OUTER },
  97949. /* right */ { 14, 5, JT_RIGHT|JT_OUTER },
  97950. /* full */ { 19, 4, JT_LEFT|JT_RIGHT|JT_OUTER },
  97951. /* inner */ { 23, 5, JT_INNER },
  97952. /* cross */ { 28, 5, JT_INNER|JT_CROSS },
  97953. };
  97954. int i, j;
  97955. apAll[0] = pA;
  97956. apAll[1] = pB;
  97957. apAll[2] = pC;
  97958. for(i=0; i<3 && apAll[i]; i++){
  97959. p = apAll[i];
  97960. for(j=0; j<ArraySize(aKeyword); j++){
  97961. if( p->n==aKeyword[j].nChar
  97962. && sqlite3StrNICmp((char*)p->z, &zKeyText[aKeyword[j].i], p->n)==0 ){
  97963. jointype |= aKeyword[j].code;
  97964. break;
  97965. }
  97966. }
  97967. testcase( j==0 || j==1 || j==2 || j==3 || j==4 || j==5 || j==6 );
  97968. if( j>=ArraySize(aKeyword) ){
  97969. jointype |= JT_ERROR;
  97970. break;
  97971. }
  97972. }
  97973. if(
  97974. (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) ||
  97975. (jointype & JT_ERROR)!=0
  97976. ){
  97977. const char *zSp = " ";
  97978. assert( pB!=0 );
  97979. if( pC==0 ){ zSp++; }
  97980. sqlite3ErrorMsg(pParse, "unknown or unsupported join type: "
  97981. "%T %T%s%T", pA, pB, zSp, pC);
  97982. jointype = JT_INNER;
  97983. }else if( (jointype & JT_OUTER)!=0
  97984. && (jointype & (JT_LEFT|JT_RIGHT))!=JT_LEFT ){
  97985. sqlite3ErrorMsg(pParse,
  97986. "RIGHT and FULL OUTER JOINs are not currently supported");
  97987. jointype = JT_INNER;
  97988. }
  97989. return jointype;
  97990. }
  97991. /*
  97992. ** Return the index of a column in a table. Return -1 if the column
  97993. ** is not contained in the table.
  97994. */
  97995. static int columnIndex(Table *pTab, const char *zCol){
  97996. int i;
  97997. for(i=0; i<pTab->nCol; i++){
  97998. if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i;
  97999. }
  98000. return -1;
  98001. }
  98002. /*
  98003. ** Search the first N tables in pSrc, from left to right, looking for a
  98004. ** table that has a column named zCol.
  98005. **
  98006. ** When found, set *piTab and *piCol to the table index and column index
  98007. ** of the matching column and return TRUE.
  98008. **
  98009. ** If not found, return FALSE.
  98010. */
  98011. static int tableAndColumnIndex(
  98012. SrcList *pSrc, /* Array of tables to search */
  98013. int N, /* Number of tables in pSrc->a[] to search */
  98014. const char *zCol, /* Name of the column we are looking for */
  98015. int *piTab, /* Write index of pSrc->a[] here */
  98016. int *piCol /* Write index of pSrc->a[*piTab].pTab->aCol[] here */
  98017. ){
  98018. int i; /* For looping over tables in pSrc */
  98019. int iCol; /* Index of column matching zCol */
  98020. assert( (piTab==0)==(piCol==0) ); /* Both or neither are NULL */
  98021. for(i=0; i<N; i++){
  98022. iCol = columnIndex(pSrc->a[i].pTab, zCol);
  98023. if( iCol>=0 ){
  98024. if( piTab ){
  98025. *piTab = i;
  98026. *piCol = iCol;
  98027. }
  98028. return 1;
  98029. }
  98030. }
  98031. return 0;
  98032. }
  98033. /*
  98034. ** This function is used to add terms implied by JOIN syntax to the
  98035. ** WHERE clause expression of a SELECT statement. The new term, which
  98036. ** is ANDed with the existing WHERE clause, is of the form:
  98037. **
  98038. ** (tab1.col1 = tab2.col2)
  98039. **
  98040. ** where tab1 is the iSrc'th table in SrcList pSrc and tab2 is the
  98041. ** (iSrc+1)'th. Column col1 is column iColLeft of tab1, and col2 is
  98042. ** column iColRight of tab2.
  98043. */
  98044. static void addWhereTerm(
  98045. Parse *pParse, /* Parsing context */
  98046. SrcList *pSrc, /* List of tables in FROM clause */
  98047. int iLeft, /* Index of first table to join in pSrc */
  98048. int iColLeft, /* Index of column in first table */
  98049. int iRight, /* Index of second table in pSrc */
  98050. int iColRight, /* Index of column in second table */
  98051. int isOuterJoin, /* True if this is an OUTER join */
  98052. Expr **ppWhere /* IN/OUT: The WHERE clause to add to */
  98053. ){
  98054. sqlite3 *db = pParse->db;
  98055. Expr *pE1;
  98056. Expr *pE2;
  98057. Expr *pEq;
  98058. assert( iLeft<iRight );
  98059. assert( pSrc->nSrc>iRight );
  98060. assert( pSrc->a[iLeft].pTab );
  98061. assert( pSrc->a[iRight].pTab );
  98062. pE1 = sqlite3CreateColumnExpr(db, pSrc, iLeft, iColLeft);
  98063. pE2 = sqlite3CreateColumnExpr(db, pSrc, iRight, iColRight);
  98064. pEq = sqlite3PExpr(pParse, TK_EQ, pE1, pE2, 0);
  98065. if( pEq && isOuterJoin ){
  98066. ExprSetProperty(pEq, EP_FromJoin);
  98067. assert( !ExprHasProperty(pEq, EP_TokenOnly|EP_Reduced) );
  98068. ExprSetVVAProperty(pEq, EP_NoReduce);
  98069. pEq->iRightJoinTable = (i16)pE2->iTable;
  98070. }
  98071. *ppWhere = sqlite3ExprAnd(db, *ppWhere, pEq);
  98072. }
  98073. /*
  98074. ** Set the EP_FromJoin property on all terms of the given expression.
  98075. ** And set the Expr.iRightJoinTable to iTable for every term in the
  98076. ** expression.
  98077. **
  98078. ** The EP_FromJoin property is used on terms of an expression to tell
  98079. ** the LEFT OUTER JOIN processing logic that this term is part of the
  98080. ** join restriction specified in the ON or USING clause and not a part
  98081. ** of the more general WHERE clause. These terms are moved over to the
  98082. ** WHERE clause during join processing but we need to remember that they
  98083. ** originated in the ON or USING clause.
  98084. **
  98085. ** The Expr.iRightJoinTable tells the WHERE clause processing that the
  98086. ** expression depends on table iRightJoinTable even if that table is not
  98087. ** explicitly mentioned in the expression. That information is needed
  98088. ** for cases like this:
  98089. **
  98090. ** SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5
  98091. **
  98092. ** The where clause needs to defer the handling of the t1.x=5
  98093. ** term until after the t2 loop of the join. In that way, a
  98094. ** NULL t2 row will be inserted whenever t1.x!=5. If we do not
  98095. ** defer the handling of t1.x=5, it will be processed immediately
  98096. ** after the t1 loop and rows with t1.x!=5 will never appear in
  98097. ** the output, which is incorrect.
  98098. */
  98099. static void setJoinExpr(Expr *p, int iTable){
  98100. while( p ){
  98101. ExprSetProperty(p, EP_FromJoin);
  98102. assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) );
  98103. ExprSetVVAProperty(p, EP_NoReduce);
  98104. p->iRightJoinTable = (i16)iTable;
  98105. setJoinExpr(p->pLeft, iTable);
  98106. p = p->pRight;
  98107. }
  98108. }
  98109. /*
  98110. ** This routine processes the join information for a SELECT statement.
  98111. ** ON and USING clauses are converted into extra terms of the WHERE clause.
  98112. ** NATURAL joins also create extra WHERE clause terms.
  98113. **
  98114. ** The terms of a FROM clause are contained in the Select.pSrc structure.
  98115. ** The left most table is the first entry in Select.pSrc. The right-most
  98116. ** table is the last entry. The join operator is held in the entry to
  98117. ** the left. Thus entry 0 contains the join operator for the join between
  98118. ** entries 0 and 1. Any ON or USING clauses associated with the join are
  98119. ** also attached to the left entry.
  98120. **
  98121. ** This routine returns the number of errors encountered.
  98122. */
  98123. static int sqliteProcessJoin(Parse *pParse, Select *p){
  98124. SrcList *pSrc; /* All tables in the FROM clause */
  98125. int i, j; /* Loop counters */
  98126. struct SrcList_item *pLeft; /* Left table being joined */
  98127. struct SrcList_item *pRight; /* Right table being joined */
  98128. pSrc = p->pSrc;
  98129. pLeft = &pSrc->a[0];
  98130. pRight = &pLeft[1];
  98131. for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){
  98132. Table *pLeftTab = pLeft->pTab;
  98133. Table *pRightTab = pRight->pTab;
  98134. int isOuter;
  98135. if( NEVER(pLeftTab==0 || pRightTab==0) ) continue;
  98136. isOuter = (pRight->jointype & JT_OUTER)!=0;
  98137. /* When the NATURAL keyword is present, add WHERE clause terms for
  98138. ** every column that the two tables have in common.
  98139. */
  98140. if( pRight->jointype & JT_NATURAL ){
  98141. if( pRight->pOn || pRight->pUsing ){
  98142. sqlite3ErrorMsg(pParse, "a NATURAL join may not have "
  98143. "an ON or USING clause", 0);
  98144. return 1;
  98145. }
  98146. for(j=0; j<pRightTab->nCol; j++){
  98147. char *zName; /* Name of column in the right table */
  98148. int iLeft; /* Matching left table */
  98149. int iLeftCol; /* Matching column in the left table */
  98150. zName = pRightTab->aCol[j].zName;
  98151. if( tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol) ){
  98152. addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, j,
  98153. isOuter, &p->pWhere);
  98154. }
  98155. }
  98156. }
  98157. /* Disallow both ON and USING clauses in the same join
  98158. */
  98159. if( pRight->pOn && pRight->pUsing ){
  98160. sqlite3ErrorMsg(pParse, "cannot have both ON and USING "
  98161. "clauses in the same join");
  98162. return 1;
  98163. }
  98164. /* Add the ON clause to the end of the WHERE clause, connected by
  98165. ** an AND operator.
  98166. */
  98167. if( pRight->pOn ){
  98168. if( isOuter ) setJoinExpr(pRight->pOn, pRight->iCursor);
  98169. p->pWhere = sqlite3ExprAnd(pParse->db, p->pWhere, pRight->pOn);
  98170. pRight->pOn = 0;
  98171. }
  98172. /* Create extra terms on the WHERE clause for each column named
  98173. ** in the USING clause. Example: If the two tables to be joined are
  98174. ** A and B and the USING clause names X, Y, and Z, then add this
  98175. ** to the WHERE clause: A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
  98176. ** Report an error if any column mentioned in the USING clause is
  98177. ** not contained in both tables to be joined.
  98178. */
  98179. if( pRight->pUsing ){
  98180. IdList *pList = pRight->pUsing;
  98181. for(j=0; j<pList->nId; j++){
  98182. char *zName; /* Name of the term in the USING clause */
  98183. int iLeft; /* Table on the left with matching column name */
  98184. int iLeftCol; /* Column number of matching column on the left */
  98185. int iRightCol; /* Column number of matching column on the right */
  98186. zName = pList->a[j].zName;
  98187. iRightCol = columnIndex(pRightTab, zName);
  98188. if( iRightCol<0
  98189. || !tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol)
  98190. ){
  98191. sqlite3ErrorMsg(pParse, "cannot join using column %s - column "
  98192. "not present in both tables", zName);
  98193. return 1;
  98194. }
  98195. addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, iRightCol,
  98196. isOuter, &p->pWhere);
  98197. }
  98198. }
  98199. }
  98200. return 0;
  98201. }
  98202. /* Forward reference */
  98203. static KeyInfo *keyInfoFromExprList(
  98204. Parse *pParse, /* Parsing context */
  98205. ExprList *pList, /* Form the KeyInfo object from this ExprList */
  98206. int iStart, /* Begin with this column of pList */
  98207. int nExtra /* Add this many extra columns to the end */
  98208. );
  98209. /*
  98210. ** Generate code that will push the record in registers regData
  98211. ** through regData+nData-1 onto the sorter.
  98212. */
  98213. static void pushOntoSorter(
  98214. Parse *pParse, /* Parser context */
  98215. SortCtx *pSort, /* Information about the ORDER BY clause */
  98216. Select *pSelect, /* The whole SELECT statement */
  98217. int regData, /* First register holding data to be sorted */
  98218. int nData, /* Number of elements in the data array */
  98219. int nPrefixReg /* No. of reg prior to regData available for use */
  98220. ){
  98221. Vdbe *v = pParse->pVdbe; /* Stmt under construction */
  98222. int bSeq = ((pSort->sortFlags & SORTFLAG_UseSorter)==0);
  98223. int nExpr = pSort->pOrderBy->nExpr; /* No. of ORDER BY terms */
  98224. int nBase = nExpr + bSeq + nData; /* Fields in sorter record */
  98225. int regBase; /* Regs for sorter record */
  98226. int regRecord = ++pParse->nMem; /* Assembled sorter record */
  98227. int nOBSat = pSort->nOBSat; /* ORDER BY terms to skip */
  98228. int op; /* Opcode to add sorter record to sorter */
  98229. assert( bSeq==0 || bSeq==1 );
  98230. if( nPrefixReg ){
  98231. assert( nPrefixReg==nExpr+bSeq );
  98232. regBase = regData - nExpr - bSeq;
  98233. }else{
  98234. regBase = pParse->nMem + 1;
  98235. pParse->nMem += nBase;
  98236. }
  98237. sqlite3ExprCodeExprList(pParse, pSort->pOrderBy, regBase, SQLITE_ECEL_DUP);
  98238. if( bSeq ){
  98239. sqlite3VdbeAddOp2(v, OP_Sequence, pSort->iECursor, regBase+nExpr);
  98240. }
  98241. if( nPrefixReg==0 ){
  98242. sqlite3ExprCodeMove(pParse, regData, regBase+nExpr+bSeq, nData);
  98243. }
  98244. sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase+nOBSat, nBase-nOBSat, regRecord);
  98245. if( nOBSat>0 ){
  98246. int regPrevKey; /* The first nOBSat columns of the previous row */
  98247. int addrFirst; /* Address of the OP_IfNot opcode */
  98248. int addrJmp; /* Address of the OP_Jump opcode */
  98249. VdbeOp *pOp; /* Opcode that opens the sorter */
  98250. int nKey; /* Number of sorting key columns, including OP_Sequence */
  98251. KeyInfo *pKI; /* Original KeyInfo on the sorter table */
  98252. regPrevKey = pParse->nMem+1;
  98253. pParse->nMem += pSort->nOBSat;
  98254. nKey = nExpr - pSort->nOBSat + bSeq;
  98255. if( bSeq ){
  98256. addrFirst = sqlite3VdbeAddOp1(v, OP_IfNot, regBase+nExpr);
  98257. }else{
  98258. addrFirst = sqlite3VdbeAddOp1(v, OP_SequenceTest, pSort->iECursor);
  98259. }
  98260. VdbeCoverage(v);
  98261. sqlite3VdbeAddOp3(v, OP_Compare, regPrevKey, regBase, pSort->nOBSat);
  98262. pOp = sqlite3VdbeGetOp(v, pSort->addrSortIndex);
  98263. if( pParse->db->mallocFailed ) return;
  98264. pOp->p2 = nKey + nData;
  98265. pKI = pOp->p4.pKeyInfo;
  98266. memset(pKI->aSortOrder, 0, pKI->nField); /* Makes OP_Jump below testable */
  98267. sqlite3VdbeChangeP4(v, -1, (char*)pKI, P4_KEYINFO);
  98268. pOp->p4.pKeyInfo = keyInfoFromExprList(pParse, pSort->pOrderBy, nOBSat, 1);
  98269. addrJmp = sqlite3VdbeCurrentAddr(v);
  98270. sqlite3VdbeAddOp3(v, OP_Jump, addrJmp+1, 0, addrJmp+1); VdbeCoverage(v);
  98271. pSort->labelBkOut = sqlite3VdbeMakeLabel(v);
  98272. pSort->regReturn = ++pParse->nMem;
  98273. sqlite3VdbeAddOp2(v, OP_Gosub, pSort->regReturn, pSort->labelBkOut);
  98274. sqlite3VdbeAddOp1(v, OP_ResetSorter, pSort->iECursor);
  98275. sqlite3VdbeJumpHere(v, addrFirst);
  98276. sqlite3ExprCodeMove(pParse, regBase, regPrevKey, pSort->nOBSat);
  98277. sqlite3VdbeJumpHere(v, addrJmp);
  98278. }
  98279. if( pSort->sortFlags & SORTFLAG_UseSorter ){
  98280. op = OP_SorterInsert;
  98281. }else{
  98282. op = OP_IdxInsert;
  98283. }
  98284. sqlite3VdbeAddOp2(v, op, pSort->iECursor, regRecord);
  98285. if( pSelect->iLimit ){
  98286. int addr1, addr2;
  98287. int iLimit;
  98288. if( pSelect->iOffset ){
  98289. iLimit = pSelect->iOffset+1;
  98290. }else{
  98291. iLimit = pSelect->iLimit;
  98292. }
  98293. addr1 = sqlite3VdbeAddOp1(v, OP_IfZero, iLimit); VdbeCoverage(v);
  98294. sqlite3VdbeAddOp2(v, OP_AddImm, iLimit, -1);
  98295. addr2 = sqlite3VdbeAddOp0(v, OP_Goto);
  98296. sqlite3VdbeJumpHere(v, addr1);
  98297. sqlite3VdbeAddOp1(v, OP_Last, pSort->iECursor);
  98298. sqlite3VdbeAddOp1(v, OP_Delete, pSort->iECursor);
  98299. sqlite3VdbeJumpHere(v, addr2);
  98300. }
  98301. }
  98302. /*
  98303. ** Add code to implement the OFFSET
  98304. */
  98305. static void codeOffset(
  98306. Vdbe *v, /* Generate code into this VM */
  98307. int iOffset, /* Register holding the offset counter */
  98308. int iContinue /* Jump here to skip the current record */
  98309. ){
  98310. if( iOffset>0 ){
  98311. int addr;
  98312. addr = sqlite3VdbeAddOp3(v, OP_IfNeg, iOffset, 0, -1); VdbeCoverage(v);
  98313. sqlite3VdbeAddOp2(v, OP_Goto, 0, iContinue);
  98314. VdbeComment((v, "skip OFFSET records"));
  98315. sqlite3VdbeJumpHere(v, addr);
  98316. }
  98317. }
  98318. /*
  98319. ** Add code that will check to make sure the N registers starting at iMem
  98320. ** form a distinct entry. iTab is a sorting index that holds previously
  98321. ** seen combinations of the N values. A new entry is made in iTab
  98322. ** if the current N values are new.
  98323. **
  98324. ** A jump to addrRepeat is made and the N+1 values are popped from the
  98325. ** stack if the top N elements are not distinct.
  98326. */
  98327. static void codeDistinct(
  98328. Parse *pParse, /* Parsing and code generating context */
  98329. int iTab, /* A sorting index used to test for distinctness */
  98330. int addrRepeat, /* Jump to here if not distinct */
  98331. int N, /* Number of elements */
  98332. int iMem /* First element */
  98333. ){
  98334. Vdbe *v;
  98335. int r1;
  98336. v = pParse->pVdbe;
  98337. r1 = sqlite3GetTempReg(pParse);
  98338. sqlite3VdbeAddOp4Int(v, OP_Found, iTab, addrRepeat, iMem, N); VdbeCoverage(v);
  98339. sqlite3VdbeAddOp3(v, OP_MakeRecord, iMem, N, r1);
  98340. sqlite3VdbeAddOp2(v, OP_IdxInsert, iTab, r1);
  98341. sqlite3ReleaseTempReg(pParse, r1);
  98342. }
  98343. #ifndef SQLITE_OMIT_SUBQUERY
  98344. /*
  98345. ** Generate an error message when a SELECT is used within a subexpression
  98346. ** (example: "a IN (SELECT * FROM table)") but it has more than 1 result
  98347. ** column. We do this in a subroutine because the error used to occur
  98348. ** in multiple places. (The error only occurs in one place now, but we
  98349. ** retain the subroutine to minimize code disruption.)
  98350. */
  98351. static int checkForMultiColumnSelectError(
  98352. Parse *pParse, /* Parse context. */
  98353. SelectDest *pDest, /* Destination of SELECT results */
  98354. int nExpr /* Number of result columns returned by SELECT */
  98355. ){
  98356. int eDest = pDest->eDest;
  98357. if( nExpr>1 && (eDest==SRT_Mem || eDest==SRT_Set) ){
  98358. sqlite3ErrorMsg(pParse, "only a single result allowed for "
  98359. "a SELECT that is part of an expression");
  98360. return 1;
  98361. }else{
  98362. return 0;
  98363. }
  98364. }
  98365. #endif
  98366. /*
  98367. ** This routine generates the code for the inside of the inner loop
  98368. ** of a SELECT.
  98369. **
  98370. ** If srcTab is negative, then the pEList expressions
  98371. ** are evaluated in order to get the data for this row. If srcTab is
  98372. ** zero or more, then data is pulled from srcTab and pEList is used only
  98373. ** to get number columns and the datatype for each column.
  98374. */
  98375. static void selectInnerLoop(
  98376. Parse *pParse, /* The parser context */
  98377. Select *p, /* The complete select statement being coded */
  98378. ExprList *pEList, /* List of values being extracted */
  98379. int srcTab, /* Pull data from this table */
  98380. SortCtx *pSort, /* If not NULL, info on how to process ORDER BY */
  98381. DistinctCtx *pDistinct, /* If not NULL, info on how to process DISTINCT */
  98382. SelectDest *pDest, /* How to dispose of the results */
  98383. int iContinue, /* Jump here to continue with next row */
  98384. int iBreak /* Jump here to break out of the inner loop */
  98385. ){
  98386. Vdbe *v = pParse->pVdbe;
  98387. int i;
  98388. int hasDistinct; /* True if the DISTINCT keyword is present */
  98389. int regResult; /* Start of memory holding result set */
  98390. int eDest = pDest->eDest; /* How to dispose of results */
  98391. int iParm = pDest->iSDParm; /* First argument to disposal method */
  98392. int nResultCol; /* Number of result columns */
  98393. int nPrefixReg = 0; /* Number of extra registers before regResult */
  98394. assert( v );
  98395. assert( pEList!=0 );
  98396. hasDistinct = pDistinct ? pDistinct->eTnctType : WHERE_DISTINCT_NOOP;
  98397. if( pSort && pSort->pOrderBy==0 ) pSort = 0;
  98398. if( pSort==0 && !hasDistinct ){
  98399. assert( iContinue!=0 );
  98400. codeOffset(v, p->iOffset, iContinue);
  98401. }
  98402. /* Pull the requested columns.
  98403. */
  98404. nResultCol = pEList->nExpr;
  98405. if( pDest->iSdst==0 ){
  98406. if( pSort ){
  98407. nPrefixReg = pSort->pOrderBy->nExpr;
  98408. if( !(pSort->sortFlags & SORTFLAG_UseSorter) ) nPrefixReg++;
  98409. pParse->nMem += nPrefixReg;
  98410. }
  98411. pDest->iSdst = pParse->nMem+1;
  98412. pParse->nMem += nResultCol;
  98413. }else if( pDest->iSdst+nResultCol > pParse->nMem ){
  98414. /* This is an error condition that can result, for example, when a SELECT
  98415. ** on the right-hand side of an INSERT contains more result columns than
  98416. ** there are columns in the table on the left. The error will be caught
  98417. ** and reported later. But we need to make sure enough memory is allocated
  98418. ** to avoid other spurious errors in the meantime. */
  98419. pParse->nMem += nResultCol;
  98420. }
  98421. pDest->nSdst = nResultCol;
  98422. regResult = pDest->iSdst;
  98423. if( srcTab>=0 ){
  98424. for(i=0; i<nResultCol; i++){
  98425. sqlite3VdbeAddOp3(v, OP_Column, srcTab, i, regResult+i);
  98426. VdbeComment((v, "%s", pEList->a[i].zName));
  98427. }
  98428. }else if( eDest!=SRT_Exists ){
  98429. /* If the destination is an EXISTS(...) expression, the actual
  98430. ** values returned by the SELECT are not required.
  98431. */
  98432. sqlite3ExprCodeExprList(pParse, pEList, regResult,
  98433. (eDest==SRT_Output||eDest==SRT_Coroutine)?SQLITE_ECEL_DUP:0);
  98434. }
  98435. /* If the DISTINCT keyword was present on the SELECT statement
  98436. ** and this row has been seen before, then do not make this row
  98437. ** part of the result.
  98438. */
  98439. if( hasDistinct ){
  98440. switch( pDistinct->eTnctType ){
  98441. case WHERE_DISTINCT_ORDERED: {
  98442. VdbeOp *pOp; /* No longer required OpenEphemeral instr. */
  98443. int iJump; /* Jump destination */
  98444. int regPrev; /* Previous row content */
  98445. /* Allocate space for the previous row */
  98446. regPrev = pParse->nMem+1;
  98447. pParse->nMem += nResultCol;
  98448. /* Change the OP_OpenEphemeral coded earlier to an OP_Null
  98449. ** sets the MEM_Cleared bit on the first register of the
  98450. ** previous value. This will cause the OP_Ne below to always
  98451. ** fail on the first iteration of the loop even if the first
  98452. ** row is all NULLs.
  98453. */
  98454. sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct);
  98455. pOp = sqlite3VdbeGetOp(v, pDistinct->addrTnct);
  98456. pOp->opcode = OP_Null;
  98457. pOp->p1 = 1;
  98458. pOp->p2 = regPrev;
  98459. iJump = sqlite3VdbeCurrentAddr(v) + nResultCol;
  98460. for(i=0; i<nResultCol; i++){
  98461. CollSeq *pColl = sqlite3ExprCollSeq(pParse, pEList->a[i].pExpr);
  98462. if( i<nResultCol-1 ){
  98463. sqlite3VdbeAddOp3(v, OP_Ne, regResult+i, iJump, regPrev+i);
  98464. VdbeCoverage(v);
  98465. }else{
  98466. sqlite3VdbeAddOp3(v, OP_Eq, regResult+i, iContinue, regPrev+i);
  98467. VdbeCoverage(v);
  98468. }
  98469. sqlite3VdbeChangeP4(v, -1, (const char *)pColl, P4_COLLSEQ);
  98470. sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
  98471. }
  98472. assert( sqlite3VdbeCurrentAddr(v)==iJump || pParse->db->mallocFailed );
  98473. sqlite3VdbeAddOp3(v, OP_Copy, regResult, regPrev, nResultCol-1);
  98474. break;
  98475. }
  98476. case WHERE_DISTINCT_UNIQUE: {
  98477. sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct);
  98478. break;
  98479. }
  98480. default: {
  98481. assert( pDistinct->eTnctType==WHERE_DISTINCT_UNORDERED );
  98482. codeDistinct(pParse, pDistinct->tabTnct, iContinue, nResultCol, regResult);
  98483. break;
  98484. }
  98485. }
  98486. if( pSort==0 ){
  98487. codeOffset(v, p->iOffset, iContinue);
  98488. }
  98489. }
  98490. switch( eDest ){
  98491. /* In this mode, write each query result to the key of the temporary
  98492. ** table iParm.
  98493. */
  98494. #ifndef SQLITE_OMIT_COMPOUND_SELECT
  98495. case SRT_Union: {
  98496. int r1;
  98497. r1 = sqlite3GetTempReg(pParse);
  98498. sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r1);
  98499. sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
  98500. sqlite3ReleaseTempReg(pParse, r1);
  98501. break;
  98502. }
  98503. /* Construct a record from the query result, but instead of
  98504. ** saving that record, use it as a key to delete elements from
  98505. ** the temporary table iParm.
  98506. */
  98507. case SRT_Except: {
  98508. sqlite3VdbeAddOp3(v, OP_IdxDelete, iParm, regResult, nResultCol);
  98509. break;
  98510. }
  98511. #endif /* SQLITE_OMIT_COMPOUND_SELECT */
  98512. /* Store the result as data using a unique key.
  98513. */
  98514. case SRT_Fifo:
  98515. case SRT_DistFifo:
  98516. case SRT_Table:
  98517. case SRT_EphemTab: {
  98518. int r1 = sqlite3GetTempRange(pParse, nPrefixReg+1);
  98519. testcase( eDest==SRT_Table );
  98520. testcase( eDest==SRT_EphemTab );
  98521. sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r1+nPrefixReg);
  98522. #ifndef SQLITE_OMIT_CTE
  98523. if( eDest==SRT_DistFifo ){
  98524. /* If the destination is DistFifo, then cursor (iParm+1) is open
  98525. ** on an ephemeral index. If the current row is already present
  98526. ** in the index, do not write it to the output. If not, add the
  98527. ** current row to the index and proceed with writing it to the
  98528. ** output table as well. */
  98529. int addr = sqlite3VdbeCurrentAddr(v) + 4;
  98530. sqlite3VdbeAddOp4Int(v, OP_Found, iParm+1, addr, r1, 0); VdbeCoverage(v);
  98531. sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm+1, r1);
  98532. assert( pSort==0 );
  98533. }
  98534. #endif
  98535. if( pSort ){
  98536. pushOntoSorter(pParse, pSort, p, r1+nPrefixReg, 1, nPrefixReg);
  98537. }else{
  98538. int r2 = sqlite3GetTempReg(pParse);
  98539. sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, r2);
  98540. sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, r2);
  98541. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  98542. sqlite3ReleaseTempReg(pParse, r2);
  98543. }
  98544. sqlite3ReleaseTempRange(pParse, r1, nPrefixReg+1);
  98545. break;
  98546. }
  98547. #ifndef SQLITE_OMIT_SUBQUERY
  98548. /* If we are creating a set for an "expr IN (SELECT ...)" construct,
  98549. ** then there should be a single item on the stack. Write this
  98550. ** item into the set table with bogus data.
  98551. */
  98552. case SRT_Set: {
  98553. assert( nResultCol==1 );
  98554. pDest->affSdst =
  98555. sqlite3CompareAffinity(pEList->a[0].pExpr, pDest->affSdst);
  98556. if( pSort ){
  98557. /* At first glance you would think we could optimize out the
  98558. ** ORDER BY in this case since the order of entries in the set
  98559. ** does not matter. But there might be a LIMIT clause, in which
  98560. ** case the order does matter */
  98561. pushOntoSorter(pParse, pSort, p, regResult, 1, nPrefixReg);
  98562. }else{
  98563. int r1 = sqlite3GetTempReg(pParse);
  98564. sqlite3VdbeAddOp4(v, OP_MakeRecord, regResult,1,r1, &pDest->affSdst, 1);
  98565. sqlite3ExprCacheAffinityChange(pParse, regResult, 1);
  98566. sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
  98567. sqlite3ReleaseTempReg(pParse, r1);
  98568. }
  98569. break;
  98570. }
  98571. /* If any row exist in the result set, record that fact and abort.
  98572. */
  98573. case SRT_Exists: {
  98574. sqlite3VdbeAddOp2(v, OP_Integer, 1, iParm);
  98575. /* The LIMIT clause will terminate the loop for us */
  98576. break;
  98577. }
  98578. /* If this is a scalar select that is part of an expression, then
  98579. ** store the results in the appropriate memory cell and break out
  98580. ** of the scan loop.
  98581. */
  98582. case SRT_Mem: {
  98583. assert( nResultCol==1 );
  98584. if( pSort ){
  98585. pushOntoSorter(pParse, pSort, p, regResult, 1, nPrefixReg);
  98586. }else{
  98587. assert( regResult==iParm );
  98588. /* The LIMIT clause will jump out of the loop for us */
  98589. }
  98590. break;
  98591. }
  98592. #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
  98593. case SRT_Coroutine: /* Send data to a co-routine */
  98594. case SRT_Output: { /* Return the results */
  98595. testcase( eDest==SRT_Coroutine );
  98596. testcase( eDest==SRT_Output );
  98597. if( pSort ){
  98598. pushOntoSorter(pParse, pSort, p, regResult, nResultCol, nPrefixReg);
  98599. }else if( eDest==SRT_Coroutine ){
  98600. sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
  98601. }else{
  98602. sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, nResultCol);
  98603. sqlite3ExprCacheAffinityChange(pParse, regResult, nResultCol);
  98604. }
  98605. break;
  98606. }
  98607. #ifndef SQLITE_OMIT_CTE
  98608. /* Write the results into a priority queue that is order according to
  98609. ** pDest->pOrderBy (in pSO). pDest->iSDParm (in iParm) is the cursor for an
  98610. ** index with pSO->nExpr+2 columns. Build a key using pSO for the first
  98611. ** pSO->nExpr columns, then make sure all keys are unique by adding a
  98612. ** final OP_Sequence column. The last column is the record as a blob.
  98613. */
  98614. case SRT_DistQueue:
  98615. case SRT_Queue: {
  98616. int nKey;
  98617. int r1, r2, r3;
  98618. int addrTest = 0;
  98619. ExprList *pSO;
  98620. pSO = pDest->pOrderBy;
  98621. assert( pSO );
  98622. nKey = pSO->nExpr;
  98623. r1 = sqlite3GetTempReg(pParse);
  98624. r2 = sqlite3GetTempRange(pParse, nKey+2);
  98625. r3 = r2+nKey+1;
  98626. if( eDest==SRT_DistQueue ){
  98627. /* If the destination is DistQueue, then cursor (iParm+1) is open
  98628. ** on a second ephemeral index that holds all values every previously
  98629. ** added to the queue. */
  98630. addrTest = sqlite3VdbeAddOp4Int(v, OP_Found, iParm+1, 0,
  98631. regResult, nResultCol);
  98632. VdbeCoverage(v);
  98633. }
  98634. sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r3);
  98635. if( eDest==SRT_DistQueue ){
  98636. sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm+1, r3);
  98637. sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
  98638. }
  98639. for(i=0; i<nKey; i++){
  98640. sqlite3VdbeAddOp2(v, OP_SCopy,
  98641. regResult + pSO->a[i].u.x.iOrderByCol - 1,
  98642. r2+i);
  98643. }
  98644. sqlite3VdbeAddOp2(v, OP_Sequence, iParm, r2+nKey);
  98645. sqlite3VdbeAddOp3(v, OP_MakeRecord, r2, nKey+2, r1);
  98646. sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
  98647. if( addrTest ) sqlite3VdbeJumpHere(v, addrTest);
  98648. sqlite3ReleaseTempReg(pParse, r1);
  98649. sqlite3ReleaseTempRange(pParse, r2, nKey+2);
  98650. break;
  98651. }
  98652. #endif /* SQLITE_OMIT_CTE */
  98653. #if !defined(SQLITE_OMIT_TRIGGER)
  98654. /* Discard the results. This is used for SELECT statements inside
  98655. ** the body of a TRIGGER. The purpose of such selects is to call
  98656. ** user-defined functions that have side effects. We do not care
  98657. ** about the actual results of the select.
  98658. */
  98659. default: {
  98660. assert( eDest==SRT_Discard );
  98661. break;
  98662. }
  98663. #endif
  98664. }
  98665. /* Jump to the end of the loop if the LIMIT is reached. Except, if
  98666. ** there is a sorter, in which case the sorter has already limited
  98667. ** the output for us.
  98668. */
  98669. if( pSort==0 && p->iLimit ){
  98670. sqlite3VdbeAddOp3(v, OP_IfZero, p->iLimit, iBreak, -1); VdbeCoverage(v);
  98671. }
  98672. }
  98673. /*
  98674. ** Allocate a KeyInfo object sufficient for an index of N key columns and
  98675. ** X extra columns.
  98676. */
  98677. SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoAlloc(sqlite3 *db, int N, int X){
  98678. KeyInfo *p = sqlite3DbMallocZero(0,
  98679. sizeof(KeyInfo) + (N+X)*(sizeof(CollSeq*)+1));
  98680. if( p ){
  98681. p->aSortOrder = (u8*)&p->aColl[N+X];
  98682. p->nField = (u16)N;
  98683. p->nXField = (u16)X;
  98684. p->enc = ENC(db);
  98685. p->db = db;
  98686. p->nRef = 1;
  98687. }else{
  98688. db->mallocFailed = 1;
  98689. }
  98690. return p;
  98691. }
  98692. /*
  98693. ** Deallocate a KeyInfo object
  98694. */
  98695. SQLITE_PRIVATE void sqlite3KeyInfoUnref(KeyInfo *p){
  98696. if( p ){
  98697. assert( p->nRef>0 );
  98698. p->nRef--;
  98699. if( p->nRef==0 ) sqlite3DbFree(0, p);
  98700. }
  98701. }
  98702. /*
  98703. ** Make a new pointer to a KeyInfo object
  98704. */
  98705. SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoRef(KeyInfo *p){
  98706. if( p ){
  98707. assert( p->nRef>0 );
  98708. p->nRef++;
  98709. }
  98710. return p;
  98711. }
  98712. #ifdef SQLITE_DEBUG
  98713. /*
  98714. ** Return TRUE if a KeyInfo object can be change. The KeyInfo object
  98715. ** can only be changed if this is just a single reference to the object.
  98716. **
  98717. ** This routine is used only inside of assert() statements.
  98718. */
  98719. SQLITE_PRIVATE int sqlite3KeyInfoIsWriteable(KeyInfo *p){ return p->nRef==1; }
  98720. #endif /* SQLITE_DEBUG */
  98721. /*
  98722. ** Given an expression list, generate a KeyInfo structure that records
  98723. ** the collating sequence for each expression in that expression list.
  98724. **
  98725. ** If the ExprList is an ORDER BY or GROUP BY clause then the resulting
  98726. ** KeyInfo structure is appropriate for initializing a virtual index to
  98727. ** implement that clause. If the ExprList is the result set of a SELECT
  98728. ** then the KeyInfo structure is appropriate for initializing a virtual
  98729. ** index to implement a DISTINCT test.
  98730. **
  98731. ** Space to hold the KeyInfo structure is obtained from malloc. The calling
  98732. ** function is responsible for seeing that this structure is eventually
  98733. ** freed.
  98734. */
  98735. static KeyInfo *keyInfoFromExprList(
  98736. Parse *pParse, /* Parsing context */
  98737. ExprList *pList, /* Form the KeyInfo object from this ExprList */
  98738. int iStart, /* Begin with this column of pList */
  98739. int nExtra /* Add this many extra columns to the end */
  98740. ){
  98741. int nExpr;
  98742. KeyInfo *pInfo;
  98743. struct ExprList_item *pItem;
  98744. sqlite3 *db = pParse->db;
  98745. int i;
  98746. nExpr = pList->nExpr;
  98747. pInfo = sqlite3KeyInfoAlloc(db, nExpr+nExtra-iStart, 1);
  98748. if( pInfo ){
  98749. assert( sqlite3KeyInfoIsWriteable(pInfo) );
  98750. for(i=iStart, pItem=pList->a+iStart; i<nExpr; i++, pItem++){
  98751. CollSeq *pColl;
  98752. pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
  98753. if( !pColl ) pColl = db->pDfltColl;
  98754. pInfo->aColl[i-iStart] = pColl;
  98755. pInfo->aSortOrder[i-iStart] = pItem->sortOrder;
  98756. }
  98757. }
  98758. return pInfo;
  98759. }
  98760. #ifndef SQLITE_OMIT_COMPOUND_SELECT
  98761. /*
  98762. ** Name of the connection operator, used for error messages.
  98763. */
  98764. static const char *selectOpName(int id){
  98765. char *z;
  98766. switch( id ){
  98767. case TK_ALL: z = "UNION ALL"; break;
  98768. case TK_INTERSECT: z = "INTERSECT"; break;
  98769. case TK_EXCEPT: z = "EXCEPT"; break;
  98770. default: z = "UNION"; break;
  98771. }
  98772. return z;
  98773. }
  98774. #endif /* SQLITE_OMIT_COMPOUND_SELECT */
  98775. #ifndef SQLITE_OMIT_EXPLAIN
  98776. /*
  98777. ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
  98778. ** is a no-op. Otherwise, it adds a single row of output to the EQP result,
  98779. ** where the caption is of the form:
  98780. **
  98781. ** "USE TEMP B-TREE FOR xxx"
  98782. **
  98783. ** where xxx is one of "DISTINCT", "ORDER BY" or "GROUP BY". Exactly which
  98784. ** is determined by the zUsage argument.
  98785. */
  98786. static void explainTempTable(Parse *pParse, const char *zUsage){
  98787. if( pParse->explain==2 ){
  98788. Vdbe *v = pParse->pVdbe;
  98789. char *zMsg = sqlite3MPrintf(pParse->db, "USE TEMP B-TREE FOR %s", zUsage);
  98790. sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
  98791. }
  98792. }
  98793. /*
  98794. ** Assign expression b to lvalue a. A second, no-op, version of this macro
  98795. ** is provided when SQLITE_OMIT_EXPLAIN is defined. This allows the code
  98796. ** in sqlite3Select() to assign values to structure member variables that
  98797. ** only exist if SQLITE_OMIT_EXPLAIN is not defined without polluting the
  98798. ** code with #ifndef directives.
  98799. */
  98800. # define explainSetInteger(a, b) a = b
  98801. #else
  98802. /* No-op versions of the explainXXX() functions and macros. */
  98803. # define explainTempTable(y,z)
  98804. # define explainSetInteger(y,z)
  98805. #endif
  98806. #if !defined(SQLITE_OMIT_EXPLAIN) && !defined(SQLITE_OMIT_COMPOUND_SELECT)
  98807. /*
  98808. ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
  98809. ** is a no-op. Otherwise, it adds a single row of output to the EQP result,
  98810. ** where the caption is of one of the two forms:
  98811. **
  98812. ** "COMPOSITE SUBQUERIES iSub1 and iSub2 (op)"
  98813. ** "COMPOSITE SUBQUERIES iSub1 and iSub2 USING TEMP B-TREE (op)"
  98814. **
  98815. ** where iSub1 and iSub2 are the integers passed as the corresponding
  98816. ** function parameters, and op is the text representation of the parameter
  98817. ** of the same name. The parameter "op" must be one of TK_UNION, TK_EXCEPT,
  98818. ** TK_INTERSECT or TK_ALL. The first form is used if argument bUseTmp is
  98819. ** false, or the second form if it is true.
  98820. */
  98821. static void explainComposite(
  98822. Parse *pParse, /* Parse context */
  98823. int op, /* One of TK_UNION, TK_EXCEPT etc. */
  98824. int iSub1, /* Subquery id 1 */
  98825. int iSub2, /* Subquery id 2 */
  98826. int bUseTmp /* True if a temp table was used */
  98827. ){
  98828. assert( op==TK_UNION || op==TK_EXCEPT || op==TK_INTERSECT || op==TK_ALL );
  98829. if( pParse->explain==2 ){
  98830. Vdbe *v = pParse->pVdbe;
  98831. char *zMsg = sqlite3MPrintf(
  98832. pParse->db, "COMPOUND SUBQUERIES %d AND %d %s(%s)", iSub1, iSub2,
  98833. bUseTmp?"USING TEMP B-TREE ":"", selectOpName(op)
  98834. );
  98835. sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
  98836. }
  98837. }
  98838. #else
  98839. /* No-op versions of the explainXXX() functions and macros. */
  98840. # define explainComposite(v,w,x,y,z)
  98841. #endif
  98842. /*
  98843. ** If the inner loop was generated using a non-null pOrderBy argument,
  98844. ** then the results were placed in a sorter. After the loop is terminated
  98845. ** we need to run the sorter and output the results. The following
  98846. ** routine generates the code needed to do that.
  98847. */
  98848. static void generateSortTail(
  98849. Parse *pParse, /* Parsing context */
  98850. Select *p, /* The SELECT statement */
  98851. SortCtx *pSort, /* Information on the ORDER BY clause */
  98852. int nColumn, /* Number of columns of data */
  98853. SelectDest *pDest /* Write the sorted results here */
  98854. ){
  98855. Vdbe *v = pParse->pVdbe; /* The prepared statement */
  98856. int addrBreak = sqlite3VdbeMakeLabel(v); /* Jump here to exit loop */
  98857. int addrContinue = sqlite3VdbeMakeLabel(v); /* Jump here for next cycle */
  98858. int addr;
  98859. int addrOnce = 0;
  98860. int iTab;
  98861. ExprList *pOrderBy = pSort->pOrderBy;
  98862. int eDest = pDest->eDest;
  98863. int iParm = pDest->iSDParm;
  98864. int regRow;
  98865. int regRowid;
  98866. int nKey;
  98867. int iSortTab; /* Sorter cursor to read from */
  98868. int nSortData; /* Trailing values to read from sorter */
  98869. int i;
  98870. int bSeq; /* True if sorter record includes seq. no. */
  98871. #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  98872. struct ExprList_item *aOutEx = p->pEList->a;
  98873. #endif
  98874. if( pSort->labelBkOut ){
  98875. sqlite3VdbeAddOp2(v, OP_Gosub, pSort->regReturn, pSort->labelBkOut);
  98876. sqlite3VdbeAddOp2(v, OP_Goto, 0, addrBreak);
  98877. sqlite3VdbeResolveLabel(v, pSort->labelBkOut);
  98878. }
  98879. iTab = pSort->iECursor;
  98880. if( eDest==SRT_Output || eDest==SRT_Coroutine ){
  98881. regRowid = 0;
  98882. regRow = pDest->iSdst;
  98883. nSortData = nColumn;
  98884. }else{
  98885. regRowid = sqlite3GetTempReg(pParse);
  98886. regRow = sqlite3GetTempReg(pParse);
  98887. nSortData = 1;
  98888. }
  98889. nKey = pOrderBy->nExpr - pSort->nOBSat;
  98890. if( pSort->sortFlags & SORTFLAG_UseSorter ){
  98891. int regSortOut = ++pParse->nMem;
  98892. iSortTab = pParse->nTab++;
  98893. if( pSort->labelBkOut ){
  98894. addrOnce = sqlite3CodeOnce(pParse); VdbeCoverage(v);
  98895. }
  98896. sqlite3VdbeAddOp3(v, OP_OpenPseudo, iSortTab, regSortOut, nKey+1+nSortData);
  98897. if( addrOnce ) sqlite3VdbeJumpHere(v, addrOnce);
  98898. addr = 1 + sqlite3VdbeAddOp2(v, OP_SorterSort, iTab, addrBreak);
  98899. VdbeCoverage(v);
  98900. codeOffset(v, p->iOffset, addrContinue);
  98901. sqlite3VdbeAddOp3(v, OP_SorterData, iTab, regSortOut, iSortTab);
  98902. bSeq = 0;
  98903. }else{
  98904. addr = 1 + sqlite3VdbeAddOp2(v, OP_Sort, iTab, addrBreak); VdbeCoverage(v);
  98905. codeOffset(v, p->iOffset, addrContinue);
  98906. iSortTab = iTab;
  98907. bSeq = 1;
  98908. }
  98909. for(i=0; i<nSortData; i++){
  98910. sqlite3VdbeAddOp3(v, OP_Column, iSortTab, nKey+bSeq+i, regRow+i);
  98911. VdbeComment((v, "%s", aOutEx[i].zName ? aOutEx[i].zName : aOutEx[i].zSpan));
  98912. }
  98913. switch( eDest ){
  98914. case SRT_Table:
  98915. case SRT_EphemTab: {
  98916. testcase( eDest==SRT_Table );
  98917. testcase( eDest==SRT_EphemTab );
  98918. sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, regRowid);
  98919. sqlite3VdbeAddOp3(v, OP_Insert, iParm, regRow, regRowid);
  98920. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  98921. break;
  98922. }
  98923. #ifndef SQLITE_OMIT_SUBQUERY
  98924. case SRT_Set: {
  98925. assert( nColumn==1 );
  98926. sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, 1, regRowid,
  98927. &pDest->affSdst, 1);
  98928. sqlite3ExprCacheAffinityChange(pParse, regRow, 1);
  98929. sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, regRowid);
  98930. break;
  98931. }
  98932. case SRT_Mem: {
  98933. assert( nColumn==1 );
  98934. sqlite3ExprCodeMove(pParse, regRow, iParm, 1);
  98935. /* The LIMIT clause will terminate the loop for us */
  98936. break;
  98937. }
  98938. #endif
  98939. default: {
  98940. assert( eDest==SRT_Output || eDest==SRT_Coroutine );
  98941. testcase( eDest==SRT_Output );
  98942. testcase( eDest==SRT_Coroutine );
  98943. if( eDest==SRT_Output ){
  98944. sqlite3VdbeAddOp2(v, OP_ResultRow, pDest->iSdst, nColumn);
  98945. sqlite3ExprCacheAffinityChange(pParse, pDest->iSdst, nColumn);
  98946. }else{
  98947. sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
  98948. }
  98949. break;
  98950. }
  98951. }
  98952. if( regRowid ){
  98953. sqlite3ReleaseTempReg(pParse, regRow);
  98954. sqlite3ReleaseTempReg(pParse, regRowid);
  98955. }
  98956. /* The bottom of the loop
  98957. */
  98958. sqlite3VdbeResolveLabel(v, addrContinue);
  98959. if( pSort->sortFlags & SORTFLAG_UseSorter ){
  98960. sqlite3VdbeAddOp2(v, OP_SorterNext, iTab, addr); VdbeCoverage(v);
  98961. }else{
  98962. sqlite3VdbeAddOp2(v, OP_Next, iTab, addr); VdbeCoverage(v);
  98963. }
  98964. if( pSort->regReturn ) sqlite3VdbeAddOp1(v, OP_Return, pSort->regReturn);
  98965. sqlite3VdbeResolveLabel(v, addrBreak);
  98966. }
  98967. /*
  98968. ** Return a pointer to a string containing the 'declaration type' of the
  98969. ** expression pExpr. The string may be treated as static by the caller.
  98970. **
  98971. ** Also try to estimate the size of the returned value and return that
  98972. ** result in *pEstWidth.
  98973. **
  98974. ** The declaration type is the exact datatype definition extracted from the
  98975. ** original CREATE TABLE statement if the expression is a column. The
  98976. ** declaration type for a ROWID field is INTEGER. Exactly when an expression
  98977. ** is considered a column can be complex in the presence of subqueries. The
  98978. ** result-set expression in all of the following SELECT statements is
  98979. ** considered a column by this function.
  98980. **
  98981. ** SELECT col FROM tbl;
  98982. ** SELECT (SELECT col FROM tbl;
  98983. ** SELECT (SELECT col FROM tbl);
  98984. ** SELECT abc FROM (SELECT col AS abc FROM tbl);
  98985. **
  98986. ** The declaration type for any expression other than a column is NULL.
  98987. **
  98988. ** This routine has either 3 or 6 parameters depending on whether or not
  98989. ** the SQLITE_ENABLE_COLUMN_METADATA compile-time option is used.
  98990. */
  98991. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  98992. # define columnType(A,B,C,D,E,F) columnTypeImpl(A,B,C,D,E,F)
  98993. static const char *columnTypeImpl(
  98994. NameContext *pNC,
  98995. Expr *pExpr,
  98996. const char **pzOrigDb,
  98997. const char **pzOrigTab,
  98998. const char **pzOrigCol,
  98999. u8 *pEstWidth
  99000. ){
  99001. char const *zOrigDb = 0;
  99002. char const *zOrigTab = 0;
  99003. char const *zOrigCol = 0;
  99004. #else /* if !defined(SQLITE_ENABLE_COLUMN_METADATA) */
  99005. # define columnType(A,B,C,D,E,F) columnTypeImpl(A,B,F)
  99006. static const char *columnTypeImpl(
  99007. NameContext *pNC,
  99008. Expr *pExpr,
  99009. u8 *pEstWidth
  99010. ){
  99011. #endif /* !defined(SQLITE_ENABLE_COLUMN_METADATA) */
  99012. char const *zType = 0;
  99013. int j;
  99014. u8 estWidth = 1;
  99015. if( NEVER(pExpr==0) || pNC->pSrcList==0 ) return 0;
  99016. switch( pExpr->op ){
  99017. case TK_AGG_COLUMN:
  99018. case TK_COLUMN: {
  99019. /* The expression is a column. Locate the table the column is being
  99020. ** extracted from in NameContext.pSrcList. This table may be real
  99021. ** database table or a subquery.
  99022. */
  99023. Table *pTab = 0; /* Table structure column is extracted from */
  99024. Select *pS = 0; /* Select the column is extracted from */
  99025. int iCol = pExpr->iColumn; /* Index of column in pTab */
  99026. testcase( pExpr->op==TK_AGG_COLUMN );
  99027. testcase( pExpr->op==TK_COLUMN );
  99028. while( pNC && !pTab ){
  99029. SrcList *pTabList = pNC->pSrcList;
  99030. for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++);
  99031. if( j<pTabList->nSrc ){
  99032. pTab = pTabList->a[j].pTab;
  99033. pS = pTabList->a[j].pSelect;
  99034. }else{
  99035. pNC = pNC->pNext;
  99036. }
  99037. }
  99038. if( pTab==0 ){
  99039. /* At one time, code such as "SELECT new.x" within a trigger would
  99040. ** cause this condition to run. Since then, we have restructured how
  99041. ** trigger code is generated and so this condition is no longer
  99042. ** possible. However, it can still be true for statements like
  99043. ** the following:
  99044. **
  99045. ** CREATE TABLE t1(col INTEGER);
  99046. ** SELECT (SELECT t1.col) FROM FROM t1;
  99047. **
  99048. ** when columnType() is called on the expression "t1.col" in the
  99049. ** sub-select. In this case, set the column type to NULL, even
  99050. ** though it should really be "INTEGER".
  99051. **
  99052. ** This is not a problem, as the column type of "t1.col" is never
  99053. ** used. When columnType() is called on the expression
  99054. ** "(SELECT t1.col)", the correct type is returned (see the TK_SELECT
  99055. ** branch below. */
  99056. break;
  99057. }
  99058. assert( pTab && pExpr->pTab==pTab );
  99059. if( pS ){
  99060. /* The "table" is actually a sub-select or a view in the FROM clause
  99061. ** of the SELECT statement. Return the declaration type and origin
  99062. ** data for the result-set column of the sub-select.
  99063. */
  99064. if( iCol>=0 && ALWAYS(iCol<pS->pEList->nExpr) ){
  99065. /* If iCol is less than zero, then the expression requests the
  99066. ** rowid of the sub-select or view. This expression is legal (see
  99067. ** test case misc2.2.2) - it always evaluates to NULL.
  99068. */
  99069. NameContext sNC;
  99070. Expr *p = pS->pEList->a[iCol].pExpr;
  99071. sNC.pSrcList = pS->pSrc;
  99072. sNC.pNext = pNC;
  99073. sNC.pParse = pNC->pParse;
  99074. zType = columnType(&sNC, p,&zOrigDb,&zOrigTab,&zOrigCol, &estWidth);
  99075. }
  99076. }else if( pTab->pSchema ){
  99077. /* A real table */
  99078. assert( !pS );
  99079. if( iCol<0 ) iCol = pTab->iPKey;
  99080. assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
  99081. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  99082. if( iCol<0 ){
  99083. zType = "INTEGER";
  99084. zOrigCol = "rowid";
  99085. }else{
  99086. zType = pTab->aCol[iCol].zType;
  99087. zOrigCol = pTab->aCol[iCol].zName;
  99088. estWidth = pTab->aCol[iCol].szEst;
  99089. }
  99090. zOrigTab = pTab->zName;
  99091. if( pNC->pParse ){
  99092. int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema);
  99093. zOrigDb = pNC->pParse->db->aDb[iDb].zName;
  99094. }
  99095. #else
  99096. if( iCol<0 ){
  99097. zType = "INTEGER";
  99098. }else{
  99099. zType = pTab->aCol[iCol].zType;
  99100. estWidth = pTab->aCol[iCol].szEst;
  99101. }
  99102. #endif
  99103. }
  99104. break;
  99105. }
  99106. #ifndef SQLITE_OMIT_SUBQUERY
  99107. case TK_SELECT: {
  99108. /* The expression is a sub-select. Return the declaration type and
  99109. ** origin info for the single column in the result set of the SELECT
  99110. ** statement.
  99111. */
  99112. NameContext sNC;
  99113. Select *pS = pExpr->x.pSelect;
  99114. Expr *p = pS->pEList->a[0].pExpr;
  99115. assert( ExprHasProperty(pExpr, EP_xIsSelect) );
  99116. sNC.pSrcList = pS->pSrc;
  99117. sNC.pNext = pNC;
  99118. sNC.pParse = pNC->pParse;
  99119. zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol, &estWidth);
  99120. break;
  99121. }
  99122. #endif
  99123. }
  99124. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  99125. if( pzOrigDb ){
  99126. assert( pzOrigTab && pzOrigCol );
  99127. *pzOrigDb = zOrigDb;
  99128. *pzOrigTab = zOrigTab;
  99129. *pzOrigCol = zOrigCol;
  99130. }
  99131. #endif
  99132. if( pEstWidth ) *pEstWidth = estWidth;
  99133. return zType;
  99134. }
  99135. /*
  99136. ** Generate code that will tell the VDBE the declaration types of columns
  99137. ** in the result set.
  99138. */
  99139. static void generateColumnTypes(
  99140. Parse *pParse, /* Parser context */
  99141. SrcList *pTabList, /* List of tables */
  99142. ExprList *pEList /* Expressions defining the result set */
  99143. ){
  99144. #ifndef SQLITE_OMIT_DECLTYPE
  99145. Vdbe *v = pParse->pVdbe;
  99146. int i;
  99147. NameContext sNC;
  99148. sNC.pSrcList = pTabList;
  99149. sNC.pParse = pParse;
  99150. for(i=0; i<pEList->nExpr; i++){
  99151. Expr *p = pEList->a[i].pExpr;
  99152. const char *zType;
  99153. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  99154. const char *zOrigDb = 0;
  99155. const char *zOrigTab = 0;
  99156. const char *zOrigCol = 0;
  99157. zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol, 0);
  99158. /* The vdbe must make its own copy of the column-type and other
  99159. ** column specific strings, in case the schema is reset before this
  99160. ** virtual machine is deleted.
  99161. */
  99162. sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, SQLITE_TRANSIENT);
  99163. sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, SQLITE_TRANSIENT);
  99164. sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, SQLITE_TRANSIENT);
  99165. #else
  99166. zType = columnType(&sNC, p, 0, 0, 0, 0);
  99167. #endif
  99168. sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, SQLITE_TRANSIENT);
  99169. }
  99170. #endif /* !defined(SQLITE_OMIT_DECLTYPE) */
  99171. }
  99172. /*
  99173. ** Generate code that will tell the VDBE the names of columns
  99174. ** in the result set. This information is used to provide the
  99175. ** azCol[] values in the callback.
  99176. */
  99177. static void generateColumnNames(
  99178. Parse *pParse, /* Parser context */
  99179. SrcList *pTabList, /* List of tables */
  99180. ExprList *pEList /* Expressions defining the result set */
  99181. ){
  99182. Vdbe *v = pParse->pVdbe;
  99183. int i, j;
  99184. sqlite3 *db = pParse->db;
  99185. int fullNames, shortNames;
  99186. #ifndef SQLITE_OMIT_EXPLAIN
  99187. /* If this is an EXPLAIN, skip this step */
  99188. if( pParse->explain ){
  99189. return;
  99190. }
  99191. #endif
  99192. if( pParse->colNamesSet || NEVER(v==0) || db->mallocFailed ) return;
  99193. pParse->colNamesSet = 1;
  99194. fullNames = (db->flags & SQLITE_FullColNames)!=0;
  99195. shortNames = (db->flags & SQLITE_ShortColNames)!=0;
  99196. sqlite3VdbeSetNumCols(v, pEList->nExpr);
  99197. for(i=0; i<pEList->nExpr; i++){
  99198. Expr *p;
  99199. p = pEList->a[i].pExpr;
  99200. if( NEVER(p==0) ) continue;
  99201. if( pEList->a[i].zName ){
  99202. char *zName = pEList->a[i].zName;
  99203. sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_TRANSIENT);
  99204. }else if( (p->op==TK_COLUMN || p->op==TK_AGG_COLUMN) && pTabList ){
  99205. Table *pTab;
  99206. char *zCol;
  99207. int iCol = p->iColumn;
  99208. for(j=0; ALWAYS(j<pTabList->nSrc); j++){
  99209. if( pTabList->a[j].iCursor==p->iTable ) break;
  99210. }
  99211. assert( j<pTabList->nSrc );
  99212. pTab = pTabList->a[j].pTab;
  99213. if( iCol<0 ) iCol = pTab->iPKey;
  99214. assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
  99215. if( iCol<0 ){
  99216. zCol = "rowid";
  99217. }else{
  99218. zCol = pTab->aCol[iCol].zName;
  99219. }
  99220. if( !shortNames && !fullNames ){
  99221. sqlite3VdbeSetColName(v, i, COLNAME_NAME,
  99222. sqlite3DbStrDup(db, pEList->a[i].zSpan), SQLITE_DYNAMIC);
  99223. }else if( fullNames ){
  99224. char *zName = 0;
  99225. zName = sqlite3MPrintf(db, "%s.%s", pTab->zName, zCol);
  99226. sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_DYNAMIC);
  99227. }else{
  99228. sqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, SQLITE_TRANSIENT);
  99229. }
  99230. }else{
  99231. const char *z = pEList->a[i].zSpan;
  99232. z = z==0 ? sqlite3MPrintf(db, "column%d", i+1) : sqlite3DbStrDup(db, z);
  99233. sqlite3VdbeSetColName(v, i, COLNAME_NAME, z, SQLITE_DYNAMIC);
  99234. }
  99235. }
  99236. generateColumnTypes(pParse, pTabList, pEList);
  99237. }
  99238. /*
  99239. ** Given an expression list (which is really the list of expressions
  99240. ** that form the result set of a SELECT statement) compute appropriate
  99241. ** column names for a table that would hold the expression list.
  99242. **
  99243. ** All column names will be unique.
  99244. **
  99245. ** Only the column names are computed. Column.zType, Column.zColl,
  99246. ** and other fields of Column are zeroed.
  99247. **
  99248. ** Return SQLITE_OK on success. If a memory allocation error occurs,
  99249. ** store NULL in *paCol and 0 in *pnCol and return SQLITE_NOMEM.
  99250. */
  99251. static int selectColumnsFromExprList(
  99252. Parse *pParse, /* Parsing context */
  99253. ExprList *pEList, /* Expr list from which to derive column names */
  99254. i16 *pnCol, /* Write the number of columns here */
  99255. Column **paCol /* Write the new column list here */
  99256. ){
  99257. sqlite3 *db = pParse->db; /* Database connection */
  99258. int i, j; /* Loop counters */
  99259. int cnt; /* Index added to make the name unique */
  99260. Column *aCol, *pCol; /* For looping over result columns */
  99261. int nCol; /* Number of columns in the result set */
  99262. Expr *p; /* Expression for a single result column */
  99263. char *zName; /* Column name */
  99264. int nName; /* Size of name in zName[] */
  99265. if( pEList ){
  99266. nCol = pEList->nExpr;
  99267. aCol = sqlite3DbMallocZero(db, sizeof(aCol[0])*nCol);
  99268. testcase( aCol==0 );
  99269. }else{
  99270. nCol = 0;
  99271. aCol = 0;
  99272. }
  99273. *pnCol = nCol;
  99274. *paCol = aCol;
  99275. for(i=0, pCol=aCol; i<nCol; i++, pCol++){
  99276. /* Get an appropriate name for the column
  99277. */
  99278. p = sqlite3ExprSkipCollate(pEList->a[i].pExpr);
  99279. if( (zName = pEList->a[i].zName)!=0 ){
  99280. /* If the column contains an "AS <name>" phrase, use <name> as the name */
  99281. zName = sqlite3DbStrDup(db, zName);
  99282. }else{
  99283. Expr *pColExpr = p; /* The expression that is the result column name */
  99284. Table *pTab; /* Table associated with this expression */
  99285. while( pColExpr->op==TK_DOT ){
  99286. pColExpr = pColExpr->pRight;
  99287. assert( pColExpr!=0 );
  99288. }
  99289. if( pColExpr->op==TK_COLUMN && ALWAYS(pColExpr->pTab!=0) ){
  99290. /* For columns use the column name name */
  99291. int iCol = pColExpr->iColumn;
  99292. pTab = pColExpr->pTab;
  99293. if( iCol<0 ) iCol = pTab->iPKey;
  99294. zName = sqlite3MPrintf(db, "%s",
  99295. iCol>=0 ? pTab->aCol[iCol].zName : "rowid");
  99296. }else if( pColExpr->op==TK_ID ){
  99297. assert( !ExprHasProperty(pColExpr, EP_IntValue) );
  99298. zName = sqlite3MPrintf(db, "%s", pColExpr->u.zToken);
  99299. }else{
  99300. /* Use the original text of the column expression as its name */
  99301. zName = sqlite3MPrintf(db, "%s", pEList->a[i].zSpan);
  99302. }
  99303. }
  99304. if( db->mallocFailed ){
  99305. sqlite3DbFree(db, zName);
  99306. break;
  99307. }
  99308. /* Make sure the column name is unique. If the name is not unique,
  99309. ** append an integer to the name so that it becomes unique.
  99310. */
  99311. nName = sqlite3Strlen30(zName);
  99312. for(j=cnt=0; j<i; j++){
  99313. if( sqlite3StrICmp(aCol[j].zName, zName)==0 ){
  99314. char *zNewName;
  99315. int k;
  99316. for(k=nName-1; k>1 && sqlite3Isdigit(zName[k]); k--){}
  99317. if( k>=0 && zName[k]==':' ) nName = k;
  99318. zName[nName] = 0;
  99319. zNewName = sqlite3MPrintf(db, "%s:%d", zName, ++cnt);
  99320. sqlite3DbFree(db, zName);
  99321. zName = zNewName;
  99322. j = -1;
  99323. if( zName==0 ) break;
  99324. }
  99325. }
  99326. pCol->zName = zName;
  99327. }
  99328. if( db->mallocFailed ){
  99329. for(j=0; j<i; j++){
  99330. sqlite3DbFree(db, aCol[j].zName);
  99331. }
  99332. sqlite3DbFree(db, aCol);
  99333. *paCol = 0;
  99334. *pnCol = 0;
  99335. return SQLITE_NOMEM;
  99336. }
  99337. return SQLITE_OK;
  99338. }
  99339. /*
  99340. ** Add type and collation information to a column list based on
  99341. ** a SELECT statement.
  99342. **
  99343. ** The column list presumably came from selectColumnNamesFromExprList().
  99344. ** The column list has only names, not types or collations. This
  99345. ** routine goes through and adds the types and collations.
  99346. **
  99347. ** This routine requires that all identifiers in the SELECT
  99348. ** statement be resolved.
  99349. */
  99350. static void selectAddColumnTypeAndCollation(
  99351. Parse *pParse, /* Parsing contexts */
  99352. Table *pTab, /* Add column type information to this table */
  99353. Select *pSelect /* SELECT used to determine types and collations */
  99354. ){
  99355. sqlite3 *db = pParse->db;
  99356. NameContext sNC;
  99357. Column *pCol;
  99358. CollSeq *pColl;
  99359. int i;
  99360. Expr *p;
  99361. struct ExprList_item *a;
  99362. u64 szAll = 0;
  99363. assert( pSelect!=0 );
  99364. assert( (pSelect->selFlags & SF_Resolved)!=0 );
  99365. assert( pTab->nCol==pSelect->pEList->nExpr || db->mallocFailed );
  99366. if( db->mallocFailed ) return;
  99367. memset(&sNC, 0, sizeof(sNC));
  99368. sNC.pSrcList = pSelect->pSrc;
  99369. a = pSelect->pEList->a;
  99370. for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
  99371. p = a[i].pExpr;
  99372. pCol->zType = sqlite3DbStrDup(db, columnType(&sNC, p,0,0,0, &pCol->szEst));
  99373. szAll += pCol->szEst;
  99374. pCol->affinity = sqlite3ExprAffinity(p);
  99375. if( pCol->affinity==0 ) pCol->affinity = SQLITE_AFF_NONE;
  99376. pColl = sqlite3ExprCollSeq(pParse, p);
  99377. if( pColl ){
  99378. pCol->zColl = sqlite3DbStrDup(db, pColl->zName);
  99379. }
  99380. }
  99381. pTab->szTabRow = sqlite3LogEst(szAll*4);
  99382. }
  99383. /*
  99384. ** Given a SELECT statement, generate a Table structure that describes
  99385. ** the result set of that SELECT.
  99386. */
  99387. SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse *pParse, Select *pSelect){
  99388. Table *pTab;
  99389. sqlite3 *db = pParse->db;
  99390. int savedFlags;
  99391. savedFlags = db->flags;
  99392. db->flags &= ~SQLITE_FullColNames;
  99393. db->flags |= SQLITE_ShortColNames;
  99394. sqlite3SelectPrep(pParse, pSelect, 0);
  99395. if( pParse->nErr ) return 0;
  99396. while( pSelect->pPrior ) pSelect = pSelect->pPrior;
  99397. db->flags = savedFlags;
  99398. pTab = sqlite3DbMallocZero(db, sizeof(Table) );
  99399. if( pTab==0 ){
  99400. return 0;
  99401. }
  99402. /* The sqlite3ResultSetOfSelect() is only used n contexts where lookaside
  99403. ** is disabled */
  99404. assert( db->lookaside.bEnabled==0 );
  99405. pTab->nRef = 1;
  99406. pTab->zName = 0;
  99407. pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
  99408. selectColumnsFromExprList(pParse, pSelect->pEList, &pTab->nCol, &pTab->aCol);
  99409. selectAddColumnTypeAndCollation(pParse, pTab, pSelect);
  99410. pTab->iPKey = -1;
  99411. if( db->mallocFailed ){
  99412. sqlite3DeleteTable(db, pTab);
  99413. return 0;
  99414. }
  99415. return pTab;
  99416. }
  99417. /*
  99418. ** Get a VDBE for the given parser context. Create a new one if necessary.
  99419. ** If an error occurs, return NULL and leave a message in pParse.
  99420. */
  99421. SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse *pParse){
  99422. Vdbe *v = pParse->pVdbe;
  99423. if( v==0 ){
  99424. v = pParse->pVdbe = sqlite3VdbeCreate(pParse);
  99425. if( v ) sqlite3VdbeAddOp0(v, OP_Init);
  99426. if( pParse->pToplevel==0
  99427. && OptimizationEnabled(pParse->db,SQLITE_FactorOutConst)
  99428. ){
  99429. pParse->okConstFactor = 1;
  99430. }
  99431. }
  99432. return v;
  99433. }
  99434. /*
  99435. ** Compute the iLimit and iOffset fields of the SELECT based on the
  99436. ** pLimit and pOffset expressions. pLimit and pOffset hold the expressions
  99437. ** that appear in the original SQL statement after the LIMIT and OFFSET
  99438. ** keywords. Or NULL if those keywords are omitted. iLimit and iOffset
  99439. ** are the integer memory register numbers for counters used to compute
  99440. ** the limit and offset. If there is no limit and/or offset, then
  99441. ** iLimit and iOffset are negative.
  99442. **
  99443. ** This routine changes the values of iLimit and iOffset only if
  99444. ** a limit or offset is defined by pLimit and pOffset. iLimit and
  99445. ** iOffset should have been preset to appropriate default values (zero)
  99446. ** prior to calling this routine.
  99447. **
  99448. ** The iOffset register (if it exists) is initialized to the value
  99449. ** of the OFFSET. The iLimit register is initialized to LIMIT. Register
  99450. ** iOffset+1 is initialized to LIMIT+OFFSET.
  99451. **
  99452. ** Only if pLimit!=0 or pOffset!=0 do the limit registers get
  99453. ** redefined. The UNION ALL operator uses this property to force
  99454. ** the reuse of the same limit and offset registers across multiple
  99455. ** SELECT statements.
  99456. */
  99457. static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){
  99458. Vdbe *v = 0;
  99459. int iLimit = 0;
  99460. int iOffset;
  99461. int addr1, n;
  99462. if( p->iLimit ) return;
  99463. /*
  99464. ** "LIMIT -1" always shows all rows. There is some
  99465. ** controversy about what the correct behavior should be.
  99466. ** The current implementation interprets "LIMIT 0" to mean
  99467. ** no rows.
  99468. */
  99469. sqlite3ExprCacheClear(pParse);
  99470. assert( p->pOffset==0 || p->pLimit!=0 );
  99471. if( p->pLimit ){
  99472. p->iLimit = iLimit = ++pParse->nMem;
  99473. v = sqlite3GetVdbe(pParse);
  99474. assert( v!=0 );
  99475. if( sqlite3ExprIsInteger(p->pLimit, &n) ){
  99476. sqlite3VdbeAddOp2(v, OP_Integer, n, iLimit);
  99477. VdbeComment((v, "LIMIT counter"));
  99478. if( n==0 ){
  99479. sqlite3VdbeAddOp2(v, OP_Goto, 0, iBreak);
  99480. }else if( n>=0 && p->nSelectRow>(u64)n ){
  99481. p->nSelectRow = n;
  99482. }
  99483. }else{
  99484. sqlite3ExprCode(pParse, p->pLimit, iLimit);
  99485. sqlite3VdbeAddOp1(v, OP_MustBeInt, iLimit); VdbeCoverage(v);
  99486. VdbeComment((v, "LIMIT counter"));
  99487. sqlite3VdbeAddOp2(v, OP_IfZero, iLimit, iBreak); VdbeCoverage(v);
  99488. }
  99489. if( p->pOffset ){
  99490. p->iOffset = iOffset = ++pParse->nMem;
  99491. pParse->nMem++; /* Allocate an extra register for limit+offset */
  99492. sqlite3ExprCode(pParse, p->pOffset, iOffset);
  99493. sqlite3VdbeAddOp1(v, OP_MustBeInt, iOffset); VdbeCoverage(v);
  99494. VdbeComment((v, "OFFSET counter"));
  99495. addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iOffset); VdbeCoverage(v);
  99496. sqlite3VdbeAddOp2(v, OP_Integer, 0, iOffset);
  99497. sqlite3VdbeJumpHere(v, addr1);
  99498. sqlite3VdbeAddOp3(v, OP_Add, iLimit, iOffset, iOffset+1);
  99499. VdbeComment((v, "LIMIT+OFFSET"));
  99500. addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iLimit); VdbeCoverage(v);
  99501. sqlite3VdbeAddOp2(v, OP_Integer, -1, iOffset+1);
  99502. sqlite3VdbeJumpHere(v, addr1);
  99503. }
  99504. }
  99505. }
  99506. #ifndef SQLITE_OMIT_COMPOUND_SELECT
  99507. /*
  99508. ** Return the appropriate collating sequence for the iCol-th column of
  99509. ** the result set for the compound-select statement "p". Return NULL if
  99510. ** the column has no default collating sequence.
  99511. **
  99512. ** The collating sequence for the compound select is taken from the
  99513. ** left-most term of the select that has a collating sequence.
  99514. */
  99515. static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){
  99516. CollSeq *pRet;
  99517. if( p->pPrior ){
  99518. pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
  99519. }else{
  99520. pRet = 0;
  99521. }
  99522. assert( iCol>=0 );
  99523. if( pRet==0 && iCol<p->pEList->nExpr ){
  99524. pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
  99525. }
  99526. return pRet;
  99527. }
  99528. /*
  99529. ** The select statement passed as the second parameter is a compound SELECT
  99530. ** with an ORDER BY clause. This function allocates and returns a KeyInfo
  99531. ** structure suitable for implementing the ORDER BY.
  99532. **
  99533. ** Space to hold the KeyInfo structure is obtained from malloc. The calling
  99534. ** function is responsible for ensuring that this structure is eventually
  99535. ** freed.
  99536. */
  99537. static KeyInfo *multiSelectOrderByKeyInfo(Parse *pParse, Select *p, int nExtra){
  99538. ExprList *pOrderBy = p->pOrderBy;
  99539. int nOrderBy = p->pOrderBy->nExpr;
  99540. sqlite3 *db = pParse->db;
  99541. KeyInfo *pRet = sqlite3KeyInfoAlloc(db, nOrderBy+nExtra, 1);
  99542. if( pRet ){
  99543. int i;
  99544. for(i=0; i<nOrderBy; i++){
  99545. struct ExprList_item *pItem = &pOrderBy->a[i];
  99546. Expr *pTerm = pItem->pExpr;
  99547. CollSeq *pColl;
  99548. if( pTerm->flags & EP_Collate ){
  99549. pColl = sqlite3ExprCollSeq(pParse, pTerm);
  99550. }else{
  99551. pColl = multiSelectCollSeq(pParse, p, pItem->u.x.iOrderByCol-1);
  99552. if( pColl==0 ) pColl = db->pDfltColl;
  99553. pOrderBy->a[i].pExpr =
  99554. sqlite3ExprAddCollateString(pParse, pTerm, pColl->zName);
  99555. }
  99556. assert( sqlite3KeyInfoIsWriteable(pRet) );
  99557. pRet->aColl[i] = pColl;
  99558. pRet->aSortOrder[i] = pOrderBy->a[i].sortOrder;
  99559. }
  99560. }
  99561. return pRet;
  99562. }
  99563. #ifndef SQLITE_OMIT_CTE
  99564. /*
  99565. ** This routine generates VDBE code to compute the content of a WITH RECURSIVE
  99566. ** query of the form:
  99567. **
  99568. ** <recursive-table> AS (<setup-query> UNION [ALL] <recursive-query>)
  99569. ** \___________/ \_______________/
  99570. ** p->pPrior p
  99571. **
  99572. **
  99573. ** There is exactly one reference to the recursive-table in the FROM clause
  99574. ** of recursive-query, marked with the SrcList->a[].isRecursive flag.
  99575. **
  99576. ** The setup-query runs once to generate an initial set of rows that go
  99577. ** into a Queue table. Rows are extracted from the Queue table one by
  99578. ** one. Each row extracted from Queue is output to pDest. Then the single
  99579. ** extracted row (now in the iCurrent table) becomes the content of the
  99580. ** recursive-table for a recursive-query run. The output of the recursive-query
  99581. ** is added back into the Queue table. Then another row is extracted from Queue
  99582. ** and the iteration continues until the Queue table is empty.
  99583. **
  99584. ** If the compound query operator is UNION then no duplicate rows are ever
  99585. ** inserted into the Queue table. The iDistinct table keeps a copy of all rows
  99586. ** that have ever been inserted into Queue and causes duplicates to be
  99587. ** discarded. If the operator is UNION ALL, then duplicates are allowed.
  99588. **
  99589. ** If the query has an ORDER BY, then entries in the Queue table are kept in
  99590. ** ORDER BY order and the first entry is extracted for each cycle. Without
  99591. ** an ORDER BY, the Queue table is just a FIFO.
  99592. **
  99593. ** If a LIMIT clause is provided, then the iteration stops after LIMIT rows
  99594. ** have been output to pDest. A LIMIT of zero means to output no rows and a
  99595. ** negative LIMIT means to output all rows. If there is also an OFFSET clause
  99596. ** with a positive value, then the first OFFSET outputs are discarded rather
  99597. ** than being sent to pDest. The LIMIT count does not begin until after OFFSET
  99598. ** rows have been skipped.
  99599. */
  99600. static void generateWithRecursiveQuery(
  99601. Parse *pParse, /* Parsing context */
  99602. Select *p, /* The recursive SELECT to be coded */
  99603. SelectDest *pDest /* What to do with query results */
  99604. ){
  99605. SrcList *pSrc = p->pSrc; /* The FROM clause of the recursive query */
  99606. int nCol = p->pEList->nExpr; /* Number of columns in the recursive table */
  99607. Vdbe *v = pParse->pVdbe; /* The prepared statement under construction */
  99608. Select *pSetup = p->pPrior; /* The setup query */
  99609. int addrTop; /* Top of the loop */
  99610. int addrCont, addrBreak; /* CONTINUE and BREAK addresses */
  99611. int iCurrent = 0; /* The Current table */
  99612. int regCurrent; /* Register holding Current table */
  99613. int iQueue; /* The Queue table */
  99614. int iDistinct = 0; /* To ensure unique results if UNION */
  99615. int eDest = SRT_Fifo; /* How to write to Queue */
  99616. SelectDest destQueue; /* SelectDest targetting the Queue table */
  99617. int i; /* Loop counter */
  99618. int rc; /* Result code */
  99619. ExprList *pOrderBy; /* The ORDER BY clause */
  99620. Expr *pLimit, *pOffset; /* Saved LIMIT and OFFSET */
  99621. int regLimit, regOffset; /* Registers used by LIMIT and OFFSET */
  99622. /* Obtain authorization to do a recursive query */
  99623. if( sqlite3AuthCheck(pParse, SQLITE_RECURSIVE, 0, 0, 0) ) return;
  99624. /* Process the LIMIT and OFFSET clauses, if they exist */
  99625. addrBreak = sqlite3VdbeMakeLabel(v);
  99626. computeLimitRegisters(pParse, p, addrBreak);
  99627. pLimit = p->pLimit;
  99628. pOffset = p->pOffset;
  99629. regLimit = p->iLimit;
  99630. regOffset = p->iOffset;
  99631. p->pLimit = p->pOffset = 0;
  99632. p->iLimit = p->iOffset = 0;
  99633. pOrderBy = p->pOrderBy;
  99634. /* Locate the cursor number of the Current table */
  99635. for(i=0; ALWAYS(i<pSrc->nSrc); i++){
  99636. if( pSrc->a[i].isRecursive ){
  99637. iCurrent = pSrc->a[i].iCursor;
  99638. break;
  99639. }
  99640. }
  99641. /* Allocate cursors numbers for Queue and Distinct. The cursor number for
  99642. ** the Distinct table must be exactly one greater than Queue in order
  99643. ** for the SRT_DistFifo and SRT_DistQueue destinations to work. */
  99644. iQueue = pParse->nTab++;
  99645. if( p->op==TK_UNION ){
  99646. eDest = pOrderBy ? SRT_DistQueue : SRT_DistFifo;
  99647. iDistinct = pParse->nTab++;
  99648. }else{
  99649. eDest = pOrderBy ? SRT_Queue : SRT_Fifo;
  99650. }
  99651. sqlite3SelectDestInit(&destQueue, eDest, iQueue);
  99652. /* Allocate cursors for Current, Queue, and Distinct. */
  99653. regCurrent = ++pParse->nMem;
  99654. sqlite3VdbeAddOp3(v, OP_OpenPseudo, iCurrent, regCurrent, nCol);
  99655. if( pOrderBy ){
  99656. KeyInfo *pKeyInfo = multiSelectOrderByKeyInfo(pParse, p, 1);
  99657. sqlite3VdbeAddOp4(v, OP_OpenEphemeral, iQueue, pOrderBy->nExpr+2, 0,
  99658. (char*)pKeyInfo, P4_KEYINFO);
  99659. destQueue.pOrderBy = pOrderBy;
  99660. }else{
  99661. sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iQueue, nCol);
  99662. }
  99663. VdbeComment((v, "Queue table"));
  99664. if( iDistinct ){
  99665. p->addrOpenEphm[0] = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iDistinct, 0);
  99666. p->selFlags |= SF_UsesEphemeral;
  99667. }
  99668. /* Detach the ORDER BY clause from the compound SELECT */
  99669. p->pOrderBy = 0;
  99670. /* Store the results of the setup-query in Queue. */
  99671. pSetup->pNext = 0;
  99672. rc = sqlite3Select(pParse, pSetup, &destQueue);
  99673. pSetup->pNext = p;
  99674. if( rc ) goto end_of_recursive_query;
  99675. /* Find the next row in the Queue and output that row */
  99676. addrTop = sqlite3VdbeAddOp2(v, OP_Rewind, iQueue, addrBreak); VdbeCoverage(v);
  99677. /* Transfer the next row in Queue over to Current */
  99678. sqlite3VdbeAddOp1(v, OP_NullRow, iCurrent); /* To reset column cache */
  99679. if( pOrderBy ){
  99680. sqlite3VdbeAddOp3(v, OP_Column, iQueue, pOrderBy->nExpr+1, regCurrent);
  99681. }else{
  99682. sqlite3VdbeAddOp2(v, OP_RowData, iQueue, regCurrent);
  99683. }
  99684. sqlite3VdbeAddOp1(v, OP_Delete, iQueue);
  99685. /* Output the single row in Current */
  99686. addrCont = sqlite3VdbeMakeLabel(v);
  99687. codeOffset(v, regOffset, addrCont);
  99688. selectInnerLoop(pParse, p, p->pEList, iCurrent,
  99689. 0, 0, pDest, addrCont, addrBreak);
  99690. if( regLimit ){
  99691. sqlite3VdbeAddOp3(v, OP_IfZero, regLimit, addrBreak, -1);
  99692. VdbeCoverage(v);
  99693. }
  99694. sqlite3VdbeResolveLabel(v, addrCont);
  99695. /* Execute the recursive SELECT taking the single row in Current as
  99696. ** the value for the recursive-table. Store the results in the Queue.
  99697. */
  99698. p->pPrior = 0;
  99699. sqlite3Select(pParse, p, &destQueue);
  99700. assert( p->pPrior==0 );
  99701. p->pPrior = pSetup;
  99702. /* Keep running the loop until the Queue is empty */
  99703. sqlite3VdbeAddOp2(v, OP_Goto, 0, addrTop);
  99704. sqlite3VdbeResolveLabel(v, addrBreak);
  99705. end_of_recursive_query:
  99706. sqlite3ExprListDelete(pParse->db, p->pOrderBy);
  99707. p->pOrderBy = pOrderBy;
  99708. p->pLimit = pLimit;
  99709. p->pOffset = pOffset;
  99710. return;
  99711. }
  99712. #endif /* SQLITE_OMIT_CTE */
  99713. /* Forward references */
  99714. static int multiSelectOrderBy(
  99715. Parse *pParse, /* Parsing context */
  99716. Select *p, /* The right-most of SELECTs to be coded */
  99717. SelectDest *pDest /* What to do with query results */
  99718. );
  99719. /*
  99720. ** This routine is called to process a compound query form from
  99721. ** two or more separate queries using UNION, UNION ALL, EXCEPT, or
  99722. ** INTERSECT
  99723. **
  99724. ** "p" points to the right-most of the two queries. the query on the
  99725. ** left is p->pPrior. The left query could also be a compound query
  99726. ** in which case this routine will be called recursively.
  99727. **
  99728. ** The results of the total query are to be written into a destination
  99729. ** of type eDest with parameter iParm.
  99730. **
  99731. ** Example 1: Consider a three-way compound SQL statement.
  99732. **
  99733. ** SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
  99734. **
  99735. ** This statement is parsed up as follows:
  99736. **
  99737. ** SELECT c FROM t3
  99738. ** |
  99739. ** `-----> SELECT b FROM t2
  99740. ** |
  99741. ** `------> SELECT a FROM t1
  99742. **
  99743. ** The arrows in the diagram above represent the Select.pPrior pointer.
  99744. ** So if this routine is called with p equal to the t3 query, then
  99745. ** pPrior will be the t2 query. p->op will be TK_UNION in this case.
  99746. **
  99747. ** Notice that because of the way SQLite parses compound SELECTs, the
  99748. ** individual selects always group from left to right.
  99749. */
  99750. static int multiSelect(
  99751. Parse *pParse, /* Parsing context */
  99752. Select *p, /* The right-most of SELECTs to be coded */
  99753. SelectDest *pDest /* What to do with query results */
  99754. ){
  99755. int rc = SQLITE_OK; /* Success code from a subroutine */
  99756. Select *pPrior; /* Another SELECT immediately to our left */
  99757. Vdbe *v; /* Generate code to this VDBE */
  99758. SelectDest dest; /* Alternative data destination */
  99759. Select *pDelete = 0; /* Chain of simple selects to delete */
  99760. sqlite3 *db; /* Database connection */
  99761. #ifndef SQLITE_OMIT_EXPLAIN
  99762. int iSub1 = 0; /* EQP id of left-hand query */
  99763. int iSub2 = 0; /* EQP id of right-hand query */
  99764. #endif
  99765. /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs. Only
  99766. ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT.
  99767. */
  99768. assert( p && p->pPrior ); /* Calling function guarantees this much */
  99769. assert( (p->selFlags & SF_Recursive)==0 || p->op==TK_ALL || p->op==TK_UNION );
  99770. db = pParse->db;
  99771. pPrior = p->pPrior;
  99772. dest = *pDest;
  99773. if( pPrior->pOrderBy ){
  99774. sqlite3ErrorMsg(pParse,"ORDER BY clause should come after %s not before",
  99775. selectOpName(p->op));
  99776. rc = 1;
  99777. goto multi_select_end;
  99778. }
  99779. if( pPrior->pLimit ){
  99780. sqlite3ErrorMsg(pParse,"LIMIT clause should come after %s not before",
  99781. selectOpName(p->op));
  99782. rc = 1;
  99783. goto multi_select_end;
  99784. }
  99785. v = sqlite3GetVdbe(pParse);
  99786. assert( v!=0 ); /* The VDBE already created by calling function */
  99787. /* Create the destination temporary table if necessary
  99788. */
  99789. if( dest.eDest==SRT_EphemTab ){
  99790. assert( p->pEList );
  99791. sqlite3VdbeAddOp2(v, OP_OpenEphemeral, dest.iSDParm, p->pEList->nExpr);
  99792. sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
  99793. dest.eDest = SRT_Table;
  99794. }
  99795. /* Make sure all SELECTs in the statement have the same number of elements
  99796. ** in their result sets.
  99797. */
  99798. assert( p->pEList && pPrior->pEList );
  99799. if( p->pEList->nExpr!=pPrior->pEList->nExpr ){
  99800. if( p->selFlags & SF_Values ){
  99801. sqlite3ErrorMsg(pParse, "all VALUES must have the same number of terms");
  99802. }else{
  99803. sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
  99804. " do not have the same number of result columns", selectOpName(p->op));
  99805. }
  99806. rc = 1;
  99807. goto multi_select_end;
  99808. }
  99809. #ifndef SQLITE_OMIT_CTE
  99810. if( p->selFlags & SF_Recursive ){
  99811. generateWithRecursiveQuery(pParse, p, &dest);
  99812. }else
  99813. #endif
  99814. /* Compound SELECTs that have an ORDER BY clause are handled separately.
  99815. */
  99816. if( p->pOrderBy ){
  99817. return multiSelectOrderBy(pParse, p, pDest);
  99818. }else
  99819. /* Generate code for the left and right SELECT statements.
  99820. */
  99821. switch( p->op ){
  99822. case TK_ALL: {
  99823. int addr = 0;
  99824. int nLimit;
  99825. assert( !pPrior->pLimit );
  99826. pPrior->iLimit = p->iLimit;
  99827. pPrior->iOffset = p->iOffset;
  99828. pPrior->pLimit = p->pLimit;
  99829. pPrior->pOffset = p->pOffset;
  99830. explainSetInteger(iSub1, pParse->iNextSelectId);
  99831. rc = sqlite3Select(pParse, pPrior, &dest);
  99832. p->pLimit = 0;
  99833. p->pOffset = 0;
  99834. if( rc ){
  99835. goto multi_select_end;
  99836. }
  99837. p->pPrior = 0;
  99838. p->iLimit = pPrior->iLimit;
  99839. p->iOffset = pPrior->iOffset;
  99840. if( p->iLimit ){
  99841. addr = sqlite3VdbeAddOp1(v, OP_IfZero, p->iLimit); VdbeCoverage(v);
  99842. VdbeComment((v, "Jump ahead if LIMIT reached"));
  99843. }
  99844. explainSetInteger(iSub2, pParse->iNextSelectId);
  99845. rc = sqlite3Select(pParse, p, &dest);
  99846. testcase( rc!=SQLITE_OK );
  99847. pDelete = p->pPrior;
  99848. p->pPrior = pPrior;
  99849. p->nSelectRow += pPrior->nSelectRow;
  99850. if( pPrior->pLimit
  99851. && sqlite3ExprIsInteger(pPrior->pLimit, &nLimit)
  99852. && nLimit>0 && p->nSelectRow > (u64)nLimit
  99853. ){
  99854. p->nSelectRow = nLimit;
  99855. }
  99856. if( addr ){
  99857. sqlite3VdbeJumpHere(v, addr);
  99858. }
  99859. break;
  99860. }
  99861. case TK_EXCEPT:
  99862. case TK_UNION: {
  99863. int unionTab; /* Cursor number of the temporary table holding result */
  99864. u8 op = 0; /* One of the SRT_ operations to apply to self */
  99865. int priorOp; /* The SRT_ operation to apply to prior selects */
  99866. Expr *pLimit, *pOffset; /* Saved values of p->nLimit and p->nOffset */
  99867. int addr;
  99868. SelectDest uniondest;
  99869. testcase( p->op==TK_EXCEPT );
  99870. testcase( p->op==TK_UNION );
  99871. priorOp = SRT_Union;
  99872. if( dest.eDest==priorOp ){
  99873. /* We can reuse a temporary table generated by a SELECT to our
  99874. ** right.
  99875. */
  99876. assert( p->pLimit==0 ); /* Not allowed on leftward elements */
  99877. assert( p->pOffset==0 ); /* Not allowed on leftward elements */
  99878. unionTab = dest.iSDParm;
  99879. }else{
  99880. /* We will need to create our own temporary table to hold the
  99881. ** intermediate results.
  99882. */
  99883. unionTab = pParse->nTab++;
  99884. assert( p->pOrderBy==0 );
  99885. addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, unionTab, 0);
  99886. assert( p->addrOpenEphm[0] == -1 );
  99887. p->addrOpenEphm[0] = addr;
  99888. findRightmost(p)->selFlags |= SF_UsesEphemeral;
  99889. assert( p->pEList );
  99890. }
  99891. /* Code the SELECT statements to our left
  99892. */
  99893. assert( !pPrior->pOrderBy );
  99894. sqlite3SelectDestInit(&uniondest, priorOp, unionTab);
  99895. explainSetInteger(iSub1, pParse->iNextSelectId);
  99896. rc = sqlite3Select(pParse, pPrior, &uniondest);
  99897. if( rc ){
  99898. goto multi_select_end;
  99899. }
  99900. /* Code the current SELECT statement
  99901. */
  99902. if( p->op==TK_EXCEPT ){
  99903. op = SRT_Except;
  99904. }else{
  99905. assert( p->op==TK_UNION );
  99906. op = SRT_Union;
  99907. }
  99908. p->pPrior = 0;
  99909. pLimit = p->pLimit;
  99910. p->pLimit = 0;
  99911. pOffset = p->pOffset;
  99912. p->pOffset = 0;
  99913. uniondest.eDest = op;
  99914. explainSetInteger(iSub2, pParse->iNextSelectId);
  99915. rc = sqlite3Select(pParse, p, &uniondest);
  99916. testcase( rc!=SQLITE_OK );
  99917. /* Query flattening in sqlite3Select() might refill p->pOrderBy.
  99918. ** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */
  99919. sqlite3ExprListDelete(db, p->pOrderBy);
  99920. pDelete = p->pPrior;
  99921. p->pPrior = pPrior;
  99922. p->pOrderBy = 0;
  99923. if( p->op==TK_UNION ) p->nSelectRow += pPrior->nSelectRow;
  99924. sqlite3ExprDelete(db, p->pLimit);
  99925. p->pLimit = pLimit;
  99926. p->pOffset = pOffset;
  99927. p->iLimit = 0;
  99928. p->iOffset = 0;
  99929. /* Convert the data in the temporary table into whatever form
  99930. ** it is that we currently need.
  99931. */
  99932. assert( unionTab==dest.iSDParm || dest.eDest!=priorOp );
  99933. if( dest.eDest!=priorOp ){
  99934. int iCont, iBreak, iStart;
  99935. assert( p->pEList );
  99936. if( dest.eDest==SRT_Output ){
  99937. Select *pFirst = p;
  99938. while( pFirst->pPrior ) pFirst = pFirst->pPrior;
  99939. generateColumnNames(pParse, 0, pFirst->pEList);
  99940. }
  99941. iBreak = sqlite3VdbeMakeLabel(v);
  99942. iCont = sqlite3VdbeMakeLabel(v);
  99943. computeLimitRegisters(pParse, p, iBreak);
  99944. sqlite3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak); VdbeCoverage(v);
  99945. iStart = sqlite3VdbeCurrentAddr(v);
  99946. selectInnerLoop(pParse, p, p->pEList, unionTab,
  99947. 0, 0, &dest, iCont, iBreak);
  99948. sqlite3VdbeResolveLabel(v, iCont);
  99949. sqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart); VdbeCoverage(v);
  99950. sqlite3VdbeResolveLabel(v, iBreak);
  99951. sqlite3VdbeAddOp2(v, OP_Close, unionTab, 0);
  99952. }
  99953. break;
  99954. }
  99955. default: assert( p->op==TK_INTERSECT ); {
  99956. int tab1, tab2;
  99957. int iCont, iBreak, iStart;
  99958. Expr *pLimit, *pOffset;
  99959. int addr;
  99960. SelectDest intersectdest;
  99961. int r1;
  99962. /* INTERSECT is different from the others since it requires
  99963. ** two temporary tables. Hence it has its own case. Begin
  99964. ** by allocating the tables we will need.
  99965. */
  99966. tab1 = pParse->nTab++;
  99967. tab2 = pParse->nTab++;
  99968. assert( p->pOrderBy==0 );
  99969. addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab1, 0);
  99970. assert( p->addrOpenEphm[0] == -1 );
  99971. p->addrOpenEphm[0] = addr;
  99972. findRightmost(p)->selFlags |= SF_UsesEphemeral;
  99973. assert( p->pEList );
  99974. /* Code the SELECTs to our left into temporary table "tab1".
  99975. */
  99976. sqlite3SelectDestInit(&intersectdest, SRT_Union, tab1);
  99977. explainSetInteger(iSub1, pParse->iNextSelectId);
  99978. rc = sqlite3Select(pParse, pPrior, &intersectdest);
  99979. if( rc ){
  99980. goto multi_select_end;
  99981. }
  99982. /* Code the current SELECT into temporary table "tab2"
  99983. */
  99984. addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab2, 0);
  99985. assert( p->addrOpenEphm[1] == -1 );
  99986. p->addrOpenEphm[1] = addr;
  99987. p->pPrior = 0;
  99988. pLimit = p->pLimit;
  99989. p->pLimit = 0;
  99990. pOffset = p->pOffset;
  99991. p->pOffset = 0;
  99992. intersectdest.iSDParm = tab2;
  99993. explainSetInteger(iSub2, pParse->iNextSelectId);
  99994. rc = sqlite3Select(pParse, p, &intersectdest);
  99995. testcase( rc!=SQLITE_OK );
  99996. pDelete = p->pPrior;
  99997. p->pPrior = pPrior;
  99998. if( p->nSelectRow>pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
  99999. sqlite3ExprDelete(db, p->pLimit);
  100000. p->pLimit = pLimit;
  100001. p->pOffset = pOffset;
  100002. /* Generate code to take the intersection of the two temporary
  100003. ** tables.
  100004. */
  100005. assert( p->pEList );
  100006. if( dest.eDest==SRT_Output ){
  100007. Select *pFirst = p;
  100008. while( pFirst->pPrior ) pFirst = pFirst->pPrior;
  100009. generateColumnNames(pParse, 0, pFirst->pEList);
  100010. }
  100011. iBreak = sqlite3VdbeMakeLabel(v);
  100012. iCont = sqlite3VdbeMakeLabel(v);
  100013. computeLimitRegisters(pParse, p, iBreak);
  100014. sqlite3VdbeAddOp2(v, OP_Rewind, tab1, iBreak); VdbeCoverage(v);
  100015. r1 = sqlite3GetTempReg(pParse);
  100016. iStart = sqlite3VdbeAddOp2(v, OP_RowKey, tab1, r1);
  100017. sqlite3VdbeAddOp4Int(v, OP_NotFound, tab2, iCont, r1, 0); VdbeCoverage(v);
  100018. sqlite3ReleaseTempReg(pParse, r1);
  100019. selectInnerLoop(pParse, p, p->pEList, tab1,
  100020. 0, 0, &dest, iCont, iBreak);
  100021. sqlite3VdbeResolveLabel(v, iCont);
  100022. sqlite3VdbeAddOp2(v, OP_Next, tab1, iStart); VdbeCoverage(v);
  100023. sqlite3VdbeResolveLabel(v, iBreak);
  100024. sqlite3VdbeAddOp2(v, OP_Close, tab2, 0);
  100025. sqlite3VdbeAddOp2(v, OP_Close, tab1, 0);
  100026. break;
  100027. }
  100028. }
  100029. explainComposite(pParse, p->op, iSub1, iSub2, p->op!=TK_ALL);
  100030. /* Compute collating sequences used by
  100031. ** temporary tables needed to implement the compound select.
  100032. ** Attach the KeyInfo structure to all temporary tables.
  100033. **
  100034. ** This section is run by the right-most SELECT statement only.
  100035. ** SELECT statements to the left always skip this part. The right-most
  100036. ** SELECT might also skip this part if it has no ORDER BY clause and
  100037. ** no temp tables are required.
  100038. */
  100039. if( p->selFlags & SF_UsesEphemeral ){
  100040. int i; /* Loop counter */
  100041. KeyInfo *pKeyInfo; /* Collating sequence for the result set */
  100042. Select *pLoop; /* For looping through SELECT statements */
  100043. CollSeq **apColl; /* For looping through pKeyInfo->aColl[] */
  100044. int nCol; /* Number of columns in result set */
  100045. assert( p->pNext==0 );
  100046. nCol = p->pEList->nExpr;
  100047. pKeyInfo = sqlite3KeyInfoAlloc(db, nCol, 1);
  100048. if( !pKeyInfo ){
  100049. rc = SQLITE_NOMEM;
  100050. goto multi_select_end;
  100051. }
  100052. for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){
  100053. *apColl = multiSelectCollSeq(pParse, p, i);
  100054. if( 0==*apColl ){
  100055. *apColl = db->pDfltColl;
  100056. }
  100057. }
  100058. for(pLoop=p; pLoop; pLoop=pLoop->pPrior){
  100059. for(i=0; i<2; i++){
  100060. int addr = pLoop->addrOpenEphm[i];
  100061. if( addr<0 ){
  100062. /* If [0] is unused then [1] is also unused. So we can
  100063. ** always safely abort as soon as the first unused slot is found */
  100064. assert( pLoop->addrOpenEphm[1]<0 );
  100065. break;
  100066. }
  100067. sqlite3VdbeChangeP2(v, addr, nCol);
  100068. sqlite3VdbeChangeP4(v, addr, (char*)sqlite3KeyInfoRef(pKeyInfo),
  100069. P4_KEYINFO);
  100070. pLoop->addrOpenEphm[i] = -1;
  100071. }
  100072. }
  100073. sqlite3KeyInfoUnref(pKeyInfo);
  100074. }
  100075. multi_select_end:
  100076. pDest->iSdst = dest.iSdst;
  100077. pDest->nSdst = dest.nSdst;
  100078. sqlite3SelectDelete(db, pDelete);
  100079. return rc;
  100080. }
  100081. #endif /* SQLITE_OMIT_COMPOUND_SELECT */
  100082. /*
  100083. ** Code an output subroutine for a coroutine implementation of a
  100084. ** SELECT statment.
  100085. **
  100086. ** The data to be output is contained in pIn->iSdst. There are
  100087. ** pIn->nSdst columns to be output. pDest is where the output should
  100088. ** be sent.
  100089. **
  100090. ** regReturn is the number of the register holding the subroutine
  100091. ** return address.
  100092. **
  100093. ** If regPrev>0 then it is the first register in a vector that
  100094. ** records the previous output. mem[regPrev] is a flag that is false
  100095. ** if there has been no previous output. If regPrev>0 then code is
  100096. ** generated to suppress duplicates. pKeyInfo is used for comparing
  100097. ** keys.
  100098. **
  100099. ** If the LIMIT found in p->iLimit is reached, jump immediately to
  100100. ** iBreak.
  100101. */
  100102. static int generateOutputSubroutine(
  100103. Parse *pParse, /* Parsing context */
  100104. Select *p, /* The SELECT statement */
  100105. SelectDest *pIn, /* Coroutine supplying data */
  100106. SelectDest *pDest, /* Where to send the data */
  100107. int regReturn, /* The return address register */
  100108. int regPrev, /* Previous result register. No uniqueness if 0 */
  100109. KeyInfo *pKeyInfo, /* For comparing with previous entry */
  100110. int iBreak /* Jump here if we hit the LIMIT */
  100111. ){
  100112. Vdbe *v = pParse->pVdbe;
  100113. int iContinue;
  100114. int addr;
  100115. addr = sqlite3VdbeCurrentAddr(v);
  100116. iContinue = sqlite3VdbeMakeLabel(v);
  100117. /* Suppress duplicates for UNION, EXCEPT, and INTERSECT
  100118. */
  100119. if( regPrev ){
  100120. int j1, j2;
  100121. j1 = sqlite3VdbeAddOp1(v, OP_IfNot, regPrev); VdbeCoverage(v);
  100122. j2 = sqlite3VdbeAddOp4(v, OP_Compare, pIn->iSdst, regPrev+1, pIn->nSdst,
  100123. (char*)sqlite3KeyInfoRef(pKeyInfo), P4_KEYINFO);
  100124. sqlite3VdbeAddOp3(v, OP_Jump, j2+2, iContinue, j2+2); VdbeCoverage(v);
  100125. sqlite3VdbeJumpHere(v, j1);
  100126. sqlite3VdbeAddOp3(v, OP_Copy, pIn->iSdst, regPrev+1, pIn->nSdst-1);
  100127. sqlite3VdbeAddOp2(v, OP_Integer, 1, regPrev);
  100128. }
  100129. if( pParse->db->mallocFailed ) return 0;
  100130. /* Suppress the first OFFSET entries if there is an OFFSET clause
  100131. */
  100132. codeOffset(v, p->iOffset, iContinue);
  100133. switch( pDest->eDest ){
  100134. /* Store the result as data using a unique key.
  100135. */
  100136. case SRT_Table:
  100137. case SRT_EphemTab: {
  100138. int r1 = sqlite3GetTempReg(pParse);
  100139. int r2 = sqlite3GetTempReg(pParse);
  100140. testcase( pDest->eDest==SRT_Table );
  100141. testcase( pDest->eDest==SRT_EphemTab );
  100142. sqlite3VdbeAddOp3(v, OP_MakeRecord, pIn->iSdst, pIn->nSdst, r1);
  100143. sqlite3VdbeAddOp2(v, OP_NewRowid, pDest->iSDParm, r2);
  100144. sqlite3VdbeAddOp3(v, OP_Insert, pDest->iSDParm, r1, r2);
  100145. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  100146. sqlite3ReleaseTempReg(pParse, r2);
  100147. sqlite3ReleaseTempReg(pParse, r1);
  100148. break;
  100149. }
  100150. #ifndef SQLITE_OMIT_SUBQUERY
  100151. /* If we are creating a set for an "expr IN (SELECT ...)" construct,
  100152. ** then there should be a single item on the stack. Write this
  100153. ** item into the set table with bogus data.
  100154. */
  100155. case SRT_Set: {
  100156. int r1;
  100157. assert( pIn->nSdst==1 );
  100158. pDest->affSdst =
  100159. sqlite3CompareAffinity(p->pEList->a[0].pExpr, pDest->affSdst);
  100160. r1 = sqlite3GetTempReg(pParse);
  100161. sqlite3VdbeAddOp4(v, OP_MakeRecord, pIn->iSdst, 1, r1, &pDest->affSdst,1);
  100162. sqlite3ExprCacheAffinityChange(pParse, pIn->iSdst, 1);
  100163. sqlite3VdbeAddOp2(v, OP_IdxInsert, pDest->iSDParm, r1);
  100164. sqlite3ReleaseTempReg(pParse, r1);
  100165. break;
  100166. }
  100167. #if 0 /* Never occurs on an ORDER BY query */
  100168. /* If any row exist in the result set, record that fact and abort.
  100169. */
  100170. case SRT_Exists: {
  100171. sqlite3VdbeAddOp2(v, OP_Integer, 1, pDest->iSDParm);
  100172. /* The LIMIT clause will terminate the loop for us */
  100173. break;
  100174. }
  100175. #endif
  100176. /* If this is a scalar select that is part of an expression, then
  100177. ** store the results in the appropriate memory cell and break out
  100178. ** of the scan loop.
  100179. */
  100180. case SRT_Mem: {
  100181. assert( pIn->nSdst==1 );
  100182. sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSDParm, 1);
  100183. /* The LIMIT clause will jump out of the loop for us */
  100184. break;
  100185. }
  100186. #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
  100187. /* The results are stored in a sequence of registers
  100188. ** starting at pDest->iSdst. Then the co-routine yields.
  100189. */
  100190. case SRT_Coroutine: {
  100191. if( pDest->iSdst==0 ){
  100192. pDest->iSdst = sqlite3GetTempRange(pParse, pIn->nSdst);
  100193. pDest->nSdst = pIn->nSdst;
  100194. }
  100195. sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSdst, pDest->nSdst);
  100196. sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
  100197. break;
  100198. }
  100199. /* If none of the above, then the result destination must be
  100200. ** SRT_Output. This routine is never called with any other
  100201. ** destination other than the ones handled above or SRT_Output.
  100202. **
  100203. ** For SRT_Output, results are stored in a sequence of registers.
  100204. ** Then the OP_ResultRow opcode is used to cause sqlite3_step() to
  100205. ** return the next row of result.
  100206. */
  100207. default: {
  100208. assert( pDest->eDest==SRT_Output );
  100209. sqlite3VdbeAddOp2(v, OP_ResultRow, pIn->iSdst, pIn->nSdst);
  100210. sqlite3ExprCacheAffinityChange(pParse, pIn->iSdst, pIn->nSdst);
  100211. break;
  100212. }
  100213. }
  100214. /* Jump to the end of the loop if the LIMIT is reached.
  100215. */
  100216. if( p->iLimit ){
  100217. sqlite3VdbeAddOp3(v, OP_IfZero, p->iLimit, iBreak, -1); VdbeCoverage(v);
  100218. }
  100219. /* Generate the subroutine return
  100220. */
  100221. sqlite3VdbeResolveLabel(v, iContinue);
  100222. sqlite3VdbeAddOp1(v, OP_Return, regReturn);
  100223. return addr;
  100224. }
  100225. /*
  100226. ** Alternative compound select code generator for cases when there
  100227. ** is an ORDER BY clause.
  100228. **
  100229. ** We assume a query of the following form:
  100230. **
  100231. ** <selectA> <operator> <selectB> ORDER BY <orderbylist>
  100232. **
  100233. ** <operator> is one of UNION ALL, UNION, EXCEPT, or INTERSECT. The idea
  100234. ** is to code both <selectA> and <selectB> with the ORDER BY clause as
  100235. ** co-routines. Then run the co-routines in parallel and merge the results
  100236. ** into the output. In addition to the two coroutines (called selectA and
  100237. ** selectB) there are 7 subroutines:
  100238. **
  100239. ** outA: Move the output of the selectA coroutine into the output
  100240. ** of the compound query.
  100241. **
  100242. ** outB: Move the output of the selectB coroutine into the output
  100243. ** of the compound query. (Only generated for UNION and
  100244. ** UNION ALL. EXCEPT and INSERTSECT never output a row that
  100245. ** appears only in B.)
  100246. **
  100247. ** AltB: Called when there is data from both coroutines and A<B.
  100248. **
  100249. ** AeqB: Called when there is data from both coroutines and A==B.
  100250. **
  100251. ** AgtB: Called when there is data from both coroutines and A>B.
  100252. **
  100253. ** EofA: Called when data is exhausted from selectA.
  100254. **
  100255. ** EofB: Called when data is exhausted from selectB.
  100256. **
  100257. ** The implementation of the latter five subroutines depend on which
  100258. ** <operator> is used:
  100259. **
  100260. **
  100261. ** UNION ALL UNION EXCEPT INTERSECT
  100262. ** ------------- ----------------- -------------- -----------------
  100263. ** AltB: outA, nextA outA, nextA outA, nextA nextA
  100264. **
  100265. ** AeqB: outA, nextA nextA nextA outA, nextA
  100266. **
  100267. ** AgtB: outB, nextB outB, nextB nextB nextB
  100268. **
  100269. ** EofA: outB, nextB outB, nextB halt halt
  100270. **
  100271. ** EofB: outA, nextA outA, nextA outA, nextA halt
  100272. **
  100273. ** In the AltB, AeqB, and AgtB subroutines, an EOF on A following nextA
  100274. ** causes an immediate jump to EofA and an EOF on B following nextB causes
  100275. ** an immediate jump to EofB. Within EofA and EofB, and EOF on entry or
  100276. ** following nextX causes a jump to the end of the select processing.
  100277. **
  100278. ** Duplicate removal in the UNION, EXCEPT, and INTERSECT cases is handled
  100279. ** within the output subroutine. The regPrev register set holds the previously
  100280. ** output value. A comparison is made against this value and the output
  100281. ** is skipped if the next results would be the same as the previous.
  100282. **
  100283. ** The implementation plan is to implement the two coroutines and seven
  100284. ** subroutines first, then put the control logic at the bottom. Like this:
  100285. **
  100286. ** goto Init
  100287. ** coA: coroutine for left query (A)
  100288. ** coB: coroutine for right query (B)
  100289. ** outA: output one row of A
  100290. ** outB: output one row of B (UNION and UNION ALL only)
  100291. ** EofA: ...
  100292. ** EofB: ...
  100293. ** AltB: ...
  100294. ** AeqB: ...
  100295. ** AgtB: ...
  100296. ** Init: initialize coroutine registers
  100297. ** yield coA
  100298. ** if eof(A) goto EofA
  100299. ** yield coB
  100300. ** if eof(B) goto EofB
  100301. ** Cmpr: Compare A, B
  100302. ** Jump AltB, AeqB, AgtB
  100303. ** End: ...
  100304. **
  100305. ** We call AltB, AeqB, AgtB, EofA, and EofB "subroutines" but they are not
  100306. ** actually called using Gosub and they do not Return. EofA and EofB loop
  100307. ** until all data is exhausted then jump to the "end" labe. AltB, AeqB,
  100308. ** and AgtB jump to either L2 or to one of EofA or EofB.
  100309. */
  100310. #ifndef SQLITE_OMIT_COMPOUND_SELECT
  100311. static int multiSelectOrderBy(
  100312. Parse *pParse, /* Parsing context */
  100313. Select *p, /* The right-most of SELECTs to be coded */
  100314. SelectDest *pDest /* What to do with query results */
  100315. ){
  100316. int i, j; /* Loop counters */
  100317. Select *pPrior; /* Another SELECT immediately to our left */
  100318. Vdbe *v; /* Generate code to this VDBE */
  100319. SelectDest destA; /* Destination for coroutine A */
  100320. SelectDest destB; /* Destination for coroutine B */
  100321. int regAddrA; /* Address register for select-A coroutine */
  100322. int regAddrB; /* Address register for select-B coroutine */
  100323. int addrSelectA; /* Address of the select-A coroutine */
  100324. int addrSelectB; /* Address of the select-B coroutine */
  100325. int regOutA; /* Address register for the output-A subroutine */
  100326. int regOutB; /* Address register for the output-B subroutine */
  100327. int addrOutA; /* Address of the output-A subroutine */
  100328. int addrOutB = 0; /* Address of the output-B subroutine */
  100329. int addrEofA; /* Address of the select-A-exhausted subroutine */
  100330. int addrEofA_noB; /* Alternate addrEofA if B is uninitialized */
  100331. int addrEofB; /* Address of the select-B-exhausted subroutine */
  100332. int addrAltB; /* Address of the A<B subroutine */
  100333. int addrAeqB; /* Address of the A==B subroutine */
  100334. int addrAgtB; /* Address of the A>B subroutine */
  100335. int regLimitA; /* Limit register for select-A */
  100336. int regLimitB; /* Limit register for select-A */
  100337. int regPrev; /* A range of registers to hold previous output */
  100338. int savedLimit; /* Saved value of p->iLimit */
  100339. int savedOffset; /* Saved value of p->iOffset */
  100340. int labelCmpr; /* Label for the start of the merge algorithm */
  100341. int labelEnd; /* Label for the end of the overall SELECT stmt */
  100342. int j1; /* Jump instructions that get retargetted */
  100343. int op; /* One of TK_ALL, TK_UNION, TK_EXCEPT, TK_INTERSECT */
  100344. KeyInfo *pKeyDup = 0; /* Comparison information for duplicate removal */
  100345. KeyInfo *pKeyMerge; /* Comparison information for merging rows */
  100346. sqlite3 *db; /* Database connection */
  100347. ExprList *pOrderBy; /* The ORDER BY clause */
  100348. int nOrderBy; /* Number of terms in the ORDER BY clause */
  100349. int *aPermute; /* Mapping from ORDER BY terms to result set columns */
  100350. #ifndef SQLITE_OMIT_EXPLAIN
  100351. int iSub1; /* EQP id of left-hand query */
  100352. int iSub2; /* EQP id of right-hand query */
  100353. #endif
  100354. assert( p->pOrderBy!=0 );
  100355. assert( pKeyDup==0 ); /* "Managed" code needs this. Ticket #3382. */
  100356. db = pParse->db;
  100357. v = pParse->pVdbe;
  100358. assert( v!=0 ); /* Already thrown the error if VDBE alloc failed */
  100359. labelEnd = sqlite3VdbeMakeLabel(v);
  100360. labelCmpr = sqlite3VdbeMakeLabel(v);
  100361. /* Patch up the ORDER BY clause
  100362. */
  100363. op = p->op;
  100364. pPrior = p->pPrior;
  100365. assert( pPrior->pOrderBy==0 );
  100366. pOrderBy = p->pOrderBy;
  100367. assert( pOrderBy );
  100368. nOrderBy = pOrderBy->nExpr;
  100369. /* For operators other than UNION ALL we have to make sure that
  100370. ** the ORDER BY clause covers every term of the result set. Add
  100371. ** terms to the ORDER BY clause as necessary.
  100372. */
  100373. if( op!=TK_ALL ){
  100374. for(i=1; db->mallocFailed==0 && i<=p->pEList->nExpr; i++){
  100375. struct ExprList_item *pItem;
  100376. for(j=0, pItem=pOrderBy->a; j<nOrderBy; j++, pItem++){
  100377. assert( pItem->u.x.iOrderByCol>0 );
  100378. if( pItem->u.x.iOrderByCol==i ) break;
  100379. }
  100380. if( j==nOrderBy ){
  100381. Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
  100382. if( pNew==0 ) return SQLITE_NOMEM;
  100383. pNew->flags |= EP_IntValue;
  100384. pNew->u.iValue = i;
  100385. pOrderBy = sqlite3ExprListAppend(pParse, pOrderBy, pNew);
  100386. if( pOrderBy ) pOrderBy->a[nOrderBy++].u.x.iOrderByCol = (u16)i;
  100387. }
  100388. }
  100389. }
  100390. /* Compute the comparison permutation and keyinfo that is used with
  100391. ** the permutation used to determine if the next
  100392. ** row of results comes from selectA or selectB. Also add explicit
  100393. ** collations to the ORDER BY clause terms so that when the subqueries
  100394. ** to the right and the left are evaluated, they use the correct
  100395. ** collation.
  100396. */
  100397. aPermute = sqlite3DbMallocRaw(db, sizeof(int)*nOrderBy);
  100398. if( aPermute ){
  100399. struct ExprList_item *pItem;
  100400. for(i=0, pItem=pOrderBy->a; i<nOrderBy; i++, pItem++){
  100401. assert( pItem->u.x.iOrderByCol>0
  100402. && pItem->u.x.iOrderByCol<=p->pEList->nExpr );
  100403. aPermute[i] = pItem->u.x.iOrderByCol - 1;
  100404. }
  100405. pKeyMerge = multiSelectOrderByKeyInfo(pParse, p, 1);
  100406. }else{
  100407. pKeyMerge = 0;
  100408. }
  100409. /* Reattach the ORDER BY clause to the query.
  100410. */
  100411. p->pOrderBy = pOrderBy;
  100412. pPrior->pOrderBy = sqlite3ExprListDup(pParse->db, pOrderBy, 0);
  100413. /* Allocate a range of temporary registers and the KeyInfo needed
  100414. ** for the logic that removes duplicate result rows when the
  100415. ** operator is UNION, EXCEPT, or INTERSECT (but not UNION ALL).
  100416. */
  100417. if( op==TK_ALL ){
  100418. regPrev = 0;
  100419. }else{
  100420. int nExpr = p->pEList->nExpr;
  100421. assert( nOrderBy>=nExpr || db->mallocFailed );
  100422. regPrev = pParse->nMem+1;
  100423. pParse->nMem += nExpr+1;
  100424. sqlite3VdbeAddOp2(v, OP_Integer, 0, regPrev);
  100425. pKeyDup = sqlite3KeyInfoAlloc(db, nExpr, 1);
  100426. if( pKeyDup ){
  100427. assert( sqlite3KeyInfoIsWriteable(pKeyDup) );
  100428. for(i=0; i<nExpr; i++){
  100429. pKeyDup->aColl[i] = multiSelectCollSeq(pParse, p, i);
  100430. pKeyDup->aSortOrder[i] = 0;
  100431. }
  100432. }
  100433. }
  100434. /* Separate the left and the right query from one another
  100435. */
  100436. p->pPrior = 0;
  100437. pPrior->pNext = 0;
  100438. sqlite3ResolveOrderGroupBy(pParse, p, p->pOrderBy, "ORDER");
  100439. if( pPrior->pPrior==0 ){
  100440. sqlite3ResolveOrderGroupBy(pParse, pPrior, pPrior->pOrderBy, "ORDER");
  100441. }
  100442. /* Compute the limit registers */
  100443. computeLimitRegisters(pParse, p, labelEnd);
  100444. if( p->iLimit && op==TK_ALL ){
  100445. regLimitA = ++pParse->nMem;
  100446. regLimitB = ++pParse->nMem;
  100447. sqlite3VdbeAddOp2(v, OP_Copy, p->iOffset ? p->iOffset+1 : p->iLimit,
  100448. regLimitA);
  100449. sqlite3VdbeAddOp2(v, OP_Copy, regLimitA, regLimitB);
  100450. }else{
  100451. regLimitA = regLimitB = 0;
  100452. }
  100453. sqlite3ExprDelete(db, p->pLimit);
  100454. p->pLimit = 0;
  100455. sqlite3ExprDelete(db, p->pOffset);
  100456. p->pOffset = 0;
  100457. regAddrA = ++pParse->nMem;
  100458. regAddrB = ++pParse->nMem;
  100459. regOutA = ++pParse->nMem;
  100460. regOutB = ++pParse->nMem;
  100461. sqlite3SelectDestInit(&destA, SRT_Coroutine, regAddrA);
  100462. sqlite3SelectDestInit(&destB, SRT_Coroutine, regAddrB);
  100463. /* Generate a coroutine to evaluate the SELECT statement to the
  100464. ** left of the compound operator - the "A" select.
  100465. */
  100466. addrSelectA = sqlite3VdbeCurrentAddr(v) + 1;
  100467. j1 = sqlite3VdbeAddOp3(v, OP_InitCoroutine, regAddrA, 0, addrSelectA);
  100468. VdbeComment((v, "left SELECT"));
  100469. pPrior->iLimit = regLimitA;
  100470. explainSetInteger(iSub1, pParse->iNextSelectId);
  100471. sqlite3Select(pParse, pPrior, &destA);
  100472. sqlite3VdbeAddOp1(v, OP_EndCoroutine, regAddrA);
  100473. sqlite3VdbeJumpHere(v, j1);
  100474. /* Generate a coroutine to evaluate the SELECT statement on
  100475. ** the right - the "B" select
  100476. */
  100477. addrSelectB = sqlite3VdbeCurrentAddr(v) + 1;
  100478. j1 = sqlite3VdbeAddOp3(v, OP_InitCoroutine, regAddrB, 0, addrSelectB);
  100479. VdbeComment((v, "right SELECT"));
  100480. savedLimit = p->iLimit;
  100481. savedOffset = p->iOffset;
  100482. p->iLimit = regLimitB;
  100483. p->iOffset = 0;
  100484. explainSetInteger(iSub2, pParse->iNextSelectId);
  100485. sqlite3Select(pParse, p, &destB);
  100486. p->iLimit = savedLimit;
  100487. p->iOffset = savedOffset;
  100488. sqlite3VdbeAddOp1(v, OP_EndCoroutine, regAddrB);
  100489. /* Generate a subroutine that outputs the current row of the A
  100490. ** select as the next output row of the compound select.
  100491. */
  100492. VdbeNoopComment((v, "Output routine for A"));
  100493. addrOutA = generateOutputSubroutine(pParse,
  100494. p, &destA, pDest, regOutA,
  100495. regPrev, pKeyDup, labelEnd);
  100496. /* Generate a subroutine that outputs the current row of the B
  100497. ** select as the next output row of the compound select.
  100498. */
  100499. if( op==TK_ALL || op==TK_UNION ){
  100500. VdbeNoopComment((v, "Output routine for B"));
  100501. addrOutB = generateOutputSubroutine(pParse,
  100502. p, &destB, pDest, regOutB,
  100503. regPrev, pKeyDup, labelEnd);
  100504. }
  100505. sqlite3KeyInfoUnref(pKeyDup);
  100506. /* Generate a subroutine to run when the results from select A
  100507. ** are exhausted and only data in select B remains.
  100508. */
  100509. if( op==TK_EXCEPT || op==TK_INTERSECT ){
  100510. addrEofA_noB = addrEofA = labelEnd;
  100511. }else{
  100512. VdbeNoopComment((v, "eof-A subroutine"));
  100513. addrEofA = sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
  100514. addrEofA_noB = sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, labelEnd);
  100515. VdbeCoverage(v);
  100516. sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofA);
  100517. p->nSelectRow += pPrior->nSelectRow;
  100518. }
  100519. /* Generate a subroutine to run when the results from select B
  100520. ** are exhausted and only data in select A remains.
  100521. */
  100522. if( op==TK_INTERSECT ){
  100523. addrEofB = addrEofA;
  100524. if( p->nSelectRow > pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
  100525. }else{
  100526. VdbeNoopComment((v, "eof-B subroutine"));
  100527. addrEofB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
  100528. sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, labelEnd); VdbeCoverage(v);
  100529. sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofB);
  100530. }
  100531. /* Generate code to handle the case of A<B
  100532. */
  100533. VdbeNoopComment((v, "A-lt-B subroutine"));
  100534. addrAltB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
  100535. sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA); VdbeCoverage(v);
  100536. sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
  100537. /* Generate code to handle the case of A==B
  100538. */
  100539. if( op==TK_ALL ){
  100540. addrAeqB = addrAltB;
  100541. }else if( op==TK_INTERSECT ){
  100542. addrAeqB = addrAltB;
  100543. addrAltB++;
  100544. }else{
  100545. VdbeNoopComment((v, "A-eq-B subroutine"));
  100546. addrAeqB =
  100547. sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA); VdbeCoverage(v);
  100548. sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
  100549. }
  100550. /* Generate code to handle the case of A>B
  100551. */
  100552. VdbeNoopComment((v, "A-gt-B subroutine"));
  100553. addrAgtB = sqlite3VdbeCurrentAddr(v);
  100554. if( op==TK_ALL || op==TK_UNION ){
  100555. sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
  100556. }
  100557. sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, addrEofB); VdbeCoverage(v);
  100558. sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
  100559. /* This code runs once to initialize everything.
  100560. */
  100561. sqlite3VdbeJumpHere(v, j1);
  100562. sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA_noB); VdbeCoverage(v);
  100563. sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, addrEofB); VdbeCoverage(v);
  100564. /* Implement the main merge loop
  100565. */
  100566. sqlite3VdbeResolveLabel(v, labelCmpr);
  100567. sqlite3VdbeAddOp4(v, OP_Permutation, 0, 0, 0, (char*)aPermute, P4_INTARRAY);
  100568. sqlite3VdbeAddOp4(v, OP_Compare, destA.iSdst, destB.iSdst, nOrderBy,
  100569. (char*)pKeyMerge, P4_KEYINFO);
  100570. sqlite3VdbeChangeP5(v, OPFLAG_PERMUTE);
  100571. sqlite3VdbeAddOp3(v, OP_Jump, addrAltB, addrAeqB, addrAgtB); VdbeCoverage(v);
  100572. /* Jump to the this point in order to terminate the query.
  100573. */
  100574. sqlite3VdbeResolveLabel(v, labelEnd);
  100575. /* Set the number of output columns
  100576. */
  100577. if( pDest->eDest==SRT_Output ){
  100578. Select *pFirst = pPrior;
  100579. while( pFirst->pPrior ) pFirst = pFirst->pPrior;
  100580. generateColumnNames(pParse, 0, pFirst->pEList);
  100581. }
  100582. /* Reassembly the compound query so that it will be freed correctly
  100583. ** by the calling function */
  100584. if( p->pPrior ){
  100585. sqlite3SelectDelete(db, p->pPrior);
  100586. }
  100587. p->pPrior = pPrior;
  100588. pPrior->pNext = p;
  100589. /*** TBD: Insert subroutine calls to close cursors on incomplete
  100590. **** subqueries ****/
  100591. explainComposite(pParse, p->op, iSub1, iSub2, 0);
  100592. return SQLITE_OK;
  100593. }
  100594. #endif
  100595. #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
  100596. /* Forward Declarations */
  100597. static void substExprList(sqlite3*, ExprList*, int, ExprList*);
  100598. static void substSelect(sqlite3*, Select *, int, ExprList *);
  100599. /*
  100600. ** Scan through the expression pExpr. Replace every reference to
  100601. ** a column in table number iTable with a copy of the iColumn-th
  100602. ** entry in pEList. (But leave references to the ROWID column
  100603. ** unchanged.)
  100604. **
  100605. ** This routine is part of the flattening procedure. A subquery
  100606. ** whose result set is defined by pEList appears as entry in the
  100607. ** FROM clause of a SELECT such that the VDBE cursor assigned to that
  100608. ** FORM clause entry is iTable. This routine make the necessary
  100609. ** changes to pExpr so that it refers directly to the source table
  100610. ** of the subquery rather the result set of the subquery.
  100611. */
  100612. static Expr *substExpr(
  100613. sqlite3 *db, /* Report malloc errors to this connection */
  100614. Expr *pExpr, /* Expr in which substitution occurs */
  100615. int iTable, /* Table to be substituted */
  100616. ExprList *pEList /* Substitute expressions */
  100617. ){
  100618. if( pExpr==0 ) return 0;
  100619. if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){
  100620. if( pExpr->iColumn<0 ){
  100621. pExpr->op = TK_NULL;
  100622. }else{
  100623. Expr *pNew;
  100624. assert( pEList!=0 && pExpr->iColumn<pEList->nExpr );
  100625. assert( pExpr->pLeft==0 && pExpr->pRight==0 );
  100626. pNew = sqlite3ExprDup(db, pEList->a[pExpr->iColumn].pExpr, 0);
  100627. sqlite3ExprDelete(db, pExpr);
  100628. pExpr = pNew;
  100629. }
  100630. }else{
  100631. pExpr->pLeft = substExpr(db, pExpr->pLeft, iTable, pEList);
  100632. pExpr->pRight = substExpr(db, pExpr->pRight, iTable, pEList);
  100633. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  100634. substSelect(db, pExpr->x.pSelect, iTable, pEList);
  100635. }else{
  100636. substExprList(db, pExpr->x.pList, iTable, pEList);
  100637. }
  100638. }
  100639. return pExpr;
  100640. }
  100641. static void substExprList(
  100642. sqlite3 *db, /* Report malloc errors here */
  100643. ExprList *pList, /* List to scan and in which to make substitutes */
  100644. int iTable, /* Table to be substituted */
  100645. ExprList *pEList /* Substitute values */
  100646. ){
  100647. int i;
  100648. if( pList==0 ) return;
  100649. for(i=0; i<pList->nExpr; i++){
  100650. pList->a[i].pExpr = substExpr(db, pList->a[i].pExpr, iTable, pEList);
  100651. }
  100652. }
  100653. static void substSelect(
  100654. sqlite3 *db, /* Report malloc errors here */
  100655. Select *p, /* SELECT statement in which to make substitutions */
  100656. int iTable, /* Table to be replaced */
  100657. ExprList *pEList /* Substitute values */
  100658. ){
  100659. SrcList *pSrc;
  100660. struct SrcList_item *pItem;
  100661. int i;
  100662. if( !p ) return;
  100663. substExprList(db, p->pEList, iTable, pEList);
  100664. substExprList(db, p->pGroupBy, iTable, pEList);
  100665. substExprList(db, p->pOrderBy, iTable, pEList);
  100666. p->pHaving = substExpr(db, p->pHaving, iTable, pEList);
  100667. p->pWhere = substExpr(db, p->pWhere, iTable, pEList);
  100668. substSelect(db, p->pPrior, iTable, pEList);
  100669. pSrc = p->pSrc;
  100670. assert( pSrc ); /* Even for (SELECT 1) we have: pSrc!=0 but pSrc->nSrc==0 */
  100671. if( ALWAYS(pSrc) ){
  100672. for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
  100673. substSelect(db, pItem->pSelect, iTable, pEList);
  100674. }
  100675. }
  100676. }
  100677. #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
  100678. #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
  100679. /*
  100680. ** This routine attempts to flatten subqueries as a performance optimization.
  100681. ** This routine returns 1 if it makes changes and 0 if no flattening occurs.
  100682. **
  100683. ** To understand the concept of flattening, consider the following
  100684. ** query:
  100685. **
  100686. ** SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
  100687. **
  100688. ** The default way of implementing this query is to execute the
  100689. ** subquery first and store the results in a temporary table, then
  100690. ** run the outer query on that temporary table. This requires two
  100691. ** passes over the data. Furthermore, because the temporary table
  100692. ** has no indices, the WHERE clause on the outer query cannot be
  100693. ** optimized.
  100694. **
  100695. ** This routine attempts to rewrite queries such as the above into
  100696. ** a single flat select, like this:
  100697. **
  100698. ** SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
  100699. **
  100700. ** The code generated for this simplification gives the same result
  100701. ** but only has to scan the data once. And because indices might
  100702. ** exist on the table t1, a complete scan of the data might be
  100703. ** avoided.
  100704. **
  100705. ** Flattening is only attempted if all of the following are true:
  100706. **
  100707. ** (1) The subquery and the outer query do not both use aggregates.
  100708. **
  100709. ** (2) The subquery is not an aggregate or the outer query is not a join.
  100710. **
  100711. ** (3) The subquery is not the right operand of a left outer join
  100712. ** (Originally ticket #306. Strengthened by ticket #3300)
  100713. **
  100714. ** (4) The subquery is not DISTINCT.
  100715. **
  100716. ** (**) At one point restrictions (4) and (5) defined a subset of DISTINCT
  100717. ** sub-queries that were excluded from this optimization. Restriction
  100718. ** (4) has since been expanded to exclude all DISTINCT subqueries.
  100719. **
  100720. ** (6) The subquery does not use aggregates or the outer query is not
  100721. ** DISTINCT.
  100722. **
  100723. ** (7) The subquery has a FROM clause. TODO: For subqueries without
  100724. ** A FROM clause, consider adding a FROM close with the special
  100725. ** table sqlite_once that consists of a single row containing a
  100726. ** single NULL.
  100727. **
  100728. ** (8) The subquery does not use LIMIT or the outer query is not a join.
  100729. **
  100730. ** (9) The subquery does not use LIMIT or the outer query does not use
  100731. ** aggregates.
  100732. **
  100733. ** (**) Restriction (10) was removed from the code on 2005-02-05 but we
  100734. ** accidently carried the comment forward until 2014-09-15. Original
  100735. ** text: "The subquery does not use aggregates or the outer query does not
  100736. ** use LIMIT."
  100737. **
  100738. ** (11) The subquery and the outer query do not both have ORDER BY clauses.
  100739. **
  100740. ** (**) Not implemented. Subsumed into restriction (3). Was previously
  100741. ** a separate restriction deriving from ticket #350.
  100742. **
  100743. ** (13) The subquery and outer query do not both use LIMIT.
  100744. **
  100745. ** (14) The subquery does not use OFFSET.
  100746. **
  100747. ** (15) The outer query is not part of a compound select or the
  100748. ** subquery does not have a LIMIT clause.
  100749. ** (See ticket #2339 and ticket [02a8e81d44]).
  100750. **
  100751. ** (16) The outer query is not an aggregate or the subquery does
  100752. ** not contain ORDER BY. (Ticket #2942) This used to not matter
  100753. ** until we introduced the group_concat() function.
  100754. **
  100755. ** (17) The sub-query is not a compound select, or it is a UNION ALL
  100756. ** compound clause made up entirely of non-aggregate queries, and
  100757. ** the parent query:
  100758. **
  100759. ** * is not itself part of a compound select,
  100760. ** * is not an aggregate or DISTINCT query, and
  100761. ** * is not a join
  100762. **
  100763. ** The parent and sub-query may contain WHERE clauses. Subject to
  100764. ** rules (11), (13) and (14), they may also contain ORDER BY,
  100765. ** LIMIT and OFFSET clauses. The subquery cannot use any compound
  100766. ** operator other than UNION ALL because all the other compound
  100767. ** operators have an implied DISTINCT which is disallowed by
  100768. ** restriction (4).
  100769. **
  100770. ** Also, each component of the sub-query must return the same number
  100771. ** of result columns. This is actually a requirement for any compound
  100772. ** SELECT statement, but all the code here does is make sure that no
  100773. ** such (illegal) sub-query is flattened. The caller will detect the
  100774. ** syntax error and return a detailed message.
  100775. **
  100776. ** (18) If the sub-query is a compound select, then all terms of the
  100777. ** ORDER by clause of the parent must be simple references to
  100778. ** columns of the sub-query.
  100779. **
  100780. ** (19) The subquery does not use LIMIT or the outer query does not
  100781. ** have a WHERE clause.
  100782. **
  100783. ** (20) If the sub-query is a compound select, then it must not use
  100784. ** an ORDER BY clause. Ticket #3773. We could relax this constraint
  100785. ** somewhat by saying that the terms of the ORDER BY clause must
  100786. ** appear as unmodified result columns in the outer query. But we
  100787. ** have other optimizations in mind to deal with that case.
  100788. **
  100789. ** (21) The subquery does not use LIMIT or the outer query is not
  100790. ** DISTINCT. (See ticket [752e1646fc]).
  100791. **
  100792. ** (22) The subquery is not a recursive CTE.
  100793. **
  100794. ** (23) The parent is not a recursive CTE, or the sub-query is not a
  100795. ** compound query. This restriction is because transforming the
  100796. ** parent to a compound query confuses the code that handles
  100797. ** recursive queries in multiSelect().
  100798. **
  100799. ** (24) The subquery is not an aggregate that uses the built-in min() or
  100800. ** or max() functions. (Without this restriction, a query like:
  100801. ** "SELECT x FROM (SELECT max(y), x FROM t1)" would not necessarily
  100802. ** return the value X for which Y was maximal.)
  100803. **
  100804. **
  100805. ** In this routine, the "p" parameter is a pointer to the outer query.
  100806. ** The subquery is p->pSrc->a[iFrom]. isAgg is true if the outer query
  100807. ** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates.
  100808. **
  100809. ** If flattening is not attempted, this routine is a no-op and returns 0.
  100810. ** If flattening is attempted this routine returns 1.
  100811. **
  100812. ** All of the expression analysis must occur on both the outer query and
  100813. ** the subquery before this routine runs.
  100814. */
  100815. static int flattenSubquery(
  100816. Parse *pParse, /* Parsing context */
  100817. Select *p, /* The parent or outer SELECT statement */
  100818. int iFrom, /* Index in p->pSrc->a[] of the inner subquery */
  100819. int isAgg, /* True if outer SELECT uses aggregate functions */
  100820. int subqueryIsAgg /* True if the subquery uses aggregate functions */
  100821. ){
  100822. const char *zSavedAuthContext = pParse->zAuthContext;
  100823. Select *pParent;
  100824. Select *pSub; /* The inner query or "subquery" */
  100825. Select *pSub1; /* Pointer to the rightmost select in sub-query */
  100826. SrcList *pSrc; /* The FROM clause of the outer query */
  100827. SrcList *pSubSrc; /* The FROM clause of the subquery */
  100828. ExprList *pList; /* The result set of the outer query */
  100829. int iParent; /* VDBE cursor number of the pSub result set temp table */
  100830. int i; /* Loop counter */
  100831. Expr *pWhere; /* The WHERE clause */
  100832. struct SrcList_item *pSubitem; /* The subquery */
  100833. sqlite3 *db = pParse->db;
  100834. /* Check to see if flattening is permitted. Return 0 if not.
  100835. */
  100836. assert( p!=0 );
  100837. assert( p->pPrior==0 ); /* Unable to flatten compound queries */
  100838. if( OptimizationDisabled(db, SQLITE_QueryFlattener) ) return 0;
  100839. pSrc = p->pSrc;
  100840. assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
  100841. pSubitem = &pSrc->a[iFrom];
  100842. iParent = pSubitem->iCursor;
  100843. pSub = pSubitem->pSelect;
  100844. assert( pSub!=0 );
  100845. if( isAgg && subqueryIsAgg ) return 0; /* Restriction (1) */
  100846. if( subqueryIsAgg && pSrc->nSrc>1 ) return 0; /* Restriction (2) */
  100847. pSubSrc = pSub->pSrc;
  100848. assert( pSubSrc );
  100849. /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants,
  100850. ** not arbitrary expressions, we allowed some combining of LIMIT and OFFSET
  100851. ** because they could be computed at compile-time. But when LIMIT and OFFSET
  100852. ** became arbitrary expressions, we were forced to add restrictions (13)
  100853. ** and (14). */
  100854. if( pSub->pLimit && p->pLimit ) return 0; /* Restriction (13) */
  100855. if( pSub->pOffset ) return 0; /* Restriction (14) */
  100856. if( (p->selFlags & SF_Compound)!=0 && pSub->pLimit ){
  100857. return 0; /* Restriction (15) */
  100858. }
  100859. if( pSubSrc->nSrc==0 ) return 0; /* Restriction (7) */
  100860. if( pSub->selFlags & SF_Distinct ) return 0; /* Restriction (5) */
  100861. if( pSub->pLimit && (pSrc->nSrc>1 || isAgg) ){
  100862. return 0; /* Restrictions (8)(9) */
  100863. }
  100864. if( (p->selFlags & SF_Distinct)!=0 && subqueryIsAgg ){
  100865. return 0; /* Restriction (6) */
  100866. }
  100867. if( p->pOrderBy && pSub->pOrderBy ){
  100868. return 0; /* Restriction (11) */
  100869. }
  100870. if( isAgg && pSub->pOrderBy ) return 0; /* Restriction (16) */
  100871. if( pSub->pLimit && p->pWhere ) return 0; /* Restriction (19) */
  100872. if( pSub->pLimit && (p->selFlags & SF_Distinct)!=0 ){
  100873. return 0; /* Restriction (21) */
  100874. }
  100875. testcase( pSub->selFlags & SF_Recursive );
  100876. testcase( pSub->selFlags & SF_MinMaxAgg );
  100877. if( pSub->selFlags & (SF_Recursive|SF_MinMaxAgg) ){
  100878. return 0; /* Restrictions (22) and (24) */
  100879. }
  100880. if( (p->selFlags & SF_Recursive) && pSub->pPrior ){
  100881. return 0; /* Restriction (23) */
  100882. }
  100883. /* OBSOLETE COMMENT 1:
  100884. ** Restriction 3: If the subquery is a join, make sure the subquery is
  100885. ** not used as the right operand of an outer join. Examples of why this
  100886. ** is not allowed:
  100887. **
  100888. ** t1 LEFT OUTER JOIN (t2 JOIN t3)
  100889. **
  100890. ** If we flatten the above, we would get
  100891. **
  100892. ** (t1 LEFT OUTER JOIN t2) JOIN t3
  100893. **
  100894. ** which is not at all the same thing.
  100895. **
  100896. ** OBSOLETE COMMENT 2:
  100897. ** Restriction 12: If the subquery is the right operand of a left outer
  100898. ** join, make sure the subquery has no WHERE clause.
  100899. ** An examples of why this is not allowed:
  100900. **
  100901. ** t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0)
  100902. **
  100903. ** If we flatten the above, we would get
  100904. **
  100905. ** (t1 LEFT OUTER JOIN t2) WHERE t2.x>0
  100906. **
  100907. ** But the t2.x>0 test will always fail on a NULL row of t2, which
  100908. ** effectively converts the OUTER JOIN into an INNER JOIN.
  100909. **
  100910. ** THIS OVERRIDES OBSOLETE COMMENTS 1 AND 2 ABOVE:
  100911. ** Ticket #3300 shows that flattening the right term of a LEFT JOIN
  100912. ** is fraught with danger. Best to avoid the whole thing. If the
  100913. ** subquery is the right term of a LEFT JOIN, then do not flatten.
  100914. */
  100915. if( (pSubitem->jointype & JT_OUTER)!=0 ){
  100916. return 0;
  100917. }
  100918. /* Restriction 17: If the sub-query is a compound SELECT, then it must
  100919. ** use only the UNION ALL operator. And none of the simple select queries
  100920. ** that make up the compound SELECT are allowed to be aggregate or distinct
  100921. ** queries.
  100922. */
  100923. if( pSub->pPrior ){
  100924. if( pSub->pOrderBy ){
  100925. return 0; /* Restriction 20 */
  100926. }
  100927. if( isAgg || (p->selFlags & SF_Distinct)!=0 || pSrc->nSrc!=1 ){
  100928. return 0;
  100929. }
  100930. for(pSub1=pSub; pSub1; pSub1=pSub1->pPrior){
  100931. testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
  100932. testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
  100933. assert( pSub->pSrc!=0 );
  100934. if( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))!=0
  100935. || (pSub1->pPrior && pSub1->op!=TK_ALL)
  100936. || pSub1->pSrc->nSrc<1
  100937. || pSub->pEList->nExpr!=pSub1->pEList->nExpr
  100938. ){
  100939. return 0;
  100940. }
  100941. testcase( pSub1->pSrc->nSrc>1 );
  100942. }
  100943. /* Restriction 18. */
  100944. if( p->pOrderBy ){
  100945. int ii;
  100946. for(ii=0; ii<p->pOrderBy->nExpr; ii++){
  100947. if( p->pOrderBy->a[ii].u.x.iOrderByCol==0 ) return 0;
  100948. }
  100949. }
  100950. }
  100951. /***** If we reach this point, flattening is permitted. *****/
  100952. SELECTTRACE(1,pParse,p,("flatten %s.%p from term %d\n",
  100953. pSub->zSelName, pSub, iFrom));
  100954. /* Authorize the subquery */
  100955. pParse->zAuthContext = pSubitem->zName;
  100956. TESTONLY(i =) sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0);
  100957. testcase( i==SQLITE_DENY );
  100958. pParse->zAuthContext = zSavedAuthContext;
  100959. /* If the sub-query is a compound SELECT statement, then (by restrictions
  100960. ** 17 and 18 above) it must be a UNION ALL and the parent query must
  100961. ** be of the form:
  100962. **
  100963. ** SELECT <expr-list> FROM (<sub-query>) <where-clause>
  100964. **
  100965. ** followed by any ORDER BY, LIMIT and/or OFFSET clauses. This block
  100966. ** creates N-1 copies of the parent query without any ORDER BY, LIMIT or
  100967. ** OFFSET clauses and joins them to the left-hand-side of the original
  100968. ** using UNION ALL operators. In this case N is the number of simple
  100969. ** select statements in the compound sub-query.
  100970. **
  100971. ** Example:
  100972. **
  100973. ** SELECT a+1 FROM (
  100974. ** SELECT x FROM tab
  100975. ** UNION ALL
  100976. ** SELECT y FROM tab
  100977. ** UNION ALL
  100978. ** SELECT abs(z*2) FROM tab2
  100979. ** ) WHERE a!=5 ORDER BY 1
  100980. **
  100981. ** Transformed into:
  100982. **
  100983. ** SELECT x+1 FROM tab WHERE x+1!=5
  100984. ** UNION ALL
  100985. ** SELECT y+1 FROM tab WHERE y+1!=5
  100986. ** UNION ALL
  100987. ** SELECT abs(z*2)+1 FROM tab2 WHERE abs(z*2)+1!=5
  100988. ** ORDER BY 1
  100989. **
  100990. ** We call this the "compound-subquery flattening".
  100991. */
  100992. for(pSub=pSub->pPrior; pSub; pSub=pSub->pPrior){
  100993. Select *pNew;
  100994. ExprList *pOrderBy = p->pOrderBy;
  100995. Expr *pLimit = p->pLimit;
  100996. Expr *pOffset = p->pOffset;
  100997. Select *pPrior = p->pPrior;
  100998. p->pOrderBy = 0;
  100999. p->pSrc = 0;
  101000. p->pPrior = 0;
  101001. p->pLimit = 0;
  101002. p->pOffset = 0;
  101003. pNew = sqlite3SelectDup(db, p, 0);
  101004. sqlite3SelectSetName(pNew, pSub->zSelName);
  101005. p->pOffset = pOffset;
  101006. p->pLimit = pLimit;
  101007. p->pOrderBy = pOrderBy;
  101008. p->pSrc = pSrc;
  101009. p->op = TK_ALL;
  101010. if( pNew==0 ){
  101011. p->pPrior = pPrior;
  101012. }else{
  101013. pNew->pPrior = pPrior;
  101014. if( pPrior ) pPrior->pNext = pNew;
  101015. pNew->pNext = p;
  101016. p->pPrior = pNew;
  101017. SELECTTRACE(2,pParse,p,
  101018. ("compound-subquery flattener creates %s.%p as peer\n",
  101019. pNew->zSelName, pNew));
  101020. }
  101021. if( db->mallocFailed ) return 1;
  101022. }
  101023. /* Begin flattening the iFrom-th entry of the FROM clause
  101024. ** in the outer query.
  101025. */
  101026. pSub = pSub1 = pSubitem->pSelect;
  101027. /* Delete the transient table structure associated with the
  101028. ** subquery
  101029. */
  101030. sqlite3DbFree(db, pSubitem->zDatabase);
  101031. sqlite3DbFree(db, pSubitem->zName);
  101032. sqlite3DbFree(db, pSubitem->zAlias);
  101033. pSubitem->zDatabase = 0;
  101034. pSubitem->zName = 0;
  101035. pSubitem->zAlias = 0;
  101036. pSubitem->pSelect = 0;
  101037. /* Defer deleting the Table object associated with the
  101038. ** subquery until code generation is
  101039. ** complete, since there may still exist Expr.pTab entries that
  101040. ** refer to the subquery even after flattening. Ticket #3346.
  101041. **
  101042. ** pSubitem->pTab is always non-NULL by test restrictions and tests above.
  101043. */
  101044. if( ALWAYS(pSubitem->pTab!=0) ){
  101045. Table *pTabToDel = pSubitem->pTab;
  101046. if( pTabToDel->nRef==1 ){
  101047. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  101048. pTabToDel->pNextZombie = pToplevel->pZombieTab;
  101049. pToplevel->pZombieTab = pTabToDel;
  101050. }else{
  101051. pTabToDel->nRef--;
  101052. }
  101053. pSubitem->pTab = 0;
  101054. }
  101055. /* The following loop runs once for each term in a compound-subquery
  101056. ** flattening (as described above). If we are doing a different kind
  101057. ** of flattening - a flattening other than a compound-subquery flattening -
  101058. ** then this loop only runs once.
  101059. **
  101060. ** This loop moves all of the FROM elements of the subquery into the
  101061. ** the FROM clause of the outer query. Before doing this, remember
  101062. ** the cursor number for the original outer query FROM element in
  101063. ** iParent. The iParent cursor will never be used. Subsequent code
  101064. ** will scan expressions looking for iParent references and replace
  101065. ** those references with expressions that resolve to the subquery FROM
  101066. ** elements we are now copying in.
  101067. */
  101068. for(pParent=p; pParent; pParent=pParent->pPrior, pSub=pSub->pPrior){
  101069. int nSubSrc;
  101070. u8 jointype = 0;
  101071. pSubSrc = pSub->pSrc; /* FROM clause of subquery */
  101072. nSubSrc = pSubSrc->nSrc; /* Number of terms in subquery FROM clause */
  101073. pSrc = pParent->pSrc; /* FROM clause of the outer query */
  101074. if( pSrc ){
  101075. assert( pParent==p ); /* First time through the loop */
  101076. jointype = pSubitem->jointype;
  101077. }else{
  101078. assert( pParent!=p ); /* 2nd and subsequent times through the loop */
  101079. pSrc = pParent->pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
  101080. if( pSrc==0 ){
  101081. assert( db->mallocFailed );
  101082. break;
  101083. }
  101084. }
  101085. /* The subquery uses a single slot of the FROM clause of the outer
  101086. ** query. If the subquery has more than one element in its FROM clause,
  101087. ** then expand the outer query to make space for it to hold all elements
  101088. ** of the subquery.
  101089. **
  101090. ** Example:
  101091. **
  101092. ** SELECT * FROM tabA, (SELECT * FROM sub1, sub2), tabB;
  101093. **
  101094. ** The outer query has 3 slots in its FROM clause. One slot of the
  101095. ** outer query (the middle slot) is used by the subquery. The next
  101096. ** block of code will expand the out query to 4 slots. The middle
  101097. ** slot is expanded to two slots in order to make space for the
  101098. ** two elements in the FROM clause of the subquery.
  101099. */
  101100. if( nSubSrc>1 ){
  101101. pParent->pSrc = pSrc = sqlite3SrcListEnlarge(db, pSrc, nSubSrc-1,iFrom+1);
  101102. if( db->mallocFailed ){
  101103. break;
  101104. }
  101105. }
  101106. /* Transfer the FROM clause terms from the subquery into the
  101107. ** outer query.
  101108. */
  101109. for(i=0; i<nSubSrc; i++){
  101110. sqlite3IdListDelete(db, pSrc->a[i+iFrom].pUsing);
  101111. pSrc->a[i+iFrom] = pSubSrc->a[i];
  101112. memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
  101113. }
  101114. pSrc->a[iFrom].jointype = jointype;
  101115. /* Now begin substituting subquery result set expressions for
  101116. ** references to the iParent in the outer query.
  101117. **
  101118. ** Example:
  101119. **
  101120. ** SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
  101121. ** \ \_____________ subquery __________/ /
  101122. ** \_____________________ outer query ______________________________/
  101123. **
  101124. ** We look at every expression in the outer query and every place we see
  101125. ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
  101126. */
  101127. pList = pParent->pEList;
  101128. for(i=0; i<pList->nExpr; i++){
  101129. if( pList->a[i].zName==0 ){
  101130. char *zName = sqlite3DbStrDup(db, pList->a[i].zSpan);
  101131. sqlite3Dequote(zName);
  101132. pList->a[i].zName = zName;
  101133. }
  101134. }
  101135. substExprList(db, pParent->pEList, iParent, pSub->pEList);
  101136. if( isAgg ){
  101137. substExprList(db, pParent->pGroupBy, iParent, pSub->pEList);
  101138. pParent->pHaving = substExpr(db, pParent->pHaving, iParent, pSub->pEList);
  101139. }
  101140. if( pSub->pOrderBy ){
  101141. /* At this point, any non-zero iOrderByCol values indicate that the
  101142. ** ORDER BY column expression is identical to the iOrderByCol'th
  101143. ** expression returned by SELECT statement pSub. Since these values
  101144. ** do not necessarily correspond to columns in SELECT statement pParent,
  101145. ** zero them before transfering the ORDER BY clause.
  101146. **
  101147. ** Not doing this may cause an error if a subsequent call to this
  101148. ** function attempts to flatten a compound sub-query into pParent
  101149. ** (the only way this can happen is if the compound sub-query is
  101150. ** currently part of pSub->pSrc). See ticket [d11a6e908f]. */
  101151. ExprList *pOrderBy = pSub->pOrderBy;
  101152. for(i=0; i<pOrderBy->nExpr; i++){
  101153. pOrderBy->a[i].u.x.iOrderByCol = 0;
  101154. }
  101155. assert( pParent->pOrderBy==0 );
  101156. assert( pSub->pPrior==0 );
  101157. pParent->pOrderBy = pOrderBy;
  101158. pSub->pOrderBy = 0;
  101159. }else if( pParent->pOrderBy ){
  101160. substExprList(db, pParent->pOrderBy, iParent, pSub->pEList);
  101161. }
  101162. if( pSub->pWhere ){
  101163. pWhere = sqlite3ExprDup(db, pSub->pWhere, 0);
  101164. }else{
  101165. pWhere = 0;
  101166. }
  101167. if( subqueryIsAgg ){
  101168. assert( pParent->pHaving==0 );
  101169. pParent->pHaving = pParent->pWhere;
  101170. pParent->pWhere = pWhere;
  101171. pParent->pHaving = substExpr(db, pParent->pHaving, iParent, pSub->pEList);
  101172. pParent->pHaving = sqlite3ExprAnd(db, pParent->pHaving,
  101173. sqlite3ExprDup(db, pSub->pHaving, 0));
  101174. assert( pParent->pGroupBy==0 );
  101175. pParent->pGroupBy = sqlite3ExprListDup(db, pSub->pGroupBy, 0);
  101176. }else{
  101177. pParent->pWhere = substExpr(db, pParent->pWhere, iParent, pSub->pEList);
  101178. pParent->pWhere = sqlite3ExprAnd(db, pParent->pWhere, pWhere);
  101179. }
  101180. /* The flattened query is distinct if either the inner or the
  101181. ** outer query is distinct.
  101182. */
  101183. pParent->selFlags |= pSub->selFlags & SF_Distinct;
  101184. /*
  101185. ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y;
  101186. **
  101187. ** One is tempted to try to add a and b to combine the limits. But this
  101188. ** does not work if either limit is negative.
  101189. */
  101190. if( pSub->pLimit ){
  101191. pParent->pLimit = pSub->pLimit;
  101192. pSub->pLimit = 0;
  101193. }
  101194. }
  101195. /* Finially, delete what is left of the subquery and return
  101196. ** success.
  101197. */
  101198. sqlite3SelectDelete(db, pSub1);
  101199. #if SELECTTRACE_ENABLED
  101200. if( sqlite3SelectTrace & 0x100 ){
  101201. sqlite3DebugPrintf("After flattening:\n");
  101202. sqlite3TreeViewSelect(0, p, 0);
  101203. }
  101204. #endif
  101205. return 1;
  101206. }
  101207. #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
  101208. /*
  101209. ** Based on the contents of the AggInfo structure indicated by the first
  101210. ** argument, this function checks if the following are true:
  101211. **
  101212. ** * the query contains just a single aggregate function,
  101213. ** * the aggregate function is either min() or max(), and
  101214. ** * the argument to the aggregate function is a column value.
  101215. **
  101216. ** If all of the above are true, then WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX
  101217. ** is returned as appropriate. Also, *ppMinMax is set to point to the
  101218. ** list of arguments passed to the aggregate before returning.
  101219. **
  101220. ** Or, if the conditions above are not met, *ppMinMax is set to 0 and
  101221. ** WHERE_ORDERBY_NORMAL is returned.
  101222. */
  101223. static u8 minMaxQuery(AggInfo *pAggInfo, ExprList **ppMinMax){
  101224. int eRet = WHERE_ORDERBY_NORMAL; /* Return value */
  101225. *ppMinMax = 0;
  101226. if( pAggInfo->nFunc==1 ){
  101227. Expr *pExpr = pAggInfo->aFunc[0].pExpr; /* Aggregate function */
  101228. ExprList *pEList = pExpr->x.pList; /* Arguments to agg function */
  101229. assert( pExpr->op==TK_AGG_FUNCTION );
  101230. if( pEList && pEList->nExpr==1 && pEList->a[0].pExpr->op==TK_AGG_COLUMN ){
  101231. const char *zFunc = pExpr->u.zToken;
  101232. if( sqlite3StrICmp(zFunc, "min")==0 ){
  101233. eRet = WHERE_ORDERBY_MIN;
  101234. *ppMinMax = pEList;
  101235. }else if( sqlite3StrICmp(zFunc, "max")==0 ){
  101236. eRet = WHERE_ORDERBY_MAX;
  101237. *ppMinMax = pEList;
  101238. }
  101239. }
  101240. }
  101241. assert( *ppMinMax==0 || (*ppMinMax)->nExpr==1 );
  101242. return eRet;
  101243. }
  101244. /*
  101245. ** The select statement passed as the first argument is an aggregate query.
  101246. ** The second argument is the associated aggregate-info object. This
  101247. ** function tests if the SELECT is of the form:
  101248. **
  101249. ** SELECT count(*) FROM <tbl>
  101250. **
  101251. ** where table is a database table, not a sub-select or view. If the query
  101252. ** does match this pattern, then a pointer to the Table object representing
  101253. ** <tbl> is returned. Otherwise, 0 is returned.
  101254. */
  101255. static Table *isSimpleCount(Select *p, AggInfo *pAggInfo){
  101256. Table *pTab;
  101257. Expr *pExpr;
  101258. assert( !p->pGroupBy );
  101259. if( p->pWhere || p->pEList->nExpr!=1
  101260. || p->pSrc->nSrc!=1 || p->pSrc->a[0].pSelect
  101261. ){
  101262. return 0;
  101263. }
  101264. pTab = p->pSrc->a[0].pTab;
  101265. pExpr = p->pEList->a[0].pExpr;
  101266. assert( pTab && !pTab->pSelect && pExpr );
  101267. if( IsVirtual(pTab) ) return 0;
  101268. if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
  101269. if( NEVER(pAggInfo->nFunc==0) ) return 0;
  101270. if( (pAggInfo->aFunc[0].pFunc->funcFlags&SQLITE_FUNC_COUNT)==0 ) return 0;
  101271. if( pExpr->flags&EP_Distinct ) return 0;
  101272. return pTab;
  101273. }
  101274. /*
  101275. ** If the source-list item passed as an argument was augmented with an
  101276. ** INDEXED BY clause, then try to locate the specified index. If there
  101277. ** was such a clause and the named index cannot be found, return
  101278. ** SQLITE_ERROR and leave an error in pParse. Otherwise, populate
  101279. ** pFrom->pIndex and return SQLITE_OK.
  101280. */
  101281. SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *pParse, struct SrcList_item *pFrom){
  101282. if( pFrom->pTab && pFrom->zIndex ){
  101283. Table *pTab = pFrom->pTab;
  101284. char *zIndex = pFrom->zIndex;
  101285. Index *pIdx;
  101286. for(pIdx=pTab->pIndex;
  101287. pIdx && sqlite3StrICmp(pIdx->zName, zIndex);
  101288. pIdx=pIdx->pNext
  101289. );
  101290. if( !pIdx ){
  101291. sqlite3ErrorMsg(pParse, "no such index: %s", zIndex, 0);
  101292. pParse->checkSchema = 1;
  101293. return SQLITE_ERROR;
  101294. }
  101295. pFrom->pIndex = pIdx;
  101296. }
  101297. return SQLITE_OK;
  101298. }
  101299. /*
  101300. ** Detect compound SELECT statements that use an ORDER BY clause with
  101301. ** an alternative collating sequence.
  101302. **
  101303. ** SELECT ... FROM t1 EXCEPT SELECT ... FROM t2 ORDER BY .. COLLATE ...
  101304. **
  101305. ** These are rewritten as a subquery:
  101306. **
  101307. ** SELECT * FROM (SELECT ... FROM t1 EXCEPT SELECT ... FROM t2)
  101308. ** ORDER BY ... COLLATE ...
  101309. **
  101310. ** This transformation is necessary because the multiSelectOrderBy() routine
  101311. ** above that generates the code for a compound SELECT with an ORDER BY clause
  101312. ** uses a merge algorithm that requires the same collating sequence on the
  101313. ** result columns as on the ORDER BY clause. See ticket
  101314. ** http://www.sqlite.org/src/info/6709574d2a
  101315. **
  101316. ** This transformation is only needed for EXCEPT, INTERSECT, and UNION.
  101317. ** The UNION ALL operator works fine with multiSelectOrderBy() even when
  101318. ** there are COLLATE terms in the ORDER BY.
  101319. */
  101320. static int convertCompoundSelectToSubquery(Walker *pWalker, Select *p){
  101321. int i;
  101322. Select *pNew;
  101323. Select *pX;
  101324. sqlite3 *db;
  101325. struct ExprList_item *a;
  101326. SrcList *pNewSrc;
  101327. Parse *pParse;
  101328. Token dummy;
  101329. if( p->pPrior==0 ) return WRC_Continue;
  101330. if( p->pOrderBy==0 ) return WRC_Continue;
  101331. for(pX=p; pX && (pX->op==TK_ALL || pX->op==TK_SELECT); pX=pX->pPrior){}
  101332. if( pX==0 ) return WRC_Continue;
  101333. a = p->pOrderBy->a;
  101334. for(i=p->pOrderBy->nExpr-1; i>=0; i--){
  101335. if( a[i].pExpr->flags & EP_Collate ) break;
  101336. }
  101337. if( i<0 ) return WRC_Continue;
  101338. /* If we reach this point, that means the transformation is required. */
  101339. pParse = pWalker->pParse;
  101340. db = pParse->db;
  101341. pNew = sqlite3DbMallocZero(db, sizeof(*pNew) );
  101342. if( pNew==0 ) return WRC_Abort;
  101343. memset(&dummy, 0, sizeof(dummy));
  101344. pNewSrc = sqlite3SrcListAppendFromTerm(pParse,0,0,0,&dummy,pNew,0,0);
  101345. if( pNewSrc==0 ) return WRC_Abort;
  101346. *pNew = *p;
  101347. p->pSrc = pNewSrc;
  101348. p->pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ALL, 0));
  101349. p->op = TK_SELECT;
  101350. p->pWhere = 0;
  101351. pNew->pGroupBy = 0;
  101352. pNew->pHaving = 0;
  101353. pNew->pOrderBy = 0;
  101354. p->pPrior = 0;
  101355. p->pNext = 0;
  101356. p->selFlags &= ~SF_Compound;
  101357. assert( pNew->pPrior!=0 );
  101358. pNew->pPrior->pNext = pNew;
  101359. pNew->pLimit = 0;
  101360. pNew->pOffset = 0;
  101361. return WRC_Continue;
  101362. }
  101363. #ifndef SQLITE_OMIT_CTE
  101364. /*
  101365. ** Argument pWith (which may be NULL) points to a linked list of nested
  101366. ** WITH contexts, from inner to outermost. If the table identified by
  101367. ** FROM clause element pItem is really a common-table-expression (CTE)
  101368. ** then return a pointer to the CTE definition for that table. Otherwise
  101369. ** return NULL.
  101370. **
  101371. ** If a non-NULL value is returned, set *ppContext to point to the With
  101372. ** object that the returned CTE belongs to.
  101373. */
  101374. static struct Cte *searchWith(
  101375. With *pWith, /* Current outermost WITH clause */
  101376. struct SrcList_item *pItem, /* FROM clause element to resolve */
  101377. With **ppContext /* OUT: WITH clause return value belongs to */
  101378. ){
  101379. const char *zName;
  101380. if( pItem->zDatabase==0 && (zName = pItem->zName)!=0 ){
  101381. With *p;
  101382. for(p=pWith; p; p=p->pOuter){
  101383. int i;
  101384. for(i=0; i<p->nCte; i++){
  101385. if( sqlite3StrICmp(zName, p->a[i].zName)==0 ){
  101386. *ppContext = p;
  101387. return &p->a[i];
  101388. }
  101389. }
  101390. }
  101391. }
  101392. return 0;
  101393. }
  101394. /* The code generator maintains a stack of active WITH clauses
  101395. ** with the inner-most WITH clause being at the top of the stack.
  101396. **
  101397. ** This routine pushes the WITH clause passed as the second argument
  101398. ** onto the top of the stack. If argument bFree is true, then this
  101399. ** WITH clause will never be popped from the stack. In this case it
  101400. ** should be freed along with the Parse object. In other cases, when
  101401. ** bFree==0, the With object will be freed along with the SELECT
  101402. ** statement with which it is associated.
  101403. */
  101404. SQLITE_PRIVATE void sqlite3WithPush(Parse *pParse, With *pWith, u8 bFree){
  101405. assert( bFree==0 || pParse->pWith==0 );
  101406. if( pWith ){
  101407. pWith->pOuter = pParse->pWith;
  101408. pParse->pWith = pWith;
  101409. pParse->bFreeWith = bFree;
  101410. }
  101411. }
  101412. /*
  101413. ** This function checks if argument pFrom refers to a CTE declared by
  101414. ** a WITH clause on the stack currently maintained by the parser. And,
  101415. ** if currently processing a CTE expression, if it is a recursive
  101416. ** reference to the current CTE.
  101417. **
  101418. ** If pFrom falls into either of the two categories above, pFrom->pTab
  101419. ** and other fields are populated accordingly. The caller should check
  101420. ** (pFrom->pTab!=0) to determine whether or not a successful match
  101421. ** was found.
  101422. **
  101423. ** Whether or not a match is found, SQLITE_OK is returned if no error
  101424. ** occurs. If an error does occur, an error message is stored in the
  101425. ** parser and some error code other than SQLITE_OK returned.
  101426. */
  101427. static int withExpand(
  101428. Walker *pWalker,
  101429. struct SrcList_item *pFrom
  101430. ){
  101431. Parse *pParse = pWalker->pParse;
  101432. sqlite3 *db = pParse->db;
  101433. struct Cte *pCte; /* Matched CTE (or NULL if no match) */
  101434. With *pWith; /* WITH clause that pCte belongs to */
  101435. assert( pFrom->pTab==0 );
  101436. pCte = searchWith(pParse->pWith, pFrom, &pWith);
  101437. if( pCte ){
  101438. Table *pTab;
  101439. ExprList *pEList;
  101440. Select *pSel;
  101441. Select *pLeft; /* Left-most SELECT statement */
  101442. int bMayRecursive; /* True if compound joined by UNION [ALL] */
  101443. With *pSavedWith; /* Initial value of pParse->pWith */
  101444. /* If pCte->zErr is non-NULL at this point, then this is an illegal
  101445. ** recursive reference to CTE pCte. Leave an error in pParse and return
  101446. ** early. If pCte->zErr is NULL, then this is not a recursive reference.
  101447. ** In this case, proceed. */
  101448. if( pCte->zErr ){
  101449. sqlite3ErrorMsg(pParse, pCte->zErr, pCte->zName);
  101450. return SQLITE_ERROR;
  101451. }
  101452. assert( pFrom->pTab==0 );
  101453. pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table));
  101454. if( pTab==0 ) return WRC_Abort;
  101455. pTab->nRef = 1;
  101456. pTab->zName = sqlite3DbStrDup(db, pCte->zName);
  101457. pTab->iPKey = -1;
  101458. pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
  101459. pTab->tabFlags |= TF_Ephemeral;
  101460. pFrom->pSelect = sqlite3SelectDup(db, pCte->pSelect, 0);
  101461. if( db->mallocFailed ) return SQLITE_NOMEM;
  101462. assert( pFrom->pSelect );
  101463. /* Check if this is a recursive CTE. */
  101464. pSel = pFrom->pSelect;
  101465. bMayRecursive = ( pSel->op==TK_ALL || pSel->op==TK_UNION );
  101466. if( bMayRecursive ){
  101467. int i;
  101468. SrcList *pSrc = pFrom->pSelect->pSrc;
  101469. for(i=0; i<pSrc->nSrc; i++){
  101470. struct SrcList_item *pItem = &pSrc->a[i];
  101471. if( pItem->zDatabase==0
  101472. && pItem->zName!=0
  101473. && 0==sqlite3StrICmp(pItem->zName, pCte->zName)
  101474. ){
  101475. pItem->pTab = pTab;
  101476. pItem->isRecursive = 1;
  101477. pTab->nRef++;
  101478. pSel->selFlags |= SF_Recursive;
  101479. }
  101480. }
  101481. }
  101482. /* Only one recursive reference is permitted. */
  101483. if( pTab->nRef>2 ){
  101484. sqlite3ErrorMsg(
  101485. pParse, "multiple references to recursive table: %s", pCte->zName
  101486. );
  101487. return SQLITE_ERROR;
  101488. }
  101489. assert( pTab->nRef==1 || ((pSel->selFlags&SF_Recursive) && pTab->nRef==2 ));
  101490. pCte->zErr = "circular reference: %s";
  101491. pSavedWith = pParse->pWith;
  101492. pParse->pWith = pWith;
  101493. sqlite3WalkSelect(pWalker, bMayRecursive ? pSel->pPrior : pSel);
  101494. for(pLeft=pSel; pLeft->pPrior; pLeft=pLeft->pPrior);
  101495. pEList = pLeft->pEList;
  101496. if( pCte->pCols ){
  101497. if( pEList->nExpr!=pCte->pCols->nExpr ){
  101498. sqlite3ErrorMsg(pParse, "table %s has %d values for %d columns",
  101499. pCte->zName, pEList->nExpr, pCte->pCols->nExpr
  101500. );
  101501. pParse->pWith = pSavedWith;
  101502. return SQLITE_ERROR;
  101503. }
  101504. pEList = pCte->pCols;
  101505. }
  101506. selectColumnsFromExprList(pParse, pEList, &pTab->nCol, &pTab->aCol);
  101507. if( bMayRecursive ){
  101508. if( pSel->selFlags & SF_Recursive ){
  101509. pCte->zErr = "multiple recursive references: %s";
  101510. }else{
  101511. pCte->zErr = "recursive reference in a subquery: %s";
  101512. }
  101513. sqlite3WalkSelect(pWalker, pSel);
  101514. }
  101515. pCte->zErr = 0;
  101516. pParse->pWith = pSavedWith;
  101517. }
  101518. return SQLITE_OK;
  101519. }
  101520. #endif
  101521. #ifndef SQLITE_OMIT_CTE
  101522. /*
  101523. ** If the SELECT passed as the second argument has an associated WITH
  101524. ** clause, pop it from the stack stored as part of the Parse object.
  101525. **
  101526. ** This function is used as the xSelectCallback2() callback by
  101527. ** sqlite3SelectExpand() when walking a SELECT tree to resolve table
  101528. ** names and other FROM clause elements.
  101529. */
  101530. static void selectPopWith(Walker *pWalker, Select *p){
  101531. Parse *pParse = pWalker->pParse;
  101532. With *pWith = findRightmost(p)->pWith;
  101533. if( pWith!=0 ){
  101534. assert( pParse->pWith==pWith );
  101535. pParse->pWith = pWith->pOuter;
  101536. }
  101537. }
  101538. #else
  101539. #define selectPopWith 0
  101540. #endif
  101541. /*
  101542. ** This routine is a Walker callback for "expanding" a SELECT statement.
  101543. ** "Expanding" means to do the following:
  101544. **
  101545. ** (1) Make sure VDBE cursor numbers have been assigned to every
  101546. ** element of the FROM clause.
  101547. **
  101548. ** (2) Fill in the pTabList->a[].pTab fields in the SrcList that
  101549. ** defines FROM clause. When views appear in the FROM clause,
  101550. ** fill pTabList->a[].pSelect with a copy of the SELECT statement
  101551. ** that implements the view. A copy is made of the view's SELECT
  101552. ** statement so that we can freely modify or delete that statement
  101553. ** without worrying about messing up the persistent representation
  101554. ** of the view.
  101555. **
  101556. ** (3) Add terms to the WHERE clause to accommodate the NATURAL keyword
  101557. ** on joins and the ON and USING clause of joins.
  101558. **
  101559. ** (4) Scan the list of columns in the result set (pEList) looking
  101560. ** for instances of the "*" operator or the TABLE.* operator.
  101561. ** If found, expand each "*" to be every column in every table
  101562. ** and TABLE.* to be every column in TABLE.
  101563. **
  101564. */
  101565. static int selectExpander(Walker *pWalker, Select *p){
  101566. Parse *pParse = pWalker->pParse;
  101567. int i, j, k;
  101568. SrcList *pTabList;
  101569. ExprList *pEList;
  101570. struct SrcList_item *pFrom;
  101571. sqlite3 *db = pParse->db;
  101572. Expr *pE, *pRight, *pExpr;
  101573. u16 selFlags = p->selFlags;
  101574. p->selFlags |= SF_Expanded;
  101575. if( db->mallocFailed ){
  101576. return WRC_Abort;
  101577. }
  101578. if( NEVER(p->pSrc==0) || (selFlags & SF_Expanded)!=0 ){
  101579. return WRC_Prune;
  101580. }
  101581. pTabList = p->pSrc;
  101582. pEList = p->pEList;
  101583. sqlite3WithPush(pParse, findRightmost(p)->pWith, 0);
  101584. /* Make sure cursor numbers have been assigned to all entries in
  101585. ** the FROM clause of the SELECT statement.
  101586. */
  101587. sqlite3SrcListAssignCursors(pParse, pTabList);
  101588. /* Look up every table named in the FROM clause of the select. If
  101589. ** an entry of the FROM clause is a subquery instead of a table or view,
  101590. ** then create a transient table structure to describe the subquery.
  101591. */
  101592. for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
  101593. Table *pTab;
  101594. assert( pFrom->isRecursive==0 || pFrom->pTab );
  101595. if( pFrom->isRecursive ) continue;
  101596. if( pFrom->pTab!=0 ){
  101597. /* This statement has already been prepared. There is no need
  101598. ** to go further. */
  101599. assert( i==0 );
  101600. #ifndef SQLITE_OMIT_CTE
  101601. selectPopWith(pWalker, p);
  101602. #endif
  101603. return WRC_Prune;
  101604. }
  101605. #ifndef SQLITE_OMIT_CTE
  101606. if( withExpand(pWalker, pFrom) ) return WRC_Abort;
  101607. if( pFrom->pTab ) {} else
  101608. #endif
  101609. if( pFrom->zName==0 ){
  101610. #ifndef SQLITE_OMIT_SUBQUERY
  101611. Select *pSel = pFrom->pSelect;
  101612. /* A sub-query in the FROM clause of a SELECT */
  101613. assert( pSel!=0 );
  101614. assert( pFrom->pTab==0 );
  101615. sqlite3WalkSelect(pWalker, pSel);
  101616. pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table));
  101617. if( pTab==0 ) return WRC_Abort;
  101618. pTab->nRef = 1;
  101619. pTab->zName = sqlite3MPrintf(db, "sqlite_sq_%p", (void*)pTab);
  101620. while( pSel->pPrior ){ pSel = pSel->pPrior; }
  101621. selectColumnsFromExprList(pParse, pSel->pEList, &pTab->nCol, &pTab->aCol);
  101622. pTab->iPKey = -1;
  101623. pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
  101624. pTab->tabFlags |= TF_Ephemeral;
  101625. #endif
  101626. }else{
  101627. /* An ordinary table or view name in the FROM clause */
  101628. assert( pFrom->pTab==0 );
  101629. pFrom->pTab = pTab = sqlite3LocateTableItem(pParse, 0, pFrom);
  101630. if( pTab==0 ) return WRC_Abort;
  101631. if( pTab->nRef==0xffff ){
  101632. sqlite3ErrorMsg(pParse, "too many references to \"%s\": max 65535",
  101633. pTab->zName);
  101634. pFrom->pTab = 0;
  101635. return WRC_Abort;
  101636. }
  101637. pTab->nRef++;
  101638. #if !defined(SQLITE_OMIT_VIEW) || !defined (SQLITE_OMIT_VIRTUALTABLE)
  101639. if( pTab->pSelect || IsVirtual(pTab) ){
  101640. /* We reach here if the named table is a really a view */
  101641. if( sqlite3ViewGetColumnNames(pParse, pTab) ) return WRC_Abort;
  101642. assert( pFrom->pSelect==0 );
  101643. pFrom->pSelect = sqlite3SelectDup(db, pTab->pSelect, 0);
  101644. sqlite3SelectSetName(pFrom->pSelect, pTab->zName);
  101645. sqlite3WalkSelect(pWalker, pFrom->pSelect);
  101646. }
  101647. #endif
  101648. }
  101649. /* Locate the index named by the INDEXED BY clause, if any. */
  101650. if( sqlite3IndexedByLookup(pParse, pFrom) ){
  101651. return WRC_Abort;
  101652. }
  101653. }
  101654. /* Process NATURAL keywords, and ON and USING clauses of joins.
  101655. */
  101656. if( db->mallocFailed || sqliteProcessJoin(pParse, p) ){
  101657. return WRC_Abort;
  101658. }
  101659. /* For every "*" that occurs in the column list, insert the names of
  101660. ** all columns in all tables. And for every TABLE.* insert the names
  101661. ** of all columns in TABLE. The parser inserted a special expression
  101662. ** with the TK_ALL operator for each "*" that it found in the column list.
  101663. ** The following code just has to locate the TK_ALL expressions and expand
  101664. ** each one to the list of all columns in all tables.
  101665. **
  101666. ** The first loop just checks to see if there are any "*" operators
  101667. ** that need expanding.
  101668. */
  101669. for(k=0; k<pEList->nExpr; k++){
  101670. pE = pEList->a[k].pExpr;
  101671. if( pE->op==TK_ALL ) break;
  101672. assert( pE->op!=TK_DOT || pE->pRight!=0 );
  101673. assert( pE->op!=TK_DOT || (pE->pLeft!=0 && pE->pLeft->op==TK_ID) );
  101674. if( pE->op==TK_DOT && pE->pRight->op==TK_ALL ) break;
  101675. }
  101676. if( k<pEList->nExpr ){
  101677. /*
  101678. ** If we get here it means the result set contains one or more "*"
  101679. ** operators that need to be expanded. Loop through each expression
  101680. ** in the result set and expand them one by one.
  101681. */
  101682. struct ExprList_item *a = pEList->a;
  101683. ExprList *pNew = 0;
  101684. int flags = pParse->db->flags;
  101685. int longNames = (flags & SQLITE_FullColNames)!=0
  101686. && (flags & SQLITE_ShortColNames)==0;
  101687. /* When processing FROM-clause subqueries, it is always the case
  101688. ** that full_column_names=OFF and short_column_names=ON. The
  101689. ** sqlite3ResultSetOfSelect() routine makes it so. */
  101690. assert( (p->selFlags & SF_NestedFrom)==0
  101691. || ((flags & SQLITE_FullColNames)==0 &&
  101692. (flags & SQLITE_ShortColNames)!=0) );
  101693. for(k=0; k<pEList->nExpr; k++){
  101694. pE = a[k].pExpr;
  101695. pRight = pE->pRight;
  101696. assert( pE->op!=TK_DOT || pRight!=0 );
  101697. if( pE->op!=TK_ALL && (pE->op!=TK_DOT || pRight->op!=TK_ALL) ){
  101698. /* This particular expression does not need to be expanded.
  101699. */
  101700. pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr);
  101701. if( pNew ){
  101702. pNew->a[pNew->nExpr-1].zName = a[k].zName;
  101703. pNew->a[pNew->nExpr-1].zSpan = a[k].zSpan;
  101704. a[k].zName = 0;
  101705. a[k].zSpan = 0;
  101706. }
  101707. a[k].pExpr = 0;
  101708. }else{
  101709. /* This expression is a "*" or a "TABLE.*" and needs to be
  101710. ** expanded. */
  101711. int tableSeen = 0; /* Set to 1 when TABLE matches */
  101712. char *zTName = 0; /* text of name of TABLE */
  101713. if( pE->op==TK_DOT ){
  101714. assert( pE->pLeft!=0 );
  101715. assert( !ExprHasProperty(pE->pLeft, EP_IntValue) );
  101716. zTName = pE->pLeft->u.zToken;
  101717. }
  101718. for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
  101719. Table *pTab = pFrom->pTab;
  101720. Select *pSub = pFrom->pSelect;
  101721. char *zTabName = pFrom->zAlias;
  101722. const char *zSchemaName = 0;
  101723. int iDb;
  101724. if( zTabName==0 ){
  101725. zTabName = pTab->zName;
  101726. }
  101727. if( db->mallocFailed ) break;
  101728. if( pSub==0 || (pSub->selFlags & SF_NestedFrom)==0 ){
  101729. pSub = 0;
  101730. if( zTName && sqlite3StrICmp(zTName, zTabName)!=0 ){
  101731. continue;
  101732. }
  101733. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  101734. zSchemaName = iDb>=0 ? db->aDb[iDb].zName : "*";
  101735. }
  101736. for(j=0; j<pTab->nCol; j++){
  101737. char *zName = pTab->aCol[j].zName;
  101738. char *zColname; /* The computed column name */
  101739. char *zToFree; /* Malloced string that needs to be freed */
  101740. Token sColname; /* Computed column name as a token */
  101741. assert( zName );
  101742. if( zTName && pSub
  101743. && sqlite3MatchSpanName(pSub->pEList->a[j].zSpan, 0, zTName, 0)==0
  101744. ){
  101745. continue;
  101746. }
  101747. /* If a column is marked as 'hidden' (currently only possible
  101748. ** for virtual tables), do not include it in the expanded
  101749. ** result-set list.
  101750. */
  101751. if( IsHiddenColumn(&pTab->aCol[j]) ){
  101752. assert(IsVirtual(pTab));
  101753. continue;
  101754. }
  101755. tableSeen = 1;
  101756. if( i>0 && zTName==0 ){
  101757. if( (pFrom->jointype & JT_NATURAL)!=0
  101758. && tableAndColumnIndex(pTabList, i, zName, 0, 0)
  101759. ){
  101760. /* In a NATURAL join, omit the join columns from the
  101761. ** table to the right of the join */
  101762. continue;
  101763. }
  101764. if( sqlite3IdListIndex(pFrom->pUsing, zName)>=0 ){
  101765. /* In a join with a USING clause, omit columns in the
  101766. ** using clause from the table on the right. */
  101767. continue;
  101768. }
  101769. }
  101770. pRight = sqlite3Expr(db, TK_ID, zName);
  101771. zColname = zName;
  101772. zToFree = 0;
  101773. if( longNames || pTabList->nSrc>1 ){
  101774. Expr *pLeft;
  101775. pLeft = sqlite3Expr(db, TK_ID, zTabName);
  101776. pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
  101777. if( zSchemaName ){
  101778. pLeft = sqlite3Expr(db, TK_ID, zSchemaName);
  101779. pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pExpr, 0);
  101780. }
  101781. if( longNames ){
  101782. zColname = sqlite3MPrintf(db, "%s.%s", zTabName, zName);
  101783. zToFree = zColname;
  101784. }
  101785. }else{
  101786. pExpr = pRight;
  101787. }
  101788. pNew = sqlite3ExprListAppend(pParse, pNew, pExpr);
  101789. sColname.z = zColname;
  101790. sColname.n = sqlite3Strlen30(zColname);
  101791. sqlite3ExprListSetName(pParse, pNew, &sColname, 0);
  101792. if( pNew && (p->selFlags & SF_NestedFrom)!=0 ){
  101793. struct ExprList_item *pX = &pNew->a[pNew->nExpr-1];
  101794. if( pSub ){
  101795. pX->zSpan = sqlite3DbStrDup(db, pSub->pEList->a[j].zSpan);
  101796. testcase( pX->zSpan==0 );
  101797. }else{
  101798. pX->zSpan = sqlite3MPrintf(db, "%s.%s.%s",
  101799. zSchemaName, zTabName, zColname);
  101800. testcase( pX->zSpan==0 );
  101801. }
  101802. pX->bSpanIsTab = 1;
  101803. }
  101804. sqlite3DbFree(db, zToFree);
  101805. }
  101806. }
  101807. if( !tableSeen ){
  101808. if( zTName ){
  101809. sqlite3ErrorMsg(pParse, "no such table: %s", zTName);
  101810. }else{
  101811. sqlite3ErrorMsg(pParse, "no tables specified");
  101812. }
  101813. }
  101814. }
  101815. }
  101816. sqlite3ExprListDelete(db, pEList);
  101817. p->pEList = pNew;
  101818. }
  101819. #if SQLITE_MAX_COLUMN
  101820. if( p->pEList && p->pEList->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
  101821. sqlite3ErrorMsg(pParse, "too many columns in result set");
  101822. }
  101823. #endif
  101824. return WRC_Continue;
  101825. }
  101826. /*
  101827. ** No-op routine for the parse-tree walker.
  101828. **
  101829. ** When this routine is the Walker.xExprCallback then expression trees
  101830. ** are walked without any actions being taken at each node. Presumably,
  101831. ** when this routine is used for Walker.xExprCallback then
  101832. ** Walker.xSelectCallback is set to do something useful for every
  101833. ** subquery in the parser tree.
  101834. */
  101835. static int exprWalkNoop(Walker *NotUsed, Expr *NotUsed2){
  101836. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  101837. return WRC_Continue;
  101838. }
  101839. /*
  101840. ** This routine "expands" a SELECT statement and all of its subqueries.
  101841. ** For additional information on what it means to "expand" a SELECT
  101842. ** statement, see the comment on the selectExpand worker callback above.
  101843. **
  101844. ** Expanding a SELECT statement is the first step in processing a
  101845. ** SELECT statement. The SELECT statement must be expanded before
  101846. ** name resolution is performed.
  101847. **
  101848. ** If anything goes wrong, an error message is written into pParse.
  101849. ** The calling function can detect the problem by looking at pParse->nErr
  101850. ** and/or pParse->db->mallocFailed.
  101851. */
  101852. static void sqlite3SelectExpand(Parse *pParse, Select *pSelect){
  101853. Walker w;
  101854. memset(&w, 0, sizeof(w));
  101855. w.xExprCallback = exprWalkNoop;
  101856. w.pParse = pParse;
  101857. if( pParse->hasCompound ){
  101858. w.xSelectCallback = convertCompoundSelectToSubquery;
  101859. sqlite3WalkSelect(&w, pSelect);
  101860. }
  101861. w.xSelectCallback = selectExpander;
  101862. w.xSelectCallback2 = selectPopWith;
  101863. sqlite3WalkSelect(&w, pSelect);
  101864. }
  101865. #ifndef SQLITE_OMIT_SUBQUERY
  101866. /*
  101867. ** This is a Walker.xSelectCallback callback for the sqlite3SelectTypeInfo()
  101868. ** interface.
  101869. **
  101870. ** For each FROM-clause subquery, add Column.zType and Column.zColl
  101871. ** information to the Table structure that represents the result set
  101872. ** of that subquery.
  101873. **
  101874. ** The Table structure that represents the result set was constructed
  101875. ** by selectExpander() but the type and collation information was omitted
  101876. ** at that point because identifiers had not yet been resolved. This
  101877. ** routine is called after identifier resolution.
  101878. */
  101879. static void selectAddSubqueryTypeInfo(Walker *pWalker, Select *p){
  101880. Parse *pParse;
  101881. int i;
  101882. SrcList *pTabList;
  101883. struct SrcList_item *pFrom;
  101884. assert( p->selFlags & SF_Resolved );
  101885. if( (p->selFlags & SF_HasTypeInfo)==0 ){
  101886. p->selFlags |= SF_HasTypeInfo;
  101887. pParse = pWalker->pParse;
  101888. pTabList = p->pSrc;
  101889. for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
  101890. Table *pTab = pFrom->pTab;
  101891. if( ALWAYS(pTab!=0) && (pTab->tabFlags & TF_Ephemeral)!=0 ){
  101892. /* A sub-query in the FROM clause of a SELECT */
  101893. Select *pSel = pFrom->pSelect;
  101894. if( pSel ){
  101895. while( pSel->pPrior ) pSel = pSel->pPrior;
  101896. selectAddColumnTypeAndCollation(pParse, pTab, pSel);
  101897. }
  101898. }
  101899. }
  101900. }
  101901. }
  101902. #endif
  101903. /*
  101904. ** This routine adds datatype and collating sequence information to
  101905. ** the Table structures of all FROM-clause subqueries in a
  101906. ** SELECT statement.
  101907. **
  101908. ** Use this routine after name resolution.
  101909. */
  101910. static void sqlite3SelectAddTypeInfo(Parse *pParse, Select *pSelect){
  101911. #ifndef SQLITE_OMIT_SUBQUERY
  101912. Walker w;
  101913. memset(&w, 0, sizeof(w));
  101914. w.xSelectCallback2 = selectAddSubqueryTypeInfo;
  101915. w.xExprCallback = exprWalkNoop;
  101916. w.pParse = pParse;
  101917. sqlite3WalkSelect(&w, pSelect);
  101918. #endif
  101919. }
  101920. /*
  101921. ** This routine sets up a SELECT statement for processing. The
  101922. ** following is accomplished:
  101923. **
  101924. ** * VDBE Cursor numbers are assigned to all FROM-clause terms.
  101925. ** * Ephemeral Table objects are created for all FROM-clause subqueries.
  101926. ** * ON and USING clauses are shifted into WHERE statements
  101927. ** * Wildcards "*" and "TABLE.*" in result sets are expanded.
  101928. ** * Identifiers in expression are matched to tables.
  101929. **
  101930. ** This routine acts recursively on all subqueries within the SELECT.
  101931. */
  101932. SQLITE_PRIVATE void sqlite3SelectPrep(
  101933. Parse *pParse, /* The parser context */
  101934. Select *p, /* The SELECT statement being coded. */
  101935. NameContext *pOuterNC /* Name context for container */
  101936. ){
  101937. sqlite3 *db;
  101938. if( NEVER(p==0) ) return;
  101939. db = pParse->db;
  101940. if( db->mallocFailed ) return;
  101941. if( p->selFlags & SF_HasTypeInfo ) return;
  101942. sqlite3SelectExpand(pParse, p);
  101943. if( pParse->nErr || db->mallocFailed ) return;
  101944. sqlite3ResolveSelectNames(pParse, p, pOuterNC);
  101945. if( pParse->nErr || db->mallocFailed ) return;
  101946. sqlite3SelectAddTypeInfo(pParse, p);
  101947. }
  101948. /*
  101949. ** Reset the aggregate accumulator.
  101950. **
  101951. ** The aggregate accumulator is a set of memory cells that hold
  101952. ** intermediate results while calculating an aggregate. This
  101953. ** routine generates code that stores NULLs in all of those memory
  101954. ** cells.
  101955. */
  101956. static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){
  101957. Vdbe *v = pParse->pVdbe;
  101958. int i;
  101959. struct AggInfo_func *pFunc;
  101960. int nReg = pAggInfo->nFunc + pAggInfo->nColumn;
  101961. if( nReg==0 ) return;
  101962. #ifdef SQLITE_DEBUG
  101963. /* Verify that all AggInfo registers are within the range specified by
  101964. ** AggInfo.mnReg..AggInfo.mxReg */
  101965. assert( nReg==pAggInfo->mxReg-pAggInfo->mnReg+1 );
  101966. for(i=0; i<pAggInfo->nColumn; i++){
  101967. assert( pAggInfo->aCol[i].iMem>=pAggInfo->mnReg
  101968. && pAggInfo->aCol[i].iMem<=pAggInfo->mxReg );
  101969. }
  101970. for(i=0; i<pAggInfo->nFunc; i++){
  101971. assert( pAggInfo->aFunc[i].iMem>=pAggInfo->mnReg
  101972. && pAggInfo->aFunc[i].iMem<=pAggInfo->mxReg );
  101973. }
  101974. #endif
  101975. sqlite3VdbeAddOp3(v, OP_Null, 0, pAggInfo->mnReg, pAggInfo->mxReg);
  101976. for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){
  101977. if( pFunc->iDistinct>=0 ){
  101978. Expr *pE = pFunc->pExpr;
  101979. assert( !ExprHasProperty(pE, EP_xIsSelect) );
  101980. if( pE->x.pList==0 || pE->x.pList->nExpr!=1 ){
  101981. sqlite3ErrorMsg(pParse, "DISTINCT aggregates must have exactly one "
  101982. "argument");
  101983. pFunc->iDistinct = -1;
  101984. }else{
  101985. KeyInfo *pKeyInfo = keyInfoFromExprList(pParse, pE->x.pList, 0, 0);
  101986. sqlite3VdbeAddOp4(v, OP_OpenEphemeral, pFunc->iDistinct, 0, 0,
  101987. (char*)pKeyInfo, P4_KEYINFO);
  101988. }
  101989. }
  101990. }
  101991. }
  101992. /*
  101993. ** Invoke the OP_AggFinalize opcode for every aggregate function
  101994. ** in the AggInfo structure.
  101995. */
  101996. static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){
  101997. Vdbe *v = pParse->pVdbe;
  101998. int i;
  101999. struct AggInfo_func *pF;
  102000. for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
  102001. ExprList *pList = pF->pExpr->x.pList;
  102002. assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
  102003. sqlite3VdbeAddOp4(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0, 0,
  102004. (void*)pF->pFunc, P4_FUNCDEF);
  102005. }
  102006. }
  102007. /*
  102008. ** Update the accumulator memory cells for an aggregate based on
  102009. ** the current cursor position.
  102010. */
  102011. static void updateAccumulator(Parse *pParse, AggInfo *pAggInfo){
  102012. Vdbe *v = pParse->pVdbe;
  102013. int i;
  102014. int regHit = 0;
  102015. int addrHitTest = 0;
  102016. struct AggInfo_func *pF;
  102017. struct AggInfo_col *pC;
  102018. pAggInfo->directMode = 1;
  102019. for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
  102020. int nArg;
  102021. int addrNext = 0;
  102022. int regAgg;
  102023. ExprList *pList = pF->pExpr->x.pList;
  102024. assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
  102025. if( pList ){
  102026. nArg = pList->nExpr;
  102027. regAgg = sqlite3GetTempRange(pParse, nArg);
  102028. sqlite3ExprCodeExprList(pParse, pList, regAgg, SQLITE_ECEL_DUP);
  102029. }else{
  102030. nArg = 0;
  102031. regAgg = 0;
  102032. }
  102033. if( pF->iDistinct>=0 ){
  102034. addrNext = sqlite3VdbeMakeLabel(v);
  102035. assert( nArg==1 );
  102036. codeDistinct(pParse, pF->iDistinct, addrNext, 1, regAgg);
  102037. }
  102038. if( pF->pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL ){
  102039. CollSeq *pColl = 0;
  102040. struct ExprList_item *pItem;
  102041. int j;
  102042. assert( pList!=0 ); /* pList!=0 if pF->pFunc has NEEDCOLL */
  102043. for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){
  102044. pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
  102045. }
  102046. if( !pColl ){
  102047. pColl = pParse->db->pDfltColl;
  102048. }
  102049. if( regHit==0 && pAggInfo->nAccumulator ) regHit = ++pParse->nMem;
  102050. sqlite3VdbeAddOp4(v, OP_CollSeq, regHit, 0, 0, (char *)pColl, P4_COLLSEQ);
  102051. }
  102052. sqlite3VdbeAddOp4(v, OP_AggStep, 0, regAgg, pF->iMem,
  102053. (void*)pF->pFunc, P4_FUNCDEF);
  102054. sqlite3VdbeChangeP5(v, (u8)nArg);
  102055. sqlite3ExprCacheAffinityChange(pParse, regAgg, nArg);
  102056. sqlite3ReleaseTempRange(pParse, regAgg, nArg);
  102057. if( addrNext ){
  102058. sqlite3VdbeResolveLabel(v, addrNext);
  102059. sqlite3ExprCacheClear(pParse);
  102060. }
  102061. }
  102062. /* Before populating the accumulator registers, clear the column cache.
  102063. ** Otherwise, if any of the required column values are already present
  102064. ** in registers, sqlite3ExprCode() may use OP_SCopy to copy the value
  102065. ** to pC->iMem. But by the time the value is used, the original register
  102066. ** may have been used, invalidating the underlying buffer holding the
  102067. ** text or blob value. See ticket [883034dcb5].
  102068. **
  102069. ** Another solution would be to change the OP_SCopy used to copy cached
  102070. ** values to an OP_Copy.
  102071. */
  102072. if( regHit ){
  102073. addrHitTest = sqlite3VdbeAddOp1(v, OP_If, regHit); VdbeCoverage(v);
  102074. }
  102075. sqlite3ExprCacheClear(pParse);
  102076. for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){
  102077. sqlite3ExprCode(pParse, pC->pExpr, pC->iMem);
  102078. }
  102079. pAggInfo->directMode = 0;
  102080. sqlite3ExprCacheClear(pParse);
  102081. if( addrHitTest ){
  102082. sqlite3VdbeJumpHere(v, addrHitTest);
  102083. }
  102084. }
  102085. /*
  102086. ** Add a single OP_Explain instruction to the VDBE to explain a simple
  102087. ** count(*) query ("SELECT count(*) FROM pTab").
  102088. */
  102089. #ifndef SQLITE_OMIT_EXPLAIN
  102090. static void explainSimpleCount(
  102091. Parse *pParse, /* Parse context */
  102092. Table *pTab, /* Table being queried */
  102093. Index *pIdx /* Index used to optimize scan, or NULL */
  102094. ){
  102095. if( pParse->explain==2 ){
  102096. int bCover = (pIdx!=0 && (HasRowid(pTab) || !IsPrimaryKeyIndex(pIdx)));
  102097. char *zEqp = sqlite3MPrintf(pParse->db, "SCAN TABLE %s%s%s",
  102098. pTab->zName,
  102099. bCover ? " USING COVERING INDEX " : "",
  102100. bCover ? pIdx->zName : ""
  102101. );
  102102. sqlite3VdbeAddOp4(
  102103. pParse->pVdbe, OP_Explain, pParse->iSelectId, 0, 0, zEqp, P4_DYNAMIC
  102104. );
  102105. }
  102106. }
  102107. #else
  102108. # define explainSimpleCount(a,b,c)
  102109. #endif
  102110. /*
  102111. ** Generate code for the SELECT statement given in the p argument.
  102112. **
  102113. ** The results are returned according to the SelectDest structure.
  102114. ** See comments in sqliteInt.h for further information.
  102115. **
  102116. ** This routine returns the number of errors. If any errors are
  102117. ** encountered, then an appropriate error message is left in
  102118. ** pParse->zErrMsg.
  102119. **
  102120. ** This routine does NOT free the Select structure passed in. The
  102121. ** calling function needs to do that.
  102122. */
  102123. SQLITE_PRIVATE int sqlite3Select(
  102124. Parse *pParse, /* The parser context */
  102125. Select *p, /* The SELECT statement being coded. */
  102126. SelectDest *pDest /* What to do with the query results */
  102127. ){
  102128. int i, j; /* Loop counters */
  102129. WhereInfo *pWInfo; /* Return from sqlite3WhereBegin() */
  102130. Vdbe *v; /* The virtual machine under construction */
  102131. int isAgg; /* True for select lists like "count(*)" */
  102132. ExprList *pEList; /* List of columns to extract. */
  102133. SrcList *pTabList; /* List of tables to select from */
  102134. Expr *pWhere; /* The WHERE clause. May be NULL */
  102135. ExprList *pGroupBy; /* The GROUP BY clause. May be NULL */
  102136. Expr *pHaving; /* The HAVING clause. May be NULL */
  102137. int rc = 1; /* Value to return from this function */
  102138. DistinctCtx sDistinct; /* Info on how to code the DISTINCT keyword */
  102139. SortCtx sSort; /* Info on how to code the ORDER BY clause */
  102140. AggInfo sAggInfo; /* Information used by aggregate queries */
  102141. int iEnd; /* Address of the end of the query */
  102142. sqlite3 *db; /* The database connection */
  102143. #ifndef SQLITE_OMIT_EXPLAIN
  102144. int iRestoreSelectId = pParse->iSelectId;
  102145. pParse->iSelectId = pParse->iNextSelectId++;
  102146. #endif
  102147. db = pParse->db;
  102148. if( p==0 || db->mallocFailed || pParse->nErr ){
  102149. return 1;
  102150. }
  102151. if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
  102152. memset(&sAggInfo, 0, sizeof(sAggInfo));
  102153. #if SELECTTRACE_ENABLED
  102154. pParse->nSelectIndent++;
  102155. SELECTTRACE(1,pParse,p, ("begin processing:\n"));
  102156. if( sqlite3SelectTrace & 0x100 ){
  102157. sqlite3TreeViewSelect(0, p, 0);
  102158. }
  102159. #endif
  102160. assert( p->pOrderBy==0 || pDest->eDest!=SRT_DistFifo );
  102161. assert( p->pOrderBy==0 || pDest->eDest!=SRT_Fifo );
  102162. assert( p->pOrderBy==0 || pDest->eDest!=SRT_DistQueue );
  102163. assert( p->pOrderBy==0 || pDest->eDest!=SRT_Queue );
  102164. if( IgnorableOrderby(pDest) ){
  102165. assert(pDest->eDest==SRT_Exists || pDest->eDest==SRT_Union ||
  102166. pDest->eDest==SRT_Except || pDest->eDest==SRT_Discard ||
  102167. pDest->eDest==SRT_Queue || pDest->eDest==SRT_DistFifo ||
  102168. pDest->eDest==SRT_DistQueue || pDest->eDest==SRT_Fifo);
  102169. /* If ORDER BY makes no difference in the output then neither does
  102170. ** DISTINCT so it can be removed too. */
  102171. sqlite3ExprListDelete(db, p->pOrderBy);
  102172. p->pOrderBy = 0;
  102173. p->selFlags &= ~SF_Distinct;
  102174. }
  102175. sqlite3SelectPrep(pParse, p, 0);
  102176. memset(&sSort, 0, sizeof(sSort));
  102177. sSort.pOrderBy = p->pOrderBy;
  102178. pTabList = p->pSrc;
  102179. pEList = p->pEList;
  102180. if( pParse->nErr || db->mallocFailed ){
  102181. goto select_end;
  102182. }
  102183. isAgg = (p->selFlags & SF_Aggregate)!=0;
  102184. assert( pEList!=0 );
  102185. /* Begin generating code.
  102186. */
  102187. v = sqlite3GetVdbe(pParse);
  102188. if( v==0 ) goto select_end;
  102189. /* If writing to memory or generating a set
  102190. ** only a single column may be output.
  102191. */
  102192. #ifndef SQLITE_OMIT_SUBQUERY
  102193. if( checkForMultiColumnSelectError(pParse, pDest, pEList->nExpr) ){
  102194. goto select_end;
  102195. }
  102196. #endif
  102197. /* Generate code for all sub-queries in the FROM clause
  102198. */
  102199. #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
  102200. for(i=0; !p->pPrior && i<pTabList->nSrc; i++){
  102201. struct SrcList_item *pItem = &pTabList->a[i];
  102202. SelectDest dest;
  102203. Select *pSub = pItem->pSelect;
  102204. int isAggSub;
  102205. if( pSub==0 ) continue;
  102206. /* Sometimes the code for a subquery will be generated more than
  102207. ** once, if the subquery is part of the WHERE clause in a LEFT JOIN,
  102208. ** for example. In that case, do not regenerate the code to manifest
  102209. ** a view or the co-routine to implement a view. The first instance
  102210. ** is sufficient, though the subroutine to manifest the view does need
  102211. ** to be invoked again. */
  102212. if( pItem->addrFillSub ){
  102213. if( pItem->viaCoroutine==0 ){
  102214. sqlite3VdbeAddOp2(v, OP_Gosub, pItem->regReturn, pItem->addrFillSub);
  102215. }
  102216. continue;
  102217. }
  102218. /* Increment Parse.nHeight by the height of the largest expression
  102219. ** tree referred to by this, the parent select. The child select
  102220. ** may contain expression trees of at most
  102221. ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit
  102222. ** more conservative than necessary, but much easier than enforcing
  102223. ** an exact limit.
  102224. */
  102225. pParse->nHeight += sqlite3SelectExprHeight(p);
  102226. isAggSub = (pSub->selFlags & SF_Aggregate)!=0;
  102227. if( flattenSubquery(pParse, p, i, isAgg, isAggSub) ){
  102228. /* This subquery can be absorbed into its parent. */
  102229. if( isAggSub ){
  102230. isAgg = 1;
  102231. p->selFlags |= SF_Aggregate;
  102232. }
  102233. i = -1;
  102234. }else if( pTabList->nSrc==1
  102235. && OptimizationEnabled(db, SQLITE_SubqCoroutine)
  102236. ){
  102237. /* Implement a co-routine that will return a single row of the result
  102238. ** set on each invocation.
  102239. */
  102240. int addrTop = sqlite3VdbeCurrentAddr(v)+1;
  102241. pItem->regReturn = ++pParse->nMem;
  102242. sqlite3VdbeAddOp3(v, OP_InitCoroutine, pItem->regReturn, 0, addrTop);
  102243. VdbeComment((v, "%s", pItem->pTab->zName));
  102244. pItem->addrFillSub = addrTop;
  102245. sqlite3SelectDestInit(&dest, SRT_Coroutine, pItem->regReturn);
  102246. explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId);
  102247. sqlite3Select(pParse, pSub, &dest);
  102248. pItem->pTab->nRowLogEst = sqlite3LogEst(pSub->nSelectRow);
  102249. pItem->viaCoroutine = 1;
  102250. pItem->regResult = dest.iSdst;
  102251. sqlite3VdbeAddOp1(v, OP_EndCoroutine, pItem->regReturn);
  102252. sqlite3VdbeJumpHere(v, addrTop-1);
  102253. sqlite3ClearTempRegCache(pParse);
  102254. }else{
  102255. /* Generate a subroutine that will fill an ephemeral table with
  102256. ** the content of this subquery. pItem->addrFillSub will point
  102257. ** to the address of the generated subroutine. pItem->regReturn
  102258. ** is a register allocated to hold the subroutine return address
  102259. */
  102260. int topAddr;
  102261. int onceAddr = 0;
  102262. int retAddr;
  102263. assert( pItem->addrFillSub==0 );
  102264. pItem->regReturn = ++pParse->nMem;
  102265. topAddr = sqlite3VdbeAddOp2(v, OP_Integer, 0, pItem->regReturn);
  102266. pItem->addrFillSub = topAddr+1;
  102267. if( pItem->isCorrelated==0 ){
  102268. /* If the subquery is not correlated and if we are not inside of
  102269. ** a trigger, then we only need to compute the value of the subquery
  102270. ** once. */
  102271. onceAddr = sqlite3CodeOnce(pParse); VdbeCoverage(v);
  102272. VdbeComment((v, "materialize \"%s\"", pItem->pTab->zName));
  102273. }else{
  102274. VdbeNoopComment((v, "materialize \"%s\"", pItem->pTab->zName));
  102275. }
  102276. sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor);
  102277. explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId);
  102278. sqlite3Select(pParse, pSub, &dest);
  102279. pItem->pTab->nRowLogEst = sqlite3LogEst(pSub->nSelectRow);
  102280. if( onceAddr ) sqlite3VdbeJumpHere(v, onceAddr);
  102281. retAddr = sqlite3VdbeAddOp1(v, OP_Return, pItem->regReturn);
  102282. VdbeComment((v, "end %s", pItem->pTab->zName));
  102283. sqlite3VdbeChangeP1(v, topAddr, retAddr);
  102284. sqlite3ClearTempRegCache(pParse);
  102285. }
  102286. if( /*pParse->nErr ||*/ db->mallocFailed ){
  102287. goto select_end;
  102288. }
  102289. pParse->nHeight -= sqlite3SelectExprHeight(p);
  102290. pTabList = p->pSrc;
  102291. if( !IgnorableOrderby(pDest) ){
  102292. sSort.pOrderBy = p->pOrderBy;
  102293. }
  102294. }
  102295. pEList = p->pEList;
  102296. #endif
  102297. pWhere = p->pWhere;
  102298. pGroupBy = p->pGroupBy;
  102299. pHaving = p->pHaving;
  102300. sDistinct.isTnct = (p->selFlags & SF_Distinct)!=0;
  102301. #ifndef SQLITE_OMIT_COMPOUND_SELECT
  102302. /* If there is are a sequence of queries, do the earlier ones first.
  102303. */
  102304. if( p->pPrior ){
  102305. rc = multiSelect(pParse, p, pDest);
  102306. explainSetInteger(pParse->iSelectId, iRestoreSelectId);
  102307. #if SELECTTRACE_ENABLED
  102308. SELECTTRACE(1,pParse,p,("end compound-select processing\n"));
  102309. pParse->nSelectIndent--;
  102310. #endif
  102311. return rc;
  102312. }
  102313. #endif
  102314. /* If the query is DISTINCT with an ORDER BY but is not an aggregate, and
  102315. ** if the select-list is the same as the ORDER BY list, then this query
  102316. ** can be rewritten as a GROUP BY. In other words, this:
  102317. **
  102318. ** SELECT DISTINCT xyz FROM ... ORDER BY xyz
  102319. **
  102320. ** is transformed to:
  102321. **
  102322. ** SELECT xyz FROM ... GROUP BY xyz
  102323. **
  102324. ** The second form is preferred as a single index (or temp-table) may be
  102325. ** used for both the ORDER BY and DISTINCT processing. As originally
  102326. ** written the query must use a temp-table for at least one of the ORDER
  102327. ** BY and DISTINCT, and an index or separate temp-table for the other.
  102328. */
  102329. if( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct
  102330. && sqlite3ExprListCompare(sSort.pOrderBy, p->pEList, -1)==0
  102331. ){
  102332. p->selFlags &= ~SF_Distinct;
  102333. p->pGroupBy = sqlite3ExprListDup(db, p->pEList, 0);
  102334. pGroupBy = p->pGroupBy;
  102335. sSort.pOrderBy = 0;
  102336. /* Notice that even thought SF_Distinct has been cleared from p->selFlags,
  102337. ** the sDistinct.isTnct is still set. Hence, isTnct represents the
  102338. ** original setting of the SF_Distinct flag, not the current setting */
  102339. assert( sDistinct.isTnct );
  102340. }
  102341. /* If there is an ORDER BY clause, then this sorting
  102342. ** index might end up being unused if the data can be
  102343. ** extracted in pre-sorted order. If that is the case, then the
  102344. ** OP_OpenEphemeral instruction will be changed to an OP_Noop once
  102345. ** we figure out that the sorting index is not needed. The addrSortIndex
  102346. ** variable is used to facilitate that change.
  102347. */
  102348. if( sSort.pOrderBy ){
  102349. KeyInfo *pKeyInfo;
  102350. pKeyInfo = keyInfoFromExprList(pParse, sSort.pOrderBy, 0, 0);
  102351. sSort.iECursor = pParse->nTab++;
  102352. sSort.addrSortIndex =
  102353. sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
  102354. sSort.iECursor, sSort.pOrderBy->nExpr+1+pEList->nExpr, 0,
  102355. (char*)pKeyInfo, P4_KEYINFO
  102356. );
  102357. }else{
  102358. sSort.addrSortIndex = -1;
  102359. }
  102360. /* If the output is destined for a temporary table, open that table.
  102361. */
  102362. if( pDest->eDest==SRT_EphemTab ){
  102363. sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pDest->iSDParm, pEList->nExpr);
  102364. }
  102365. /* Set the limiter.
  102366. */
  102367. iEnd = sqlite3VdbeMakeLabel(v);
  102368. p->nSelectRow = LARGEST_INT64;
  102369. computeLimitRegisters(pParse, p, iEnd);
  102370. if( p->iLimit==0 && sSort.addrSortIndex>=0 ){
  102371. sqlite3VdbeGetOp(v, sSort.addrSortIndex)->opcode = OP_SorterOpen;
  102372. sSort.sortFlags |= SORTFLAG_UseSorter;
  102373. }
  102374. /* Open a virtual index to use for the distinct set.
  102375. */
  102376. if( p->selFlags & SF_Distinct ){
  102377. sDistinct.tabTnct = pParse->nTab++;
  102378. sDistinct.addrTnct = sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
  102379. sDistinct.tabTnct, 0, 0,
  102380. (char*)keyInfoFromExprList(pParse, p->pEList,0,0),
  102381. P4_KEYINFO);
  102382. sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
  102383. sDistinct.eTnctType = WHERE_DISTINCT_UNORDERED;
  102384. }else{
  102385. sDistinct.eTnctType = WHERE_DISTINCT_NOOP;
  102386. }
  102387. if( !isAgg && pGroupBy==0 ){
  102388. /* No aggregate functions and no GROUP BY clause */
  102389. u16 wctrlFlags = (sDistinct.isTnct ? WHERE_WANT_DISTINCT : 0);
  102390. /* Begin the database scan. */
  102391. pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, sSort.pOrderBy,
  102392. p->pEList, wctrlFlags, 0);
  102393. if( pWInfo==0 ) goto select_end;
  102394. if( sqlite3WhereOutputRowCount(pWInfo) < p->nSelectRow ){
  102395. p->nSelectRow = sqlite3WhereOutputRowCount(pWInfo);
  102396. }
  102397. if( sDistinct.isTnct && sqlite3WhereIsDistinct(pWInfo) ){
  102398. sDistinct.eTnctType = sqlite3WhereIsDistinct(pWInfo);
  102399. }
  102400. if( sSort.pOrderBy ){
  102401. sSort.nOBSat = sqlite3WhereIsOrdered(pWInfo);
  102402. if( sSort.nOBSat==sSort.pOrderBy->nExpr ){
  102403. sSort.pOrderBy = 0;
  102404. }
  102405. }
  102406. /* If sorting index that was created by a prior OP_OpenEphemeral
  102407. ** instruction ended up not being needed, then change the OP_OpenEphemeral
  102408. ** into an OP_Noop.
  102409. */
  102410. if( sSort.addrSortIndex>=0 && sSort.pOrderBy==0 ){
  102411. sqlite3VdbeChangeToNoop(v, sSort.addrSortIndex);
  102412. }
  102413. /* Use the standard inner loop. */
  102414. selectInnerLoop(pParse, p, pEList, -1, &sSort, &sDistinct, pDest,
  102415. sqlite3WhereContinueLabel(pWInfo),
  102416. sqlite3WhereBreakLabel(pWInfo));
  102417. /* End the database scan loop.
  102418. */
  102419. sqlite3WhereEnd(pWInfo);
  102420. }else{
  102421. /* This case when there exist aggregate functions or a GROUP BY clause
  102422. ** or both */
  102423. NameContext sNC; /* Name context for processing aggregate information */
  102424. int iAMem; /* First Mem address for storing current GROUP BY */
  102425. int iBMem; /* First Mem address for previous GROUP BY */
  102426. int iUseFlag; /* Mem address holding flag indicating that at least
  102427. ** one row of the input to the aggregator has been
  102428. ** processed */
  102429. int iAbortFlag; /* Mem address which causes query abort if positive */
  102430. int groupBySort; /* Rows come from source in GROUP BY order */
  102431. int addrEnd; /* End of processing for this SELECT */
  102432. int sortPTab = 0; /* Pseudotable used to decode sorting results */
  102433. int sortOut = 0; /* Output register from the sorter */
  102434. int orderByGrp = 0; /* True if the GROUP BY and ORDER BY are the same */
  102435. /* Remove any and all aliases between the result set and the
  102436. ** GROUP BY clause.
  102437. */
  102438. if( pGroupBy ){
  102439. int k; /* Loop counter */
  102440. struct ExprList_item *pItem; /* For looping over expression in a list */
  102441. for(k=p->pEList->nExpr, pItem=p->pEList->a; k>0; k--, pItem++){
  102442. pItem->u.x.iAlias = 0;
  102443. }
  102444. for(k=pGroupBy->nExpr, pItem=pGroupBy->a; k>0; k--, pItem++){
  102445. pItem->u.x.iAlias = 0;
  102446. }
  102447. if( p->nSelectRow>100 ) p->nSelectRow = 100;
  102448. }else{
  102449. p->nSelectRow = 1;
  102450. }
  102451. /* If there is both a GROUP BY and an ORDER BY clause and they are
  102452. ** identical, then it may be possible to disable the ORDER BY clause
  102453. ** on the grounds that the GROUP BY will cause elements to come out
  102454. ** in the correct order. It also may not - the GROUP BY may use a
  102455. ** database index that causes rows to be grouped together as required
  102456. ** but not actually sorted. Either way, record the fact that the
  102457. ** ORDER BY and GROUP BY clauses are the same by setting the orderByGrp
  102458. ** variable. */
  102459. if( sqlite3ExprListCompare(pGroupBy, sSort.pOrderBy, -1)==0 ){
  102460. orderByGrp = 1;
  102461. }
  102462. /* Create a label to jump to when we want to abort the query */
  102463. addrEnd = sqlite3VdbeMakeLabel(v);
  102464. /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in
  102465. ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the
  102466. ** SELECT statement.
  102467. */
  102468. memset(&sNC, 0, sizeof(sNC));
  102469. sNC.pParse = pParse;
  102470. sNC.pSrcList = pTabList;
  102471. sNC.pAggInfo = &sAggInfo;
  102472. sAggInfo.mnReg = pParse->nMem+1;
  102473. sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr : 0;
  102474. sAggInfo.pGroupBy = pGroupBy;
  102475. sqlite3ExprAnalyzeAggList(&sNC, pEList);
  102476. sqlite3ExprAnalyzeAggList(&sNC, sSort.pOrderBy);
  102477. if( pHaving ){
  102478. sqlite3ExprAnalyzeAggregates(&sNC, pHaving);
  102479. }
  102480. sAggInfo.nAccumulator = sAggInfo.nColumn;
  102481. for(i=0; i<sAggInfo.nFunc; i++){
  102482. assert( !ExprHasProperty(sAggInfo.aFunc[i].pExpr, EP_xIsSelect) );
  102483. sNC.ncFlags |= NC_InAggFunc;
  102484. sqlite3ExprAnalyzeAggList(&sNC, sAggInfo.aFunc[i].pExpr->x.pList);
  102485. sNC.ncFlags &= ~NC_InAggFunc;
  102486. }
  102487. sAggInfo.mxReg = pParse->nMem;
  102488. if( db->mallocFailed ) goto select_end;
  102489. /* Processing for aggregates with GROUP BY is very different and
  102490. ** much more complex than aggregates without a GROUP BY.
  102491. */
  102492. if( pGroupBy ){
  102493. KeyInfo *pKeyInfo; /* Keying information for the group by clause */
  102494. int j1; /* A-vs-B comparision jump */
  102495. int addrOutputRow; /* Start of subroutine that outputs a result row */
  102496. int regOutputRow; /* Return address register for output subroutine */
  102497. int addrSetAbort; /* Set the abort flag and return */
  102498. int addrTopOfLoop; /* Top of the input loop */
  102499. int addrSortingIdx; /* The OP_OpenEphemeral for the sorting index */
  102500. int addrReset; /* Subroutine for resetting the accumulator */
  102501. int regReset; /* Return address register for reset subroutine */
  102502. /* If there is a GROUP BY clause we might need a sorting index to
  102503. ** implement it. Allocate that sorting index now. If it turns out
  102504. ** that we do not need it after all, the OP_SorterOpen instruction
  102505. ** will be converted into a Noop.
  102506. */
  102507. sAggInfo.sortingIdx = pParse->nTab++;
  102508. pKeyInfo = keyInfoFromExprList(pParse, pGroupBy, 0, 0);
  102509. addrSortingIdx = sqlite3VdbeAddOp4(v, OP_SorterOpen,
  102510. sAggInfo.sortingIdx, sAggInfo.nSortingColumn,
  102511. 0, (char*)pKeyInfo, P4_KEYINFO);
  102512. /* Initialize memory locations used by GROUP BY aggregate processing
  102513. */
  102514. iUseFlag = ++pParse->nMem;
  102515. iAbortFlag = ++pParse->nMem;
  102516. regOutputRow = ++pParse->nMem;
  102517. addrOutputRow = sqlite3VdbeMakeLabel(v);
  102518. regReset = ++pParse->nMem;
  102519. addrReset = sqlite3VdbeMakeLabel(v);
  102520. iAMem = pParse->nMem + 1;
  102521. pParse->nMem += pGroupBy->nExpr;
  102522. iBMem = pParse->nMem + 1;
  102523. pParse->nMem += pGroupBy->nExpr;
  102524. sqlite3VdbeAddOp2(v, OP_Integer, 0, iAbortFlag);
  102525. VdbeComment((v, "clear abort flag"));
  102526. sqlite3VdbeAddOp2(v, OP_Integer, 0, iUseFlag);
  102527. VdbeComment((v, "indicate accumulator empty"));
  102528. sqlite3VdbeAddOp3(v, OP_Null, 0, iAMem, iAMem+pGroupBy->nExpr-1);
  102529. /* Begin a loop that will extract all source rows in GROUP BY order.
  102530. ** This might involve two separate loops with an OP_Sort in between, or
  102531. ** it might be a single loop that uses an index to extract information
  102532. ** in the right order to begin with.
  102533. */
  102534. sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
  102535. pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pGroupBy, 0,
  102536. WHERE_GROUPBY | (orderByGrp ? WHERE_SORTBYGROUP : 0), 0
  102537. );
  102538. if( pWInfo==0 ) goto select_end;
  102539. if( sqlite3WhereIsOrdered(pWInfo)==pGroupBy->nExpr ){
  102540. /* The optimizer is able to deliver rows in group by order so
  102541. ** we do not have to sort. The OP_OpenEphemeral table will be
  102542. ** cancelled later because we still need to use the pKeyInfo
  102543. */
  102544. groupBySort = 0;
  102545. }else{
  102546. /* Rows are coming out in undetermined order. We have to push
  102547. ** each row into a sorting index, terminate the first loop,
  102548. ** then loop over the sorting index in order to get the output
  102549. ** in sorted order
  102550. */
  102551. int regBase;
  102552. int regRecord;
  102553. int nCol;
  102554. int nGroupBy;
  102555. explainTempTable(pParse,
  102556. (sDistinct.isTnct && (p->selFlags&SF_Distinct)==0) ?
  102557. "DISTINCT" : "GROUP BY");
  102558. groupBySort = 1;
  102559. nGroupBy = pGroupBy->nExpr;
  102560. nCol = nGroupBy;
  102561. j = nGroupBy;
  102562. for(i=0; i<sAggInfo.nColumn; i++){
  102563. if( sAggInfo.aCol[i].iSorterColumn>=j ){
  102564. nCol++;
  102565. j++;
  102566. }
  102567. }
  102568. regBase = sqlite3GetTempRange(pParse, nCol);
  102569. sqlite3ExprCacheClear(pParse);
  102570. sqlite3ExprCodeExprList(pParse, pGroupBy, regBase, 0);
  102571. j = nGroupBy;
  102572. for(i=0; i<sAggInfo.nColumn; i++){
  102573. struct AggInfo_col *pCol = &sAggInfo.aCol[i];
  102574. if( pCol->iSorterColumn>=j ){
  102575. int r1 = j + regBase;
  102576. int r2;
  102577. r2 = sqlite3ExprCodeGetColumn(pParse,
  102578. pCol->pTab, pCol->iColumn, pCol->iTable, r1, 0);
  102579. if( r1!=r2 ){
  102580. sqlite3VdbeAddOp2(v, OP_SCopy, r2, r1);
  102581. }
  102582. j++;
  102583. }
  102584. }
  102585. regRecord = sqlite3GetTempReg(pParse);
  102586. sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regRecord);
  102587. sqlite3VdbeAddOp2(v, OP_SorterInsert, sAggInfo.sortingIdx, regRecord);
  102588. sqlite3ReleaseTempReg(pParse, regRecord);
  102589. sqlite3ReleaseTempRange(pParse, regBase, nCol);
  102590. sqlite3WhereEnd(pWInfo);
  102591. sAggInfo.sortingIdxPTab = sortPTab = pParse->nTab++;
  102592. sortOut = sqlite3GetTempReg(pParse);
  102593. sqlite3VdbeAddOp3(v, OP_OpenPseudo, sortPTab, sortOut, nCol);
  102594. sqlite3VdbeAddOp2(v, OP_SorterSort, sAggInfo.sortingIdx, addrEnd);
  102595. VdbeComment((v, "GROUP BY sort")); VdbeCoverage(v);
  102596. sAggInfo.useSortingIdx = 1;
  102597. sqlite3ExprCacheClear(pParse);
  102598. }
  102599. /* If the index or temporary table used by the GROUP BY sort
  102600. ** will naturally deliver rows in the order required by the ORDER BY
  102601. ** clause, cancel the ephemeral table open coded earlier.
  102602. **
  102603. ** This is an optimization - the correct answer should result regardless.
  102604. ** Use the SQLITE_GroupByOrder flag with SQLITE_TESTCTRL_OPTIMIZER to
  102605. ** disable this optimization for testing purposes. */
  102606. if( orderByGrp && OptimizationEnabled(db, SQLITE_GroupByOrder)
  102607. && (groupBySort || sqlite3WhereIsSorted(pWInfo))
  102608. ){
  102609. sSort.pOrderBy = 0;
  102610. sqlite3VdbeChangeToNoop(v, sSort.addrSortIndex);
  102611. }
  102612. /* Evaluate the current GROUP BY terms and store in b0, b1, b2...
  102613. ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth)
  102614. ** Then compare the current GROUP BY terms against the GROUP BY terms
  102615. ** from the previous row currently stored in a0, a1, a2...
  102616. */
  102617. addrTopOfLoop = sqlite3VdbeCurrentAddr(v);
  102618. sqlite3ExprCacheClear(pParse);
  102619. if( groupBySort ){
  102620. sqlite3VdbeAddOp3(v, OP_SorterData, sAggInfo.sortingIdx, sortOut,sortPTab);
  102621. }
  102622. for(j=0; j<pGroupBy->nExpr; j++){
  102623. if( groupBySort ){
  102624. sqlite3VdbeAddOp3(v, OP_Column, sortPTab, j, iBMem+j);
  102625. }else{
  102626. sAggInfo.directMode = 1;
  102627. sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j);
  102628. }
  102629. }
  102630. sqlite3VdbeAddOp4(v, OP_Compare, iAMem, iBMem, pGroupBy->nExpr,
  102631. (char*)sqlite3KeyInfoRef(pKeyInfo), P4_KEYINFO);
  102632. j1 = sqlite3VdbeCurrentAddr(v);
  102633. sqlite3VdbeAddOp3(v, OP_Jump, j1+1, 0, j1+1); VdbeCoverage(v);
  102634. /* Generate code that runs whenever the GROUP BY changes.
  102635. ** Changes in the GROUP BY are detected by the previous code
  102636. ** block. If there were no changes, this block is skipped.
  102637. **
  102638. ** This code copies current group by terms in b0,b1,b2,...
  102639. ** over to a0,a1,a2. It then calls the output subroutine
  102640. ** and resets the aggregate accumulator registers in preparation
  102641. ** for the next GROUP BY batch.
  102642. */
  102643. sqlite3ExprCodeMove(pParse, iBMem, iAMem, pGroupBy->nExpr);
  102644. sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
  102645. VdbeComment((v, "output one row"));
  102646. sqlite3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd); VdbeCoverage(v);
  102647. VdbeComment((v, "check abort flag"));
  102648. sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
  102649. VdbeComment((v, "reset accumulator"));
  102650. /* Update the aggregate accumulators based on the content of
  102651. ** the current row
  102652. */
  102653. sqlite3VdbeJumpHere(v, j1);
  102654. updateAccumulator(pParse, &sAggInfo);
  102655. sqlite3VdbeAddOp2(v, OP_Integer, 1, iUseFlag);
  102656. VdbeComment((v, "indicate data in accumulator"));
  102657. /* End of the loop
  102658. */
  102659. if( groupBySort ){
  102660. sqlite3VdbeAddOp2(v, OP_SorterNext, sAggInfo.sortingIdx, addrTopOfLoop);
  102661. VdbeCoverage(v);
  102662. }else{
  102663. sqlite3WhereEnd(pWInfo);
  102664. sqlite3VdbeChangeToNoop(v, addrSortingIdx);
  102665. }
  102666. /* Output the final row of result
  102667. */
  102668. sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
  102669. VdbeComment((v, "output final row"));
  102670. /* Jump over the subroutines
  102671. */
  102672. sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEnd);
  102673. /* Generate a subroutine that outputs a single row of the result
  102674. ** set. This subroutine first looks at the iUseFlag. If iUseFlag
  102675. ** is less than or equal to zero, the subroutine is a no-op. If
  102676. ** the processing calls for the query to abort, this subroutine
  102677. ** increments the iAbortFlag memory location before returning in
  102678. ** order to signal the caller to abort.
  102679. */
  102680. addrSetAbort = sqlite3VdbeCurrentAddr(v);
  102681. sqlite3VdbeAddOp2(v, OP_Integer, 1, iAbortFlag);
  102682. VdbeComment((v, "set abort flag"));
  102683. sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
  102684. sqlite3VdbeResolveLabel(v, addrOutputRow);
  102685. addrOutputRow = sqlite3VdbeCurrentAddr(v);
  102686. sqlite3VdbeAddOp2(v, OP_IfPos, iUseFlag, addrOutputRow+2); VdbeCoverage(v);
  102687. VdbeComment((v, "Groupby result generator entry point"));
  102688. sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
  102689. finalizeAggFunctions(pParse, &sAggInfo);
  102690. sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, SQLITE_JUMPIFNULL);
  102691. selectInnerLoop(pParse, p, p->pEList, -1, &sSort,
  102692. &sDistinct, pDest,
  102693. addrOutputRow+1, addrSetAbort);
  102694. sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
  102695. VdbeComment((v, "end groupby result generator"));
  102696. /* Generate a subroutine that will reset the group-by accumulator
  102697. */
  102698. sqlite3VdbeResolveLabel(v, addrReset);
  102699. resetAccumulator(pParse, &sAggInfo);
  102700. sqlite3VdbeAddOp1(v, OP_Return, regReset);
  102701. } /* endif pGroupBy. Begin aggregate queries without GROUP BY: */
  102702. else {
  102703. ExprList *pDel = 0;
  102704. #ifndef SQLITE_OMIT_BTREECOUNT
  102705. Table *pTab;
  102706. if( (pTab = isSimpleCount(p, &sAggInfo))!=0 ){
  102707. /* If isSimpleCount() returns a pointer to a Table structure, then
  102708. ** the SQL statement is of the form:
  102709. **
  102710. ** SELECT count(*) FROM <tbl>
  102711. **
  102712. ** where the Table structure returned represents table <tbl>.
  102713. **
  102714. ** This statement is so common that it is optimized specially. The
  102715. ** OP_Count instruction is executed either on the intkey table that
  102716. ** contains the data for table <tbl> or on one of its indexes. It
  102717. ** is better to execute the op on an index, as indexes are almost
  102718. ** always spread across less pages than their corresponding tables.
  102719. */
  102720. const int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  102721. const int iCsr = pParse->nTab++; /* Cursor to scan b-tree */
  102722. Index *pIdx; /* Iterator variable */
  102723. KeyInfo *pKeyInfo = 0; /* Keyinfo for scanned index */
  102724. Index *pBest = 0; /* Best index found so far */
  102725. int iRoot = pTab->tnum; /* Root page of scanned b-tree */
  102726. sqlite3CodeVerifySchema(pParse, iDb);
  102727. sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
  102728. /* Search for the index that has the lowest scan cost.
  102729. **
  102730. ** (2011-04-15) Do not do a full scan of an unordered index.
  102731. **
  102732. ** (2013-10-03) Do not count the entries in a partial index.
  102733. **
  102734. ** In practice the KeyInfo structure will not be used. It is only
  102735. ** passed to keep OP_OpenRead happy.
  102736. */
  102737. if( !HasRowid(pTab) ) pBest = sqlite3PrimaryKeyIndex(pTab);
  102738. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  102739. if( pIdx->bUnordered==0
  102740. && pIdx->szIdxRow<pTab->szTabRow
  102741. && pIdx->pPartIdxWhere==0
  102742. && (!pBest || pIdx->szIdxRow<pBest->szIdxRow)
  102743. ){
  102744. pBest = pIdx;
  102745. }
  102746. }
  102747. if( pBest ){
  102748. iRoot = pBest->tnum;
  102749. pKeyInfo = sqlite3KeyInfoOfIndex(pParse, pBest);
  102750. }
  102751. /* Open a read-only cursor, execute the OP_Count, close the cursor. */
  102752. sqlite3VdbeAddOp4Int(v, OP_OpenRead, iCsr, iRoot, iDb, 1);
  102753. if( pKeyInfo ){
  102754. sqlite3VdbeChangeP4(v, -1, (char *)pKeyInfo, P4_KEYINFO);
  102755. }
  102756. sqlite3VdbeAddOp2(v, OP_Count, iCsr, sAggInfo.aFunc[0].iMem);
  102757. sqlite3VdbeAddOp1(v, OP_Close, iCsr);
  102758. explainSimpleCount(pParse, pTab, pBest);
  102759. }else
  102760. #endif /* SQLITE_OMIT_BTREECOUNT */
  102761. {
  102762. /* Check if the query is of one of the following forms:
  102763. **
  102764. ** SELECT min(x) FROM ...
  102765. ** SELECT max(x) FROM ...
  102766. **
  102767. ** If it is, then ask the code in where.c to attempt to sort results
  102768. ** as if there was an "ORDER ON x" or "ORDER ON x DESC" clause.
  102769. ** If where.c is able to produce results sorted in this order, then
  102770. ** add vdbe code to break out of the processing loop after the
  102771. ** first iteration (since the first iteration of the loop is
  102772. ** guaranteed to operate on the row with the minimum or maximum
  102773. ** value of x, the only row required).
  102774. **
  102775. ** A special flag must be passed to sqlite3WhereBegin() to slightly
  102776. ** modify behavior as follows:
  102777. **
  102778. ** + If the query is a "SELECT min(x)", then the loop coded by
  102779. ** where.c should not iterate over any values with a NULL value
  102780. ** for x.
  102781. **
  102782. ** + The optimizer code in where.c (the thing that decides which
  102783. ** index or indices to use) should place a different priority on
  102784. ** satisfying the 'ORDER BY' clause than it does in other cases.
  102785. ** Refer to code and comments in where.c for details.
  102786. */
  102787. ExprList *pMinMax = 0;
  102788. u8 flag = WHERE_ORDERBY_NORMAL;
  102789. assert( p->pGroupBy==0 );
  102790. assert( flag==0 );
  102791. if( p->pHaving==0 ){
  102792. flag = minMaxQuery(&sAggInfo, &pMinMax);
  102793. }
  102794. assert( flag==0 || (pMinMax!=0 && pMinMax->nExpr==1) );
  102795. if( flag ){
  102796. pMinMax = sqlite3ExprListDup(db, pMinMax, 0);
  102797. pDel = pMinMax;
  102798. if( pMinMax && !db->mallocFailed ){
  102799. pMinMax->a[0].sortOrder = flag!=WHERE_ORDERBY_MIN ?1:0;
  102800. pMinMax->a[0].pExpr->op = TK_COLUMN;
  102801. }
  102802. }
  102803. /* This case runs if the aggregate has no GROUP BY clause. The
  102804. ** processing is much simpler since there is only a single row
  102805. ** of output.
  102806. */
  102807. resetAccumulator(pParse, &sAggInfo);
  102808. pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pMinMax,0,flag,0);
  102809. if( pWInfo==0 ){
  102810. sqlite3ExprListDelete(db, pDel);
  102811. goto select_end;
  102812. }
  102813. updateAccumulator(pParse, &sAggInfo);
  102814. assert( pMinMax==0 || pMinMax->nExpr==1 );
  102815. if( sqlite3WhereIsOrdered(pWInfo)>0 ){
  102816. sqlite3VdbeAddOp2(v, OP_Goto, 0, sqlite3WhereBreakLabel(pWInfo));
  102817. VdbeComment((v, "%s() by index",
  102818. (flag==WHERE_ORDERBY_MIN?"min":"max")));
  102819. }
  102820. sqlite3WhereEnd(pWInfo);
  102821. finalizeAggFunctions(pParse, &sAggInfo);
  102822. }
  102823. sSort.pOrderBy = 0;
  102824. sqlite3ExprIfFalse(pParse, pHaving, addrEnd, SQLITE_JUMPIFNULL);
  102825. selectInnerLoop(pParse, p, p->pEList, -1, 0, 0,
  102826. pDest, addrEnd, addrEnd);
  102827. sqlite3ExprListDelete(db, pDel);
  102828. }
  102829. sqlite3VdbeResolveLabel(v, addrEnd);
  102830. } /* endif aggregate query */
  102831. if( sDistinct.eTnctType==WHERE_DISTINCT_UNORDERED ){
  102832. explainTempTable(pParse, "DISTINCT");
  102833. }
  102834. /* If there is an ORDER BY clause, then we need to sort the results
  102835. ** and send them to the callback one by one.
  102836. */
  102837. if( sSort.pOrderBy ){
  102838. explainTempTable(pParse, sSort.nOBSat>0 ? "RIGHT PART OF ORDER BY":"ORDER BY");
  102839. generateSortTail(pParse, p, &sSort, pEList->nExpr, pDest);
  102840. }
  102841. /* Jump here to skip this query
  102842. */
  102843. sqlite3VdbeResolveLabel(v, iEnd);
  102844. /* The SELECT was successfully coded. Set the return code to 0
  102845. ** to indicate no errors.
  102846. */
  102847. rc = 0;
  102848. /* Control jumps to here if an error is encountered above, or upon
  102849. ** successful coding of the SELECT.
  102850. */
  102851. select_end:
  102852. explainSetInteger(pParse->iSelectId, iRestoreSelectId);
  102853. /* Identify column names if results of the SELECT are to be output.
  102854. */
  102855. if( rc==SQLITE_OK && pDest->eDest==SRT_Output ){
  102856. generateColumnNames(pParse, pTabList, pEList);
  102857. }
  102858. sqlite3DbFree(db, sAggInfo.aCol);
  102859. sqlite3DbFree(db, sAggInfo.aFunc);
  102860. #if SELECTTRACE_ENABLED
  102861. SELECTTRACE(1,pParse,p,("end processing\n"));
  102862. pParse->nSelectIndent--;
  102863. #endif
  102864. return rc;
  102865. }
  102866. #ifdef SQLITE_DEBUG
  102867. /*
  102868. ** Generate a human-readable description of a the Select object.
  102869. */
  102870. SQLITE_PRIVATE void sqlite3TreeViewSelect(TreeView *pView, const Select *p, u8 moreToFollow){
  102871. int n = 0;
  102872. pView = sqlite3TreeViewPush(pView, moreToFollow);
  102873. sqlite3TreeViewLine(pView, "SELECT%s%s",
  102874. ((p->selFlags & SF_Distinct) ? " DISTINCT" : ""),
  102875. ((p->selFlags & SF_Aggregate) ? " agg_flag" : "")
  102876. );
  102877. if( p->pSrc && p->pSrc->nSrc ) n++;
  102878. if( p->pWhere ) n++;
  102879. if( p->pGroupBy ) n++;
  102880. if( p->pHaving ) n++;
  102881. if( p->pOrderBy ) n++;
  102882. if( p->pLimit ) n++;
  102883. if( p->pOffset ) n++;
  102884. if( p->pPrior ) n++;
  102885. sqlite3TreeViewExprList(pView, p->pEList, (n--)>0, "result-set");
  102886. if( p->pSrc && p->pSrc->nSrc ){
  102887. int i;
  102888. pView = sqlite3TreeViewPush(pView, (n--)>0);
  102889. sqlite3TreeViewLine(pView, "FROM");
  102890. for(i=0; i<p->pSrc->nSrc; i++){
  102891. struct SrcList_item *pItem = &p->pSrc->a[i];
  102892. StrAccum x;
  102893. char zLine[100];
  102894. sqlite3StrAccumInit(&x, zLine, sizeof(zLine), 0);
  102895. sqlite3XPrintf(&x, 0, "{%d,*}", pItem->iCursor);
  102896. if( pItem->zDatabase ){
  102897. sqlite3XPrintf(&x, 0, " %s.%s", pItem->zDatabase, pItem->zName);
  102898. }else if( pItem->zName ){
  102899. sqlite3XPrintf(&x, 0, " %s", pItem->zName);
  102900. }
  102901. if( pItem->pTab ){
  102902. sqlite3XPrintf(&x, 0, " tabname=%Q", pItem->pTab->zName);
  102903. }
  102904. if( pItem->zAlias ){
  102905. sqlite3XPrintf(&x, 0, " (AS %s)", pItem->zAlias);
  102906. }
  102907. if( pItem->jointype & JT_LEFT ){
  102908. sqlite3XPrintf(&x, 0, " LEFT-JOIN");
  102909. }
  102910. sqlite3StrAccumFinish(&x);
  102911. sqlite3TreeViewItem(pView, zLine, i<p->pSrc->nSrc-1);
  102912. if( pItem->pSelect ){
  102913. sqlite3TreeViewSelect(pView, pItem->pSelect, 0);
  102914. }
  102915. sqlite3TreeViewPop(pView);
  102916. }
  102917. sqlite3TreeViewPop(pView);
  102918. }
  102919. if( p->pWhere ){
  102920. sqlite3TreeViewItem(pView, "WHERE", (n--)>0);
  102921. sqlite3TreeViewExpr(pView, p->pWhere, 0);
  102922. sqlite3TreeViewPop(pView);
  102923. }
  102924. if( p->pGroupBy ){
  102925. sqlite3TreeViewExprList(pView, p->pGroupBy, (n--)>0, "GROUPBY");
  102926. }
  102927. if( p->pHaving ){
  102928. sqlite3TreeViewItem(pView, "HAVING", (n--)>0);
  102929. sqlite3TreeViewExpr(pView, p->pHaving, 0);
  102930. sqlite3TreeViewPop(pView);
  102931. }
  102932. if( p->pOrderBy ){
  102933. sqlite3TreeViewExprList(pView, p->pOrderBy, (n--)>0, "ORDERBY");
  102934. }
  102935. if( p->pLimit ){
  102936. sqlite3TreeViewItem(pView, "LIMIT", (n--)>0);
  102937. sqlite3TreeViewExpr(pView, p->pLimit, 0);
  102938. sqlite3TreeViewPop(pView);
  102939. }
  102940. if( p->pOffset ){
  102941. sqlite3TreeViewItem(pView, "OFFSET", (n--)>0);
  102942. sqlite3TreeViewExpr(pView, p->pOffset, 0);
  102943. sqlite3TreeViewPop(pView);
  102944. }
  102945. if( p->pPrior ){
  102946. const char *zOp = "UNION";
  102947. switch( p->op ){
  102948. case TK_ALL: zOp = "UNION ALL"; break;
  102949. case TK_INTERSECT: zOp = "INTERSECT"; break;
  102950. case TK_EXCEPT: zOp = "EXCEPT"; break;
  102951. }
  102952. sqlite3TreeViewItem(pView, zOp, (n--)>0);
  102953. sqlite3TreeViewSelect(pView, p->pPrior, 0);
  102954. sqlite3TreeViewPop(pView);
  102955. }
  102956. sqlite3TreeViewPop(pView);
  102957. }
  102958. #endif /* SQLITE_DEBUG */
  102959. /************** End of select.c **********************************************/
  102960. /************** Begin file table.c *******************************************/
  102961. /*
  102962. ** 2001 September 15
  102963. **
  102964. ** The author disclaims copyright to this source code. In place of
  102965. ** a legal notice, here is a blessing:
  102966. **
  102967. ** May you do good and not evil.
  102968. ** May you find forgiveness for yourself and forgive others.
  102969. ** May you share freely, never taking more than you give.
  102970. **
  102971. *************************************************************************
  102972. ** This file contains the sqlite3_get_table() and sqlite3_free_table()
  102973. ** interface routines. These are just wrappers around the main
  102974. ** interface routine of sqlite3_exec().
  102975. **
  102976. ** These routines are in a separate files so that they will not be linked
  102977. ** if they are not used.
  102978. */
  102979. /* #include <stdlib.h> */
  102980. /* #include <string.h> */
  102981. #ifndef SQLITE_OMIT_GET_TABLE
  102982. /*
  102983. ** This structure is used to pass data from sqlite3_get_table() through
  102984. ** to the callback function is uses to build the result.
  102985. */
  102986. typedef struct TabResult {
  102987. char **azResult; /* Accumulated output */
  102988. char *zErrMsg; /* Error message text, if an error occurs */
  102989. u32 nAlloc; /* Slots allocated for azResult[] */
  102990. u32 nRow; /* Number of rows in the result */
  102991. u32 nColumn; /* Number of columns in the result */
  102992. u32 nData; /* Slots used in azResult[]. (nRow+1)*nColumn */
  102993. int rc; /* Return code from sqlite3_exec() */
  102994. } TabResult;
  102995. /*
  102996. ** This routine is called once for each row in the result table. Its job
  102997. ** is to fill in the TabResult structure appropriately, allocating new
  102998. ** memory as necessary.
  102999. */
  103000. static int sqlite3_get_table_cb(void *pArg, int nCol, char **argv, char **colv){
  103001. TabResult *p = (TabResult*)pArg; /* Result accumulator */
  103002. int need; /* Slots needed in p->azResult[] */
  103003. int i; /* Loop counter */
  103004. char *z; /* A single column of result */
  103005. /* Make sure there is enough space in p->azResult to hold everything
  103006. ** we need to remember from this invocation of the callback.
  103007. */
  103008. if( p->nRow==0 && argv!=0 ){
  103009. need = nCol*2;
  103010. }else{
  103011. need = nCol;
  103012. }
  103013. if( p->nData + need > p->nAlloc ){
  103014. char **azNew;
  103015. p->nAlloc = p->nAlloc*2 + need;
  103016. azNew = sqlite3_realloc64( p->azResult, sizeof(char*)*p->nAlloc );
  103017. if( azNew==0 ) goto malloc_failed;
  103018. p->azResult = azNew;
  103019. }
  103020. /* If this is the first row, then generate an extra row containing
  103021. ** the names of all columns.
  103022. */
  103023. if( p->nRow==0 ){
  103024. p->nColumn = nCol;
  103025. for(i=0; i<nCol; i++){
  103026. z = sqlite3_mprintf("%s", colv[i]);
  103027. if( z==0 ) goto malloc_failed;
  103028. p->azResult[p->nData++] = z;
  103029. }
  103030. }else if( (int)p->nColumn!=nCol ){
  103031. sqlite3_free(p->zErrMsg);
  103032. p->zErrMsg = sqlite3_mprintf(
  103033. "sqlite3_get_table() called with two or more incompatible queries"
  103034. );
  103035. p->rc = SQLITE_ERROR;
  103036. return 1;
  103037. }
  103038. /* Copy over the row data
  103039. */
  103040. if( argv!=0 ){
  103041. for(i=0; i<nCol; i++){
  103042. if( argv[i]==0 ){
  103043. z = 0;
  103044. }else{
  103045. int n = sqlite3Strlen30(argv[i])+1;
  103046. z = sqlite3_malloc( n );
  103047. if( z==0 ) goto malloc_failed;
  103048. memcpy(z, argv[i], n);
  103049. }
  103050. p->azResult[p->nData++] = z;
  103051. }
  103052. p->nRow++;
  103053. }
  103054. return 0;
  103055. malloc_failed:
  103056. p->rc = SQLITE_NOMEM;
  103057. return 1;
  103058. }
  103059. /*
  103060. ** Query the database. But instead of invoking a callback for each row,
  103061. ** malloc() for space to hold the result and return the entire results
  103062. ** at the conclusion of the call.
  103063. **
  103064. ** The result that is written to ***pazResult is held in memory obtained
  103065. ** from malloc(). But the caller cannot free this memory directly.
  103066. ** Instead, the entire table should be passed to sqlite3_free_table() when
  103067. ** the calling procedure is finished using it.
  103068. */
  103069. SQLITE_API int sqlite3_get_table(
  103070. sqlite3 *db, /* The database on which the SQL executes */
  103071. const char *zSql, /* The SQL to be executed */
  103072. char ***pazResult, /* Write the result table here */
  103073. int *pnRow, /* Write the number of rows in the result here */
  103074. int *pnColumn, /* Write the number of columns of result here */
  103075. char **pzErrMsg /* Write error messages here */
  103076. ){
  103077. int rc;
  103078. TabResult res;
  103079. #ifdef SQLITE_ENABLE_API_ARMOR
  103080. if( pazResult==0 ) return SQLITE_MISUSE_BKPT;
  103081. #endif
  103082. *pazResult = 0;
  103083. if( pnColumn ) *pnColumn = 0;
  103084. if( pnRow ) *pnRow = 0;
  103085. if( pzErrMsg ) *pzErrMsg = 0;
  103086. res.zErrMsg = 0;
  103087. res.nRow = 0;
  103088. res.nColumn = 0;
  103089. res.nData = 1;
  103090. res.nAlloc = 20;
  103091. res.rc = SQLITE_OK;
  103092. res.azResult = sqlite3_malloc(sizeof(char*)*res.nAlloc );
  103093. if( res.azResult==0 ){
  103094. db->errCode = SQLITE_NOMEM;
  103095. return SQLITE_NOMEM;
  103096. }
  103097. res.azResult[0] = 0;
  103098. rc = sqlite3_exec(db, zSql, sqlite3_get_table_cb, &res, pzErrMsg);
  103099. assert( sizeof(res.azResult[0])>= sizeof(res.nData) );
  103100. res.azResult[0] = SQLITE_INT_TO_PTR(res.nData);
  103101. if( (rc&0xff)==SQLITE_ABORT ){
  103102. sqlite3_free_table(&res.azResult[1]);
  103103. if( res.zErrMsg ){
  103104. if( pzErrMsg ){
  103105. sqlite3_free(*pzErrMsg);
  103106. *pzErrMsg = sqlite3_mprintf("%s",res.zErrMsg);
  103107. }
  103108. sqlite3_free(res.zErrMsg);
  103109. }
  103110. db->errCode = res.rc; /* Assume 32-bit assignment is atomic */
  103111. return res.rc;
  103112. }
  103113. sqlite3_free(res.zErrMsg);
  103114. if( rc!=SQLITE_OK ){
  103115. sqlite3_free_table(&res.azResult[1]);
  103116. return rc;
  103117. }
  103118. if( res.nAlloc>res.nData ){
  103119. char **azNew;
  103120. azNew = sqlite3_realloc( res.azResult, sizeof(char*)*res.nData );
  103121. if( azNew==0 ){
  103122. sqlite3_free_table(&res.azResult[1]);
  103123. db->errCode = SQLITE_NOMEM;
  103124. return SQLITE_NOMEM;
  103125. }
  103126. res.azResult = azNew;
  103127. }
  103128. *pazResult = &res.azResult[1];
  103129. if( pnColumn ) *pnColumn = res.nColumn;
  103130. if( pnRow ) *pnRow = res.nRow;
  103131. return rc;
  103132. }
  103133. /*
  103134. ** This routine frees the space the sqlite3_get_table() malloced.
  103135. */
  103136. SQLITE_API void sqlite3_free_table(
  103137. char **azResult /* Result returned from sqlite3_get_table() */
  103138. ){
  103139. if( azResult ){
  103140. int i, n;
  103141. azResult--;
  103142. assert( azResult!=0 );
  103143. n = SQLITE_PTR_TO_INT(azResult[0]);
  103144. for(i=1; i<n; i++){ if( azResult[i] ) sqlite3_free(azResult[i]); }
  103145. sqlite3_free(azResult);
  103146. }
  103147. }
  103148. #endif /* SQLITE_OMIT_GET_TABLE */
  103149. /************** End of table.c ***********************************************/
  103150. /************** Begin file trigger.c *****************************************/
  103151. /*
  103152. **
  103153. ** The author disclaims copyright to this source code. In place of
  103154. ** a legal notice, here is a blessing:
  103155. **
  103156. ** May you do good and not evil.
  103157. ** May you find forgiveness for yourself and forgive others.
  103158. ** May you share freely, never taking more than you give.
  103159. **
  103160. *************************************************************************
  103161. ** This file contains the implementation for TRIGGERs
  103162. */
  103163. #ifndef SQLITE_OMIT_TRIGGER
  103164. /*
  103165. ** Delete a linked list of TriggerStep structures.
  103166. */
  103167. SQLITE_PRIVATE void sqlite3DeleteTriggerStep(sqlite3 *db, TriggerStep *pTriggerStep){
  103168. while( pTriggerStep ){
  103169. TriggerStep * pTmp = pTriggerStep;
  103170. pTriggerStep = pTriggerStep->pNext;
  103171. sqlite3ExprDelete(db, pTmp->pWhere);
  103172. sqlite3ExprListDelete(db, pTmp->pExprList);
  103173. sqlite3SelectDelete(db, pTmp->pSelect);
  103174. sqlite3IdListDelete(db, pTmp->pIdList);
  103175. sqlite3DbFree(db, pTmp);
  103176. }
  103177. }
  103178. /*
  103179. ** Given table pTab, return a list of all the triggers attached to
  103180. ** the table. The list is connected by Trigger.pNext pointers.
  103181. **
  103182. ** All of the triggers on pTab that are in the same database as pTab
  103183. ** are already attached to pTab->pTrigger. But there might be additional
  103184. ** triggers on pTab in the TEMP schema. This routine prepends all
  103185. ** TEMP triggers on pTab to the beginning of the pTab->pTrigger list
  103186. ** and returns the combined list.
  103187. **
  103188. ** To state it another way: This routine returns a list of all triggers
  103189. ** that fire off of pTab. The list will include any TEMP triggers on
  103190. ** pTab as well as the triggers lised in pTab->pTrigger.
  103191. */
  103192. SQLITE_PRIVATE Trigger *sqlite3TriggerList(Parse *pParse, Table *pTab){
  103193. Schema * const pTmpSchema = pParse->db->aDb[1].pSchema;
  103194. Trigger *pList = 0; /* List of triggers to return */
  103195. if( pParse->disableTriggers ){
  103196. return 0;
  103197. }
  103198. if( pTmpSchema!=pTab->pSchema ){
  103199. HashElem *p;
  103200. assert( sqlite3SchemaMutexHeld(pParse->db, 0, pTmpSchema) );
  103201. for(p=sqliteHashFirst(&pTmpSchema->trigHash); p; p=sqliteHashNext(p)){
  103202. Trigger *pTrig = (Trigger *)sqliteHashData(p);
  103203. if( pTrig->pTabSchema==pTab->pSchema
  103204. && 0==sqlite3StrICmp(pTrig->table, pTab->zName)
  103205. ){
  103206. pTrig->pNext = (pList ? pList : pTab->pTrigger);
  103207. pList = pTrig;
  103208. }
  103209. }
  103210. }
  103211. return (pList ? pList : pTab->pTrigger);
  103212. }
  103213. /*
  103214. ** This is called by the parser when it sees a CREATE TRIGGER statement
  103215. ** up to the point of the BEGIN before the trigger actions. A Trigger
  103216. ** structure is generated based on the information available and stored
  103217. ** in pParse->pNewTrigger. After the trigger actions have been parsed, the
  103218. ** sqlite3FinishTrigger() function is called to complete the trigger
  103219. ** construction process.
  103220. */
  103221. SQLITE_PRIVATE void sqlite3BeginTrigger(
  103222. Parse *pParse, /* The parse context of the CREATE TRIGGER statement */
  103223. Token *pName1, /* The name of the trigger */
  103224. Token *pName2, /* The name of the trigger */
  103225. int tr_tm, /* One of TK_BEFORE, TK_AFTER, TK_INSTEAD */
  103226. int op, /* One of TK_INSERT, TK_UPDATE, TK_DELETE */
  103227. IdList *pColumns, /* column list if this is an UPDATE OF trigger */
  103228. SrcList *pTableName,/* The name of the table/view the trigger applies to */
  103229. Expr *pWhen, /* WHEN clause */
  103230. int isTemp, /* True if the TEMPORARY keyword is present */
  103231. int noErr /* Suppress errors if the trigger already exists */
  103232. ){
  103233. Trigger *pTrigger = 0; /* The new trigger */
  103234. Table *pTab; /* Table that the trigger fires off of */
  103235. char *zName = 0; /* Name of the trigger */
  103236. sqlite3 *db = pParse->db; /* The database connection */
  103237. int iDb; /* The database to store the trigger in */
  103238. Token *pName; /* The unqualified db name */
  103239. DbFixer sFix; /* State vector for the DB fixer */
  103240. int iTabDb; /* Index of the database holding pTab */
  103241. assert( pName1!=0 ); /* pName1->z might be NULL, but not pName1 itself */
  103242. assert( pName2!=0 );
  103243. assert( op==TK_INSERT || op==TK_UPDATE || op==TK_DELETE );
  103244. assert( op>0 && op<0xff );
  103245. if( isTemp ){
  103246. /* If TEMP was specified, then the trigger name may not be qualified. */
  103247. if( pName2->n>0 ){
  103248. sqlite3ErrorMsg(pParse, "temporary trigger may not have qualified name");
  103249. goto trigger_cleanup;
  103250. }
  103251. iDb = 1;
  103252. pName = pName1;
  103253. }else{
  103254. /* Figure out the db that the trigger will be created in */
  103255. iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
  103256. if( iDb<0 ){
  103257. goto trigger_cleanup;
  103258. }
  103259. }
  103260. if( !pTableName || db->mallocFailed ){
  103261. goto trigger_cleanup;
  103262. }
  103263. /* A long-standing parser bug is that this syntax was allowed:
  103264. **
  103265. ** CREATE TRIGGER attached.demo AFTER INSERT ON attached.tab ....
  103266. ** ^^^^^^^^
  103267. **
  103268. ** To maintain backwards compatibility, ignore the database
  103269. ** name on pTableName if we are reparsing out of SQLITE_MASTER.
  103270. */
  103271. if( db->init.busy && iDb!=1 ){
  103272. sqlite3DbFree(db, pTableName->a[0].zDatabase);
  103273. pTableName->a[0].zDatabase = 0;
  103274. }
  103275. /* If the trigger name was unqualified, and the table is a temp table,
  103276. ** then set iDb to 1 to create the trigger in the temporary database.
  103277. ** If sqlite3SrcListLookup() returns 0, indicating the table does not
  103278. ** exist, the error is caught by the block below.
  103279. */
  103280. pTab = sqlite3SrcListLookup(pParse, pTableName);
  103281. if( db->init.busy==0 && pName2->n==0 && pTab
  103282. && pTab->pSchema==db->aDb[1].pSchema ){
  103283. iDb = 1;
  103284. }
  103285. /* Ensure the table name matches database name and that the table exists */
  103286. if( db->mallocFailed ) goto trigger_cleanup;
  103287. assert( pTableName->nSrc==1 );
  103288. sqlite3FixInit(&sFix, pParse, iDb, "trigger", pName);
  103289. if( sqlite3FixSrcList(&sFix, pTableName) ){
  103290. goto trigger_cleanup;
  103291. }
  103292. pTab = sqlite3SrcListLookup(pParse, pTableName);
  103293. if( !pTab ){
  103294. /* The table does not exist. */
  103295. if( db->init.iDb==1 ){
  103296. /* Ticket #3810.
  103297. ** Normally, whenever a table is dropped, all associated triggers are
  103298. ** dropped too. But if a TEMP trigger is created on a non-TEMP table
  103299. ** and the table is dropped by a different database connection, the
  103300. ** trigger is not visible to the database connection that does the
  103301. ** drop so the trigger cannot be dropped. This results in an
  103302. ** "orphaned trigger" - a trigger whose associated table is missing.
  103303. */
  103304. db->init.orphanTrigger = 1;
  103305. }
  103306. goto trigger_cleanup;
  103307. }
  103308. if( IsVirtual(pTab) ){
  103309. sqlite3ErrorMsg(pParse, "cannot create triggers on virtual tables");
  103310. goto trigger_cleanup;
  103311. }
  103312. /* Check that the trigger name is not reserved and that no trigger of the
  103313. ** specified name exists */
  103314. zName = sqlite3NameFromToken(db, pName);
  103315. if( !zName || SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
  103316. goto trigger_cleanup;
  103317. }
  103318. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  103319. if( sqlite3HashFind(&(db->aDb[iDb].pSchema->trigHash),zName) ){
  103320. if( !noErr ){
  103321. sqlite3ErrorMsg(pParse, "trigger %T already exists", pName);
  103322. }else{
  103323. assert( !db->init.busy );
  103324. sqlite3CodeVerifySchema(pParse, iDb);
  103325. }
  103326. goto trigger_cleanup;
  103327. }
  103328. /* Do not create a trigger on a system table */
  103329. if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
  103330. sqlite3ErrorMsg(pParse, "cannot create trigger on system table");
  103331. pParse->nErr++;
  103332. goto trigger_cleanup;
  103333. }
  103334. /* INSTEAD of triggers are only for views and views only support INSTEAD
  103335. ** of triggers.
  103336. */
  103337. if( pTab->pSelect && tr_tm!=TK_INSTEAD ){
  103338. sqlite3ErrorMsg(pParse, "cannot create %s trigger on view: %S",
  103339. (tr_tm == TK_BEFORE)?"BEFORE":"AFTER", pTableName, 0);
  103340. goto trigger_cleanup;
  103341. }
  103342. if( !pTab->pSelect && tr_tm==TK_INSTEAD ){
  103343. sqlite3ErrorMsg(pParse, "cannot create INSTEAD OF"
  103344. " trigger on table: %S", pTableName, 0);
  103345. goto trigger_cleanup;
  103346. }
  103347. iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  103348. #ifndef SQLITE_OMIT_AUTHORIZATION
  103349. {
  103350. int code = SQLITE_CREATE_TRIGGER;
  103351. const char *zDb = db->aDb[iTabDb].zName;
  103352. const char *zDbTrig = isTemp ? db->aDb[1].zName : zDb;
  103353. if( iTabDb==1 || isTemp ) code = SQLITE_CREATE_TEMP_TRIGGER;
  103354. if( sqlite3AuthCheck(pParse, code, zName, pTab->zName, zDbTrig) ){
  103355. goto trigger_cleanup;
  103356. }
  103357. if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iTabDb),0,zDb)){
  103358. goto trigger_cleanup;
  103359. }
  103360. }
  103361. #endif
  103362. /* INSTEAD OF triggers can only appear on views and BEFORE triggers
  103363. ** cannot appear on views. So we might as well translate every
  103364. ** INSTEAD OF trigger into a BEFORE trigger. It simplifies code
  103365. ** elsewhere.
  103366. */
  103367. if (tr_tm == TK_INSTEAD){
  103368. tr_tm = TK_BEFORE;
  103369. }
  103370. /* Build the Trigger object */
  103371. pTrigger = (Trigger*)sqlite3DbMallocZero(db, sizeof(Trigger));
  103372. if( pTrigger==0 ) goto trigger_cleanup;
  103373. pTrigger->zName = zName;
  103374. zName = 0;
  103375. pTrigger->table = sqlite3DbStrDup(db, pTableName->a[0].zName);
  103376. pTrigger->pSchema = db->aDb[iDb].pSchema;
  103377. pTrigger->pTabSchema = pTab->pSchema;
  103378. pTrigger->op = (u8)op;
  103379. pTrigger->tr_tm = tr_tm==TK_BEFORE ? TRIGGER_BEFORE : TRIGGER_AFTER;
  103380. pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
  103381. pTrigger->pColumns = sqlite3IdListDup(db, pColumns);
  103382. assert( pParse->pNewTrigger==0 );
  103383. pParse->pNewTrigger = pTrigger;
  103384. trigger_cleanup:
  103385. sqlite3DbFree(db, zName);
  103386. sqlite3SrcListDelete(db, pTableName);
  103387. sqlite3IdListDelete(db, pColumns);
  103388. sqlite3ExprDelete(db, pWhen);
  103389. if( !pParse->pNewTrigger ){
  103390. sqlite3DeleteTrigger(db, pTrigger);
  103391. }else{
  103392. assert( pParse->pNewTrigger==pTrigger );
  103393. }
  103394. }
  103395. /*
  103396. ** This routine is called after all of the trigger actions have been parsed
  103397. ** in order to complete the process of building the trigger.
  103398. */
  103399. SQLITE_PRIVATE void sqlite3FinishTrigger(
  103400. Parse *pParse, /* Parser context */
  103401. TriggerStep *pStepList, /* The triggered program */
  103402. Token *pAll /* Token that describes the complete CREATE TRIGGER */
  103403. ){
  103404. Trigger *pTrig = pParse->pNewTrigger; /* Trigger being finished */
  103405. char *zName; /* Name of trigger */
  103406. sqlite3 *db = pParse->db; /* The database */
  103407. DbFixer sFix; /* Fixer object */
  103408. int iDb; /* Database containing the trigger */
  103409. Token nameToken; /* Trigger name for error reporting */
  103410. pParse->pNewTrigger = 0;
  103411. if( NEVER(pParse->nErr) || !pTrig ) goto triggerfinish_cleanup;
  103412. zName = pTrig->zName;
  103413. iDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
  103414. pTrig->step_list = pStepList;
  103415. while( pStepList ){
  103416. pStepList->pTrig = pTrig;
  103417. pStepList = pStepList->pNext;
  103418. }
  103419. nameToken.z = pTrig->zName;
  103420. nameToken.n = sqlite3Strlen30(nameToken.z);
  103421. sqlite3FixInit(&sFix, pParse, iDb, "trigger", &nameToken);
  103422. if( sqlite3FixTriggerStep(&sFix, pTrig->step_list)
  103423. || sqlite3FixExpr(&sFix, pTrig->pWhen)
  103424. ){
  103425. goto triggerfinish_cleanup;
  103426. }
  103427. /* if we are not initializing,
  103428. ** build the sqlite_master entry
  103429. */
  103430. if( !db->init.busy ){
  103431. Vdbe *v;
  103432. char *z;
  103433. /* Make an entry in the sqlite_master table */
  103434. v = sqlite3GetVdbe(pParse);
  103435. if( v==0 ) goto triggerfinish_cleanup;
  103436. sqlite3BeginWriteOperation(pParse, 0, iDb);
  103437. z = sqlite3DbStrNDup(db, (char*)pAll->z, pAll->n);
  103438. sqlite3NestedParse(pParse,
  103439. "INSERT INTO %Q.%s VALUES('trigger',%Q,%Q,0,'CREATE TRIGGER %q')",
  103440. db->aDb[iDb].zName, SCHEMA_TABLE(iDb), zName,
  103441. pTrig->table, z);
  103442. sqlite3DbFree(db, z);
  103443. sqlite3ChangeCookie(pParse, iDb);
  103444. sqlite3VdbeAddParseSchemaOp(v, iDb,
  103445. sqlite3MPrintf(db, "type='trigger' AND name='%q'", zName));
  103446. }
  103447. if( db->init.busy ){
  103448. Trigger *pLink = pTrig;
  103449. Hash *pHash = &db->aDb[iDb].pSchema->trigHash;
  103450. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  103451. pTrig = sqlite3HashInsert(pHash, zName, pTrig);
  103452. if( pTrig ){
  103453. db->mallocFailed = 1;
  103454. }else if( pLink->pSchema==pLink->pTabSchema ){
  103455. Table *pTab;
  103456. pTab = sqlite3HashFind(&pLink->pTabSchema->tblHash, pLink->table);
  103457. assert( pTab!=0 );
  103458. pLink->pNext = pTab->pTrigger;
  103459. pTab->pTrigger = pLink;
  103460. }
  103461. }
  103462. triggerfinish_cleanup:
  103463. sqlite3DeleteTrigger(db, pTrig);
  103464. assert( !pParse->pNewTrigger );
  103465. sqlite3DeleteTriggerStep(db, pStepList);
  103466. }
  103467. /*
  103468. ** Turn a SELECT statement (that the pSelect parameter points to) into
  103469. ** a trigger step. Return a pointer to a TriggerStep structure.
  103470. **
  103471. ** The parser calls this routine when it finds a SELECT statement in
  103472. ** body of a TRIGGER.
  103473. */
  103474. SQLITE_PRIVATE TriggerStep *sqlite3TriggerSelectStep(sqlite3 *db, Select *pSelect){
  103475. TriggerStep *pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep));
  103476. if( pTriggerStep==0 ) {
  103477. sqlite3SelectDelete(db, pSelect);
  103478. return 0;
  103479. }
  103480. pTriggerStep->op = TK_SELECT;
  103481. pTriggerStep->pSelect = pSelect;
  103482. pTriggerStep->orconf = OE_Default;
  103483. return pTriggerStep;
  103484. }
  103485. /*
  103486. ** Allocate space to hold a new trigger step. The allocated space
  103487. ** holds both the TriggerStep object and the TriggerStep.target.z string.
  103488. **
  103489. ** If an OOM error occurs, NULL is returned and db->mallocFailed is set.
  103490. */
  103491. static TriggerStep *triggerStepAllocate(
  103492. sqlite3 *db, /* Database connection */
  103493. u8 op, /* Trigger opcode */
  103494. Token *pName /* The target name */
  103495. ){
  103496. TriggerStep *pTriggerStep;
  103497. pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep) + pName->n);
  103498. if( pTriggerStep ){
  103499. char *z = (char*)&pTriggerStep[1];
  103500. memcpy(z, pName->z, pName->n);
  103501. pTriggerStep->target.z = z;
  103502. pTriggerStep->target.n = pName->n;
  103503. pTriggerStep->op = op;
  103504. }
  103505. return pTriggerStep;
  103506. }
  103507. /*
  103508. ** Build a trigger step out of an INSERT statement. Return a pointer
  103509. ** to the new trigger step.
  103510. **
  103511. ** The parser calls this routine when it sees an INSERT inside the
  103512. ** body of a trigger.
  103513. */
  103514. SQLITE_PRIVATE TriggerStep *sqlite3TriggerInsertStep(
  103515. sqlite3 *db, /* The database connection */
  103516. Token *pTableName, /* Name of the table into which we insert */
  103517. IdList *pColumn, /* List of columns in pTableName to insert into */
  103518. Select *pSelect, /* A SELECT statement that supplies values */
  103519. u8 orconf /* The conflict algorithm (OE_Abort, OE_Replace, etc.) */
  103520. ){
  103521. TriggerStep *pTriggerStep;
  103522. assert(pSelect != 0 || db->mallocFailed);
  103523. pTriggerStep = triggerStepAllocate(db, TK_INSERT, pTableName);
  103524. if( pTriggerStep ){
  103525. pTriggerStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
  103526. pTriggerStep->pIdList = pColumn;
  103527. pTriggerStep->orconf = orconf;
  103528. }else{
  103529. sqlite3IdListDelete(db, pColumn);
  103530. }
  103531. sqlite3SelectDelete(db, pSelect);
  103532. return pTriggerStep;
  103533. }
  103534. /*
  103535. ** Construct a trigger step that implements an UPDATE statement and return
  103536. ** a pointer to that trigger step. The parser calls this routine when it
  103537. ** sees an UPDATE statement inside the body of a CREATE TRIGGER.
  103538. */
  103539. SQLITE_PRIVATE TriggerStep *sqlite3TriggerUpdateStep(
  103540. sqlite3 *db, /* The database connection */
  103541. Token *pTableName, /* Name of the table to be updated */
  103542. ExprList *pEList, /* The SET clause: list of column and new values */
  103543. Expr *pWhere, /* The WHERE clause */
  103544. u8 orconf /* The conflict algorithm. (OE_Abort, OE_Ignore, etc) */
  103545. ){
  103546. TriggerStep *pTriggerStep;
  103547. pTriggerStep = triggerStepAllocate(db, TK_UPDATE, pTableName);
  103548. if( pTriggerStep ){
  103549. pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE);
  103550. pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
  103551. pTriggerStep->orconf = orconf;
  103552. }
  103553. sqlite3ExprListDelete(db, pEList);
  103554. sqlite3ExprDelete(db, pWhere);
  103555. return pTriggerStep;
  103556. }
  103557. /*
  103558. ** Construct a trigger step that implements a DELETE statement and return
  103559. ** a pointer to that trigger step. The parser calls this routine when it
  103560. ** sees a DELETE statement inside the body of a CREATE TRIGGER.
  103561. */
  103562. SQLITE_PRIVATE TriggerStep *sqlite3TriggerDeleteStep(
  103563. sqlite3 *db, /* Database connection */
  103564. Token *pTableName, /* The table from which rows are deleted */
  103565. Expr *pWhere /* The WHERE clause */
  103566. ){
  103567. TriggerStep *pTriggerStep;
  103568. pTriggerStep = triggerStepAllocate(db, TK_DELETE, pTableName);
  103569. if( pTriggerStep ){
  103570. pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
  103571. pTriggerStep->orconf = OE_Default;
  103572. }
  103573. sqlite3ExprDelete(db, pWhere);
  103574. return pTriggerStep;
  103575. }
  103576. /*
  103577. ** Recursively delete a Trigger structure
  103578. */
  103579. SQLITE_PRIVATE void sqlite3DeleteTrigger(sqlite3 *db, Trigger *pTrigger){
  103580. if( pTrigger==0 ) return;
  103581. sqlite3DeleteTriggerStep(db, pTrigger->step_list);
  103582. sqlite3DbFree(db, pTrigger->zName);
  103583. sqlite3DbFree(db, pTrigger->table);
  103584. sqlite3ExprDelete(db, pTrigger->pWhen);
  103585. sqlite3IdListDelete(db, pTrigger->pColumns);
  103586. sqlite3DbFree(db, pTrigger);
  103587. }
  103588. /*
  103589. ** This function is called to drop a trigger from the database schema.
  103590. **
  103591. ** This may be called directly from the parser and therefore identifies
  103592. ** the trigger by name. The sqlite3DropTriggerPtr() routine does the
  103593. ** same job as this routine except it takes a pointer to the trigger
  103594. ** instead of the trigger name.
  103595. **/
  103596. SQLITE_PRIVATE void sqlite3DropTrigger(Parse *pParse, SrcList *pName, int noErr){
  103597. Trigger *pTrigger = 0;
  103598. int i;
  103599. const char *zDb;
  103600. const char *zName;
  103601. sqlite3 *db = pParse->db;
  103602. if( db->mallocFailed ) goto drop_trigger_cleanup;
  103603. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  103604. goto drop_trigger_cleanup;
  103605. }
  103606. assert( pName->nSrc==1 );
  103607. zDb = pName->a[0].zDatabase;
  103608. zName = pName->a[0].zName;
  103609. assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
  103610. for(i=OMIT_TEMPDB; i<db->nDb; i++){
  103611. int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
  103612. if( zDb && sqlite3StrICmp(db->aDb[j].zName, zDb) ) continue;
  103613. assert( sqlite3SchemaMutexHeld(db, j, 0) );
  103614. pTrigger = sqlite3HashFind(&(db->aDb[j].pSchema->trigHash), zName);
  103615. if( pTrigger ) break;
  103616. }
  103617. if( !pTrigger ){
  103618. if( !noErr ){
  103619. sqlite3ErrorMsg(pParse, "no such trigger: %S", pName, 0);
  103620. }else{
  103621. sqlite3CodeVerifyNamedSchema(pParse, zDb);
  103622. }
  103623. pParse->checkSchema = 1;
  103624. goto drop_trigger_cleanup;
  103625. }
  103626. sqlite3DropTriggerPtr(pParse, pTrigger);
  103627. drop_trigger_cleanup:
  103628. sqlite3SrcListDelete(db, pName);
  103629. }
  103630. /*
  103631. ** Return a pointer to the Table structure for the table that a trigger
  103632. ** is set on.
  103633. */
  103634. static Table *tableOfTrigger(Trigger *pTrigger){
  103635. return sqlite3HashFind(&pTrigger->pTabSchema->tblHash, pTrigger->table);
  103636. }
  103637. /*
  103638. ** Drop a trigger given a pointer to that trigger.
  103639. */
  103640. SQLITE_PRIVATE void sqlite3DropTriggerPtr(Parse *pParse, Trigger *pTrigger){
  103641. Table *pTable;
  103642. Vdbe *v;
  103643. sqlite3 *db = pParse->db;
  103644. int iDb;
  103645. iDb = sqlite3SchemaToIndex(pParse->db, pTrigger->pSchema);
  103646. assert( iDb>=0 && iDb<db->nDb );
  103647. pTable = tableOfTrigger(pTrigger);
  103648. assert( pTable );
  103649. assert( pTable->pSchema==pTrigger->pSchema || iDb==1 );
  103650. #ifndef SQLITE_OMIT_AUTHORIZATION
  103651. {
  103652. int code = SQLITE_DROP_TRIGGER;
  103653. const char *zDb = db->aDb[iDb].zName;
  103654. const char *zTab = SCHEMA_TABLE(iDb);
  103655. if( iDb==1 ) code = SQLITE_DROP_TEMP_TRIGGER;
  103656. if( sqlite3AuthCheck(pParse, code, pTrigger->zName, pTable->zName, zDb) ||
  103657. sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
  103658. return;
  103659. }
  103660. }
  103661. #endif
  103662. /* Generate code to destroy the database record of the trigger.
  103663. */
  103664. assert( pTable!=0 );
  103665. if( (v = sqlite3GetVdbe(pParse))!=0 ){
  103666. int base;
  103667. static const int iLn = VDBE_OFFSET_LINENO(2);
  103668. static const VdbeOpList dropTrigger[] = {
  103669. { OP_Rewind, 0, ADDR(9), 0},
  103670. { OP_String8, 0, 1, 0}, /* 1 */
  103671. { OP_Column, 0, 1, 2},
  103672. { OP_Ne, 2, ADDR(8), 1},
  103673. { OP_String8, 0, 1, 0}, /* 4: "trigger" */
  103674. { OP_Column, 0, 0, 2},
  103675. { OP_Ne, 2, ADDR(8), 1},
  103676. { OP_Delete, 0, 0, 0},
  103677. { OP_Next, 0, ADDR(1), 0}, /* 8 */
  103678. };
  103679. sqlite3BeginWriteOperation(pParse, 0, iDb);
  103680. sqlite3OpenMasterTable(pParse, iDb);
  103681. base = sqlite3VdbeAddOpList(v, ArraySize(dropTrigger), dropTrigger, iLn);
  103682. sqlite3VdbeChangeP4(v, base+1, pTrigger->zName, P4_TRANSIENT);
  103683. sqlite3VdbeChangeP4(v, base+4, "trigger", P4_STATIC);
  103684. sqlite3ChangeCookie(pParse, iDb);
  103685. sqlite3VdbeAddOp2(v, OP_Close, 0, 0);
  103686. sqlite3VdbeAddOp4(v, OP_DropTrigger, iDb, 0, 0, pTrigger->zName, 0);
  103687. if( pParse->nMem<3 ){
  103688. pParse->nMem = 3;
  103689. }
  103690. }
  103691. }
  103692. /*
  103693. ** Remove a trigger from the hash tables of the sqlite* pointer.
  103694. */
  103695. SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTrigger(sqlite3 *db, int iDb, const char *zName){
  103696. Trigger *pTrigger;
  103697. Hash *pHash;
  103698. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  103699. pHash = &(db->aDb[iDb].pSchema->trigHash);
  103700. pTrigger = sqlite3HashInsert(pHash, zName, 0);
  103701. if( ALWAYS(pTrigger) ){
  103702. if( pTrigger->pSchema==pTrigger->pTabSchema ){
  103703. Table *pTab = tableOfTrigger(pTrigger);
  103704. Trigger **pp;
  103705. for(pp=&pTab->pTrigger; *pp!=pTrigger; pp=&((*pp)->pNext));
  103706. *pp = (*pp)->pNext;
  103707. }
  103708. sqlite3DeleteTrigger(db, pTrigger);
  103709. db->flags |= SQLITE_InternChanges;
  103710. }
  103711. }
  103712. /*
  103713. ** pEList is the SET clause of an UPDATE statement. Each entry
  103714. ** in pEList is of the format <id>=<expr>. If any of the entries
  103715. ** in pEList have an <id> which matches an identifier in pIdList,
  103716. ** then return TRUE. If pIdList==NULL, then it is considered a
  103717. ** wildcard that matches anything. Likewise if pEList==NULL then
  103718. ** it matches anything so always return true. Return false only
  103719. ** if there is no match.
  103720. */
  103721. static int checkColumnOverlap(IdList *pIdList, ExprList *pEList){
  103722. int e;
  103723. if( pIdList==0 || NEVER(pEList==0) ) return 1;
  103724. for(e=0; e<pEList->nExpr; e++){
  103725. if( sqlite3IdListIndex(pIdList, pEList->a[e].zName)>=0 ) return 1;
  103726. }
  103727. return 0;
  103728. }
  103729. /*
  103730. ** Return a list of all triggers on table pTab if there exists at least
  103731. ** one trigger that must be fired when an operation of type 'op' is
  103732. ** performed on the table, and, if that operation is an UPDATE, if at
  103733. ** least one of the columns in pChanges is being modified.
  103734. */
  103735. SQLITE_PRIVATE Trigger *sqlite3TriggersExist(
  103736. Parse *pParse, /* Parse context */
  103737. Table *pTab, /* The table the contains the triggers */
  103738. int op, /* one of TK_DELETE, TK_INSERT, TK_UPDATE */
  103739. ExprList *pChanges, /* Columns that change in an UPDATE statement */
  103740. int *pMask /* OUT: Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
  103741. ){
  103742. int mask = 0;
  103743. Trigger *pList = 0;
  103744. Trigger *p;
  103745. if( (pParse->db->flags & SQLITE_EnableTrigger)!=0 ){
  103746. pList = sqlite3TriggerList(pParse, pTab);
  103747. }
  103748. assert( pList==0 || IsVirtual(pTab)==0 );
  103749. for(p=pList; p; p=p->pNext){
  103750. if( p->op==op && checkColumnOverlap(p->pColumns, pChanges) ){
  103751. mask |= p->tr_tm;
  103752. }
  103753. }
  103754. if( pMask ){
  103755. *pMask = mask;
  103756. }
  103757. return (mask ? pList : 0);
  103758. }
  103759. /*
  103760. ** Convert the pStep->target token into a SrcList and return a pointer
  103761. ** to that SrcList.
  103762. **
  103763. ** This routine adds a specific database name, if needed, to the target when
  103764. ** forming the SrcList. This prevents a trigger in one database from
  103765. ** referring to a target in another database. An exception is when the
  103766. ** trigger is in TEMP in which case it can refer to any other database it
  103767. ** wants.
  103768. */
  103769. static SrcList *targetSrcList(
  103770. Parse *pParse, /* The parsing context */
  103771. TriggerStep *pStep /* The trigger containing the target token */
  103772. ){
  103773. int iDb; /* Index of the database to use */
  103774. SrcList *pSrc; /* SrcList to be returned */
  103775. pSrc = sqlite3SrcListAppend(pParse->db, 0, &pStep->target, 0);
  103776. if( pSrc ){
  103777. assert( pSrc->nSrc>0 );
  103778. assert( pSrc->a!=0 );
  103779. iDb = sqlite3SchemaToIndex(pParse->db, pStep->pTrig->pSchema);
  103780. if( iDb==0 || iDb>=2 ){
  103781. sqlite3 *db = pParse->db;
  103782. assert( iDb<pParse->db->nDb );
  103783. pSrc->a[pSrc->nSrc-1].zDatabase = sqlite3DbStrDup(db, db->aDb[iDb].zName);
  103784. }
  103785. }
  103786. return pSrc;
  103787. }
  103788. /*
  103789. ** Generate VDBE code for the statements inside the body of a single
  103790. ** trigger.
  103791. */
  103792. static int codeTriggerProgram(
  103793. Parse *pParse, /* The parser context */
  103794. TriggerStep *pStepList, /* List of statements inside the trigger body */
  103795. int orconf /* Conflict algorithm. (OE_Abort, etc) */
  103796. ){
  103797. TriggerStep *pStep;
  103798. Vdbe *v = pParse->pVdbe;
  103799. sqlite3 *db = pParse->db;
  103800. assert( pParse->pTriggerTab && pParse->pToplevel );
  103801. assert( pStepList );
  103802. assert( v!=0 );
  103803. for(pStep=pStepList; pStep; pStep=pStep->pNext){
  103804. /* Figure out the ON CONFLICT policy that will be used for this step
  103805. ** of the trigger program. If the statement that caused this trigger
  103806. ** to fire had an explicit ON CONFLICT, then use it. Otherwise, use
  103807. ** the ON CONFLICT policy that was specified as part of the trigger
  103808. ** step statement. Example:
  103809. **
  103810. ** CREATE TRIGGER AFTER INSERT ON t1 BEGIN;
  103811. ** INSERT OR REPLACE INTO t2 VALUES(new.a, new.b);
  103812. ** END;
  103813. **
  103814. ** INSERT INTO t1 ... ; -- insert into t2 uses REPLACE policy
  103815. ** INSERT OR IGNORE INTO t1 ... ; -- insert into t2 uses IGNORE policy
  103816. */
  103817. pParse->eOrconf = (orconf==OE_Default)?pStep->orconf:(u8)orconf;
  103818. assert( pParse->okConstFactor==0 );
  103819. switch( pStep->op ){
  103820. case TK_UPDATE: {
  103821. sqlite3Update(pParse,
  103822. targetSrcList(pParse, pStep),
  103823. sqlite3ExprListDup(db, pStep->pExprList, 0),
  103824. sqlite3ExprDup(db, pStep->pWhere, 0),
  103825. pParse->eOrconf
  103826. );
  103827. break;
  103828. }
  103829. case TK_INSERT: {
  103830. sqlite3Insert(pParse,
  103831. targetSrcList(pParse, pStep),
  103832. sqlite3SelectDup(db, pStep->pSelect, 0),
  103833. sqlite3IdListDup(db, pStep->pIdList),
  103834. pParse->eOrconf
  103835. );
  103836. break;
  103837. }
  103838. case TK_DELETE: {
  103839. sqlite3DeleteFrom(pParse,
  103840. targetSrcList(pParse, pStep),
  103841. sqlite3ExprDup(db, pStep->pWhere, 0)
  103842. );
  103843. break;
  103844. }
  103845. default: assert( pStep->op==TK_SELECT ); {
  103846. SelectDest sDest;
  103847. Select *pSelect = sqlite3SelectDup(db, pStep->pSelect, 0);
  103848. sqlite3SelectDestInit(&sDest, SRT_Discard, 0);
  103849. sqlite3Select(pParse, pSelect, &sDest);
  103850. sqlite3SelectDelete(db, pSelect);
  103851. break;
  103852. }
  103853. }
  103854. if( pStep->op!=TK_SELECT ){
  103855. sqlite3VdbeAddOp0(v, OP_ResetCount);
  103856. }
  103857. }
  103858. return 0;
  103859. }
  103860. #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  103861. /*
  103862. ** This function is used to add VdbeComment() annotations to a VDBE
  103863. ** program. It is not used in production code, only for debugging.
  103864. */
  103865. static const char *onErrorText(int onError){
  103866. switch( onError ){
  103867. case OE_Abort: return "abort";
  103868. case OE_Rollback: return "rollback";
  103869. case OE_Fail: return "fail";
  103870. case OE_Replace: return "replace";
  103871. case OE_Ignore: return "ignore";
  103872. case OE_Default: return "default";
  103873. }
  103874. return "n/a";
  103875. }
  103876. #endif
  103877. /*
  103878. ** Parse context structure pFrom has just been used to create a sub-vdbe
  103879. ** (trigger program). If an error has occurred, transfer error information
  103880. ** from pFrom to pTo.
  103881. */
  103882. static void transferParseError(Parse *pTo, Parse *pFrom){
  103883. assert( pFrom->zErrMsg==0 || pFrom->nErr );
  103884. assert( pTo->zErrMsg==0 || pTo->nErr );
  103885. if( pTo->nErr==0 ){
  103886. pTo->zErrMsg = pFrom->zErrMsg;
  103887. pTo->nErr = pFrom->nErr;
  103888. }else{
  103889. sqlite3DbFree(pFrom->db, pFrom->zErrMsg);
  103890. }
  103891. }
  103892. /*
  103893. ** Create and populate a new TriggerPrg object with a sub-program
  103894. ** implementing trigger pTrigger with ON CONFLICT policy orconf.
  103895. */
  103896. static TriggerPrg *codeRowTrigger(
  103897. Parse *pParse, /* Current parse context */
  103898. Trigger *pTrigger, /* Trigger to code */
  103899. Table *pTab, /* The table pTrigger is attached to */
  103900. int orconf /* ON CONFLICT policy to code trigger program with */
  103901. ){
  103902. Parse *pTop = sqlite3ParseToplevel(pParse);
  103903. sqlite3 *db = pParse->db; /* Database handle */
  103904. TriggerPrg *pPrg; /* Value to return */
  103905. Expr *pWhen = 0; /* Duplicate of trigger WHEN expression */
  103906. Vdbe *v; /* Temporary VM */
  103907. NameContext sNC; /* Name context for sub-vdbe */
  103908. SubProgram *pProgram = 0; /* Sub-vdbe for trigger program */
  103909. Parse *pSubParse; /* Parse context for sub-vdbe */
  103910. int iEndTrigger = 0; /* Label to jump to if WHEN is false */
  103911. assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
  103912. assert( pTop->pVdbe );
  103913. /* Allocate the TriggerPrg and SubProgram objects. To ensure that they
  103914. ** are freed if an error occurs, link them into the Parse.pTriggerPrg
  103915. ** list of the top-level Parse object sooner rather than later. */
  103916. pPrg = sqlite3DbMallocZero(db, sizeof(TriggerPrg));
  103917. if( !pPrg ) return 0;
  103918. pPrg->pNext = pTop->pTriggerPrg;
  103919. pTop->pTriggerPrg = pPrg;
  103920. pPrg->pProgram = pProgram = sqlite3DbMallocZero(db, sizeof(SubProgram));
  103921. if( !pProgram ) return 0;
  103922. sqlite3VdbeLinkSubProgram(pTop->pVdbe, pProgram);
  103923. pPrg->pTrigger = pTrigger;
  103924. pPrg->orconf = orconf;
  103925. pPrg->aColmask[0] = 0xffffffff;
  103926. pPrg->aColmask[1] = 0xffffffff;
  103927. /* Allocate and populate a new Parse context to use for coding the
  103928. ** trigger sub-program. */
  103929. pSubParse = sqlite3StackAllocZero(db, sizeof(Parse));
  103930. if( !pSubParse ) return 0;
  103931. memset(&sNC, 0, sizeof(sNC));
  103932. sNC.pParse = pSubParse;
  103933. pSubParse->db = db;
  103934. pSubParse->pTriggerTab = pTab;
  103935. pSubParse->pToplevel = pTop;
  103936. pSubParse->zAuthContext = pTrigger->zName;
  103937. pSubParse->eTriggerOp = pTrigger->op;
  103938. pSubParse->nQueryLoop = pParse->nQueryLoop;
  103939. v = sqlite3GetVdbe(pSubParse);
  103940. if( v ){
  103941. VdbeComment((v, "Start: %s.%s (%s %s%s%s ON %s)",
  103942. pTrigger->zName, onErrorText(orconf),
  103943. (pTrigger->tr_tm==TRIGGER_BEFORE ? "BEFORE" : "AFTER"),
  103944. (pTrigger->op==TK_UPDATE ? "UPDATE" : ""),
  103945. (pTrigger->op==TK_INSERT ? "INSERT" : ""),
  103946. (pTrigger->op==TK_DELETE ? "DELETE" : ""),
  103947. pTab->zName
  103948. ));
  103949. #ifndef SQLITE_OMIT_TRACE
  103950. sqlite3VdbeChangeP4(v, -1,
  103951. sqlite3MPrintf(db, "-- TRIGGER %s", pTrigger->zName), P4_DYNAMIC
  103952. );
  103953. #endif
  103954. /* If one was specified, code the WHEN clause. If it evaluates to false
  103955. ** (or NULL) the sub-vdbe is immediately halted by jumping to the
  103956. ** OP_Halt inserted at the end of the program. */
  103957. if( pTrigger->pWhen ){
  103958. pWhen = sqlite3ExprDup(db, pTrigger->pWhen, 0);
  103959. if( SQLITE_OK==sqlite3ResolveExprNames(&sNC, pWhen)
  103960. && db->mallocFailed==0
  103961. ){
  103962. iEndTrigger = sqlite3VdbeMakeLabel(v);
  103963. sqlite3ExprIfFalse(pSubParse, pWhen, iEndTrigger, SQLITE_JUMPIFNULL);
  103964. }
  103965. sqlite3ExprDelete(db, pWhen);
  103966. }
  103967. /* Code the trigger program into the sub-vdbe. */
  103968. codeTriggerProgram(pSubParse, pTrigger->step_list, orconf);
  103969. /* Insert an OP_Halt at the end of the sub-program. */
  103970. if( iEndTrigger ){
  103971. sqlite3VdbeResolveLabel(v, iEndTrigger);
  103972. }
  103973. sqlite3VdbeAddOp0(v, OP_Halt);
  103974. VdbeComment((v, "End: %s.%s", pTrigger->zName, onErrorText(orconf)));
  103975. transferParseError(pParse, pSubParse);
  103976. if( db->mallocFailed==0 ){
  103977. pProgram->aOp = sqlite3VdbeTakeOpArray(v, &pProgram->nOp, &pTop->nMaxArg);
  103978. }
  103979. pProgram->nMem = pSubParse->nMem;
  103980. pProgram->nCsr = pSubParse->nTab;
  103981. pProgram->nOnce = pSubParse->nOnce;
  103982. pProgram->token = (void *)pTrigger;
  103983. pPrg->aColmask[0] = pSubParse->oldmask;
  103984. pPrg->aColmask[1] = pSubParse->newmask;
  103985. sqlite3VdbeDelete(v);
  103986. }
  103987. assert( !pSubParse->pAinc && !pSubParse->pZombieTab );
  103988. assert( !pSubParse->pTriggerPrg && !pSubParse->nMaxArg );
  103989. sqlite3ParserReset(pSubParse);
  103990. sqlite3StackFree(db, pSubParse);
  103991. return pPrg;
  103992. }
  103993. /*
  103994. ** Return a pointer to a TriggerPrg object containing the sub-program for
  103995. ** trigger pTrigger with default ON CONFLICT algorithm orconf. If no such
  103996. ** TriggerPrg object exists, a new object is allocated and populated before
  103997. ** being returned.
  103998. */
  103999. static TriggerPrg *getRowTrigger(
  104000. Parse *pParse, /* Current parse context */
  104001. Trigger *pTrigger, /* Trigger to code */
  104002. Table *pTab, /* The table trigger pTrigger is attached to */
  104003. int orconf /* ON CONFLICT algorithm. */
  104004. ){
  104005. Parse *pRoot = sqlite3ParseToplevel(pParse);
  104006. TriggerPrg *pPrg;
  104007. assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
  104008. /* It may be that this trigger has already been coded (or is in the
  104009. ** process of being coded). If this is the case, then an entry with
  104010. ** a matching TriggerPrg.pTrigger field will be present somewhere
  104011. ** in the Parse.pTriggerPrg list. Search for such an entry. */
  104012. for(pPrg=pRoot->pTriggerPrg;
  104013. pPrg && (pPrg->pTrigger!=pTrigger || pPrg->orconf!=orconf);
  104014. pPrg=pPrg->pNext
  104015. );
  104016. /* If an existing TriggerPrg could not be located, create a new one. */
  104017. if( !pPrg ){
  104018. pPrg = codeRowTrigger(pParse, pTrigger, pTab, orconf);
  104019. }
  104020. return pPrg;
  104021. }
  104022. /*
  104023. ** Generate code for the trigger program associated with trigger p on
  104024. ** table pTab. The reg, orconf and ignoreJump parameters passed to this
  104025. ** function are the same as those described in the header function for
  104026. ** sqlite3CodeRowTrigger()
  104027. */
  104028. SQLITE_PRIVATE void sqlite3CodeRowTriggerDirect(
  104029. Parse *pParse, /* Parse context */
  104030. Trigger *p, /* Trigger to code */
  104031. Table *pTab, /* The table to code triggers from */
  104032. int reg, /* Reg array containing OLD.* and NEW.* values */
  104033. int orconf, /* ON CONFLICT policy */
  104034. int ignoreJump /* Instruction to jump to for RAISE(IGNORE) */
  104035. ){
  104036. Vdbe *v = sqlite3GetVdbe(pParse); /* Main VM */
  104037. TriggerPrg *pPrg;
  104038. pPrg = getRowTrigger(pParse, p, pTab, orconf);
  104039. assert( pPrg || pParse->nErr || pParse->db->mallocFailed );
  104040. /* Code the OP_Program opcode in the parent VDBE. P4 of the OP_Program
  104041. ** is a pointer to the sub-vdbe containing the trigger program. */
  104042. if( pPrg ){
  104043. int bRecursive = (p->zName && 0==(pParse->db->flags&SQLITE_RecTriggers));
  104044. sqlite3VdbeAddOp3(v, OP_Program, reg, ignoreJump, ++pParse->nMem);
  104045. sqlite3VdbeChangeP4(v, -1, (const char *)pPrg->pProgram, P4_SUBPROGRAM);
  104046. VdbeComment(
  104047. (v, "Call: %s.%s", (p->zName?p->zName:"fkey"), onErrorText(orconf)));
  104048. /* Set the P5 operand of the OP_Program instruction to non-zero if
  104049. ** recursive invocation of this trigger program is disallowed. Recursive
  104050. ** invocation is disallowed if (a) the sub-program is really a trigger,
  104051. ** not a foreign key action, and (b) the flag to enable recursive triggers
  104052. ** is clear. */
  104053. sqlite3VdbeChangeP5(v, (u8)bRecursive);
  104054. }
  104055. }
  104056. /*
  104057. ** This is called to code the required FOR EACH ROW triggers for an operation
  104058. ** on table pTab. The operation to code triggers for (INSERT, UPDATE or DELETE)
  104059. ** is given by the op parameter. The tr_tm parameter determines whether the
  104060. ** BEFORE or AFTER triggers are coded. If the operation is an UPDATE, then
  104061. ** parameter pChanges is passed the list of columns being modified.
  104062. **
  104063. ** If there are no triggers that fire at the specified time for the specified
  104064. ** operation on pTab, this function is a no-op.
  104065. **
  104066. ** The reg argument is the address of the first in an array of registers
  104067. ** that contain the values substituted for the new.* and old.* references
  104068. ** in the trigger program. If N is the number of columns in table pTab
  104069. ** (a copy of pTab->nCol), then registers are populated as follows:
  104070. **
  104071. ** Register Contains
  104072. ** ------------------------------------------------------
  104073. ** reg+0 OLD.rowid
  104074. ** reg+1 OLD.* value of left-most column of pTab
  104075. ** ... ...
  104076. ** reg+N OLD.* value of right-most column of pTab
  104077. ** reg+N+1 NEW.rowid
  104078. ** reg+N+2 OLD.* value of left-most column of pTab
  104079. ** ... ...
  104080. ** reg+N+N+1 NEW.* value of right-most column of pTab
  104081. **
  104082. ** For ON DELETE triggers, the registers containing the NEW.* values will
  104083. ** never be accessed by the trigger program, so they are not allocated or
  104084. ** populated by the caller (there is no data to populate them with anyway).
  104085. ** Similarly, for ON INSERT triggers the values stored in the OLD.* registers
  104086. ** are never accessed, and so are not allocated by the caller. So, for an
  104087. ** ON INSERT trigger, the value passed to this function as parameter reg
  104088. ** is not a readable register, although registers (reg+N) through
  104089. ** (reg+N+N+1) are.
  104090. **
  104091. ** Parameter orconf is the default conflict resolution algorithm for the
  104092. ** trigger program to use (REPLACE, IGNORE etc.). Parameter ignoreJump
  104093. ** is the instruction that control should jump to if a trigger program
  104094. ** raises an IGNORE exception.
  104095. */
  104096. SQLITE_PRIVATE void sqlite3CodeRowTrigger(
  104097. Parse *pParse, /* Parse context */
  104098. Trigger *pTrigger, /* List of triggers on table pTab */
  104099. int op, /* One of TK_UPDATE, TK_INSERT, TK_DELETE */
  104100. ExprList *pChanges, /* Changes list for any UPDATE OF triggers */
  104101. int tr_tm, /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
  104102. Table *pTab, /* The table to code triggers from */
  104103. int reg, /* The first in an array of registers (see above) */
  104104. int orconf, /* ON CONFLICT policy */
  104105. int ignoreJump /* Instruction to jump to for RAISE(IGNORE) */
  104106. ){
  104107. Trigger *p; /* Used to iterate through pTrigger list */
  104108. assert( op==TK_UPDATE || op==TK_INSERT || op==TK_DELETE );
  104109. assert( tr_tm==TRIGGER_BEFORE || tr_tm==TRIGGER_AFTER );
  104110. assert( (op==TK_UPDATE)==(pChanges!=0) );
  104111. for(p=pTrigger; p; p=p->pNext){
  104112. /* Sanity checking: The schema for the trigger and for the table are
  104113. ** always defined. The trigger must be in the same schema as the table
  104114. ** or else it must be a TEMP trigger. */
  104115. assert( p->pSchema!=0 );
  104116. assert( p->pTabSchema!=0 );
  104117. assert( p->pSchema==p->pTabSchema
  104118. || p->pSchema==pParse->db->aDb[1].pSchema );
  104119. /* Determine whether we should code this trigger */
  104120. if( p->op==op
  104121. && p->tr_tm==tr_tm
  104122. && checkColumnOverlap(p->pColumns, pChanges)
  104123. ){
  104124. sqlite3CodeRowTriggerDirect(pParse, p, pTab, reg, orconf, ignoreJump);
  104125. }
  104126. }
  104127. }
  104128. /*
  104129. ** Triggers may access values stored in the old.* or new.* pseudo-table.
  104130. ** This function returns a 32-bit bitmask indicating which columns of the
  104131. ** old.* or new.* tables actually are used by triggers. This information
  104132. ** may be used by the caller, for example, to avoid having to load the entire
  104133. ** old.* record into memory when executing an UPDATE or DELETE command.
  104134. **
  104135. ** Bit 0 of the returned mask is set if the left-most column of the
  104136. ** table may be accessed using an [old|new].<col> reference. Bit 1 is set if
  104137. ** the second leftmost column value is required, and so on. If there
  104138. ** are more than 32 columns in the table, and at least one of the columns
  104139. ** with an index greater than 32 may be accessed, 0xffffffff is returned.
  104140. **
  104141. ** It is not possible to determine if the old.rowid or new.rowid column is
  104142. ** accessed by triggers. The caller must always assume that it is.
  104143. **
  104144. ** Parameter isNew must be either 1 or 0. If it is 0, then the mask returned
  104145. ** applies to the old.* table. If 1, the new.* table.
  104146. **
  104147. ** Parameter tr_tm must be a mask with one or both of the TRIGGER_BEFORE
  104148. ** and TRIGGER_AFTER bits set. Values accessed by BEFORE triggers are only
  104149. ** included in the returned mask if the TRIGGER_BEFORE bit is set in the
  104150. ** tr_tm parameter. Similarly, values accessed by AFTER triggers are only
  104151. ** included in the returned mask if the TRIGGER_AFTER bit is set in tr_tm.
  104152. */
  104153. SQLITE_PRIVATE u32 sqlite3TriggerColmask(
  104154. Parse *pParse, /* Parse context */
  104155. Trigger *pTrigger, /* List of triggers on table pTab */
  104156. ExprList *pChanges, /* Changes list for any UPDATE OF triggers */
  104157. int isNew, /* 1 for new.* ref mask, 0 for old.* ref mask */
  104158. int tr_tm, /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
  104159. Table *pTab, /* The table to code triggers from */
  104160. int orconf /* Default ON CONFLICT policy for trigger steps */
  104161. ){
  104162. const int op = pChanges ? TK_UPDATE : TK_DELETE;
  104163. u32 mask = 0;
  104164. Trigger *p;
  104165. assert( isNew==1 || isNew==0 );
  104166. for(p=pTrigger; p; p=p->pNext){
  104167. if( p->op==op && (tr_tm&p->tr_tm)
  104168. && checkColumnOverlap(p->pColumns,pChanges)
  104169. ){
  104170. TriggerPrg *pPrg;
  104171. pPrg = getRowTrigger(pParse, p, pTab, orconf);
  104172. if( pPrg ){
  104173. mask |= pPrg->aColmask[isNew];
  104174. }
  104175. }
  104176. }
  104177. return mask;
  104178. }
  104179. #endif /* !defined(SQLITE_OMIT_TRIGGER) */
  104180. /************** End of trigger.c *********************************************/
  104181. /************** Begin file update.c ******************************************/
  104182. /*
  104183. ** 2001 September 15
  104184. **
  104185. ** The author disclaims copyright to this source code. In place of
  104186. ** a legal notice, here is a blessing:
  104187. **
  104188. ** May you do good and not evil.
  104189. ** May you find forgiveness for yourself and forgive others.
  104190. ** May you share freely, never taking more than you give.
  104191. **
  104192. *************************************************************************
  104193. ** This file contains C code routines that are called by the parser
  104194. ** to handle UPDATE statements.
  104195. */
  104196. #ifndef SQLITE_OMIT_VIRTUALTABLE
  104197. /* Forward declaration */
  104198. static void updateVirtualTable(
  104199. Parse *pParse, /* The parsing context */
  104200. SrcList *pSrc, /* The virtual table to be modified */
  104201. Table *pTab, /* The virtual table */
  104202. ExprList *pChanges, /* The columns to change in the UPDATE statement */
  104203. Expr *pRowidExpr, /* Expression used to recompute the rowid */
  104204. int *aXRef, /* Mapping from columns of pTab to entries in pChanges */
  104205. Expr *pWhere, /* WHERE clause of the UPDATE statement */
  104206. int onError /* ON CONFLICT strategy */
  104207. );
  104208. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  104209. /*
  104210. ** The most recently coded instruction was an OP_Column to retrieve the
  104211. ** i-th column of table pTab. This routine sets the P4 parameter of the
  104212. ** OP_Column to the default value, if any.
  104213. **
  104214. ** The default value of a column is specified by a DEFAULT clause in the
  104215. ** column definition. This was either supplied by the user when the table
  104216. ** was created, or added later to the table definition by an ALTER TABLE
  104217. ** command. If the latter, then the row-records in the table btree on disk
  104218. ** may not contain a value for the column and the default value, taken
  104219. ** from the P4 parameter of the OP_Column instruction, is returned instead.
  104220. ** If the former, then all row-records are guaranteed to include a value
  104221. ** for the column and the P4 value is not required.
  104222. **
  104223. ** Column definitions created by an ALTER TABLE command may only have
  104224. ** literal default values specified: a number, null or a string. (If a more
  104225. ** complicated default expression value was provided, it is evaluated
  104226. ** when the ALTER TABLE is executed and one of the literal values written
  104227. ** into the sqlite_master table.)
  104228. **
  104229. ** Therefore, the P4 parameter is only required if the default value for
  104230. ** the column is a literal number, string or null. The sqlite3ValueFromExpr()
  104231. ** function is capable of transforming these types of expressions into
  104232. ** sqlite3_value objects.
  104233. **
  104234. ** If parameter iReg is not negative, code an OP_RealAffinity instruction
  104235. ** on register iReg. This is used when an equivalent integer value is
  104236. ** stored in place of an 8-byte floating point value in order to save
  104237. ** space.
  104238. */
  104239. SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *v, Table *pTab, int i, int iReg){
  104240. assert( pTab!=0 );
  104241. if( !pTab->pSelect ){
  104242. sqlite3_value *pValue = 0;
  104243. u8 enc = ENC(sqlite3VdbeDb(v));
  104244. Column *pCol = &pTab->aCol[i];
  104245. VdbeComment((v, "%s.%s", pTab->zName, pCol->zName));
  104246. assert( i<pTab->nCol );
  104247. sqlite3ValueFromExpr(sqlite3VdbeDb(v), pCol->pDflt, enc,
  104248. pCol->affinity, &pValue);
  104249. if( pValue ){
  104250. sqlite3VdbeChangeP4(v, -1, (const char *)pValue, P4_MEM);
  104251. }
  104252. #ifndef SQLITE_OMIT_FLOATING_POINT
  104253. if( pTab->aCol[i].affinity==SQLITE_AFF_REAL ){
  104254. sqlite3VdbeAddOp1(v, OP_RealAffinity, iReg);
  104255. }
  104256. #endif
  104257. }
  104258. }
  104259. /*
  104260. ** Process an UPDATE statement.
  104261. **
  104262. ** UPDATE OR IGNORE table_wxyz SET a=b, c=d WHERE e<5 AND f NOT NULL;
  104263. ** \_______/ \________/ \______/ \________________/
  104264. * onError pTabList pChanges pWhere
  104265. */
  104266. SQLITE_PRIVATE void sqlite3Update(
  104267. Parse *pParse, /* The parser context */
  104268. SrcList *pTabList, /* The table in which we should change things */
  104269. ExprList *pChanges, /* Things to be changed */
  104270. Expr *pWhere, /* The WHERE clause. May be null */
  104271. int onError /* How to handle constraint errors */
  104272. ){
  104273. int i, j; /* Loop counters */
  104274. Table *pTab; /* The table to be updated */
  104275. int addrTop = 0; /* VDBE instruction address of the start of the loop */
  104276. WhereInfo *pWInfo; /* Information about the WHERE clause */
  104277. Vdbe *v; /* The virtual database engine */
  104278. Index *pIdx; /* For looping over indices */
  104279. Index *pPk; /* The PRIMARY KEY index for WITHOUT ROWID tables */
  104280. int nIdx; /* Number of indices that need updating */
  104281. int iBaseCur; /* Base cursor number */
  104282. int iDataCur; /* Cursor for the canonical data btree */
  104283. int iIdxCur; /* Cursor for the first index */
  104284. sqlite3 *db; /* The database structure */
  104285. int *aRegIdx = 0; /* One register assigned to each index to be updated */
  104286. int *aXRef = 0; /* aXRef[i] is the index in pChanges->a[] of the
  104287. ** an expression for the i-th column of the table.
  104288. ** aXRef[i]==-1 if the i-th column is not changed. */
  104289. u8 *aToOpen; /* 1 for tables and indices to be opened */
  104290. u8 chngPk; /* PRIMARY KEY changed in a WITHOUT ROWID table */
  104291. u8 chngRowid; /* Rowid changed in a normal table */
  104292. u8 chngKey; /* Either chngPk or chngRowid */
  104293. Expr *pRowidExpr = 0; /* Expression defining the new record number */
  104294. AuthContext sContext; /* The authorization context */
  104295. NameContext sNC; /* The name-context to resolve expressions in */
  104296. int iDb; /* Database containing the table being updated */
  104297. int okOnePass; /* True for one-pass algorithm without the FIFO */
  104298. int hasFK; /* True if foreign key processing is required */
  104299. int labelBreak; /* Jump here to break out of UPDATE loop */
  104300. int labelContinue; /* Jump here to continue next step of UPDATE loop */
  104301. #ifndef SQLITE_OMIT_TRIGGER
  104302. int isView; /* True when updating a view (INSTEAD OF trigger) */
  104303. Trigger *pTrigger; /* List of triggers on pTab, if required */
  104304. int tmask; /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
  104305. #endif
  104306. int newmask; /* Mask of NEW.* columns accessed by BEFORE triggers */
  104307. int iEph = 0; /* Ephemeral table holding all primary key values */
  104308. int nKey = 0; /* Number of elements in regKey for WITHOUT ROWID */
  104309. int aiCurOnePass[2]; /* The write cursors opened by WHERE_ONEPASS */
  104310. /* Register Allocations */
  104311. int regRowCount = 0; /* A count of rows changed */
  104312. int regOldRowid; /* The old rowid */
  104313. int regNewRowid; /* The new rowid */
  104314. int regNew; /* Content of the NEW.* table in triggers */
  104315. int regOld = 0; /* Content of OLD.* table in triggers */
  104316. int regRowSet = 0; /* Rowset of rows to be updated */
  104317. int regKey = 0; /* composite PRIMARY KEY value */
  104318. memset(&sContext, 0, sizeof(sContext));
  104319. db = pParse->db;
  104320. if( pParse->nErr || db->mallocFailed ){
  104321. goto update_cleanup;
  104322. }
  104323. assert( pTabList->nSrc==1 );
  104324. /* Locate the table which we want to update.
  104325. */
  104326. pTab = sqlite3SrcListLookup(pParse, pTabList);
  104327. if( pTab==0 ) goto update_cleanup;
  104328. iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  104329. /* Figure out if we have any triggers and if the table being
  104330. ** updated is a view.
  104331. */
  104332. #ifndef SQLITE_OMIT_TRIGGER
  104333. pTrigger = sqlite3TriggersExist(pParse, pTab, TK_UPDATE, pChanges, &tmask);
  104334. isView = pTab->pSelect!=0;
  104335. assert( pTrigger || tmask==0 );
  104336. #else
  104337. # define pTrigger 0
  104338. # define isView 0
  104339. # define tmask 0
  104340. #endif
  104341. #ifdef SQLITE_OMIT_VIEW
  104342. # undef isView
  104343. # define isView 0
  104344. #endif
  104345. if( sqlite3ViewGetColumnNames(pParse, pTab) ){
  104346. goto update_cleanup;
  104347. }
  104348. if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
  104349. goto update_cleanup;
  104350. }
  104351. /* Allocate a cursors for the main database table and for all indices.
  104352. ** The index cursors might not be used, but if they are used they
  104353. ** need to occur right after the database cursor. So go ahead and
  104354. ** allocate enough space, just in case.
  104355. */
  104356. pTabList->a[0].iCursor = iBaseCur = iDataCur = pParse->nTab++;
  104357. iIdxCur = iDataCur+1;
  104358. pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab);
  104359. for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){
  104360. if( IsPrimaryKeyIndex(pIdx) && pPk!=0 ){
  104361. iDataCur = pParse->nTab;
  104362. pTabList->a[0].iCursor = iDataCur;
  104363. }
  104364. pParse->nTab++;
  104365. }
  104366. /* Allocate space for aXRef[], aRegIdx[], and aToOpen[].
  104367. ** Initialize aXRef[] and aToOpen[] to their default values.
  104368. */
  104369. aXRef = sqlite3DbMallocRaw(db, sizeof(int) * (pTab->nCol+nIdx) + nIdx+2 );
  104370. if( aXRef==0 ) goto update_cleanup;
  104371. aRegIdx = aXRef+pTab->nCol;
  104372. aToOpen = (u8*)(aRegIdx+nIdx);
  104373. memset(aToOpen, 1, nIdx+1);
  104374. aToOpen[nIdx+1] = 0;
  104375. for(i=0; i<pTab->nCol; i++) aXRef[i] = -1;
  104376. /* Initialize the name-context */
  104377. memset(&sNC, 0, sizeof(sNC));
  104378. sNC.pParse = pParse;
  104379. sNC.pSrcList = pTabList;
  104380. /* Resolve the column names in all the expressions of the
  104381. ** of the UPDATE statement. Also find the column index
  104382. ** for each column to be updated in the pChanges array. For each
  104383. ** column to be updated, make sure we have authorization to change
  104384. ** that column.
  104385. */
  104386. chngRowid = chngPk = 0;
  104387. for(i=0; i<pChanges->nExpr; i++){
  104388. if( sqlite3ResolveExprNames(&sNC, pChanges->a[i].pExpr) ){
  104389. goto update_cleanup;
  104390. }
  104391. for(j=0; j<pTab->nCol; j++){
  104392. if( sqlite3StrICmp(pTab->aCol[j].zName, pChanges->a[i].zName)==0 ){
  104393. if( j==pTab->iPKey ){
  104394. chngRowid = 1;
  104395. pRowidExpr = pChanges->a[i].pExpr;
  104396. }else if( pPk && (pTab->aCol[j].colFlags & COLFLAG_PRIMKEY)!=0 ){
  104397. chngPk = 1;
  104398. }
  104399. aXRef[j] = i;
  104400. break;
  104401. }
  104402. }
  104403. if( j>=pTab->nCol ){
  104404. if( pPk==0 && sqlite3IsRowid(pChanges->a[i].zName) ){
  104405. j = -1;
  104406. chngRowid = 1;
  104407. pRowidExpr = pChanges->a[i].pExpr;
  104408. }else{
  104409. sqlite3ErrorMsg(pParse, "no such column: %s", pChanges->a[i].zName);
  104410. pParse->checkSchema = 1;
  104411. goto update_cleanup;
  104412. }
  104413. }
  104414. #ifndef SQLITE_OMIT_AUTHORIZATION
  104415. {
  104416. int rc;
  104417. rc = sqlite3AuthCheck(pParse, SQLITE_UPDATE, pTab->zName,
  104418. j<0 ? "ROWID" : pTab->aCol[j].zName,
  104419. db->aDb[iDb].zName);
  104420. if( rc==SQLITE_DENY ){
  104421. goto update_cleanup;
  104422. }else if( rc==SQLITE_IGNORE ){
  104423. aXRef[j] = -1;
  104424. }
  104425. }
  104426. #endif
  104427. }
  104428. assert( (chngRowid & chngPk)==0 );
  104429. assert( chngRowid==0 || chngRowid==1 );
  104430. assert( chngPk==0 || chngPk==1 );
  104431. chngKey = chngRowid + chngPk;
  104432. /* The SET expressions are not actually used inside the WHERE loop.
  104433. ** So reset the colUsed mask
  104434. */
  104435. pTabList->a[0].colUsed = 0;
  104436. hasFK = sqlite3FkRequired(pParse, pTab, aXRef, chngKey);
  104437. /* There is one entry in the aRegIdx[] array for each index on the table
  104438. ** being updated. Fill in aRegIdx[] with a register number that will hold
  104439. ** the key for accessing each index.
  104440. */
  104441. for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
  104442. int reg;
  104443. if( chngKey || hasFK || pIdx->pPartIdxWhere || pIdx==pPk ){
  104444. reg = ++pParse->nMem;
  104445. }else{
  104446. reg = 0;
  104447. for(i=0; i<pIdx->nKeyCol; i++){
  104448. if( aXRef[pIdx->aiColumn[i]]>=0 ){
  104449. reg = ++pParse->nMem;
  104450. break;
  104451. }
  104452. }
  104453. }
  104454. if( reg==0 ) aToOpen[j+1] = 0;
  104455. aRegIdx[j] = reg;
  104456. }
  104457. /* Begin generating code. */
  104458. v = sqlite3GetVdbe(pParse);
  104459. if( v==0 ) goto update_cleanup;
  104460. if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
  104461. sqlite3BeginWriteOperation(pParse, 1, iDb);
  104462. #ifndef SQLITE_OMIT_VIRTUALTABLE
  104463. /* Virtual tables must be handled separately */
  104464. if( IsVirtual(pTab) ){
  104465. updateVirtualTable(pParse, pTabList, pTab, pChanges, pRowidExpr, aXRef,
  104466. pWhere, onError);
  104467. pWhere = 0;
  104468. pTabList = 0;
  104469. goto update_cleanup;
  104470. }
  104471. #endif
  104472. /* Allocate required registers. */
  104473. regRowSet = ++pParse->nMem;
  104474. regOldRowid = regNewRowid = ++pParse->nMem;
  104475. if( chngPk || pTrigger || hasFK ){
  104476. regOld = pParse->nMem + 1;
  104477. pParse->nMem += pTab->nCol;
  104478. }
  104479. if( chngKey || pTrigger || hasFK ){
  104480. regNewRowid = ++pParse->nMem;
  104481. }
  104482. regNew = pParse->nMem + 1;
  104483. pParse->nMem += pTab->nCol;
  104484. /* Start the view context. */
  104485. if( isView ){
  104486. sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
  104487. }
  104488. /* If we are trying to update a view, realize that view into
  104489. ** an ephemeral table.
  104490. */
  104491. #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
  104492. if( isView ){
  104493. sqlite3MaterializeView(pParse, pTab, pWhere, iDataCur);
  104494. }
  104495. #endif
  104496. /* Resolve the column names in all the expressions in the
  104497. ** WHERE clause.
  104498. */
  104499. if( sqlite3ResolveExprNames(&sNC, pWhere) ){
  104500. goto update_cleanup;
  104501. }
  104502. /* Begin the database scan
  104503. */
  104504. if( HasRowid(pTab) ){
  104505. sqlite3VdbeAddOp3(v, OP_Null, 0, regRowSet, regOldRowid);
  104506. pWInfo = sqlite3WhereBegin(
  104507. pParse, pTabList, pWhere, 0, 0, WHERE_ONEPASS_DESIRED, iIdxCur
  104508. );
  104509. if( pWInfo==0 ) goto update_cleanup;
  104510. okOnePass = sqlite3WhereOkOnePass(pWInfo, aiCurOnePass);
  104511. /* Remember the rowid of every item to be updated.
  104512. */
  104513. sqlite3VdbeAddOp2(v, OP_Rowid, iDataCur, regOldRowid);
  104514. if( !okOnePass ){
  104515. sqlite3VdbeAddOp2(v, OP_RowSetAdd, regRowSet, regOldRowid);
  104516. }
  104517. /* End the database scan loop.
  104518. */
  104519. sqlite3WhereEnd(pWInfo);
  104520. }else{
  104521. int iPk; /* First of nPk memory cells holding PRIMARY KEY value */
  104522. i16 nPk; /* Number of components of the PRIMARY KEY */
  104523. int addrOpen; /* Address of the OpenEphemeral instruction */
  104524. assert( pPk!=0 );
  104525. nPk = pPk->nKeyCol;
  104526. iPk = pParse->nMem+1;
  104527. pParse->nMem += nPk;
  104528. regKey = ++pParse->nMem;
  104529. iEph = pParse->nTab++;
  104530. sqlite3VdbeAddOp2(v, OP_Null, 0, iPk);
  104531. addrOpen = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iEph, nPk);
  104532. sqlite3VdbeSetP4KeyInfo(pParse, pPk);
  104533. pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0, 0,
  104534. WHERE_ONEPASS_DESIRED, iIdxCur);
  104535. if( pWInfo==0 ) goto update_cleanup;
  104536. okOnePass = sqlite3WhereOkOnePass(pWInfo, aiCurOnePass);
  104537. for(i=0; i<nPk; i++){
  104538. sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, pPk->aiColumn[i],
  104539. iPk+i);
  104540. }
  104541. if( okOnePass ){
  104542. sqlite3VdbeChangeToNoop(v, addrOpen);
  104543. nKey = nPk;
  104544. regKey = iPk;
  104545. }else{
  104546. sqlite3VdbeAddOp4(v, OP_MakeRecord, iPk, nPk, regKey,
  104547. sqlite3IndexAffinityStr(v, pPk), nPk);
  104548. sqlite3VdbeAddOp2(v, OP_IdxInsert, iEph, regKey);
  104549. }
  104550. sqlite3WhereEnd(pWInfo);
  104551. }
  104552. /* Initialize the count of updated rows
  104553. */
  104554. if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab ){
  104555. regRowCount = ++pParse->nMem;
  104556. sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
  104557. }
  104558. labelBreak = sqlite3VdbeMakeLabel(v);
  104559. if( !isView ){
  104560. /*
  104561. ** Open every index that needs updating. Note that if any
  104562. ** index could potentially invoke a REPLACE conflict resolution
  104563. ** action, then we need to open all indices because we might need
  104564. ** to be deleting some records.
  104565. */
  104566. if( onError==OE_Replace ){
  104567. memset(aToOpen, 1, nIdx+1);
  104568. }else{
  104569. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  104570. if( pIdx->onError==OE_Replace ){
  104571. memset(aToOpen, 1, nIdx+1);
  104572. break;
  104573. }
  104574. }
  104575. }
  104576. if( okOnePass ){
  104577. if( aiCurOnePass[0]>=0 ) aToOpen[aiCurOnePass[0]-iBaseCur] = 0;
  104578. if( aiCurOnePass[1]>=0 ) aToOpen[aiCurOnePass[1]-iBaseCur] = 0;
  104579. }
  104580. sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, iBaseCur, aToOpen,
  104581. 0, 0);
  104582. }
  104583. /* Top of the update loop */
  104584. if( okOnePass ){
  104585. if( aToOpen[iDataCur-iBaseCur] ){
  104586. assert( pPk!=0 );
  104587. sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelBreak, regKey, nKey);
  104588. VdbeCoverageNeverTaken(v);
  104589. }
  104590. labelContinue = labelBreak;
  104591. sqlite3VdbeAddOp2(v, OP_IsNull, pPk ? regKey : regOldRowid, labelBreak);
  104592. VdbeCoverageIf(v, pPk==0);
  104593. VdbeCoverageIf(v, pPk!=0);
  104594. }else if( pPk ){
  104595. labelContinue = sqlite3VdbeMakeLabel(v);
  104596. sqlite3VdbeAddOp2(v, OP_Rewind, iEph, labelBreak); VdbeCoverage(v);
  104597. addrTop = sqlite3VdbeAddOp2(v, OP_RowKey, iEph, regKey);
  104598. sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelContinue, regKey, 0);
  104599. VdbeCoverage(v);
  104600. }else{
  104601. labelContinue = sqlite3VdbeAddOp3(v, OP_RowSetRead, regRowSet, labelBreak,
  104602. regOldRowid);
  104603. VdbeCoverage(v);
  104604. sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, labelContinue, regOldRowid);
  104605. VdbeCoverage(v);
  104606. }
  104607. /* If the record number will change, set register regNewRowid to
  104608. ** contain the new value. If the record number is not being modified,
  104609. ** then regNewRowid is the same register as regOldRowid, which is
  104610. ** already populated. */
  104611. assert( chngKey || pTrigger || hasFK || regOldRowid==regNewRowid );
  104612. if( chngRowid ){
  104613. sqlite3ExprCode(pParse, pRowidExpr, regNewRowid);
  104614. sqlite3VdbeAddOp1(v, OP_MustBeInt, regNewRowid); VdbeCoverage(v);
  104615. }
  104616. /* Compute the old pre-UPDATE content of the row being changed, if that
  104617. ** information is needed */
  104618. if( chngPk || hasFK || pTrigger ){
  104619. u32 oldmask = (hasFK ? sqlite3FkOldmask(pParse, pTab) : 0);
  104620. oldmask |= sqlite3TriggerColmask(pParse,
  104621. pTrigger, pChanges, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onError
  104622. );
  104623. for(i=0; i<pTab->nCol; i++){
  104624. if( oldmask==0xffffffff
  104625. || (i<32 && (oldmask & MASKBIT32(i))!=0)
  104626. || (pTab->aCol[i].colFlags & COLFLAG_PRIMKEY)!=0
  104627. ){
  104628. testcase( oldmask!=0xffffffff && i==31 );
  104629. sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, i, regOld+i);
  104630. }else{
  104631. sqlite3VdbeAddOp2(v, OP_Null, 0, regOld+i);
  104632. }
  104633. }
  104634. if( chngRowid==0 && pPk==0 ){
  104635. sqlite3VdbeAddOp2(v, OP_Copy, regOldRowid, regNewRowid);
  104636. }
  104637. }
  104638. /* Populate the array of registers beginning at regNew with the new
  104639. ** row data. This array is used to check constants, create the new
  104640. ** table and index records, and as the values for any new.* references
  104641. ** made by triggers.
  104642. **
  104643. ** If there are one or more BEFORE triggers, then do not populate the
  104644. ** registers associated with columns that are (a) not modified by
  104645. ** this UPDATE statement and (b) not accessed by new.* references. The
  104646. ** values for registers not modified by the UPDATE must be reloaded from
  104647. ** the database after the BEFORE triggers are fired anyway (as the trigger
  104648. ** may have modified them). So not loading those that are not going to
  104649. ** be used eliminates some redundant opcodes.
  104650. */
  104651. newmask = sqlite3TriggerColmask(
  104652. pParse, pTrigger, pChanges, 1, TRIGGER_BEFORE, pTab, onError
  104653. );
  104654. /*sqlite3VdbeAddOp3(v, OP_Null, 0, regNew, regNew+pTab->nCol-1);*/
  104655. for(i=0; i<pTab->nCol; i++){
  104656. if( i==pTab->iPKey ){
  104657. sqlite3VdbeAddOp2(v, OP_Null, 0, regNew+i);
  104658. }else{
  104659. j = aXRef[i];
  104660. if( j>=0 ){
  104661. sqlite3ExprCode(pParse, pChanges->a[j].pExpr, regNew+i);
  104662. }else if( 0==(tmask&TRIGGER_BEFORE) || i>31 || (newmask & MASKBIT32(i)) ){
  104663. /* This branch loads the value of a column that will not be changed
  104664. ** into a register. This is done if there are no BEFORE triggers, or
  104665. ** if there are one or more BEFORE triggers that use this value via
  104666. ** a new.* reference in a trigger program.
  104667. */
  104668. testcase( i==31 );
  104669. testcase( i==32 );
  104670. sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, i, regNew+i);
  104671. }else{
  104672. sqlite3VdbeAddOp2(v, OP_Null, 0, regNew+i);
  104673. }
  104674. }
  104675. }
  104676. /* Fire any BEFORE UPDATE triggers. This happens before constraints are
  104677. ** verified. One could argue that this is wrong.
  104678. */
  104679. if( tmask&TRIGGER_BEFORE ){
  104680. sqlite3TableAffinity(v, pTab, regNew);
  104681. sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges,
  104682. TRIGGER_BEFORE, pTab, regOldRowid, onError, labelContinue);
  104683. /* The row-trigger may have deleted the row being updated. In this
  104684. ** case, jump to the next row. No updates or AFTER triggers are
  104685. ** required. This behavior - what happens when the row being updated
  104686. ** is deleted or renamed by a BEFORE trigger - is left undefined in the
  104687. ** documentation.
  104688. */
  104689. if( pPk ){
  104690. sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelContinue,regKey,nKey);
  104691. VdbeCoverage(v);
  104692. }else{
  104693. sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, labelContinue, regOldRowid);
  104694. VdbeCoverage(v);
  104695. }
  104696. /* If it did not delete it, the row-trigger may still have modified
  104697. ** some of the columns of the row being updated. Load the values for
  104698. ** all columns not modified by the update statement into their
  104699. ** registers in case this has happened.
  104700. */
  104701. for(i=0; i<pTab->nCol; i++){
  104702. if( aXRef[i]<0 && i!=pTab->iPKey ){
  104703. sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, i, regNew+i);
  104704. }
  104705. }
  104706. }
  104707. if( !isView ){
  104708. int j1 = 0; /* Address of jump instruction */
  104709. int bReplace = 0; /* True if REPLACE conflict resolution might happen */
  104710. /* Do constraint checks. */
  104711. assert( regOldRowid>0 );
  104712. sqlite3GenerateConstraintChecks(pParse, pTab, aRegIdx, iDataCur, iIdxCur,
  104713. regNewRowid, regOldRowid, chngKey, onError, labelContinue, &bReplace);
  104714. /* Do FK constraint checks. */
  104715. if( hasFK ){
  104716. sqlite3FkCheck(pParse, pTab, regOldRowid, 0, aXRef, chngKey);
  104717. }
  104718. /* Delete the index entries associated with the current record. */
  104719. if( bReplace || chngKey ){
  104720. if( pPk ){
  104721. j1 = sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, 0, regKey, nKey);
  104722. }else{
  104723. j1 = sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, 0, regOldRowid);
  104724. }
  104725. VdbeCoverageNeverTaken(v);
  104726. }
  104727. sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur, aRegIdx);
  104728. /* If changing the record number, delete the old record. */
  104729. if( hasFK || chngKey || pPk!=0 ){
  104730. sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, 0);
  104731. }
  104732. if( bReplace || chngKey ){
  104733. sqlite3VdbeJumpHere(v, j1);
  104734. }
  104735. if( hasFK ){
  104736. sqlite3FkCheck(pParse, pTab, 0, regNewRowid, aXRef, chngKey);
  104737. }
  104738. /* Insert the new index entries and the new record. */
  104739. sqlite3CompleteInsertion(pParse, pTab, iDataCur, iIdxCur,
  104740. regNewRowid, aRegIdx, 1, 0, 0);
  104741. /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
  104742. ** handle rows (possibly in other tables) that refer via a foreign key
  104743. ** to the row just updated. */
  104744. if( hasFK ){
  104745. sqlite3FkActions(pParse, pTab, pChanges, regOldRowid, aXRef, chngKey);
  104746. }
  104747. }
  104748. /* Increment the row counter
  104749. */
  104750. if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab){
  104751. sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
  104752. }
  104753. sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges,
  104754. TRIGGER_AFTER, pTab, regOldRowid, onError, labelContinue);
  104755. /* Repeat the above with the next record to be updated, until
  104756. ** all record selected by the WHERE clause have been updated.
  104757. */
  104758. if( okOnePass ){
  104759. /* Nothing to do at end-of-loop for a single-pass */
  104760. }else if( pPk ){
  104761. sqlite3VdbeResolveLabel(v, labelContinue);
  104762. sqlite3VdbeAddOp2(v, OP_Next, iEph, addrTop); VdbeCoverage(v);
  104763. }else{
  104764. sqlite3VdbeAddOp2(v, OP_Goto, 0, labelContinue);
  104765. }
  104766. sqlite3VdbeResolveLabel(v, labelBreak);
  104767. /* Close all tables */
  104768. for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
  104769. assert( aRegIdx );
  104770. if( aToOpen[i+1] ){
  104771. sqlite3VdbeAddOp2(v, OP_Close, iIdxCur+i, 0);
  104772. }
  104773. }
  104774. if( iDataCur<iIdxCur ) sqlite3VdbeAddOp2(v, OP_Close, iDataCur, 0);
  104775. /* Update the sqlite_sequence table by storing the content of the
  104776. ** maximum rowid counter values recorded while inserting into
  104777. ** autoincrement tables.
  104778. */
  104779. if( pParse->nested==0 && pParse->pTriggerTab==0 ){
  104780. sqlite3AutoincrementEnd(pParse);
  104781. }
  104782. /*
  104783. ** Return the number of rows that were changed. If this routine is
  104784. ** generating code because of a call to sqlite3NestedParse(), do not
  104785. ** invoke the callback function.
  104786. */
  104787. if( (db->flags&SQLITE_CountRows) && !pParse->pTriggerTab && !pParse->nested ){
  104788. sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
  104789. sqlite3VdbeSetNumCols(v, 1);
  104790. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows updated", SQLITE_STATIC);
  104791. }
  104792. update_cleanup:
  104793. sqlite3AuthContextPop(&sContext);
  104794. sqlite3DbFree(db, aXRef); /* Also frees aRegIdx[] and aToOpen[] */
  104795. sqlite3SrcListDelete(db, pTabList);
  104796. sqlite3ExprListDelete(db, pChanges);
  104797. sqlite3ExprDelete(db, pWhere);
  104798. return;
  104799. }
  104800. /* Make sure "isView" and other macros defined above are undefined. Otherwise
  104801. ** they may interfere with compilation of other functions in this file
  104802. ** (or in another file, if this file becomes part of the amalgamation). */
  104803. #ifdef isView
  104804. #undef isView
  104805. #endif
  104806. #ifdef pTrigger
  104807. #undef pTrigger
  104808. #endif
  104809. #ifndef SQLITE_OMIT_VIRTUALTABLE
  104810. /*
  104811. ** Generate code for an UPDATE of a virtual table.
  104812. **
  104813. ** The strategy is that we create an ephemeral table that contains
  104814. ** for each row to be changed:
  104815. **
  104816. ** (A) The original rowid of that row.
  104817. ** (B) The revised rowid for the row. (note1)
  104818. ** (C) The content of every column in the row.
  104819. **
  104820. ** Then we loop over this ephemeral table and for each row in
  104821. ** the ephemeral table call VUpdate.
  104822. **
  104823. ** When finished, drop the ephemeral table.
  104824. **
  104825. ** (note1) Actually, if we know in advance that (A) is always the same
  104826. ** as (B) we only store (A), then duplicate (A) when pulling
  104827. ** it out of the ephemeral table before calling VUpdate.
  104828. */
  104829. static void updateVirtualTable(
  104830. Parse *pParse, /* The parsing context */
  104831. SrcList *pSrc, /* The virtual table to be modified */
  104832. Table *pTab, /* The virtual table */
  104833. ExprList *pChanges, /* The columns to change in the UPDATE statement */
  104834. Expr *pRowid, /* Expression used to recompute the rowid */
  104835. int *aXRef, /* Mapping from columns of pTab to entries in pChanges */
  104836. Expr *pWhere, /* WHERE clause of the UPDATE statement */
  104837. int onError /* ON CONFLICT strategy */
  104838. ){
  104839. Vdbe *v = pParse->pVdbe; /* Virtual machine under construction */
  104840. ExprList *pEList = 0; /* The result set of the SELECT statement */
  104841. Select *pSelect = 0; /* The SELECT statement */
  104842. Expr *pExpr; /* Temporary expression */
  104843. int ephemTab; /* Table holding the result of the SELECT */
  104844. int i; /* Loop counter */
  104845. int addr; /* Address of top of loop */
  104846. int iReg; /* First register in set passed to OP_VUpdate */
  104847. sqlite3 *db = pParse->db; /* Database connection */
  104848. const char *pVTab = (const char*)sqlite3GetVTable(db, pTab);
  104849. SelectDest dest;
  104850. /* Construct the SELECT statement that will find the new values for
  104851. ** all updated rows.
  104852. */
  104853. pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ID, "_rowid_"));
  104854. if( pRowid ){
  104855. pEList = sqlite3ExprListAppend(pParse, pEList,
  104856. sqlite3ExprDup(db, pRowid, 0));
  104857. }
  104858. assert( pTab->iPKey<0 );
  104859. for(i=0; i<pTab->nCol; i++){
  104860. if( aXRef[i]>=0 ){
  104861. pExpr = sqlite3ExprDup(db, pChanges->a[aXRef[i]].pExpr, 0);
  104862. }else{
  104863. pExpr = sqlite3Expr(db, TK_ID, pTab->aCol[i].zName);
  104864. }
  104865. pEList = sqlite3ExprListAppend(pParse, pEList, pExpr);
  104866. }
  104867. pSelect = sqlite3SelectNew(pParse, pEList, pSrc, pWhere, 0, 0, 0, 0, 0, 0);
  104868. /* Create the ephemeral table into which the update results will
  104869. ** be stored.
  104870. */
  104871. assert( v );
  104872. ephemTab = pParse->nTab++;
  104873. sqlite3VdbeAddOp2(v, OP_OpenEphemeral, ephemTab, pTab->nCol+1+(pRowid!=0));
  104874. sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
  104875. /* fill the ephemeral table
  104876. */
  104877. sqlite3SelectDestInit(&dest, SRT_Table, ephemTab);
  104878. sqlite3Select(pParse, pSelect, &dest);
  104879. /* Generate code to scan the ephemeral table and call VUpdate. */
  104880. iReg = ++pParse->nMem;
  104881. pParse->nMem += pTab->nCol+1;
  104882. addr = sqlite3VdbeAddOp2(v, OP_Rewind, ephemTab, 0); VdbeCoverage(v);
  104883. sqlite3VdbeAddOp3(v, OP_Column, ephemTab, 0, iReg);
  104884. sqlite3VdbeAddOp3(v, OP_Column, ephemTab, (pRowid?1:0), iReg+1);
  104885. for(i=0; i<pTab->nCol; i++){
  104886. sqlite3VdbeAddOp3(v, OP_Column, ephemTab, i+1+(pRowid!=0), iReg+2+i);
  104887. }
  104888. sqlite3VtabMakeWritable(pParse, pTab);
  104889. sqlite3VdbeAddOp4(v, OP_VUpdate, 0, pTab->nCol+2, iReg, pVTab, P4_VTAB);
  104890. sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
  104891. sqlite3MayAbort(pParse);
  104892. sqlite3VdbeAddOp2(v, OP_Next, ephemTab, addr+1); VdbeCoverage(v);
  104893. sqlite3VdbeJumpHere(v, addr);
  104894. sqlite3VdbeAddOp2(v, OP_Close, ephemTab, 0);
  104895. /* Cleanup */
  104896. sqlite3SelectDelete(db, pSelect);
  104897. }
  104898. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  104899. /************** End of update.c **********************************************/
  104900. /************** Begin file vacuum.c ******************************************/
  104901. /*
  104902. ** 2003 April 6
  104903. **
  104904. ** The author disclaims copyright to this source code. In place of
  104905. ** a legal notice, here is a blessing:
  104906. **
  104907. ** May you do good and not evil.
  104908. ** May you find forgiveness for yourself and forgive others.
  104909. ** May you share freely, never taking more than you give.
  104910. **
  104911. *************************************************************************
  104912. ** This file contains code used to implement the VACUUM command.
  104913. **
  104914. ** Most of the code in this file may be omitted by defining the
  104915. ** SQLITE_OMIT_VACUUM macro.
  104916. */
  104917. #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
  104918. /*
  104919. ** Finalize a prepared statement. If there was an error, store the
  104920. ** text of the error message in *pzErrMsg. Return the result code.
  104921. */
  104922. static int vacuumFinalize(sqlite3 *db, sqlite3_stmt *pStmt, char **pzErrMsg){
  104923. int rc;
  104924. rc = sqlite3VdbeFinalize((Vdbe*)pStmt);
  104925. if( rc ){
  104926. sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
  104927. }
  104928. return rc;
  104929. }
  104930. /*
  104931. ** Execute zSql on database db. Return an error code.
  104932. */
  104933. static int execSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
  104934. sqlite3_stmt *pStmt;
  104935. VVA_ONLY( int rc; )
  104936. if( !zSql ){
  104937. return SQLITE_NOMEM;
  104938. }
  104939. if( SQLITE_OK!=sqlite3_prepare(db, zSql, -1, &pStmt, 0) ){
  104940. sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
  104941. return sqlite3_errcode(db);
  104942. }
  104943. VVA_ONLY( rc = ) sqlite3_step(pStmt);
  104944. assert( rc!=SQLITE_ROW || (db->flags&SQLITE_CountRows) );
  104945. return vacuumFinalize(db, pStmt, pzErrMsg);
  104946. }
  104947. /*
  104948. ** Execute zSql on database db. The statement returns exactly
  104949. ** one column. Execute this as SQL on the same database.
  104950. */
  104951. static int execExecSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
  104952. sqlite3_stmt *pStmt;
  104953. int rc;
  104954. rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
  104955. if( rc!=SQLITE_OK ) return rc;
  104956. while( SQLITE_ROW==sqlite3_step(pStmt) ){
  104957. rc = execSql(db, pzErrMsg, (char*)sqlite3_column_text(pStmt, 0));
  104958. if( rc!=SQLITE_OK ){
  104959. vacuumFinalize(db, pStmt, pzErrMsg);
  104960. return rc;
  104961. }
  104962. }
  104963. return vacuumFinalize(db, pStmt, pzErrMsg);
  104964. }
  104965. /*
  104966. ** The VACUUM command is used to clean up the database,
  104967. ** collapse free space, etc. It is modelled after the VACUUM command
  104968. ** in PostgreSQL. The VACUUM command works as follows:
  104969. **
  104970. ** (1) Create a new transient database file
  104971. ** (2) Copy all content from the database being vacuumed into
  104972. ** the new transient database file
  104973. ** (3) Copy content from the transient database back into the
  104974. ** original database.
  104975. **
  104976. ** The transient database requires temporary disk space approximately
  104977. ** equal to the size of the original database. The copy operation of
  104978. ** step (3) requires additional temporary disk space approximately equal
  104979. ** to the size of the original database for the rollback journal.
  104980. ** Hence, temporary disk space that is approximately 2x the size of the
  104981. ** original database is required. Every page of the database is written
  104982. ** approximately 3 times: Once for step (2) and twice for step (3).
  104983. ** Two writes per page are required in step (3) because the original
  104984. ** database content must be written into the rollback journal prior to
  104985. ** overwriting the database with the vacuumed content.
  104986. **
  104987. ** Only 1x temporary space and only 1x writes would be required if
  104988. ** the copy of step (3) were replace by deleting the original database
  104989. ** and renaming the transient database as the original. But that will
  104990. ** not work if other processes are attached to the original database.
  104991. ** And a power loss in between deleting the original and renaming the
  104992. ** transient would cause the database file to appear to be deleted
  104993. ** following reboot.
  104994. */
  104995. SQLITE_PRIVATE void sqlite3Vacuum(Parse *pParse){
  104996. Vdbe *v = sqlite3GetVdbe(pParse);
  104997. if( v ){
  104998. sqlite3VdbeAddOp2(v, OP_Vacuum, 0, 0);
  104999. sqlite3VdbeUsesBtree(v, 0);
  105000. }
  105001. return;
  105002. }
  105003. /*
  105004. ** This routine implements the OP_Vacuum opcode of the VDBE.
  105005. */
  105006. SQLITE_PRIVATE int sqlite3RunVacuum(char **pzErrMsg, sqlite3 *db){
  105007. int rc = SQLITE_OK; /* Return code from service routines */
  105008. Btree *pMain; /* The database being vacuumed */
  105009. Btree *pTemp; /* The temporary database we vacuum into */
  105010. char *zSql = 0; /* SQL statements */
  105011. int saved_flags; /* Saved value of the db->flags */
  105012. int saved_nChange; /* Saved value of db->nChange */
  105013. int saved_nTotalChange; /* Saved value of db->nTotalChange */
  105014. void (*saved_xTrace)(void*,const char*); /* Saved db->xTrace */
  105015. Db *pDb = 0; /* Database to detach at end of vacuum */
  105016. int isMemDb; /* True if vacuuming a :memory: database */
  105017. int nRes; /* Bytes of reserved space at the end of each page */
  105018. int nDb; /* Number of attached databases */
  105019. if( !db->autoCommit ){
  105020. sqlite3SetString(pzErrMsg, db, "cannot VACUUM from within a transaction");
  105021. return SQLITE_ERROR;
  105022. }
  105023. if( db->nVdbeActive>1 ){
  105024. sqlite3SetString(pzErrMsg, db,"cannot VACUUM - SQL statements in progress");
  105025. return SQLITE_ERROR;
  105026. }
  105027. /* Save the current value of the database flags so that it can be
  105028. ** restored before returning. Then set the writable-schema flag, and
  105029. ** disable CHECK and foreign key constraints. */
  105030. saved_flags = db->flags;
  105031. saved_nChange = db->nChange;
  105032. saved_nTotalChange = db->nTotalChange;
  105033. saved_xTrace = db->xTrace;
  105034. db->flags |= SQLITE_WriteSchema | SQLITE_IgnoreChecks | SQLITE_PreferBuiltin;
  105035. db->flags &= ~(SQLITE_ForeignKeys | SQLITE_ReverseOrder);
  105036. db->xTrace = 0;
  105037. pMain = db->aDb[0].pBt;
  105038. isMemDb = sqlite3PagerIsMemdb(sqlite3BtreePager(pMain));
  105039. /* Attach the temporary database as 'vacuum_db'. The synchronous pragma
  105040. ** can be set to 'off' for this file, as it is not recovered if a crash
  105041. ** occurs anyway. The integrity of the database is maintained by a
  105042. ** (possibly synchronous) transaction opened on the main database before
  105043. ** sqlite3BtreeCopyFile() is called.
  105044. **
  105045. ** An optimisation would be to use a non-journaled pager.
  105046. ** (Later:) I tried setting "PRAGMA vacuum_db.journal_mode=OFF" but
  105047. ** that actually made the VACUUM run slower. Very little journalling
  105048. ** actually occurs when doing a vacuum since the vacuum_db is initially
  105049. ** empty. Only the journal header is written. Apparently it takes more
  105050. ** time to parse and run the PRAGMA to turn journalling off than it does
  105051. ** to write the journal header file.
  105052. */
  105053. nDb = db->nDb;
  105054. if( sqlite3TempInMemory(db) ){
  105055. zSql = "ATTACH ':memory:' AS vacuum_db;";
  105056. }else{
  105057. zSql = "ATTACH '' AS vacuum_db;";
  105058. }
  105059. rc = execSql(db, pzErrMsg, zSql);
  105060. if( db->nDb>nDb ){
  105061. pDb = &db->aDb[db->nDb-1];
  105062. assert( strcmp(pDb->zName,"vacuum_db")==0 );
  105063. }
  105064. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  105065. pTemp = db->aDb[db->nDb-1].pBt;
  105066. /* The call to execSql() to attach the temp database has left the file
  105067. ** locked (as there was more than one active statement when the transaction
  105068. ** to read the schema was concluded. Unlock it here so that this doesn't
  105069. ** cause problems for the call to BtreeSetPageSize() below. */
  105070. sqlite3BtreeCommit(pTemp);
  105071. nRes = sqlite3BtreeGetReserve(pMain);
  105072. /* A VACUUM cannot change the pagesize of an encrypted database. */
  105073. #ifdef SQLITE_HAS_CODEC
  105074. if( db->nextPagesize ){
  105075. extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
  105076. int nKey;
  105077. char *zKey;
  105078. sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
  105079. if( nKey ) db->nextPagesize = 0;
  105080. }
  105081. #endif
  105082. rc = execSql(db, pzErrMsg, "PRAGMA vacuum_db.synchronous=OFF");
  105083. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  105084. /* Begin a transaction and take an exclusive lock on the main database
  105085. ** file. This is done before the sqlite3BtreeGetPageSize(pMain) call below,
  105086. ** to ensure that we do not try to change the page-size on a WAL database.
  105087. */
  105088. rc = execSql(db, pzErrMsg, "BEGIN;");
  105089. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  105090. rc = sqlite3BtreeBeginTrans(pMain, 2);
  105091. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  105092. /* Do not attempt to change the page size for a WAL database */
  105093. if( sqlite3PagerGetJournalMode(sqlite3BtreePager(pMain))
  105094. ==PAGER_JOURNALMODE_WAL ){
  105095. db->nextPagesize = 0;
  105096. }
  105097. if( sqlite3BtreeSetPageSize(pTemp, sqlite3BtreeGetPageSize(pMain), nRes, 0)
  105098. || (!isMemDb && sqlite3BtreeSetPageSize(pTemp, db->nextPagesize, nRes, 0))
  105099. || NEVER(db->mallocFailed)
  105100. ){
  105101. rc = SQLITE_NOMEM;
  105102. goto end_of_vacuum;
  105103. }
  105104. #ifndef SQLITE_OMIT_AUTOVACUUM
  105105. sqlite3BtreeSetAutoVacuum(pTemp, db->nextAutovac>=0 ? db->nextAutovac :
  105106. sqlite3BtreeGetAutoVacuum(pMain));
  105107. #endif
  105108. /* Query the schema of the main database. Create a mirror schema
  105109. ** in the temporary database.
  105110. */
  105111. rc = execExecSql(db, pzErrMsg,
  105112. "SELECT 'CREATE TABLE vacuum_db.' || substr(sql,14) "
  105113. " FROM sqlite_master WHERE type='table' AND name!='sqlite_sequence'"
  105114. " AND coalesce(rootpage,1)>0"
  105115. );
  105116. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  105117. rc = execExecSql(db, pzErrMsg,
  105118. "SELECT 'CREATE INDEX vacuum_db.' || substr(sql,14)"
  105119. " FROM sqlite_master WHERE sql LIKE 'CREATE INDEX %' ");
  105120. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  105121. rc = execExecSql(db, pzErrMsg,
  105122. "SELECT 'CREATE UNIQUE INDEX vacuum_db.' || substr(sql,21) "
  105123. " FROM sqlite_master WHERE sql LIKE 'CREATE UNIQUE INDEX %'");
  105124. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  105125. /* Loop through the tables in the main database. For each, do
  105126. ** an "INSERT INTO vacuum_db.xxx SELECT * FROM main.xxx;" to copy
  105127. ** the contents to the temporary database.
  105128. */
  105129. rc = execExecSql(db, pzErrMsg,
  105130. "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
  105131. "|| ' SELECT * FROM main.' || quote(name) || ';'"
  105132. "FROM main.sqlite_master "
  105133. "WHERE type = 'table' AND name!='sqlite_sequence' "
  105134. " AND coalesce(rootpage,1)>0"
  105135. );
  105136. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  105137. /* Copy over the sequence table
  105138. */
  105139. rc = execExecSql(db, pzErrMsg,
  105140. "SELECT 'DELETE FROM vacuum_db.' || quote(name) || ';' "
  105141. "FROM vacuum_db.sqlite_master WHERE name='sqlite_sequence' "
  105142. );
  105143. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  105144. rc = execExecSql(db, pzErrMsg,
  105145. "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
  105146. "|| ' SELECT * FROM main.' || quote(name) || ';' "
  105147. "FROM vacuum_db.sqlite_master WHERE name=='sqlite_sequence';"
  105148. );
  105149. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  105150. /* Copy the triggers, views, and virtual tables from the main database
  105151. ** over to the temporary database. None of these objects has any
  105152. ** associated storage, so all we have to do is copy their entries
  105153. ** from the SQLITE_MASTER table.
  105154. */
  105155. rc = execSql(db, pzErrMsg,
  105156. "INSERT INTO vacuum_db.sqlite_master "
  105157. " SELECT type, name, tbl_name, rootpage, sql"
  105158. " FROM main.sqlite_master"
  105159. " WHERE type='view' OR type='trigger'"
  105160. " OR (type='table' AND rootpage=0)"
  105161. );
  105162. if( rc ) goto end_of_vacuum;
  105163. /* At this point, there is a write transaction open on both the
  105164. ** vacuum database and the main database. Assuming no error occurs,
  105165. ** both transactions are closed by this block - the main database
  105166. ** transaction by sqlite3BtreeCopyFile() and the other by an explicit
  105167. ** call to sqlite3BtreeCommit().
  105168. */
  105169. {
  105170. u32 meta;
  105171. int i;
  105172. /* This array determines which meta meta values are preserved in the
  105173. ** vacuum. Even entries are the meta value number and odd entries
  105174. ** are an increment to apply to the meta value after the vacuum.
  105175. ** The increment is used to increase the schema cookie so that other
  105176. ** connections to the same database will know to reread the schema.
  105177. */
  105178. static const unsigned char aCopy[] = {
  105179. BTREE_SCHEMA_VERSION, 1, /* Add one to the old schema cookie */
  105180. BTREE_DEFAULT_CACHE_SIZE, 0, /* Preserve the default page cache size */
  105181. BTREE_TEXT_ENCODING, 0, /* Preserve the text encoding */
  105182. BTREE_USER_VERSION, 0, /* Preserve the user version */
  105183. BTREE_APPLICATION_ID, 0, /* Preserve the application id */
  105184. };
  105185. assert( 1==sqlite3BtreeIsInTrans(pTemp) );
  105186. assert( 1==sqlite3BtreeIsInTrans(pMain) );
  105187. /* Copy Btree meta values */
  105188. for(i=0; i<ArraySize(aCopy); i+=2){
  105189. /* GetMeta() and UpdateMeta() cannot fail in this context because
  105190. ** we already have page 1 loaded into cache and marked dirty. */
  105191. sqlite3BtreeGetMeta(pMain, aCopy[i], &meta);
  105192. rc = sqlite3BtreeUpdateMeta(pTemp, aCopy[i], meta+aCopy[i+1]);
  105193. if( NEVER(rc!=SQLITE_OK) ) goto end_of_vacuum;
  105194. }
  105195. rc = sqlite3BtreeCopyFile(pMain, pTemp);
  105196. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  105197. rc = sqlite3BtreeCommit(pTemp);
  105198. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  105199. #ifndef SQLITE_OMIT_AUTOVACUUM
  105200. sqlite3BtreeSetAutoVacuum(pMain, sqlite3BtreeGetAutoVacuum(pTemp));
  105201. #endif
  105202. }
  105203. assert( rc==SQLITE_OK );
  105204. rc = sqlite3BtreeSetPageSize(pMain, sqlite3BtreeGetPageSize(pTemp), nRes,1);
  105205. end_of_vacuum:
  105206. /* Restore the original value of db->flags */
  105207. db->flags = saved_flags;
  105208. db->nChange = saved_nChange;
  105209. db->nTotalChange = saved_nTotalChange;
  105210. db->xTrace = saved_xTrace;
  105211. sqlite3BtreeSetPageSize(pMain, -1, -1, 1);
  105212. /* Currently there is an SQL level transaction open on the vacuum
  105213. ** database. No locks are held on any other files (since the main file
  105214. ** was committed at the btree level). So it safe to end the transaction
  105215. ** by manually setting the autoCommit flag to true and detaching the
  105216. ** vacuum database. The vacuum_db journal file is deleted when the pager
  105217. ** is closed by the DETACH.
  105218. */
  105219. db->autoCommit = 1;
  105220. if( pDb ){
  105221. sqlite3BtreeClose(pDb->pBt);
  105222. pDb->pBt = 0;
  105223. pDb->pSchema = 0;
  105224. }
  105225. /* This both clears the schemas and reduces the size of the db->aDb[]
  105226. ** array. */
  105227. sqlite3ResetAllSchemasOfConnection(db);
  105228. return rc;
  105229. }
  105230. #endif /* SQLITE_OMIT_VACUUM && SQLITE_OMIT_ATTACH */
  105231. /************** End of vacuum.c **********************************************/
  105232. /************** Begin file vtab.c ********************************************/
  105233. /*
  105234. ** 2006 June 10
  105235. **
  105236. ** The author disclaims copyright to this source code. In place of
  105237. ** a legal notice, here is a blessing:
  105238. **
  105239. ** May you do good and not evil.
  105240. ** May you find forgiveness for yourself and forgive others.
  105241. ** May you share freely, never taking more than you give.
  105242. **
  105243. *************************************************************************
  105244. ** This file contains code used to help implement virtual tables.
  105245. */
  105246. #ifndef SQLITE_OMIT_VIRTUALTABLE
  105247. /*
  105248. ** Before a virtual table xCreate() or xConnect() method is invoked, the
  105249. ** sqlite3.pVtabCtx member variable is set to point to an instance of
  105250. ** this struct allocated on the stack. It is used by the implementation of
  105251. ** the sqlite3_declare_vtab() and sqlite3_vtab_config() APIs, both of which
  105252. ** are invoked only from within xCreate and xConnect methods.
  105253. */
  105254. struct VtabCtx {
  105255. VTable *pVTable; /* The virtual table being constructed */
  105256. Table *pTab; /* The Table object to which the virtual table belongs */
  105257. };
  105258. /*
  105259. ** The actual function that does the work of creating a new module.
  105260. ** This function implements the sqlite3_create_module() and
  105261. ** sqlite3_create_module_v2() interfaces.
  105262. */
  105263. static int createModule(
  105264. sqlite3 *db, /* Database in which module is registered */
  105265. const char *zName, /* Name assigned to this module */
  105266. const sqlite3_module *pModule, /* The definition of the module */
  105267. void *pAux, /* Context pointer for xCreate/xConnect */
  105268. void (*xDestroy)(void *) /* Module destructor function */
  105269. ){
  105270. int rc = SQLITE_OK;
  105271. int nName;
  105272. sqlite3_mutex_enter(db->mutex);
  105273. nName = sqlite3Strlen30(zName);
  105274. if( sqlite3HashFind(&db->aModule, zName) ){
  105275. rc = SQLITE_MISUSE_BKPT;
  105276. }else{
  105277. Module *pMod;
  105278. pMod = (Module *)sqlite3DbMallocRaw(db, sizeof(Module) + nName + 1);
  105279. if( pMod ){
  105280. Module *pDel;
  105281. char *zCopy = (char *)(&pMod[1]);
  105282. memcpy(zCopy, zName, nName+1);
  105283. pMod->zName = zCopy;
  105284. pMod->pModule = pModule;
  105285. pMod->pAux = pAux;
  105286. pMod->xDestroy = xDestroy;
  105287. pDel = (Module *)sqlite3HashInsert(&db->aModule,zCopy,(void*)pMod);
  105288. assert( pDel==0 || pDel==pMod );
  105289. if( pDel ){
  105290. db->mallocFailed = 1;
  105291. sqlite3DbFree(db, pDel);
  105292. }
  105293. }
  105294. }
  105295. rc = sqlite3ApiExit(db, rc);
  105296. if( rc!=SQLITE_OK && xDestroy ) xDestroy(pAux);
  105297. sqlite3_mutex_leave(db->mutex);
  105298. return rc;
  105299. }
  105300. /*
  105301. ** External API function used to create a new virtual-table module.
  105302. */
  105303. SQLITE_API int sqlite3_create_module(
  105304. sqlite3 *db, /* Database in which module is registered */
  105305. const char *zName, /* Name assigned to this module */
  105306. const sqlite3_module *pModule, /* The definition of the module */
  105307. void *pAux /* Context pointer for xCreate/xConnect */
  105308. ){
  105309. #ifdef SQLITE_ENABLE_API_ARMOR
  105310. if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
  105311. #endif
  105312. return createModule(db, zName, pModule, pAux, 0);
  105313. }
  105314. /*
  105315. ** External API function used to create a new virtual-table module.
  105316. */
  105317. SQLITE_API int sqlite3_create_module_v2(
  105318. sqlite3 *db, /* Database in which module is registered */
  105319. const char *zName, /* Name assigned to this module */
  105320. const sqlite3_module *pModule, /* The definition of the module */
  105321. void *pAux, /* Context pointer for xCreate/xConnect */
  105322. void (*xDestroy)(void *) /* Module destructor function */
  105323. ){
  105324. #ifdef SQLITE_ENABLE_API_ARMOR
  105325. if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
  105326. #endif
  105327. return createModule(db, zName, pModule, pAux, xDestroy);
  105328. }
  105329. /*
  105330. ** Lock the virtual table so that it cannot be disconnected.
  105331. ** Locks nest. Every lock should have a corresponding unlock.
  105332. ** If an unlock is omitted, resources leaks will occur.
  105333. **
  105334. ** If a disconnect is attempted while a virtual table is locked,
  105335. ** the disconnect is deferred until all locks have been removed.
  105336. */
  105337. SQLITE_PRIVATE void sqlite3VtabLock(VTable *pVTab){
  105338. pVTab->nRef++;
  105339. }
  105340. /*
  105341. ** pTab is a pointer to a Table structure representing a virtual-table.
  105342. ** Return a pointer to the VTable object used by connection db to access
  105343. ** this virtual-table, if one has been created, or NULL otherwise.
  105344. */
  105345. SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3 *db, Table *pTab){
  105346. VTable *pVtab;
  105347. assert( IsVirtual(pTab) );
  105348. for(pVtab=pTab->pVTable; pVtab && pVtab->db!=db; pVtab=pVtab->pNext);
  105349. return pVtab;
  105350. }
  105351. /*
  105352. ** Decrement the ref-count on a virtual table object. When the ref-count
  105353. ** reaches zero, call the xDisconnect() method to delete the object.
  105354. */
  105355. SQLITE_PRIVATE void sqlite3VtabUnlock(VTable *pVTab){
  105356. sqlite3 *db = pVTab->db;
  105357. assert( db );
  105358. assert( pVTab->nRef>0 );
  105359. assert( db->magic==SQLITE_MAGIC_OPEN || db->magic==SQLITE_MAGIC_ZOMBIE );
  105360. pVTab->nRef--;
  105361. if( pVTab->nRef==0 ){
  105362. sqlite3_vtab *p = pVTab->pVtab;
  105363. if( p ){
  105364. p->pModule->xDisconnect(p);
  105365. }
  105366. sqlite3DbFree(db, pVTab);
  105367. }
  105368. }
  105369. /*
  105370. ** Table p is a virtual table. This function moves all elements in the
  105371. ** p->pVTable list to the sqlite3.pDisconnect lists of their associated
  105372. ** database connections to be disconnected at the next opportunity.
  105373. ** Except, if argument db is not NULL, then the entry associated with
  105374. ** connection db is left in the p->pVTable list.
  105375. */
  105376. static VTable *vtabDisconnectAll(sqlite3 *db, Table *p){
  105377. VTable *pRet = 0;
  105378. VTable *pVTable = p->pVTable;
  105379. p->pVTable = 0;
  105380. /* Assert that the mutex (if any) associated with the BtShared database
  105381. ** that contains table p is held by the caller. See header comments
  105382. ** above function sqlite3VtabUnlockList() for an explanation of why
  105383. ** this makes it safe to access the sqlite3.pDisconnect list of any
  105384. ** database connection that may have an entry in the p->pVTable list.
  105385. */
  105386. assert( db==0 || sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
  105387. while( pVTable ){
  105388. sqlite3 *db2 = pVTable->db;
  105389. VTable *pNext = pVTable->pNext;
  105390. assert( db2 );
  105391. if( db2==db ){
  105392. pRet = pVTable;
  105393. p->pVTable = pRet;
  105394. pRet->pNext = 0;
  105395. }else{
  105396. pVTable->pNext = db2->pDisconnect;
  105397. db2->pDisconnect = pVTable;
  105398. }
  105399. pVTable = pNext;
  105400. }
  105401. assert( !db || pRet );
  105402. return pRet;
  105403. }
  105404. /*
  105405. ** Table *p is a virtual table. This function removes the VTable object
  105406. ** for table *p associated with database connection db from the linked
  105407. ** list in p->pVTab. It also decrements the VTable ref count. This is
  105408. ** used when closing database connection db to free all of its VTable
  105409. ** objects without disturbing the rest of the Schema object (which may
  105410. ** be being used by other shared-cache connections).
  105411. */
  105412. SQLITE_PRIVATE void sqlite3VtabDisconnect(sqlite3 *db, Table *p){
  105413. VTable **ppVTab;
  105414. assert( IsVirtual(p) );
  105415. assert( sqlite3BtreeHoldsAllMutexes(db) );
  105416. assert( sqlite3_mutex_held(db->mutex) );
  105417. for(ppVTab=&p->pVTable; *ppVTab; ppVTab=&(*ppVTab)->pNext){
  105418. if( (*ppVTab)->db==db ){
  105419. VTable *pVTab = *ppVTab;
  105420. *ppVTab = pVTab->pNext;
  105421. sqlite3VtabUnlock(pVTab);
  105422. break;
  105423. }
  105424. }
  105425. }
  105426. /*
  105427. ** Disconnect all the virtual table objects in the sqlite3.pDisconnect list.
  105428. **
  105429. ** This function may only be called when the mutexes associated with all
  105430. ** shared b-tree databases opened using connection db are held by the
  105431. ** caller. This is done to protect the sqlite3.pDisconnect list. The
  105432. ** sqlite3.pDisconnect list is accessed only as follows:
  105433. **
  105434. ** 1) By this function. In this case, all BtShared mutexes and the mutex
  105435. ** associated with the database handle itself must be held.
  105436. **
  105437. ** 2) By function vtabDisconnectAll(), when it adds a VTable entry to
  105438. ** the sqlite3.pDisconnect list. In this case either the BtShared mutex
  105439. ** associated with the database the virtual table is stored in is held
  105440. ** or, if the virtual table is stored in a non-sharable database, then
  105441. ** the database handle mutex is held.
  105442. **
  105443. ** As a result, a sqlite3.pDisconnect cannot be accessed simultaneously
  105444. ** by multiple threads. It is thread-safe.
  105445. */
  105446. SQLITE_PRIVATE void sqlite3VtabUnlockList(sqlite3 *db){
  105447. VTable *p = db->pDisconnect;
  105448. db->pDisconnect = 0;
  105449. assert( sqlite3BtreeHoldsAllMutexes(db) );
  105450. assert( sqlite3_mutex_held(db->mutex) );
  105451. if( p ){
  105452. sqlite3ExpirePreparedStatements(db);
  105453. do {
  105454. VTable *pNext = p->pNext;
  105455. sqlite3VtabUnlock(p);
  105456. p = pNext;
  105457. }while( p );
  105458. }
  105459. }
  105460. /*
  105461. ** Clear any and all virtual-table information from the Table record.
  105462. ** This routine is called, for example, just before deleting the Table
  105463. ** record.
  105464. **
  105465. ** Since it is a virtual-table, the Table structure contains a pointer
  105466. ** to the head of a linked list of VTable structures. Each VTable
  105467. ** structure is associated with a single sqlite3* user of the schema.
  105468. ** The reference count of the VTable structure associated with database
  105469. ** connection db is decremented immediately (which may lead to the
  105470. ** structure being xDisconnected and free). Any other VTable structures
  105471. ** in the list are moved to the sqlite3.pDisconnect list of the associated
  105472. ** database connection.
  105473. */
  105474. SQLITE_PRIVATE void sqlite3VtabClear(sqlite3 *db, Table *p){
  105475. if( !db || db->pnBytesFreed==0 ) vtabDisconnectAll(0, p);
  105476. if( p->azModuleArg ){
  105477. int i;
  105478. for(i=0; i<p->nModuleArg; i++){
  105479. if( i!=1 ) sqlite3DbFree(db, p->azModuleArg[i]);
  105480. }
  105481. sqlite3DbFree(db, p->azModuleArg);
  105482. }
  105483. }
  105484. /*
  105485. ** Add a new module argument to pTable->azModuleArg[].
  105486. ** The string is not copied - the pointer is stored. The
  105487. ** string will be freed automatically when the table is
  105488. ** deleted.
  105489. */
  105490. static void addModuleArgument(sqlite3 *db, Table *pTable, char *zArg){
  105491. int i = pTable->nModuleArg++;
  105492. int nBytes = sizeof(char *)*(1+pTable->nModuleArg);
  105493. char **azModuleArg;
  105494. azModuleArg = sqlite3DbRealloc(db, pTable->azModuleArg, nBytes);
  105495. if( azModuleArg==0 ){
  105496. int j;
  105497. for(j=0; j<i; j++){
  105498. sqlite3DbFree(db, pTable->azModuleArg[j]);
  105499. }
  105500. sqlite3DbFree(db, zArg);
  105501. sqlite3DbFree(db, pTable->azModuleArg);
  105502. pTable->nModuleArg = 0;
  105503. }else{
  105504. azModuleArg[i] = zArg;
  105505. azModuleArg[i+1] = 0;
  105506. }
  105507. pTable->azModuleArg = azModuleArg;
  105508. }
  105509. /*
  105510. ** The parser calls this routine when it first sees a CREATE VIRTUAL TABLE
  105511. ** statement. The module name has been parsed, but the optional list
  105512. ** of parameters that follow the module name are still pending.
  105513. */
  105514. SQLITE_PRIVATE void sqlite3VtabBeginParse(
  105515. Parse *pParse, /* Parsing context */
  105516. Token *pName1, /* Name of new table, or database name */
  105517. Token *pName2, /* Name of new table or NULL */
  105518. Token *pModuleName, /* Name of the module for the virtual table */
  105519. int ifNotExists /* No error if the table already exists */
  105520. ){
  105521. int iDb; /* The database the table is being created in */
  105522. Table *pTable; /* The new virtual table */
  105523. sqlite3 *db; /* Database connection */
  105524. sqlite3StartTable(pParse, pName1, pName2, 0, 0, 1, ifNotExists);
  105525. pTable = pParse->pNewTable;
  105526. if( pTable==0 ) return;
  105527. assert( 0==pTable->pIndex );
  105528. db = pParse->db;
  105529. iDb = sqlite3SchemaToIndex(db, pTable->pSchema);
  105530. assert( iDb>=0 );
  105531. pTable->tabFlags |= TF_Virtual;
  105532. pTable->nModuleArg = 0;
  105533. addModuleArgument(db, pTable, sqlite3NameFromToken(db, pModuleName));
  105534. addModuleArgument(db, pTable, 0);
  105535. addModuleArgument(db, pTable, sqlite3DbStrDup(db, pTable->zName));
  105536. pParse->sNameToken.n = (int)(&pModuleName->z[pModuleName->n] - pName1->z);
  105537. #ifndef SQLITE_OMIT_AUTHORIZATION
  105538. /* Creating a virtual table invokes the authorization callback twice.
  105539. ** The first invocation, to obtain permission to INSERT a row into the
  105540. ** sqlite_master table, has already been made by sqlite3StartTable().
  105541. ** The second call, to obtain permission to create the table, is made now.
  105542. */
  105543. if( pTable->azModuleArg ){
  105544. sqlite3AuthCheck(pParse, SQLITE_CREATE_VTABLE, pTable->zName,
  105545. pTable->azModuleArg[0], pParse->db->aDb[iDb].zName);
  105546. }
  105547. #endif
  105548. }
  105549. /*
  105550. ** This routine takes the module argument that has been accumulating
  105551. ** in pParse->zArg[] and appends it to the list of arguments on the
  105552. ** virtual table currently under construction in pParse->pTable.
  105553. */
  105554. static void addArgumentToVtab(Parse *pParse){
  105555. if( pParse->sArg.z && pParse->pNewTable ){
  105556. const char *z = (const char*)pParse->sArg.z;
  105557. int n = pParse->sArg.n;
  105558. sqlite3 *db = pParse->db;
  105559. addModuleArgument(db, pParse->pNewTable, sqlite3DbStrNDup(db, z, n));
  105560. }
  105561. }
  105562. /*
  105563. ** The parser calls this routine after the CREATE VIRTUAL TABLE statement
  105564. ** has been completely parsed.
  105565. */
  105566. SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse *pParse, Token *pEnd){
  105567. Table *pTab = pParse->pNewTable; /* The table being constructed */
  105568. sqlite3 *db = pParse->db; /* The database connection */
  105569. if( pTab==0 ) return;
  105570. addArgumentToVtab(pParse);
  105571. pParse->sArg.z = 0;
  105572. if( pTab->nModuleArg<1 ) return;
  105573. /* If the CREATE VIRTUAL TABLE statement is being entered for the
  105574. ** first time (in other words if the virtual table is actually being
  105575. ** created now instead of just being read out of sqlite_master) then
  105576. ** do additional initialization work and store the statement text
  105577. ** in the sqlite_master table.
  105578. */
  105579. if( !db->init.busy ){
  105580. char *zStmt;
  105581. char *zWhere;
  105582. int iDb;
  105583. Vdbe *v;
  105584. /* Compute the complete text of the CREATE VIRTUAL TABLE statement */
  105585. if( pEnd ){
  105586. pParse->sNameToken.n = (int)(pEnd->z - pParse->sNameToken.z) + pEnd->n;
  105587. }
  105588. zStmt = sqlite3MPrintf(db, "CREATE VIRTUAL TABLE %T", &pParse->sNameToken);
  105589. /* A slot for the record has already been allocated in the
  105590. ** SQLITE_MASTER table. We just need to update that slot with all
  105591. ** the information we've collected.
  105592. **
  105593. ** The VM register number pParse->regRowid holds the rowid of an
  105594. ** entry in the sqlite_master table tht was created for this vtab
  105595. ** by sqlite3StartTable().
  105596. */
  105597. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  105598. sqlite3NestedParse(pParse,
  105599. "UPDATE %Q.%s "
  105600. "SET type='table', name=%Q, tbl_name=%Q, rootpage=0, sql=%Q "
  105601. "WHERE rowid=#%d",
  105602. db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
  105603. pTab->zName,
  105604. pTab->zName,
  105605. zStmt,
  105606. pParse->regRowid
  105607. );
  105608. sqlite3DbFree(db, zStmt);
  105609. v = sqlite3GetVdbe(pParse);
  105610. sqlite3ChangeCookie(pParse, iDb);
  105611. sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);
  105612. zWhere = sqlite3MPrintf(db, "name='%q' AND type='table'", pTab->zName);
  105613. sqlite3VdbeAddParseSchemaOp(v, iDb, zWhere);
  105614. sqlite3VdbeAddOp4(v, OP_VCreate, iDb, 0, 0,
  105615. pTab->zName, sqlite3Strlen30(pTab->zName) + 1);
  105616. }
  105617. /* If we are rereading the sqlite_master table create the in-memory
  105618. ** record of the table. The xConnect() method is not called until
  105619. ** the first time the virtual table is used in an SQL statement. This
  105620. ** allows a schema that contains virtual tables to be loaded before
  105621. ** the required virtual table implementations are registered. */
  105622. else {
  105623. Table *pOld;
  105624. Schema *pSchema = pTab->pSchema;
  105625. const char *zName = pTab->zName;
  105626. assert( sqlite3SchemaMutexHeld(db, 0, pSchema) );
  105627. pOld = sqlite3HashInsert(&pSchema->tblHash, zName, pTab);
  105628. if( pOld ){
  105629. db->mallocFailed = 1;
  105630. assert( pTab==pOld ); /* Malloc must have failed inside HashInsert() */
  105631. return;
  105632. }
  105633. pParse->pNewTable = 0;
  105634. }
  105635. }
  105636. /*
  105637. ** The parser calls this routine when it sees the first token
  105638. ** of an argument to the module name in a CREATE VIRTUAL TABLE statement.
  105639. */
  105640. SQLITE_PRIVATE void sqlite3VtabArgInit(Parse *pParse){
  105641. addArgumentToVtab(pParse);
  105642. pParse->sArg.z = 0;
  105643. pParse->sArg.n = 0;
  105644. }
  105645. /*
  105646. ** The parser calls this routine for each token after the first token
  105647. ** in an argument to the module name in a CREATE VIRTUAL TABLE statement.
  105648. */
  105649. SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse *pParse, Token *p){
  105650. Token *pArg = &pParse->sArg;
  105651. if( pArg->z==0 ){
  105652. pArg->z = p->z;
  105653. pArg->n = p->n;
  105654. }else{
  105655. assert(pArg->z < p->z);
  105656. pArg->n = (int)(&p->z[p->n] - pArg->z);
  105657. }
  105658. }
  105659. /*
  105660. ** Invoke a virtual table constructor (either xCreate or xConnect). The
  105661. ** pointer to the function to invoke is passed as the fourth parameter
  105662. ** to this procedure.
  105663. */
  105664. static int vtabCallConstructor(
  105665. sqlite3 *db,
  105666. Table *pTab,
  105667. Module *pMod,
  105668. int (*xConstruct)(sqlite3*,void*,int,const char*const*,sqlite3_vtab**,char**),
  105669. char **pzErr
  105670. ){
  105671. VtabCtx sCtx, *pPriorCtx;
  105672. VTable *pVTable;
  105673. int rc;
  105674. const char *const*azArg = (const char *const*)pTab->azModuleArg;
  105675. int nArg = pTab->nModuleArg;
  105676. char *zErr = 0;
  105677. char *zModuleName = sqlite3MPrintf(db, "%s", pTab->zName);
  105678. int iDb;
  105679. if( !zModuleName ){
  105680. return SQLITE_NOMEM;
  105681. }
  105682. pVTable = sqlite3DbMallocZero(db, sizeof(VTable));
  105683. if( !pVTable ){
  105684. sqlite3DbFree(db, zModuleName);
  105685. return SQLITE_NOMEM;
  105686. }
  105687. pVTable->db = db;
  105688. pVTable->pMod = pMod;
  105689. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  105690. pTab->azModuleArg[1] = db->aDb[iDb].zName;
  105691. /* Invoke the virtual table constructor */
  105692. assert( &db->pVtabCtx );
  105693. assert( xConstruct );
  105694. sCtx.pTab = pTab;
  105695. sCtx.pVTable = pVTable;
  105696. pPriorCtx = db->pVtabCtx;
  105697. db->pVtabCtx = &sCtx;
  105698. rc = xConstruct(db, pMod->pAux, nArg, azArg, &pVTable->pVtab, &zErr);
  105699. db->pVtabCtx = pPriorCtx;
  105700. if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
  105701. if( SQLITE_OK!=rc ){
  105702. if( zErr==0 ){
  105703. *pzErr = sqlite3MPrintf(db, "vtable constructor failed: %s", zModuleName);
  105704. }else {
  105705. *pzErr = sqlite3MPrintf(db, "%s", zErr);
  105706. sqlite3_free(zErr);
  105707. }
  105708. sqlite3DbFree(db, pVTable);
  105709. }else if( ALWAYS(pVTable->pVtab) ){
  105710. /* Justification of ALWAYS(): A correct vtab constructor must allocate
  105711. ** the sqlite3_vtab object if successful. */
  105712. memset(pVTable->pVtab, 0, sizeof(pVTable->pVtab[0]));
  105713. pVTable->pVtab->pModule = pMod->pModule;
  105714. pVTable->nRef = 1;
  105715. if( sCtx.pTab ){
  105716. const char *zFormat = "vtable constructor did not declare schema: %s";
  105717. *pzErr = sqlite3MPrintf(db, zFormat, pTab->zName);
  105718. sqlite3VtabUnlock(pVTable);
  105719. rc = SQLITE_ERROR;
  105720. }else{
  105721. int iCol;
  105722. /* If everything went according to plan, link the new VTable structure
  105723. ** into the linked list headed by pTab->pVTable. Then loop through the
  105724. ** columns of the table to see if any of them contain the token "hidden".
  105725. ** If so, set the Column COLFLAG_HIDDEN flag and remove the token from
  105726. ** the type string. */
  105727. pVTable->pNext = pTab->pVTable;
  105728. pTab->pVTable = pVTable;
  105729. for(iCol=0; iCol<pTab->nCol; iCol++){
  105730. char *zType = pTab->aCol[iCol].zType;
  105731. int nType;
  105732. int i = 0;
  105733. if( !zType ) continue;
  105734. nType = sqlite3Strlen30(zType);
  105735. if( sqlite3StrNICmp("hidden", zType, 6)||(zType[6] && zType[6]!=' ') ){
  105736. for(i=0; i<nType; i++){
  105737. if( (0==sqlite3StrNICmp(" hidden", &zType[i], 7))
  105738. && (zType[i+7]=='\0' || zType[i+7]==' ')
  105739. ){
  105740. i++;
  105741. break;
  105742. }
  105743. }
  105744. }
  105745. if( i<nType ){
  105746. int j;
  105747. int nDel = 6 + (zType[i+6] ? 1 : 0);
  105748. for(j=i; (j+nDel)<=nType; j++){
  105749. zType[j] = zType[j+nDel];
  105750. }
  105751. if( zType[i]=='\0' && i>0 ){
  105752. assert(zType[i-1]==' ');
  105753. zType[i-1] = '\0';
  105754. }
  105755. pTab->aCol[iCol].colFlags |= COLFLAG_HIDDEN;
  105756. }
  105757. }
  105758. }
  105759. }
  105760. sqlite3DbFree(db, zModuleName);
  105761. return rc;
  105762. }
  105763. /*
  105764. ** This function is invoked by the parser to call the xConnect() method
  105765. ** of the virtual table pTab. If an error occurs, an error code is returned
  105766. ** and an error left in pParse.
  105767. **
  105768. ** This call is a no-op if table pTab is not a virtual table.
  105769. */
  105770. SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse *pParse, Table *pTab){
  105771. sqlite3 *db = pParse->db;
  105772. const char *zMod;
  105773. Module *pMod;
  105774. int rc;
  105775. assert( pTab );
  105776. if( (pTab->tabFlags & TF_Virtual)==0 || sqlite3GetVTable(db, pTab) ){
  105777. return SQLITE_OK;
  105778. }
  105779. /* Locate the required virtual table module */
  105780. zMod = pTab->azModuleArg[0];
  105781. pMod = (Module*)sqlite3HashFind(&db->aModule, zMod);
  105782. if( !pMod ){
  105783. const char *zModule = pTab->azModuleArg[0];
  105784. sqlite3ErrorMsg(pParse, "no such module: %s", zModule);
  105785. rc = SQLITE_ERROR;
  105786. }else{
  105787. char *zErr = 0;
  105788. rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xConnect, &zErr);
  105789. if( rc!=SQLITE_OK ){
  105790. sqlite3ErrorMsg(pParse, "%s", zErr);
  105791. }
  105792. sqlite3DbFree(db, zErr);
  105793. }
  105794. return rc;
  105795. }
  105796. /*
  105797. ** Grow the db->aVTrans[] array so that there is room for at least one
  105798. ** more v-table. Return SQLITE_NOMEM if a malloc fails, or SQLITE_OK otherwise.
  105799. */
  105800. static int growVTrans(sqlite3 *db){
  105801. const int ARRAY_INCR = 5;
  105802. /* Grow the sqlite3.aVTrans array if required */
  105803. if( (db->nVTrans%ARRAY_INCR)==0 ){
  105804. VTable **aVTrans;
  105805. int nBytes = sizeof(sqlite3_vtab *) * (db->nVTrans + ARRAY_INCR);
  105806. aVTrans = sqlite3DbRealloc(db, (void *)db->aVTrans, nBytes);
  105807. if( !aVTrans ){
  105808. return SQLITE_NOMEM;
  105809. }
  105810. memset(&aVTrans[db->nVTrans], 0, sizeof(sqlite3_vtab *)*ARRAY_INCR);
  105811. db->aVTrans = aVTrans;
  105812. }
  105813. return SQLITE_OK;
  105814. }
  105815. /*
  105816. ** Add the virtual table pVTab to the array sqlite3.aVTrans[]. Space should
  105817. ** have already been reserved using growVTrans().
  105818. */
  105819. static void addToVTrans(sqlite3 *db, VTable *pVTab){
  105820. /* Add pVtab to the end of sqlite3.aVTrans */
  105821. db->aVTrans[db->nVTrans++] = pVTab;
  105822. sqlite3VtabLock(pVTab);
  105823. }
  105824. /*
  105825. ** This function is invoked by the vdbe to call the xCreate method
  105826. ** of the virtual table named zTab in database iDb.
  105827. **
  105828. ** If an error occurs, *pzErr is set to point an an English language
  105829. ** description of the error and an SQLITE_XXX error code is returned.
  105830. ** In this case the caller must call sqlite3DbFree(db, ) on *pzErr.
  105831. */
  105832. SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3 *db, int iDb, const char *zTab, char **pzErr){
  105833. int rc = SQLITE_OK;
  105834. Table *pTab;
  105835. Module *pMod;
  105836. const char *zMod;
  105837. pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
  105838. assert( pTab && (pTab->tabFlags & TF_Virtual)!=0 && !pTab->pVTable );
  105839. /* Locate the required virtual table module */
  105840. zMod = pTab->azModuleArg[0];
  105841. pMod = (Module*)sqlite3HashFind(&db->aModule, zMod);
  105842. /* If the module has been registered and includes a Create method,
  105843. ** invoke it now. If the module has not been registered, return an
  105844. ** error. Otherwise, do nothing.
  105845. */
  105846. if( !pMod ){
  105847. *pzErr = sqlite3MPrintf(db, "no such module: %s", zMod);
  105848. rc = SQLITE_ERROR;
  105849. }else{
  105850. rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xCreate, pzErr);
  105851. }
  105852. /* Justification of ALWAYS(): The xConstructor method is required to
  105853. ** create a valid sqlite3_vtab if it returns SQLITE_OK. */
  105854. if( rc==SQLITE_OK && ALWAYS(sqlite3GetVTable(db, pTab)) ){
  105855. rc = growVTrans(db);
  105856. if( rc==SQLITE_OK ){
  105857. addToVTrans(db, sqlite3GetVTable(db, pTab));
  105858. }
  105859. }
  105860. return rc;
  105861. }
  105862. /*
  105863. ** This function is used to set the schema of a virtual table. It is only
  105864. ** valid to call this function from within the xCreate() or xConnect() of a
  105865. ** virtual table module.
  105866. */
  105867. SQLITE_API int sqlite3_declare_vtab(sqlite3 *db, const char *zCreateTable){
  105868. Parse *pParse;
  105869. int rc = SQLITE_OK;
  105870. Table *pTab;
  105871. char *zErr = 0;
  105872. #ifdef SQLITE_ENABLE_API_ARMOR
  105873. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  105874. #endif
  105875. sqlite3_mutex_enter(db->mutex);
  105876. if( !db->pVtabCtx || !(pTab = db->pVtabCtx->pTab) ){
  105877. sqlite3Error(db, SQLITE_MISUSE);
  105878. sqlite3_mutex_leave(db->mutex);
  105879. return SQLITE_MISUSE_BKPT;
  105880. }
  105881. assert( (pTab->tabFlags & TF_Virtual)!=0 );
  105882. pParse = sqlite3StackAllocZero(db, sizeof(*pParse));
  105883. if( pParse==0 ){
  105884. rc = SQLITE_NOMEM;
  105885. }else{
  105886. pParse->declareVtab = 1;
  105887. pParse->db = db;
  105888. pParse->nQueryLoop = 1;
  105889. if( SQLITE_OK==sqlite3RunParser(pParse, zCreateTable, &zErr)
  105890. && pParse->pNewTable
  105891. && !db->mallocFailed
  105892. && !pParse->pNewTable->pSelect
  105893. && (pParse->pNewTable->tabFlags & TF_Virtual)==0
  105894. ){
  105895. if( !pTab->aCol ){
  105896. pTab->aCol = pParse->pNewTable->aCol;
  105897. pTab->nCol = pParse->pNewTable->nCol;
  105898. pParse->pNewTable->nCol = 0;
  105899. pParse->pNewTable->aCol = 0;
  105900. }
  105901. db->pVtabCtx->pTab = 0;
  105902. }else{
  105903. sqlite3ErrorWithMsg(db, SQLITE_ERROR, (zErr ? "%s" : 0), zErr);
  105904. sqlite3DbFree(db, zErr);
  105905. rc = SQLITE_ERROR;
  105906. }
  105907. pParse->declareVtab = 0;
  105908. if( pParse->pVdbe ){
  105909. sqlite3VdbeFinalize(pParse->pVdbe);
  105910. }
  105911. sqlite3DeleteTable(db, pParse->pNewTable);
  105912. sqlite3ParserReset(pParse);
  105913. sqlite3StackFree(db, pParse);
  105914. }
  105915. assert( (rc&0xff)==rc );
  105916. rc = sqlite3ApiExit(db, rc);
  105917. sqlite3_mutex_leave(db->mutex);
  105918. return rc;
  105919. }
  105920. /*
  105921. ** This function is invoked by the vdbe to call the xDestroy method
  105922. ** of the virtual table named zTab in database iDb. This occurs
  105923. ** when a DROP TABLE is mentioned.
  105924. **
  105925. ** This call is a no-op if zTab is not a virtual table.
  105926. */
  105927. SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3 *db, int iDb, const char *zTab){
  105928. int rc = SQLITE_OK;
  105929. Table *pTab;
  105930. pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
  105931. if( ALWAYS(pTab!=0 && pTab->pVTable!=0) ){
  105932. VTable *p = vtabDisconnectAll(db, pTab);
  105933. assert( rc==SQLITE_OK );
  105934. rc = p->pMod->pModule->xDestroy(p->pVtab);
  105935. /* Remove the sqlite3_vtab* from the aVTrans[] array, if applicable */
  105936. if( rc==SQLITE_OK ){
  105937. assert( pTab->pVTable==p && p->pNext==0 );
  105938. p->pVtab = 0;
  105939. pTab->pVTable = 0;
  105940. sqlite3VtabUnlock(p);
  105941. }
  105942. }
  105943. return rc;
  105944. }
  105945. /*
  105946. ** This function invokes either the xRollback or xCommit method
  105947. ** of each of the virtual tables in the sqlite3.aVTrans array. The method
  105948. ** called is identified by the second argument, "offset", which is
  105949. ** the offset of the method to call in the sqlite3_module structure.
  105950. **
  105951. ** The array is cleared after invoking the callbacks.
  105952. */
  105953. static void callFinaliser(sqlite3 *db, int offset){
  105954. int i;
  105955. if( db->aVTrans ){
  105956. for(i=0; i<db->nVTrans; i++){
  105957. VTable *pVTab = db->aVTrans[i];
  105958. sqlite3_vtab *p = pVTab->pVtab;
  105959. if( p ){
  105960. int (*x)(sqlite3_vtab *);
  105961. x = *(int (**)(sqlite3_vtab *))((char *)p->pModule + offset);
  105962. if( x ) x(p);
  105963. }
  105964. pVTab->iSavepoint = 0;
  105965. sqlite3VtabUnlock(pVTab);
  105966. }
  105967. sqlite3DbFree(db, db->aVTrans);
  105968. db->nVTrans = 0;
  105969. db->aVTrans = 0;
  105970. }
  105971. }
  105972. /*
  105973. ** Invoke the xSync method of all virtual tables in the sqlite3.aVTrans
  105974. ** array. Return the error code for the first error that occurs, or
  105975. ** SQLITE_OK if all xSync operations are successful.
  105976. **
  105977. ** If an error message is available, leave it in p->zErrMsg.
  105978. */
  105979. SQLITE_PRIVATE int sqlite3VtabSync(sqlite3 *db, Vdbe *p){
  105980. int i;
  105981. int rc = SQLITE_OK;
  105982. VTable **aVTrans = db->aVTrans;
  105983. db->aVTrans = 0;
  105984. for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
  105985. int (*x)(sqlite3_vtab *);
  105986. sqlite3_vtab *pVtab = aVTrans[i]->pVtab;
  105987. if( pVtab && (x = pVtab->pModule->xSync)!=0 ){
  105988. rc = x(pVtab);
  105989. sqlite3VtabImportErrmsg(p, pVtab);
  105990. }
  105991. }
  105992. db->aVTrans = aVTrans;
  105993. return rc;
  105994. }
  105995. /*
  105996. ** Invoke the xRollback method of all virtual tables in the
  105997. ** sqlite3.aVTrans array. Then clear the array itself.
  105998. */
  105999. SQLITE_PRIVATE int sqlite3VtabRollback(sqlite3 *db){
  106000. callFinaliser(db, offsetof(sqlite3_module,xRollback));
  106001. return SQLITE_OK;
  106002. }
  106003. /*
  106004. ** Invoke the xCommit method of all virtual tables in the
  106005. ** sqlite3.aVTrans array. Then clear the array itself.
  106006. */
  106007. SQLITE_PRIVATE int sqlite3VtabCommit(sqlite3 *db){
  106008. callFinaliser(db, offsetof(sqlite3_module,xCommit));
  106009. return SQLITE_OK;
  106010. }
  106011. /*
  106012. ** If the virtual table pVtab supports the transaction interface
  106013. ** (xBegin/xRollback/xCommit and optionally xSync) and a transaction is
  106014. ** not currently open, invoke the xBegin method now.
  106015. **
  106016. ** If the xBegin call is successful, place the sqlite3_vtab pointer
  106017. ** in the sqlite3.aVTrans array.
  106018. */
  106019. SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *db, VTable *pVTab){
  106020. int rc = SQLITE_OK;
  106021. const sqlite3_module *pModule;
  106022. /* Special case: If db->aVTrans is NULL and db->nVTrans is greater
  106023. ** than zero, then this function is being called from within a
  106024. ** virtual module xSync() callback. It is illegal to write to
  106025. ** virtual module tables in this case, so return SQLITE_LOCKED.
  106026. */
  106027. if( sqlite3VtabInSync(db) ){
  106028. return SQLITE_LOCKED;
  106029. }
  106030. if( !pVTab ){
  106031. return SQLITE_OK;
  106032. }
  106033. pModule = pVTab->pVtab->pModule;
  106034. if( pModule->xBegin ){
  106035. int i;
  106036. /* If pVtab is already in the aVTrans array, return early */
  106037. for(i=0; i<db->nVTrans; i++){
  106038. if( db->aVTrans[i]==pVTab ){
  106039. return SQLITE_OK;
  106040. }
  106041. }
  106042. /* Invoke the xBegin method. If successful, add the vtab to the
  106043. ** sqlite3.aVTrans[] array. */
  106044. rc = growVTrans(db);
  106045. if( rc==SQLITE_OK ){
  106046. rc = pModule->xBegin(pVTab->pVtab);
  106047. if( rc==SQLITE_OK ){
  106048. addToVTrans(db, pVTab);
  106049. }
  106050. }
  106051. }
  106052. return rc;
  106053. }
  106054. /*
  106055. ** Invoke either the xSavepoint, xRollbackTo or xRelease method of all
  106056. ** virtual tables that currently have an open transaction. Pass iSavepoint
  106057. ** as the second argument to the virtual table method invoked.
  106058. **
  106059. ** If op is SAVEPOINT_BEGIN, the xSavepoint method is invoked. If it is
  106060. ** SAVEPOINT_ROLLBACK, the xRollbackTo method. Otherwise, if op is
  106061. ** SAVEPOINT_RELEASE, then the xRelease method of each virtual table with
  106062. ** an open transaction is invoked.
  106063. **
  106064. ** If any virtual table method returns an error code other than SQLITE_OK,
  106065. ** processing is abandoned and the error returned to the caller of this
  106066. ** function immediately. If all calls to virtual table methods are successful,
  106067. ** SQLITE_OK is returned.
  106068. */
  106069. SQLITE_PRIVATE int sqlite3VtabSavepoint(sqlite3 *db, int op, int iSavepoint){
  106070. int rc = SQLITE_OK;
  106071. assert( op==SAVEPOINT_RELEASE||op==SAVEPOINT_ROLLBACK||op==SAVEPOINT_BEGIN );
  106072. assert( iSavepoint>=0 );
  106073. if( db->aVTrans ){
  106074. int i;
  106075. for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
  106076. VTable *pVTab = db->aVTrans[i];
  106077. const sqlite3_module *pMod = pVTab->pMod->pModule;
  106078. if( pVTab->pVtab && pMod->iVersion>=2 ){
  106079. int (*xMethod)(sqlite3_vtab *, int);
  106080. switch( op ){
  106081. case SAVEPOINT_BEGIN:
  106082. xMethod = pMod->xSavepoint;
  106083. pVTab->iSavepoint = iSavepoint+1;
  106084. break;
  106085. case SAVEPOINT_ROLLBACK:
  106086. xMethod = pMod->xRollbackTo;
  106087. break;
  106088. default:
  106089. xMethod = pMod->xRelease;
  106090. break;
  106091. }
  106092. if( xMethod && pVTab->iSavepoint>iSavepoint ){
  106093. rc = xMethod(pVTab->pVtab, iSavepoint);
  106094. }
  106095. }
  106096. }
  106097. }
  106098. return rc;
  106099. }
  106100. /*
  106101. ** The first parameter (pDef) is a function implementation. The
  106102. ** second parameter (pExpr) is the first argument to this function.
  106103. ** If pExpr is a column in a virtual table, then let the virtual
  106104. ** table implementation have an opportunity to overload the function.
  106105. **
  106106. ** This routine is used to allow virtual table implementations to
  106107. ** overload MATCH, LIKE, GLOB, and REGEXP operators.
  106108. **
  106109. ** Return either the pDef argument (indicating no change) or a
  106110. ** new FuncDef structure that is marked as ephemeral using the
  106111. ** SQLITE_FUNC_EPHEM flag.
  106112. */
  106113. SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(
  106114. sqlite3 *db, /* Database connection for reporting malloc problems */
  106115. FuncDef *pDef, /* Function to possibly overload */
  106116. int nArg, /* Number of arguments to the function */
  106117. Expr *pExpr /* First argument to the function */
  106118. ){
  106119. Table *pTab;
  106120. sqlite3_vtab *pVtab;
  106121. sqlite3_module *pMod;
  106122. void (*xFunc)(sqlite3_context*,int,sqlite3_value**) = 0;
  106123. void *pArg = 0;
  106124. FuncDef *pNew;
  106125. int rc = 0;
  106126. char *zLowerName;
  106127. unsigned char *z;
  106128. /* Check to see the left operand is a column in a virtual table */
  106129. if( NEVER(pExpr==0) ) return pDef;
  106130. if( pExpr->op!=TK_COLUMN ) return pDef;
  106131. pTab = pExpr->pTab;
  106132. if( NEVER(pTab==0) ) return pDef;
  106133. if( (pTab->tabFlags & TF_Virtual)==0 ) return pDef;
  106134. pVtab = sqlite3GetVTable(db, pTab)->pVtab;
  106135. assert( pVtab!=0 );
  106136. assert( pVtab->pModule!=0 );
  106137. pMod = (sqlite3_module *)pVtab->pModule;
  106138. if( pMod->xFindFunction==0 ) return pDef;
  106139. /* Call the xFindFunction method on the virtual table implementation
  106140. ** to see if the implementation wants to overload this function
  106141. */
  106142. zLowerName = sqlite3DbStrDup(db, pDef->zName);
  106143. if( zLowerName ){
  106144. for(z=(unsigned char*)zLowerName; *z; z++){
  106145. *z = sqlite3UpperToLower[*z];
  106146. }
  106147. rc = pMod->xFindFunction(pVtab, nArg, zLowerName, &xFunc, &pArg);
  106148. sqlite3DbFree(db, zLowerName);
  106149. }
  106150. if( rc==0 ){
  106151. return pDef;
  106152. }
  106153. /* Create a new ephemeral function definition for the overloaded
  106154. ** function */
  106155. pNew = sqlite3DbMallocZero(db, sizeof(*pNew)
  106156. + sqlite3Strlen30(pDef->zName) + 1);
  106157. if( pNew==0 ){
  106158. return pDef;
  106159. }
  106160. *pNew = *pDef;
  106161. pNew->zName = (char *)&pNew[1];
  106162. memcpy(pNew->zName, pDef->zName, sqlite3Strlen30(pDef->zName)+1);
  106163. pNew->xFunc = xFunc;
  106164. pNew->pUserData = pArg;
  106165. pNew->funcFlags |= SQLITE_FUNC_EPHEM;
  106166. return pNew;
  106167. }
  106168. /*
  106169. ** Make sure virtual table pTab is contained in the pParse->apVirtualLock[]
  106170. ** array so that an OP_VBegin will get generated for it. Add pTab to the
  106171. ** array if it is missing. If pTab is already in the array, this routine
  106172. ** is a no-op.
  106173. */
  106174. SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse *pParse, Table *pTab){
  106175. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  106176. int i, n;
  106177. Table **apVtabLock;
  106178. assert( IsVirtual(pTab) );
  106179. for(i=0; i<pToplevel->nVtabLock; i++){
  106180. if( pTab==pToplevel->apVtabLock[i] ) return;
  106181. }
  106182. n = (pToplevel->nVtabLock+1)*sizeof(pToplevel->apVtabLock[0]);
  106183. apVtabLock = sqlite3_realloc(pToplevel->apVtabLock, n);
  106184. if( apVtabLock ){
  106185. pToplevel->apVtabLock = apVtabLock;
  106186. pToplevel->apVtabLock[pToplevel->nVtabLock++] = pTab;
  106187. }else{
  106188. pToplevel->db->mallocFailed = 1;
  106189. }
  106190. }
  106191. /*
  106192. ** Return the ON CONFLICT resolution mode in effect for the virtual
  106193. ** table update operation currently in progress.
  106194. **
  106195. ** The results of this routine are undefined unless it is called from
  106196. ** within an xUpdate method.
  106197. */
  106198. SQLITE_API int sqlite3_vtab_on_conflict(sqlite3 *db){
  106199. static const unsigned char aMap[] = {
  106200. SQLITE_ROLLBACK, SQLITE_ABORT, SQLITE_FAIL, SQLITE_IGNORE, SQLITE_REPLACE
  106201. };
  106202. #ifdef SQLITE_ENABLE_API_ARMOR
  106203. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  106204. #endif
  106205. assert( OE_Rollback==1 && OE_Abort==2 && OE_Fail==3 );
  106206. assert( OE_Ignore==4 && OE_Replace==5 );
  106207. assert( db->vtabOnConflict>=1 && db->vtabOnConflict<=5 );
  106208. return (int)aMap[db->vtabOnConflict-1];
  106209. }
  106210. /*
  106211. ** Call from within the xCreate() or xConnect() methods to provide
  106212. ** the SQLite core with additional information about the behavior
  106213. ** of the virtual table being implemented.
  106214. */
  106215. SQLITE_API int sqlite3_vtab_config(sqlite3 *db, int op, ...){
  106216. va_list ap;
  106217. int rc = SQLITE_OK;
  106218. #ifdef SQLITE_ENABLE_API_ARMOR
  106219. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  106220. #endif
  106221. sqlite3_mutex_enter(db->mutex);
  106222. va_start(ap, op);
  106223. switch( op ){
  106224. case SQLITE_VTAB_CONSTRAINT_SUPPORT: {
  106225. VtabCtx *p = db->pVtabCtx;
  106226. if( !p ){
  106227. rc = SQLITE_MISUSE_BKPT;
  106228. }else{
  106229. assert( p->pTab==0 || (p->pTab->tabFlags & TF_Virtual)!=0 );
  106230. p->pVTable->bConstraint = (u8)va_arg(ap, int);
  106231. }
  106232. break;
  106233. }
  106234. default:
  106235. rc = SQLITE_MISUSE_BKPT;
  106236. break;
  106237. }
  106238. va_end(ap);
  106239. if( rc!=SQLITE_OK ) sqlite3Error(db, rc);
  106240. sqlite3_mutex_leave(db->mutex);
  106241. return rc;
  106242. }
  106243. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  106244. /************** End of vtab.c ************************************************/
  106245. /************** Begin file where.c *******************************************/
  106246. /*
  106247. ** 2001 September 15
  106248. **
  106249. ** The author disclaims copyright to this source code. In place of
  106250. ** a legal notice, here is a blessing:
  106251. **
  106252. ** May you do good and not evil.
  106253. ** May you find forgiveness for yourself and forgive others.
  106254. ** May you share freely, never taking more than you give.
  106255. **
  106256. *************************************************************************
  106257. ** This module contains C code that generates VDBE code used to process
  106258. ** the WHERE clause of SQL statements. This module is responsible for
  106259. ** generating the code that loops through a table looking for applicable
  106260. ** rows. Indices are selected and used to speed the search when doing
  106261. ** so is applicable. Because this module is responsible for selecting
  106262. ** indices, you might also think of this module as the "query optimizer".
  106263. */
  106264. /************** Include whereInt.h in the middle of where.c ******************/
  106265. /************** Begin file whereInt.h ****************************************/
  106266. /*
  106267. ** 2013-11-12
  106268. **
  106269. ** The author disclaims copyright to this source code. In place of
  106270. ** a legal notice, here is a blessing:
  106271. **
  106272. ** May you do good and not evil.
  106273. ** May you find forgiveness for yourself and forgive others.
  106274. ** May you share freely, never taking more than you give.
  106275. **
  106276. *************************************************************************
  106277. **
  106278. ** This file contains structure and macro definitions for the query
  106279. ** planner logic in "where.c". These definitions are broken out into
  106280. ** a separate source file for easier editing.
  106281. */
  106282. /*
  106283. ** Trace output macros
  106284. */
  106285. #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
  106286. /***/ int sqlite3WhereTrace = 0;
  106287. #endif
  106288. #if defined(SQLITE_DEBUG) \
  106289. && (defined(SQLITE_TEST) || defined(SQLITE_ENABLE_WHERETRACE))
  106290. # define WHERETRACE(K,X) if(sqlite3WhereTrace&(K)) sqlite3DebugPrintf X
  106291. # define WHERETRACE_ENABLED 1
  106292. #else
  106293. # define WHERETRACE(K,X)
  106294. #endif
  106295. /* Forward references
  106296. */
  106297. typedef struct WhereClause WhereClause;
  106298. typedef struct WhereMaskSet WhereMaskSet;
  106299. typedef struct WhereOrInfo WhereOrInfo;
  106300. typedef struct WhereAndInfo WhereAndInfo;
  106301. typedef struct WhereLevel WhereLevel;
  106302. typedef struct WhereLoop WhereLoop;
  106303. typedef struct WherePath WherePath;
  106304. typedef struct WhereTerm WhereTerm;
  106305. typedef struct WhereLoopBuilder WhereLoopBuilder;
  106306. typedef struct WhereScan WhereScan;
  106307. typedef struct WhereOrCost WhereOrCost;
  106308. typedef struct WhereOrSet WhereOrSet;
  106309. /*
  106310. ** This object contains information needed to implement a single nested
  106311. ** loop in WHERE clause.
  106312. **
  106313. ** Contrast this object with WhereLoop. This object describes the
  106314. ** implementation of the loop. WhereLoop describes the algorithm.
  106315. ** This object contains a pointer to the WhereLoop algorithm as one of
  106316. ** its elements.
  106317. **
  106318. ** The WhereInfo object contains a single instance of this object for
  106319. ** each term in the FROM clause (which is to say, for each of the
  106320. ** nested loops as implemented). The order of WhereLevel objects determines
  106321. ** the loop nested order, with WhereInfo.a[0] being the outer loop and
  106322. ** WhereInfo.a[WhereInfo.nLevel-1] being the inner loop.
  106323. */
  106324. struct WhereLevel {
  106325. int iLeftJoin; /* Memory cell used to implement LEFT OUTER JOIN */
  106326. int iTabCur; /* The VDBE cursor used to access the table */
  106327. int iIdxCur; /* The VDBE cursor used to access pIdx */
  106328. int addrBrk; /* Jump here to break out of the loop */
  106329. int addrNxt; /* Jump here to start the next IN combination */
  106330. int addrSkip; /* Jump here for next iteration of skip-scan */
  106331. int addrCont; /* Jump here to continue with the next loop cycle */
  106332. int addrFirst; /* First instruction of interior of the loop */
  106333. int addrBody; /* Beginning of the body of this loop */
  106334. u8 iFrom; /* Which entry in the FROM clause */
  106335. u8 op, p3, p5; /* Opcode, P3 & P5 of the opcode that ends the loop */
  106336. int p1, p2; /* Operands of the opcode used to ends the loop */
  106337. union { /* Information that depends on pWLoop->wsFlags */
  106338. struct {
  106339. int nIn; /* Number of entries in aInLoop[] */
  106340. struct InLoop {
  106341. int iCur; /* The VDBE cursor used by this IN operator */
  106342. int addrInTop; /* Top of the IN loop */
  106343. u8 eEndLoopOp; /* IN Loop terminator. OP_Next or OP_Prev */
  106344. } *aInLoop; /* Information about each nested IN operator */
  106345. } in; /* Used when pWLoop->wsFlags&WHERE_IN_ABLE */
  106346. Index *pCovidx; /* Possible covering index for WHERE_MULTI_OR */
  106347. } u;
  106348. struct WhereLoop *pWLoop; /* The selected WhereLoop object */
  106349. Bitmask notReady; /* FROM entries not usable at this level */
  106350. };
  106351. /*
  106352. ** Each instance of this object represents an algorithm for evaluating one
  106353. ** term of a join. Every term of the FROM clause will have at least
  106354. ** one corresponding WhereLoop object (unless INDEXED BY constraints
  106355. ** prevent a query solution - which is an error) and many terms of the
  106356. ** FROM clause will have multiple WhereLoop objects, each describing a
  106357. ** potential way of implementing that FROM-clause term, together with
  106358. ** dependencies and cost estimates for using the chosen algorithm.
  106359. **
  106360. ** Query planning consists of building up a collection of these WhereLoop
  106361. ** objects, then computing a particular sequence of WhereLoop objects, with
  106362. ** one WhereLoop object per FROM clause term, that satisfy all dependencies
  106363. ** and that minimize the overall cost.
  106364. */
  106365. struct WhereLoop {
  106366. Bitmask prereq; /* Bitmask of other loops that must run first */
  106367. Bitmask maskSelf; /* Bitmask identifying table iTab */
  106368. #ifdef SQLITE_DEBUG
  106369. char cId; /* Symbolic ID of this loop for debugging use */
  106370. #endif
  106371. u8 iTab; /* Position in FROM clause of table for this loop */
  106372. u8 iSortIdx; /* Sorting index number. 0==None */
  106373. LogEst rSetup; /* One-time setup cost (ex: create transient index) */
  106374. LogEst rRun; /* Cost of running each loop */
  106375. LogEst nOut; /* Estimated number of output rows */
  106376. union {
  106377. struct { /* Information for internal btree tables */
  106378. u16 nEq; /* Number of equality constraints */
  106379. Index *pIndex; /* Index used, or NULL */
  106380. } btree;
  106381. struct { /* Information for virtual tables */
  106382. int idxNum; /* Index number */
  106383. u8 needFree; /* True if sqlite3_free(idxStr) is needed */
  106384. i8 isOrdered; /* True if satisfies ORDER BY */
  106385. u16 omitMask; /* Terms that may be omitted */
  106386. char *idxStr; /* Index identifier string */
  106387. } vtab;
  106388. } u;
  106389. u32 wsFlags; /* WHERE_* flags describing the plan */
  106390. u16 nLTerm; /* Number of entries in aLTerm[] */
  106391. u16 nSkip; /* Number of NULL aLTerm[] entries */
  106392. /**** whereLoopXfer() copies fields above ***********************/
  106393. # define WHERE_LOOP_XFER_SZ offsetof(WhereLoop,nLSlot)
  106394. u16 nLSlot; /* Number of slots allocated for aLTerm[] */
  106395. WhereTerm **aLTerm; /* WhereTerms used */
  106396. WhereLoop *pNextLoop; /* Next WhereLoop object in the WhereClause */
  106397. WhereTerm *aLTermSpace[3]; /* Initial aLTerm[] space */
  106398. };
  106399. /* This object holds the prerequisites and the cost of running a
  106400. ** subquery on one operand of an OR operator in the WHERE clause.
  106401. ** See WhereOrSet for additional information
  106402. */
  106403. struct WhereOrCost {
  106404. Bitmask prereq; /* Prerequisites */
  106405. LogEst rRun; /* Cost of running this subquery */
  106406. LogEst nOut; /* Number of outputs for this subquery */
  106407. };
  106408. /* The WhereOrSet object holds a set of possible WhereOrCosts that
  106409. ** correspond to the subquery(s) of OR-clause processing. Only the
  106410. ** best N_OR_COST elements are retained.
  106411. */
  106412. #define N_OR_COST 3
  106413. struct WhereOrSet {
  106414. u16 n; /* Number of valid a[] entries */
  106415. WhereOrCost a[N_OR_COST]; /* Set of best costs */
  106416. };
  106417. /* Forward declaration of methods */
  106418. static int whereLoopResize(sqlite3*, WhereLoop*, int);
  106419. /*
  106420. ** Each instance of this object holds a sequence of WhereLoop objects
  106421. ** that implement some or all of a query plan.
  106422. **
  106423. ** Think of each WhereLoop object as a node in a graph with arcs
  106424. ** showing dependencies and costs for travelling between nodes. (That is
  106425. ** not a completely accurate description because WhereLoop costs are a
  106426. ** vector, not a scalar, and because dependencies are many-to-one, not
  106427. ** one-to-one as are graph nodes. But it is a useful visualization aid.)
  106428. ** Then a WherePath object is a path through the graph that visits some
  106429. ** or all of the WhereLoop objects once.
  106430. **
  106431. ** The "solver" works by creating the N best WherePath objects of length
  106432. ** 1. Then using those as a basis to compute the N best WherePath objects
  106433. ** of length 2. And so forth until the length of WherePaths equals the
  106434. ** number of nodes in the FROM clause. The best (lowest cost) WherePath
  106435. ** at the end is the chosen query plan.
  106436. */
  106437. struct WherePath {
  106438. Bitmask maskLoop; /* Bitmask of all WhereLoop objects in this path */
  106439. Bitmask revLoop; /* aLoop[]s that should be reversed for ORDER BY */
  106440. LogEst nRow; /* Estimated number of rows generated by this path */
  106441. LogEst rCost; /* Total cost of this path */
  106442. LogEst rUnsorted; /* Total cost of this path ignoring sorting costs */
  106443. i8 isOrdered; /* No. of ORDER BY terms satisfied. -1 for unknown */
  106444. WhereLoop **aLoop; /* Array of WhereLoop objects implementing this path */
  106445. };
  106446. /*
  106447. ** The query generator uses an array of instances of this structure to
  106448. ** help it analyze the subexpressions of the WHERE clause. Each WHERE
  106449. ** clause subexpression is separated from the others by AND operators,
  106450. ** usually, or sometimes subexpressions separated by OR.
  106451. **
  106452. ** All WhereTerms are collected into a single WhereClause structure.
  106453. ** The following identity holds:
  106454. **
  106455. ** WhereTerm.pWC->a[WhereTerm.idx] == WhereTerm
  106456. **
  106457. ** When a term is of the form:
  106458. **
  106459. ** X <op> <expr>
  106460. **
  106461. ** where X is a column name and <op> is one of certain operators,
  106462. ** then WhereTerm.leftCursor and WhereTerm.u.leftColumn record the
  106463. ** cursor number and column number for X. WhereTerm.eOperator records
  106464. ** the <op> using a bitmask encoding defined by WO_xxx below. The
  106465. ** use of a bitmask encoding for the operator allows us to search
  106466. ** quickly for terms that match any of several different operators.
  106467. **
  106468. ** A WhereTerm might also be two or more subterms connected by OR:
  106469. **
  106470. ** (t1.X <op> <expr>) OR (t1.Y <op> <expr>) OR ....
  106471. **
  106472. ** In this second case, wtFlag has the TERM_ORINFO bit set and eOperator==WO_OR
  106473. ** and the WhereTerm.u.pOrInfo field points to auxiliary information that
  106474. ** is collected about the OR clause.
  106475. **
  106476. ** If a term in the WHERE clause does not match either of the two previous
  106477. ** categories, then eOperator==0. The WhereTerm.pExpr field is still set
  106478. ** to the original subexpression content and wtFlags is set up appropriately
  106479. ** but no other fields in the WhereTerm object are meaningful.
  106480. **
  106481. ** When eOperator!=0, prereqRight and prereqAll record sets of cursor numbers,
  106482. ** but they do so indirectly. A single WhereMaskSet structure translates
  106483. ** cursor number into bits and the translated bit is stored in the prereq
  106484. ** fields. The translation is used in order to maximize the number of
  106485. ** bits that will fit in a Bitmask. The VDBE cursor numbers might be
  106486. ** spread out over the non-negative integers. For example, the cursor
  106487. ** numbers might be 3, 8, 9, 10, 20, 23, 41, and 45. The WhereMaskSet
  106488. ** translates these sparse cursor numbers into consecutive integers
  106489. ** beginning with 0 in order to make the best possible use of the available
  106490. ** bits in the Bitmask. So, in the example above, the cursor numbers
  106491. ** would be mapped into integers 0 through 7.
  106492. **
  106493. ** The number of terms in a join is limited by the number of bits
  106494. ** in prereqRight and prereqAll. The default is 64 bits, hence SQLite
  106495. ** is only able to process joins with 64 or fewer tables.
  106496. */
  106497. struct WhereTerm {
  106498. Expr *pExpr; /* Pointer to the subexpression that is this term */
  106499. int iParent; /* Disable pWC->a[iParent] when this term disabled */
  106500. int leftCursor; /* Cursor number of X in "X <op> <expr>" */
  106501. union {
  106502. int leftColumn; /* Column number of X in "X <op> <expr>" */
  106503. WhereOrInfo *pOrInfo; /* Extra information if (eOperator & WO_OR)!=0 */
  106504. WhereAndInfo *pAndInfo; /* Extra information if (eOperator& WO_AND)!=0 */
  106505. } u;
  106506. LogEst truthProb; /* Probability of truth for this expression */
  106507. u16 eOperator; /* A WO_xx value describing <op> */
  106508. u8 wtFlags; /* TERM_xxx bit flags. See below */
  106509. u8 nChild; /* Number of children that must disable us */
  106510. WhereClause *pWC; /* The clause this term is part of */
  106511. Bitmask prereqRight; /* Bitmask of tables used by pExpr->pRight */
  106512. Bitmask prereqAll; /* Bitmask of tables referenced by pExpr */
  106513. };
  106514. /*
  106515. ** Allowed values of WhereTerm.wtFlags
  106516. */
  106517. #define TERM_DYNAMIC 0x01 /* Need to call sqlite3ExprDelete(db, pExpr) */
  106518. #define TERM_VIRTUAL 0x02 /* Added by the optimizer. Do not code */
  106519. #define TERM_CODED 0x04 /* This term is already coded */
  106520. #define TERM_COPIED 0x08 /* Has a child */
  106521. #define TERM_ORINFO 0x10 /* Need to free the WhereTerm.u.pOrInfo object */
  106522. #define TERM_ANDINFO 0x20 /* Need to free the WhereTerm.u.pAndInfo obj */
  106523. #define TERM_OR_OK 0x40 /* Used during OR-clause processing */
  106524. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  106525. # define TERM_VNULL 0x80 /* Manufactured x>NULL or x<=NULL term */
  106526. #else
  106527. # define TERM_VNULL 0x00 /* Disabled if not using stat3 */
  106528. #endif
  106529. /*
  106530. ** An instance of the WhereScan object is used as an iterator for locating
  106531. ** terms in the WHERE clause that are useful to the query planner.
  106532. */
  106533. struct WhereScan {
  106534. WhereClause *pOrigWC; /* Original, innermost WhereClause */
  106535. WhereClause *pWC; /* WhereClause currently being scanned */
  106536. char *zCollName; /* Required collating sequence, if not NULL */
  106537. char idxaff; /* Must match this affinity, if zCollName!=NULL */
  106538. unsigned char nEquiv; /* Number of entries in aEquiv[] */
  106539. unsigned char iEquiv; /* Next unused slot in aEquiv[] */
  106540. u32 opMask; /* Acceptable operators */
  106541. int k; /* Resume scanning at this->pWC->a[this->k] */
  106542. int aEquiv[22]; /* Cursor,Column pairs for equivalence classes */
  106543. };
  106544. /*
  106545. ** An instance of the following structure holds all information about a
  106546. ** WHERE clause. Mostly this is a container for one or more WhereTerms.
  106547. **
  106548. ** Explanation of pOuter: For a WHERE clause of the form
  106549. **
  106550. ** a AND ((b AND c) OR (d AND e)) AND f
  106551. **
  106552. ** There are separate WhereClause objects for the whole clause and for
  106553. ** the subclauses "(b AND c)" and "(d AND e)". The pOuter field of the
  106554. ** subclauses points to the WhereClause object for the whole clause.
  106555. */
  106556. struct WhereClause {
  106557. WhereInfo *pWInfo; /* WHERE clause processing context */
  106558. WhereClause *pOuter; /* Outer conjunction */
  106559. u8 op; /* Split operator. TK_AND or TK_OR */
  106560. int nTerm; /* Number of terms */
  106561. int nSlot; /* Number of entries in a[] */
  106562. WhereTerm *a; /* Each a[] describes a term of the WHERE cluase */
  106563. #if defined(SQLITE_SMALL_STACK)
  106564. WhereTerm aStatic[1]; /* Initial static space for a[] */
  106565. #else
  106566. WhereTerm aStatic[8]; /* Initial static space for a[] */
  106567. #endif
  106568. };
  106569. /*
  106570. ** A WhereTerm with eOperator==WO_OR has its u.pOrInfo pointer set to
  106571. ** a dynamically allocated instance of the following structure.
  106572. */
  106573. struct WhereOrInfo {
  106574. WhereClause wc; /* Decomposition into subterms */
  106575. Bitmask indexable; /* Bitmask of all indexable tables in the clause */
  106576. };
  106577. /*
  106578. ** A WhereTerm with eOperator==WO_AND has its u.pAndInfo pointer set to
  106579. ** a dynamically allocated instance of the following structure.
  106580. */
  106581. struct WhereAndInfo {
  106582. WhereClause wc; /* The subexpression broken out */
  106583. };
  106584. /*
  106585. ** An instance of the following structure keeps track of a mapping
  106586. ** between VDBE cursor numbers and bits of the bitmasks in WhereTerm.
  106587. **
  106588. ** The VDBE cursor numbers are small integers contained in
  106589. ** SrcList_item.iCursor and Expr.iTable fields. For any given WHERE
  106590. ** clause, the cursor numbers might not begin with 0 and they might
  106591. ** contain gaps in the numbering sequence. But we want to make maximum
  106592. ** use of the bits in our bitmasks. This structure provides a mapping
  106593. ** from the sparse cursor numbers into consecutive integers beginning
  106594. ** with 0.
  106595. **
  106596. ** If WhereMaskSet.ix[A]==B it means that The A-th bit of a Bitmask
  106597. ** corresponds VDBE cursor number B. The A-th bit of a bitmask is 1<<A.
  106598. **
  106599. ** For example, if the WHERE clause expression used these VDBE
  106600. ** cursors: 4, 5, 8, 29, 57, 73. Then the WhereMaskSet structure
  106601. ** would map those cursor numbers into bits 0 through 5.
  106602. **
  106603. ** Note that the mapping is not necessarily ordered. In the example
  106604. ** above, the mapping might go like this: 4->3, 5->1, 8->2, 29->0,
  106605. ** 57->5, 73->4. Or one of 719 other combinations might be used. It
  106606. ** does not really matter. What is important is that sparse cursor
  106607. ** numbers all get mapped into bit numbers that begin with 0 and contain
  106608. ** no gaps.
  106609. */
  106610. struct WhereMaskSet {
  106611. int n; /* Number of assigned cursor values */
  106612. int ix[BMS]; /* Cursor assigned to each bit */
  106613. };
  106614. /*
  106615. ** This object is a convenience wrapper holding all information needed
  106616. ** to construct WhereLoop objects for a particular query.
  106617. */
  106618. struct WhereLoopBuilder {
  106619. WhereInfo *pWInfo; /* Information about this WHERE */
  106620. WhereClause *pWC; /* WHERE clause terms */
  106621. ExprList *pOrderBy; /* ORDER BY clause */
  106622. WhereLoop *pNew; /* Template WhereLoop */
  106623. WhereOrSet *pOrSet; /* Record best loops here, if not NULL */
  106624. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  106625. UnpackedRecord *pRec; /* Probe for stat4 (if required) */
  106626. int nRecValid; /* Number of valid fields currently in pRec */
  106627. #endif
  106628. };
  106629. /*
  106630. ** The WHERE clause processing routine has two halves. The
  106631. ** first part does the start of the WHERE loop and the second
  106632. ** half does the tail of the WHERE loop. An instance of
  106633. ** this structure is returned by the first half and passed
  106634. ** into the second half to give some continuity.
  106635. **
  106636. ** An instance of this object holds the complete state of the query
  106637. ** planner.
  106638. */
  106639. struct WhereInfo {
  106640. Parse *pParse; /* Parsing and code generating context */
  106641. SrcList *pTabList; /* List of tables in the join */
  106642. ExprList *pOrderBy; /* The ORDER BY clause or NULL */
  106643. ExprList *pResultSet; /* Result set. DISTINCT operates on these */
  106644. WhereLoop *pLoops; /* List of all WhereLoop objects */
  106645. Bitmask revMask; /* Mask of ORDER BY terms that need reversing */
  106646. LogEst nRowOut; /* Estimated number of output rows */
  106647. u16 wctrlFlags; /* Flags originally passed to sqlite3WhereBegin() */
  106648. i8 nOBSat; /* Number of ORDER BY terms satisfied by indices */
  106649. u8 sorted; /* True if really sorted (not just grouped) */
  106650. u8 okOnePass; /* Ok to use one-pass algorithm for UPDATE/DELETE */
  106651. u8 untestedTerms; /* Not all WHERE terms resolved by outer loop */
  106652. u8 eDistinct; /* One of the WHERE_DISTINCT_* values below */
  106653. u8 nLevel; /* Number of nested loop */
  106654. int iTop; /* The very beginning of the WHERE loop */
  106655. int iContinue; /* Jump here to continue with next record */
  106656. int iBreak; /* Jump here to break out of the loop */
  106657. int savedNQueryLoop; /* pParse->nQueryLoop outside the WHERE loop */
  106658. int aiCurOnePass[2]; /* OP_OpenWrite cursors for the ONEPASS opt */
  106659. WhereMaskSet sMaskSet; /* Map cursor numbers to bitmasks */
  106660. WhereClause sWC; /* Decomposition of the WHERE clause */
  106661. WhereLevel a[1]; /* Information about each nest loop in WHERE */
  106662. };
  106663. /*
  106664. ** Bitmasks for the operators on WhereTerm objects. These are all
  106665. ** operators that are of interest to the query planner. An
  106666. ** OR-ed combination of these values can be used when searching for
  106667. ** particular WhereTerms within a WhereClause.
  106668. */
  106669. #define WO_IN 0x001
  106670. #define WO_EQ 0x002
  106671. #define WO_LT (WO_EQ<<(TK_LT-TK_EQ))
  106672. #define WO_LE (WO_EQ<<(TK_LE-TK_EQ))
  106673. #define WO_GT (WO_EQ<<(TK_GT-TK_EQ))
  106674. #define WO_GE (WO_EQ<<(TK_GE-TK_EQ))
  106675. #define WO_MATCH 0x040
  106676. #define WO_ISNULL 0x080
  106677. #define WO_OR 0x100 /* Two or more OR-connected terms */
  106678. #define WO_AND 0x200 /* Two or more AND-connected terms */
  106679. #define WO_EQUIV 0x400 /* Of the form A==B, both columns */
  106680. #define WO_NOOP 0x800 /* This term does not restrict search space */
  106681. #define WO_ALL 0xfff /* Mask of all possible WO_* values */
  106682. #define WO_SINGLE 0x0ff /* Mask of all non-compound WO_* values */
  106683. /*
  106684. ** These are definitions of bits in the WhereLoop.wsFlags field.
  106685. ** The particular combination of bits in each WhereLoop help to
  106686. ** determine the algorithm that WhereLoop represents.
  106687. */
  106688. #define WHERE_COLUMN_EQ 0x00000001 /* x=EXPR */
  106689. #define WHERE_COLUMN_RANGE 0x00000002 /* x<EXPR and/or x>EXPR */
  106690. #define WHERE_COLUMN_IN 0x00000004 /* x IN (...) */
  106691. #define WHERE_COLUMN_NULL 0x00000008 /* x IS NULL */
  106692. #define WHERE_CONSTRAINT 0x0000000f /* Any of the WHERE_COLUMN_xxx values */
  106693. #define WHERE_TOP_LIMIT 0x00000010 /* x<EXPR or x<=EXPR constraint */
  106694. #define WHERE_BTM_LIMIT 0x00000020 /* x>EXPR or x>=EXPR constraint */
  106695. #define WHERE_BOTH_LIMIT 0x00000030 /* Both x>EXPR and x<EXPR */
  106696. #define WHERE_IDX_ONLY 0x00000040 /* Use index only - omit table */
  106697. #define WHERE_IPK 0x00000100 /* x is the INTEGER PRIMARY KEY */
  106698. #define WHERE_INDEXED 0x00000200 /* WhereLoop.u.btree.pIndex is valid */
  106699. #define WHERE_VIRTUALTABLE 0x00000400 /* WhereLoop.u.vtab is valid */
  106700. #define WHERE_IN_ABLE 0x00000800 /* Able to support an IN operator */
  106701. #define WHERE_ONEROW 0x00001000 /* Selects no more than one row */
  106702. #define WHERE_MULTI_OR 0x00002000 /* OR using multiple indices */
  106703. #define WHERE_AUTO_INDEX 0x00004000 /* Uses an ephemeral index */
  106704. #define WHERE_SKIPSCAN 0x00008000 /* Uses the skip-scan algorithm */
  106705. #define WHERE_UNQ_WANTED 0x00010000 /* WHERE_ONEROW would have been helpful*/
  106706. #define WHERE_PARTIALIDX 0x00020000 /* The automatic index is partial */
  106707. /************** End of whereInt.h ********************************************/
  106708. /************** Continuing where we left off in where.c **********************/
  106709. /*
  106710. ** Return the estimated number of output rows from a WHERE clause
  106711. */
  106712. SQLITE_PRIVATE u64 sqlite3WhereOutputRowCount(WhereInfo *pWInfo){
  106713. return sqlite3LogEstToInt(pWInfo->nRowOut);
  106714. }
  106715. /*
  106716. ** Return one of the WHERE_DISTINCT_xxxxx values to indicate how this
  106717. ** WHERE clause returns outputs for DISTINCT processing.
  106718. */
  106719. SQLITE_PRIVATE int sqlite3WhereIsDistinct(WhereInfo *pWInfo){
  106720. return pWInfo->eDistinct;
  106721. }
  106722. /*
  106723. ** Return TRUE if the WHERE clause returns rows in ORDER BY order.
  106724. ** Return FALSE if the output needs to be sorted.
  106725. */
  106726. SQLITE_PRIVATE int sqlite3WhereIsOrdered(WhereInfo *pWInfo){
  106727. return pWInfo->nOBSat;
  106728. }
  106729. /*
  106730. ** Return the VDBE address or label to jump to in order to continue
  106731. ** immediately with the next row of a WHERE clause.
  106732. */
  106733. SQLITE_PRIVATE int sqlite3WhereContinueLabel(WhereInfo *pWInfo){
  106734. assert( pWInfo->iContinue!=0 );
  106735. return pWInfo->iContinue;
  106736. }
  106737. /*
  106738. ** Return the VDBE address or label to jump to in order to break
  106739. ** out of a WHERE loop.
  106740. */
  106741. SQLITE_PRIVATE int sqlite3WhereBreakLabel(WhereInfo *pWInfo){
  106742. return pWInfo->iBreak;
  106743. }
  106744. /*
  106745. ** Return TRUE if an UPDATE or DELETE statement can operate directly on
  106746. ** the rowids returned by a WHERE clause. Return FALSE if doing an
  106747. ** UPDATE or DELETE might change subsequent WHERE clause results.
  106748. **
  106749. ** If the ONEPASS optimization is used (if this routine returns true)
  106750. ** then also write the indices of open cursors used by ONEPASS
  106751. ** into aiCur[0] and aiCur[1]. iaCur[0] gets the cursor of the data
  106752. ** table and iaCur[1] gets the cursor used by an auxiliary index.
  106753. ** Either value may be -1, indicating that cursor is not used.
  106754. ** Any cursors returned will have been opened for writing.
  106755. **
  106756. ** aiCur[0] and aiCur[1] both get -1 if the where-clause logic is
  106757. ** unable to use the ONEPASS optimization.
  106758. */
  106759. SQLITE_PRIVATE int sqlite3WhereOkOnePass(WhereInfo *pWInfo, int *aiCur){
  106760. memcpy(aiCur, pWInfo->aiCurOnePass, sizeof(int)*2);
  106761. return pWInfo->okOnePass;
  106762. }
  106763. /*
  106764. ** Move the content of pSrc into pDest
  106765. */
  106766. static void whereOrMove(WhereOrSet *pDest, WhereOrSet *pSrc){
  106767. pDest->n = pSrc->n;
  106768. memcpy(pDest->a, pSrc->a, pDest->n*sizeof(pDest->a[0]));
  106769. }
  106770. /*
  106771. ** Try to insert a new prerequisite/cost entry into the WhereOrSet pSet.
  106772. **
  106773. ** The new entry might overwrite an existing entry, or it might be
  106774. ** appended, or it might be discarded. Do whatever is the right thing
  106775. ** so that pSet keeps the N_OR_COST best entries seen so far.
  106776. */
  106777. static int whereOrInsert(
  106778. WhereOrSet *pSet, /* The WhereOrSet to be updated */
  106779. Bitmask prereq, /* Prerequisites of the new entry */
  106780. LogEst rRun, /* Run-cost of the new entry */
  106781. LogEst nOut /* Number of outputs for the new entry */
  106782. ){
  106783. u16 i;
  106784. WhereOrCost *p;
  106785. for(i=pSet->n, p=pSet->a; i>0; i--, p++){
  106786. if( rRun<=p->rRun && (prereq & p->prereq)==prereq ){
  106787. goto whereOrInsert_done;
  106788. }
  106789. if( p->rRun<=rRun && (p->prereq & prereq)==p->prereq ){
  106790. return 0;
  106791. }
  106792. }
  106793. if( pSet->n<N_OR_COST ){
  106794. p = &pSet->a[pSet->n++];
  106795. p->nOut = nOut;
  106796. }else{
  106797. p = pSet->a;
  106798. for(i=1; i<pSet->n; i++){
  106799. if( p->rRun>pSet->a[i].rRun ) p = pSet->a + i;
  106800. }
  106801. if( p->rRun<=rRun ) return 0;
  106802. }
  106803. whereOrInsert_done:
  106804. p->prereq = prereq;
  106805. p->rRun = rRun;
  106806. if( p->nOut>nOut ) p->nOut = nOut;
  106807. return 1;
  106808. }
  106809. /*
  106810. ** Initialize a preallocated WhereClause structure.
  106811. */
  106812. static void whereClauseInit(
  106813. WhereClause *pWC, /* The WhereClause to be initialized */
  106814. WhereInfo *pWInfo /* The WHERE processing context */
  106815. ){
  106816. pWC->pWInfo = pWInfo;
  106817. pWC->pOuter = 0;
  106818. pWC->nTerm = 0;
  106819. pWC->nSlot = ArraySize(pWC->aStatic);
  106820. pWC->a = pWC->aStatic;
  106821. }
  106822. /* Forward reference */
  106823. static void whereClauseClear(WhereClause*);
  106824. /*
  106825. ** Deallocate all memory associated with a WhereOrInfo object.
  106826. */
  106827. static void whereOrInfoDelete(sqlite3 *db, WhereOrInfo *p){
  106828. whereClauseClear(&p->wc);
  106829. sqlite3DbFree(db, p);
  106830. }
  106831. /*
  106832. ** Deallocate all memory associated with a WhereAndInfo object.
  106833. */
  106834. static void whereAndInfoDelete(sqlite3 *db, WhereAndInfo *p){
  106835. whereClauseClear(&p->wc);
  106836. sqlite3DbFree(db, p);
  106837. }
  106838. /*
  106839. ** Deallocate a WhereClause structure. The WhereClause structure
  106840. ** itself is not freed. This routine is the inverse of whereClauseInit().
  106841. */
  106842. static void whereClauseClear(WhereClause *pWC){
  106843. int i;
  106844. WhereTerm *a;
  106845. sqlite3 *db = pWC->pWInfo->pParse->db;
  106846. for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){
  106847. if( a->wtFlags & TERM_DYNAMIC ){
  106848. sqlite3ExprDelete(db, a->pExpr);
  106849. }
  106850. if( a->wtFlags & TERM_ORINFO ){
  106851. whereOrInfoDelete(db, a->u.pOrInfo);
  106852. }else if( a->wtFlags & TERM_ANDINFO ){
  106853. whereAndInfoDelete(db, a->u.pAndInfo);
  106854. }
  106855. }
  106856. if( pWC->a!=pWC->aStatic ){
  106857. sqlite3DbFree(db, pWC->a);
  106858. }
  106859. }
  106860. /*
  106861. ** Add a single new WhereTerm entry to the WhereClause object pWC.
  106862. ** The new WhereTerm object is constructed from Expr p and with wtFlags.
  106863. ** The index in pWC->a[] of the new WhereTerm is returned on success.
  106864. ** 0 is returned if the new WhereTerm could not be added due to a memory
  106865. ** allocation error. The memory allocation failure will be recorded in
  106866. ** the db->mallocFailed flag so that higher-level functions can detect it.
  106867. **
  106868. ** This routine will increase the size of the pWC->a[] array as necessary.
  106869. **
  106870. ** If the wtFlags argument includes TERM_DYNAMIC, then responsibility
  106871. ** for freeing the expression p is assumed by the WhereClause object pWC.
  106872. ** This is true even if this routine fails to allocate a new WhereTerm.
  106873. **
  106874. ** WARNING: This routine might reallocate the space used to store
  106875. ** WhereTerms. All pointers to WhereTerms should be invalidated after
  106876. ** calling this routine. Such pointers may be reinitialized by referencing
  106877. ** the pWC->a[] array.
  106878. */
  106879. static int whereClauseInsert(WhereClause *pWC, Expr *p, u8 wtFlags){
  106880. WhereTerm *pTerm;
  106881. int idx;
  106882. testcase( wtFlags & TERM_VIRTUAL );
  106883. if( pWC->nTerm>=pWC->nSlot ){
  106884. WhereTerm *pOld = pWC->a;
  106885. sqlite3 *db = pWC->pWInfo->pParse->db;
  106886. pWC->a = sqlite3DbMallocRaw(db, sizeof(pWC->a[0])*pWC->nSlot*2 );
  106887. if( pWC->a==0 ){
  106888. if( wtFlags & TERM_DYNAMIC ){
  106889. sqlite3ExprDelete(db, p);
  106890. }
  106891. pWC->a = pOld;
  106892. return 0;
  106893. }
  106894. memcpy(pWC->a, pOld, sizeof(pWC->a[0])*pWC->nTerm);
  106895. if( pOld!=pWC->aStatic ){
  106896. sqlite3DbFree(db, pOld);
  106897. }
  106898. pWC->nSlot = sqlite3DbMallocSize(db, pWC->a)/sizeof(pWC->a[0]);
  106899. }
  106900. pTerm = &pWC->a[idx = pWC->nTerm++];
  106901. if( p && ExprHasProperty(p, EP_Unlikely) ){
  106902. pTerm->truthProb = sqlite3LogEst(p->iTable) - 270;
  106903. }else{
  106904. pTerm->truthProb = 1;
  106905. }
  106906. pTerm->pExpr = sqlite3ExprSkipCollate(p);
  106907. pTerm->wtFlags = wtFlags;
  106908. pTerm->pWC = pWC;
  106909. pTerm->iParent = -1;
  106910. return idx;
  106911. }
  106912. /*
  106913. ** This routine identifies subexpressions in the WHERE clause where
  106914. ** each subexpression is separated by the AND operator or some other
  106915. ** operator specified in the op parameter. The WhereClause structure
  106916. ** is filled with pointers to subexpressions. For example:
  106917. **
  106918. ** WHERE a=='hello' AND coalesce(b,11)<10 AND (c+12!=d OR c==22)
  106919. ** \________/ \_______________/ \________________/
  106920. ** slot[0] slot[1] slot[2]
  106921. **
  106922. ** The original WHERE clause in pExpr is unaltered. All this routine
  106923. ** does is make slot[] entries point to substructure within pExpr.
  106924. **
  106925. ** In the previous sentence and in the diagram, "slot[]" refers to
  106926. ** the WhereClause.a[] array. The slot[] array grows as needed to contain
  106927. ** all terms of the WHERE clause.
  106928. */
  106929. static void whereSplit(WhereClause *pWC, Expr *pExpr, u8 op){
  106930. pWC->op = op;
  106931. if( pExpr==0 ) return;
  106932. if( pExpr->op!=op ){
  106933. whereClauseInsert(pWC, pExpr, 0);
  106934. }else{
  106935. whereSplit(pWC, pExpr->pLeft, op);
  106936. whereSplit(pWC, pExpr->pRight, op);
  106937. }
  106938. }
  106939. /*
  106940. ** Initialize a WhereMaskSet object
  106941. */
  106942. #define initMaskSet(P) (P)->n=0
  106943. /*
  106944. ** Return the bitmask for the given cursor number. Return 0 if
  106945. ** iCursor is not in the set.
  106946. */
  106947. static Bitmask getMask(WhereMaskSet *pMaskSet, int iCursor){
  106948. int i;
  106949. assert( pMaskSet->n<=(int)sizeof(Bitmask)*8 );
  106950. for(i=0; i<pMaskSet->n; i++){
  106951. if( pMaskSet->ix[i]==iCursor ){
  106952. return MASKBIT(i);
  106953. }
  106954. }
  106955. return 0;
  106956. }
  106957. /*
  106958. ** Create a new mask for cursor iCursor.
  106959. **
  106960. ** There is one cursor per table in the FROM clause. The number of
  106961. ** tables in the FROM clause is limited by a test early in the
  106962. ** sqlite3WhereBegin() routine. So we know that the pMaskSet->ix[]
  106963. ** array will never overflow.
  106964. */
  106965. static void createMask(WhereMaskSet *pMaskSet, int iCursor){
  106966. assert( pMaskSet->n < ArraySize(pMaskSet->ix) );
  106967. pMaskSet->ix[pMaskSet->n++] = iCursor;
  106968. }
  106969. /*
  106970. ** These routines walk (recursively) an expression tree and generate
  106971. ** a bitmask indicating which tables are used in that expression
  106972. ** tree.
  106973. */
  106974. static Bitmask exprListTableUsage(WhereMaskSet*, ExprList*);
  106975. static Bitmask exprSelectTableUsage(WhereMaskSet*, Select*);
  106976. static Bitmask exprTableUsage(WhereMaskSet *pMaskSet, Expr *p){
  106977. Bitmask mask = 0;
  106978. if( p==0 ) return 0;
  106979. if( p->op==TK_COLUMN ){
  106980. mask = getMask(pMaskSet, p->iTable);
  106981. return mask;
  106982. }
  106983. mask = exprTableUsage(pMaskSet, p->pRight);
  106984. mask |= exprTableUsage(pMaskSet, p->pLeft);
  106985. if( ExprHasProperty(p, EP_xIsSelect) ){
  106986. mask |= exprSelectTableUsage(pMaskSet, p->x.pSelect);
  106987. }else{
  106988. mask |= exprListTableUsage(pMaskSet, p->x.pList);
  106989. }
  106990. return mask;
  106991. }
  106992. static Bitmask exprListTableUsage(WhereMaskSet *pMaskSet, ExprList *pList){
  106993. int i;
  106994. Bitmask mask = 0;
  106995. if( pList ){
  106996. for(i=0; i<pList->nExpr; i++){
  106997. mask |= exprTableUsage(pMaskSet, pList->a[i].pExpr);
  106998. }
  106999. }
  107000. return mask;
  107001. }
  107002. static Bitmask exprSelectTableUsage(WhereMaskSet *pMaskSet, Select *pS){
  107003. Bitmask mask = 0;
  107004. while( pS ){
  107005. SrcList *pSrc = pS->pSrc;
  107006. mask |= exprListTableUsage(pMaskSet, pS->pEList);
  107007. mask |= exprListTableUsage(pMaskSet, pS->pGroupBy);
  107008. mask |= exprListTableUsage(pMaskSet, pS->pOrderBy);
  107009. mask |= exprTableUsage(pMaskSet, pS->pWhere);
  107010. mask |= exprTableUsage(pMaskSet, pS->pHaving);
  107011. if( ALWAYS(pSrc!=0) ){
  107012. int i;
  107013. for(i=0; i<pSrc->nSrc; i++){
  107014. mask |= exprSelectTableUsage(pMaskSet, pSrc->a[i].pSelect);
  107015. mask |= exprTableUsage(pMaskSet, pSrc->a[i].pOn);
  107016. }
  107017. }
  107018. pS = pS->pPrior;
  107019. }
  107020. return mask;
  107021. }
  107022. /*
  107023. ** Return TRUE if the given operator is one of the operators that is
  107024. ** allowed for an indexable WHERE clause term. The allowed operators are
  107025. ** "=", "<", ">", "<=", ">=", "IN", and "IS NULL"
  107026. */
  107027. static int allowedOp(int op){
  107028. assert( TK_GT>TK_EQ && TK_GT<TK_GE );
  107029. assert( TK_LT>TK_EQ && TK_LT<TK_GE );
  107030. assert( TK_LE>TK_EQ && TK_LE<TK_GE );
  107031. assert( TK_GE==TK_EQ+4 );
  107032. return op==TK_IN || (op>=TK_EQ && op<=TK_GE) || op==TK_ISNULL;
  107033. }
  107034. /*
  107035. ** Commute a comparison operator. Expressions of the form "X op Y"
  107036. ** are converted into "Y op X".
  107037. **
  107038. ** If left/right precedence rules come into play when determining the
  107039. ** collating sequence, then COLLATE operators are adjusted to ensure
  107040. ** that the collating sequence does not change. For example:
  107041. ** "Y collate NOCASE op X" becomes "X op Y" because any collation sequence on
  107042. ** the left hand side of a comparison overrides any collation sequence
  107043. ** attached to the right. For the same reason the EP_Collate flag
  107044. ** is not commuted.
  107045. */
  107046. static void exprCommute(Parse *pParse, Expr *pExpr){
  107047. u16 expRight = (pExpr->pRight->flags & EP_Collate);
  107048. u16 expLeft = (pExpr->pLeft->flags & EP_Collate);
  107049. assert( allowedOp(pExpr->op) && pExpr->op!=TK_IN );
  107050. if( expRight==expLeft ){
  107051. /* Either X and Y both have COLLATE operator or neither do */
  107052. if( expRight ){
  107053. /* Both X and Y have COLLATE operators. Make sure X is always
  107054. ** used by clearing the EP_Collate flag from Y. */
  107055. pExpr->pRight->flags &= ~EP_Collate;
  107056. }else if( sqlite3ExprCollSeq(pParse, pExpr->pLeft)!=0 ){
  107057. /* Neither X nor Y have COLLATE operators, but X has a non-default
  107058. ** collating sequence. So add the EP_Collate marker on X to cause
  107059. ** it to be searched first. */
  107060. pExpr->pLeft->flags |= EP_Collate;
  107061. }
  107062. }
  107063. SWAP(Expr*,pExpr->pRight,pExpr->pLeft);
  107064. if( pExpr->op>=TK_GT ){
  107065. assert( TK_LT==TK_GT+2 );
  107066. assert( TK_GE==TK_LE+2 );
  107067. assert( TK_GT>TK_EQ );
  107068. assert( TK_GT<TK_LE );
  107069. assert( pExpr->op>=TK_GT && pExpr->op<=TK_GE );
  107070. pExpr->op = ((pExpr->op-TK_GT)^2)+TK_GT;
  107071. }
  107072. }
  107073. /*
  107074. ** Translate from TK_xx operator to WO_xx bitmask.
  107075. */
  107076. static u16 operatorMask(int op){
  107077. u16 c;
  107078. assert( allowedOp(op) );
  107079. if( op==TK_IN ){
  107080. c = WO_IN;
  107081. }else if( op==TK_ISNULL ){
  107082. c = WO_ISNULL;
  107083. }else{
  107084. assert( (WO_EQ<<(op-TK_EQ)) < 0x7fff );
  107085. c = (u16)(WO_EQ<<(op-TK_EQ));
  107086. }
  107087. assert( op!=TK_ISNULL || c==WO_ISNULL );
  107088. assert( op!=TK_IN || c==WO_IN );
  107089. assert( op!=TK_EQ || c==WO_EQ );
  107090. assert( op!=TK_LT || c==WO_LT );
  107091. assert( op!=TK_LE || c==WO_LE );
  107092. assert( op!=TK_GT || c==WO_GT );
  107093. assert( op!=TK_GE || c==WO_GE );
  107094. return c;
  107095. }
  107096. /*
  107097. ** Advance to the next WhereTerm that matches according to the criteria
  107098. ** established when the pScan object was initialized by whereScanInit().
  107099. ** Return NULL if there are no more matching WhereTerms.
  107100. */
  107101. static WhereTerm *whereScanNext(WhereScan *pScan){
  107102. int iCur; /* The cursor on the LHS of the term */
  107103. int iColumn; /* The column on the LHS of the term. -1 for IPK */
  107104. Expr *pX; /* An expression being tested */
  107105. WhereClause *pWC; /* Shorthand for pScan->pWC */
  107106. WhereTerm *pTerm; /* The term being tested */
  107107. int k = pScan->k; /* Where to start scanning */
  107108. while( pScan->iEquiv<=pScan->nEquiv ){
  107109. iCur = pScan->aEquiv[pScan->iEquiv-2];
  107110. iColumn = pScan->aEquiv[pScan->iEquiv-1];
  107111. while( (pWC = pScan->pWC)!=0 ){
  107112. for(pTerm=pWC->a+k; k<pWC->nTerm; k++, pTerm++){
  107113. if( pTerm->leftCursor==iCur
  107114. && pTerm->u.leftColumn==iColumn
  107115. && (pScan->iEquiv<=2 || !ExprHasProperty(pTerm->pExpr, EP_FromJoin))
  107116. ){
  107117. if( (pTerm->eOperator & WO_EQUIV)!=0
  107118. && pScan->nEquiv<ArraySize(pScan->aEquiv)
  107119. ){
  107120. int j;
  107121. pX = sqlite3ExprSkipCollate(pTerm->pExpr->pRight);
  107122. assert( pX->op==TK_COLUMN );
  107123. for(j=0; j<pScan->nEquiv; j+=2){
  107124. if( pScan->aEquiv[j]==pX->iTable
  107125. && pScan->aEquiv[j+1]==pX->iColumn ){
  107126. break;
  107127. }
  107128. }
  107129. if( j==pScan->nEquiv ){
  107130. pScan->aEquiv[j] = pX->iTable;
  107131. pScan->aEquiv[j+1] = pX->iColumn;
  107132. pScan->nEquiv += 2;
  107133. }
  107134. }
  107135. if( (pTerm->eOperator & pScan->opMask)!=0 ){
  107136. /* Verify the affinity and collating sequence match */
  107137. if( pScan->zCollName && (pTerm->eOperator & WO_ISNULL)==0 ){
  107138. CollSeq *pColl;
  107139. Parse *pParse = pWC->pWInfo->pParse;
  107140. pX = pTerm->pExpr;
  107141. if( !sqlite3IndexAffinityOk(pX, pScan->idxaff) ){
  107142. continue;
  107143. }
  107144. assert(pX->pLeft);
  107145. pColl = sqlite3BinaryCompareCollSeq(pParse,
  107146. pX->pLeft, pX->pRight);
  107147. if( pColl==0 ) pColl = pParse->db->pDfltColl;
  107148. if( sqlite3StrICmp(pColl->zName, pScan->zCollName) ){
  107149. continue;
  107150. }
  107151. }
  107152. if( (pTerm->eOperator & WO_EQ)!=0
  107153. && (pX = pTerm->pExpr->pRight)->op==TK_COLUMN
  107154. && pX->iTable==pScan->aEquiv[0]
  107155. && pX->iColumn==pScan->aEquiv[1]
  107156. ){
  107157. continue;
  107158. }
  107159. pScan->k = k+1;
  107160. return pTerm;
  107161. }
  107162. }
  107163. }
  107164. pScan->pWC = pScan->pWC->pOuter;
  107165. k = 0;
  107166. }
  107167. pScan->pWC = pScan->pOrigWC;
  107168. k = 0;
  107169. pScan->iEquiv += 2;
  107170. }
  107171. return 0;
  107172. }
  107173. /*
  107174. ** Initialize a WHERE clause scanner object. Return a pointer to the
  107175. ** first match. Return NULL if there are no matches.
  107176. **
  107177. ** The scanner will be searching the WHERE clause pWC. It will look
  107178. ** for terms of the form "X <op> <expr>" where X is column iColumn of table
  107179. ** iCur. The <op> must be one of the operators described by opMask.
  107180. **
  107181. ** If the search is for X and the WHERE clause contains terms of the
  107182. ** form X=Y then this routine might also return terms of the form
  107183. ** "Y <op> <expr>". The number of levels of transitivity is limited,
  107184. ** but is enough to handle most commonly occurring SQL statements.
  107185. **
  107186. ** If X is not the INTEGER PRIMARY KEY then X must be compatible with
  107187. ** index pIdx.
  107188. */
  107189. static WhereTerm *whereScanInit(
  107190. WhereScan *pScan, /* The WhereScan object being initialized */
  107191. WhereClause *pWC, /* The WHERE clause to be scanned */
  107192. int iCur, /* Cursor to scan for */
  107193. int iColumn, /* Column to scan for */
  107194. u32 opMask, /* Operator(s) to scan for */
  107195. Index *pIdx /* Must be compatible with this index */
  107196. ){
  107197. int j;
  107198. /* memset(pScan, 0, sizeof(*pScan)); */
  107199. pScan->pOrigWC = pWC;
  107200. pScan->pWC = pWC;
  107201. if( pIdx && iColumn>=0 ){
  107202. pScan->idxaff = pIdx->pTable->aCol[iColumn].affinity;
  107203. for(j=0; pIdx->aiColumn[j]!=iColumn; j++){
  107204. if( NEVER(j>pIdx->nColumn) ) return 0;
  107205. }
  107206. pScan->zCollName = pIdx->azColl[j];
  107207. }else{
  107208. pScan->idxaff = 0;
  107209. pScan->zCollName = 0;
  107210. }
  107211. pScan->opMask = opMask;
  107212. pScan->k = 0;
  107213. pScan->aEquiv[0] = iCur;
  107214. pScan->aEquiv[1] = iColumn;
  107215. pScan->nEquiv = 2;
  107216. pScan->iEquiv = 2;
  107217. return whereScanNext(pScan);
  107218. }
  107219. /*
  107220. ** Search for a term in the WHERE clause that is of the form "X <op> <expr>"
  107221. ** where X is a reference to the iColumn of table iCur and <op> is one of
  107222. ** the WO_xx operator codes specified by the op parameter.
  107223. ** Return a pointer to the term. Return 0 if not found.
  107224. **
  107225. ** The term returned might by Y=<expr> if there is another constraint in
  107226. ** the WHERE clause that specifies that X=Y. Any such constraints will be
  107227. ** identified by the WO_EQUIV bit in the pTerm->eOperator field. The
  107228. ** aEquiv[] array holds X and all its equivalents, with each SQL variable
  107229. ** taking up two slots in aEquiv[]. The first slot is for the cursor number
  107230. ** and the second is for the column number. There are 22 slots in aEquiv[]
  107231. ** so that means we can look for X plus up to 10 other equivalent values.
  107232. ** Hence a search for X will return <expr> if X=A1 and A1=A2 and A2=A3
  107233. ** and ... and A9=A10 and A10=<expr>.
  107234. **
  107235. ** If there are multiple terms in the WHERE clause of the form "X <op> <expr>"
  107236. ** then try for the one with no dependencies on <expr> - in other words where
  107237. ** <expr> is a constant expression of some kind. Only return entries of
  107238. ** the form "X <op> Y" where Y is a column in another table if no terms of
  107239. ** the form "X <op> <const-expr>" exist. If no terms with a constant RHS
  107240. ** exist, try to return a term that does not use WO_EQUIV.
  107241. */
  107242. static WhereTerm *findTerm(
  107243. WhereClause *pWC, /* The WHERE clause to be searched */
  107244. int iCur, /* Cursor number of LHS */
  107245. int iColumn, /* Column number of LHS */
  107246. Bitmask notReady, /* RHS must not overlap with this mask */
  107247. u32 op, /* Mask of WO_xx values describing operator */
  107248. Index *pIdx /* Must be compatible with this index, if not NULL */
  107249. ){
  107250. WhereTerm *pResult = 0;
  107251. WhereTerm *p;
  107252. WhereScan scan;
  107253. p = whereScanInit(&scan, pWC, iCur, iColumn, op, pIdx);
  107254. while( p ){
  107255. if( (p->prereqRight & notReady)==0 ){
  107256. if( p->prereqRight==0 && (p->eOperator&WO_EQ)!=0 ){
  107257. return p;
  107258. }
  107259. if( pResult==0 ) pResult = p;
  107260. }
  107261. p = whereScanNext(&scan);
  107262. }
  107263. return pResult;
  107264. }
  107265. /* Forward reference */
  107266. static void exprAnalyze(SrcList*, WhereClause*, int);
  107267. /*
  107268. ** Call exprAnalyze on all terms in a WHERE clause.
  107269. */
  107270. static void exprAnalyzeAll(
  107271. SrcList *pTabList, /* the FROM clause */
  107272. WhereClause *pWC /* the WHERE clause to be analyzed */
  107273. ){
  107274. int i;
  107275. for(i=pWC->nTerm-1; i>=0; i--){
  107276. exprAnalyze(pTabList, pWC, i);
  107277. }
  107278. }
  107279. #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
  107280. /*
  107281. ** Check to see if the given expression is a LIKE or GLOB operator that
  107282. ** can be optimized using inequality constraints. Return TRUE if it is
  107283. ** so and false if not.
  107284. **
  107285. ** In order for the operator to be optimizible, the RHS must be a string
  107286. ** literal that does not begin with a wildcard.
  107287. */
  107288. static int isLikeOrGlob(
  107289. Parse *pParse, /* Parsing and code generating context */
  107290. Expr *pExpr, /* Test this expression */
  107291. Expr **ppPrefix, /* Pointer to TK_STRING expression with pattern prefix */
  107292. int *pisComplete, /* True if the only wildcard is % in the last character */
  107293. int *pnoCase /* True if uppercase is equivalent to lowercase */
  107294. ){
  107295. const char *z = 0; /* String on RHS of LIKE operator */
  107296. Expr *pRight, *pLeft; /* Right and left size of LIKE operator */
  107297. ExprList *pList; /* List of operands to the LIKE operator */
  107298. int c; /* One character in z[] */
  107299. int cnt; /* Number of non-wildcard prefix characters */
  107300. char wc[3]; /* Wildcard characters */
  107301. sqlite3 *db = pParse->db; /* Database connection */
  107302. sqlite3_value *pVal = 0;
  107303. int op; /* Opcode of pRight */
  107304. if( !sqlite3IsLikeFunction(db, pExpr, pnoCase, wc) ){
  107305. return 0;
  107306. }
  107307. #ifdef SQLITE_EBCDIC
  107308. if( *pnoCase ) return 0;
  107309. #endif
  107310. pList = pExpr->x.pList;
  107311. pLeft = pList->a[1].pExpr;
  107312. if( pLeft->op!=TK_COLUMN
  107313. || sqlite3ExprAffinity(pLeft)!=SQLITE_AFF_TEXT
  107314. || IsVirtual(pLeft->pTab)
  107315. ){
  107316. /* IMP: R-02065-49465 The left-hand side of the LIKE or GLOB operator must
  107317. ** be the name of an indexed column with TEXT affinity. */
  107318. return 0;
  107319. }
  107320. assert( pLeft->iColumn!=(-1) ); /* Because IPK never has AFF_TEXT */
  107321. pRight = sqlite3ExprSkipCollate(pList->a[0].pExpr);
  107322. op = pRight->op;
  107323. if( op==TK_VARIABLE ){
  107324. Vdbe *pReprepare = pParse->pReprepare;
  107325. int iCol = pRight->iColumn;
  107326. pVal = sqlite3VdbeGetBoundValue(pReprepare, iCol, SQLITE_AFF_NONE);
  107327. if( pVal && sqlite3_value_type(pVal)==SQLITE_TEXT ){
  107328. z = (char *)sqlite3_value_text(pVal);
  107329. }
  107330. sqlite3VdbeSetVarmask(pParse->pVdbe, iCol);
  107331. assert( pRight->op==TK_VARIABLE || pRight->op==TK_REGISTER );
  107332. }else if( op==TK_STRING ){
  107333. z = pRight->u.zToken;
  107334. }
  107335. if( z ){
  107336. cnt = 0;
  107337. while( (c=z[cnt])!=0 && c!=wc[0] && c!=wc[1] && c!=wc[2] ){
  107338. cnt++;
  107339. }
  107340. if( cnt!=0 && 255!=(u8)z[cnt-1] ){
  107341. Expr *pPrefix;
  107342. *pisComplete = c==wc[0] && z[cnt+1]==0;
  107343. pPrefix = sqlite3Expr(db, TK_STRING, z);
  107344. if( pPrefix ) pPrefix->u.zToken[cnt] = 0;
  107345. *ppPrefix = pPrefix;
  107346. if( op==TK_VARIABLE ){
  107347. Vdbe *v = pParse->pVdbe;
  107348. sqlite3VdbeSetVarmask(v, pRight->iColumn);
  107349. if( *pisComplete && pRight->u.zToken[1] ){
  107350. /* If the rhs of the LIKE expression is a variable, and the current
  107351. ** value of the variable means there is no need to invoke the LIKE
  107352. ** function, then no OP_Variable will be added to the program.
  107353. ** This causes problems for the sqlite3_bind_parameter_name()
  107354. ** API. To work around them, add a dummy OP_Variable here.
  107355. */
  107356. int r1 = sqlite3GetTempReg(pParse);
  107357. sqlite3ExprCodeTarget(pParse, pRight, r1);
  107358. sqlite3VdbeChangeP3(v, sqlite3VdbeCurrentAddr(v)-1, 0);
  107359. sqlite3ReleaseTempReg(pParse, r1);
  107360. }
  107361. }
  107362. }else{
  107363. z = 0;
  107364. }
  107365. }
  107366. sqlite3ValueFree(pVal);
  107367. return (z!=0);
  107368. }
  107369. #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
  107370. #ifndef SQLITE_OMIT_VIRTUALTABLE
  107371. /*
  107372. ** Check to see if the given expression is of the form
  107373. **
  107374. ** column MATCH expr
  107375. **
  107376. ** If it is then return TRUE. If not, return FALSE.
  107377. */
  107378. static int isMatchOfColumn(
  107379. Expr *pExpr /* Test this expression */
  107380. ){
  107381. ExprList *pList;
  107382. if( pExpr->op!=TK_FUNCTION ){
  107383. return 0;
  107384. }
  107385. if( sqlite3StrICmp(pExpr->u.zToken,"match")!=0 ){
  107386. return 0;
  107387. }
  107388. pList = pExpr->x.pList;
  107389. if( pList->nExpr!=2 ){
  107390. return 0;
  107391. }
  107392. if( pList->a[1].pExpr->op != TK_COLUMN ){
  107393. return 0;
  107394. }
  107395. return 1;
  107396. }
  107397. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  107398. /*
  107399. ** If the pBase expression originated in the ON or USING clause of
  107400. ** a join, then transfer the appropriate markings over to derived.
  107401. */
  107402. static void transferJoinMarkings(Expr *pDerived, Expr *pBase){
  107403. if( pDerived ){
  107404. pDerived->flags |= pBase->flags & EP_FromJoin;
  107405. pDerived->iRightJoinTable = pBase->iRightJoinTable;
  107406. }
  107407. }
  107408. /*
  107409. ** Mark term iChild as being a child of term iParent
  107410. */
  107411. static void markTermAsChild(WhereClause *pWC, int iChild, int iParent){
  107412. pWC->a[iChild].iParent = iParent;
  107413. pWC->a[iChild].truthProb = pWC->a[iParent].truthProb;
  107414. pWC->a[iParent].nChild++;
  107415. }
  107416. #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
  107417. /*
  107418. ** Analyze a term that consists of two or more OR-connected
  107419. ** subterms. So in:
  107420. **
  107421. ** ... WHERE (a=5) AND (b=7 OR c=9 OR d=13) AND (d=13)
  107422. ** ^^^^^^^^^^^^^^^^^^^^
  107423. **
  107424. ** This routine analyzes terms such as the middle term in the above example.
  107425. ** A WhereOrTerm object is computed and attached to the term under
  107426. ** analysis, regardless of the outcome of the analysis. Hence:
  107427. **
  107428. ** WhereTerm.wtFlags |= TERM_ORINFO
  107429. ** WhereTerm.u.pOrInfo = a dynamically allocated WhereOrTerm object
  107430. **
  107431. ** The term being analyzed must have two or more of OR-connected subterms.
  107432. ** A single subterm might be a set of AND-connected sub-subterms.
  107433. ** Examples of terms under analysis:
  107434. **
  107435. ** (A) t1.x=t2.y OR t1.x=t2.z OR t1.y=15 OR t1.z=t3.a+5
  107436. ** (B) x=expr1 OR expr2=x OR x=expr3
  107437. ** (C) t1.x=t2.y OR (t1.x=t2.z AND t1.y=15)
  107438. ** (D) x=expr1 OR (y>11 AND y<22 AND z LIKE '*hello*')
  107439. ** (E) (p.a=1 AND q.b=2 AND r.c=3) OR (p.x=4 AND q.y=5 AND r.z=6)
  107440. **
  107441. ** CASE 1:
  107442. **
  107443. ** If all subterms are of the form T.C=expr for some single column of C and
  107444. ** a single table T (as shown in example B above) then create a new virtual
  107445. ** term that is an equivalent IN expression. In other words, if the term
  107446. ** being analyzed is:
  107447. **
  107448. ** x = expr1 OR expr2 = x OR x = expr3
  107449. **
  107450. ** then create a new virtual term like this:
  107451. **
  107452. ** x IN (expr1,expr2,expr3)
  107453. **
  107454. ** CASE 2:
  107455. **
  107456. ** If all subterms are indexable by a single table T, then set
  107457. **
  107458. ** WhereTerm.eOperator = WO_OR
  107459. ** WhereTerm.u.pOrInfo->indexable |= the cursor number for table T
  107460. **
  107461. ** A subterm is "indexable" if it is of the form
  107462. ** "T.C <op> <expr>" where C is any column of table T and
  107463. ** <op> is one of "=", "<", "<=", ">", ">=", "IS NULL", or "IN".
  107464. ** A subterm is also indexable if it is an AND of two or more
  107465. ** subsubterms at least one of which is indexable. Indexable AND
  107466. ** subterms have their eOperator set to WO_AND and they have
  107467. ** u.pAndInfo set to a dynamically allocated WhereAndTerm object.
  107468. **
  107469. ** From another point of view, "indexable" means that the subterm could
  107470. ** potentially be used with an index if an appropriate index exists.
  107471. ** This analysis does not consider whether or not the index exists; that
  107472. ** is decided elsewhere. This analysis only looks at whether subterms
  107473. ** appropriate for indexing exist.
  107474. **
  107475. ** All examples A through E above satisfy case 2. But if a term
  107476. ** also satisfies case 1 (such as B) we know that the optimizer will
  107477. ** always prefer case 1, so in that case we pretend that case 2 is not
  107478. ** satisfied.
  107479. **
  107480. ** It might be the case that multiple tables are indexable. For example,
  107481. ** (E) above is indexable on tables P, Q, and R.
  107482. **
  107483. ** Terms that satisfy case 2 are candidates for lookup by using
  107484. ** separate indices to find rowids for each subterm and composing
  107485. ** the union of all rowids using a RowSet object. This is similar
  107486. ** to "bitmap indices" in other database engines.
  107487. **
  107488. ** OTHERWISE:
  107489. **
  107490. ** If neither case 1 nor case 2 apply, then leave the eOperator set to
  107491. ** zero. This term is not useful for search.
  107492. */
  107493. static void exprAnalyzeOrTerm(
  107494. SrcList *pSrc, /* the FROM clause */
  107495. WhereClause *pWC, /* the complete WHERE clause */
  107496. int idxTerm /* Index of the OR-term to be analyzed */
  107497. ){
  107498. WhereInfo *pWInfo = pWC->pWInfo; /* WHERE clause processing context */
  107499. Parse *pParse = pWInfo->pParse; /* Parser context */
  107500. sqlite3 *db = pParse->db; /* Database connection */
  107501. WhereTerm *pTerm = &pWC->a[idxTerm]; /* The term to be analyzed */
  107502. Expr *pExpr = pTerm->pExpr; /* The expression of the term */
  107503. int i; /* Loop counters */
  107504. WhereClause *pOrWc; /* Breakup of pTerm into subterms */
  107505. WhereTerm *pOrTerm; /* A Sub-term within the pOrWc */
  107506. WhereOrInfo *pOrInfo; /* Additional information associated with pTerm */
  107507. Bitmask chngToIN; /* Tables that might satisfy case 1 */
  107508. Bitmask indexable; /* Tables that are indexable, satisfying case 2 */
  107509. /*
  107510. ** Break the OR clause into its separate subterms. The subterms are
  107511. ** stored in a WhereClause structure containing within the WhereOrInfo
  107512. ** object that is attached to the original OR clause term.
  107513. */
  107514. assert( (pTerm->wtFlags & (TERM_DYNAMIC|TERM_ORINFO|TERM_ANDINFO))==0 );
  107515. assert( pExpr->op==TK_OR );
  107516. pTerm->u.pOrInfo = pOrInfo = sqlite3DbMallocZero(db, sizeof(*pOrInfo));
  107517. if( pOrInfo==0 ) return;
  107518. pTerm->wtFlags |= TERM_ORINFO;
  107519. pOrWc = &pOrInfo->wc;
  107520. whereClauseInit(pOrWc, pWInfo);
  107521. whereSplit(pOrWc, pExpr, TK_OR);
  107522. exprAnalyzeAll(pSrc, pOrWc);
  107523. if( db->mallocFailed ) return;
  107524. assert( pOrWc->nTerm>=2 );
  107525. /*
  107526. ** Compute the set of tables that might satisfy cases 1 or 2.
  107527. */
  107528. indexable = ~(Bitmask)0;
  107529. chngToIN = ~(Bitmask)0;
  107530. for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0 && indexable; i--, pOrTerm++){
  107531. if( (pOrTerm->eOperator & WO_SINGLE)==0 ){
  107532. WhereAndInfo *pAndInfo;
  107533. assert( (pOrTerm->wtFlags & (TERM_ANDINFO|TERM_ORINFO))==0 );
  107534. chngToIN = 0;
  107535. pAndInfo = sqlite3DbMallocRaw(db, sizeof(*pAndInfo));
  107536. if( pAndInfo ){
  107537. WhereClause *pAndWC;
  107538. WhereTerm *pAndTerm;
  107539. int j;
  107540. Bitmask b = 0;
  107541. pOrTerm->u.pAndInfo = pAndInfo;
  107542. pOrTerm->wtFlags |= TERM_ANDINFO;
  107543. pOrTerm->eOperator = WO_AND;
  107544. pAndWC = &pAndInfo->wc;
  107545. whereClauseInit(pAndWC, pWC->pWInfo);
  107546. whereSplit(pAndWC, pOrTerm->pExpr, TK_AND);
  107547. exprAnalyzeAll(pSrc, pAndWC);
  107548. pAndWC->pOuter = pWC;
  107549. testcase( db->mallocFailed );
  107550. if( !db->mallocFailed ){
  107551. for(j=0, pAndTerm=pAndWC->a; j<pAndWC->nTerm; j++, pAndTerm++){
  107552. assert( pAndTerm->pExpr );
  107553. if( allowedOp(pAndTerm->pExpr->op) ){
  107554. b |= getMask(&pWInfo->sMaskSet, pAndTerm->leftCursor);
  107555. }
  107556. }
  107557. }
  107558. indexable &= b;
  107559. }
  107560. }else if( pOrTerm->wtFlags & TERM_COPIED ){
  107561. /* Skip this term for now. We revisit it when we process the
  107562. ** corresponding TERM_VIRTUAL term */
  107563. }else{
  107564. Bitmask b;
  107565. b = getMask(&pWInfo->sMaskSet, pOrTerm->leftCursor);
  107566. if( pOrTerm->wtFlags & TERM_VIRTUAL ){
  107567. WhereTerm *pOther = &pOrWc->a[pOrTerm->iParent];
  107568. b |= getMask(&pWInfo->sMaskSet, pOther->leftCursor);
  107569. }
  107570. indexable &= b;
  107571. if( (pOrTerm->eOperator & WO_EQ)==0 ){
  107572. chngToIN = 0;
  107573. }else{
  107574. chngToIN &= b;
  107575. }
  107576. }
  107577. }
  107578. /*
  107579. ** Record the set of tables that satisfy case 2. The set might be
  107580. ** empty.
  107581. */
  107582. pOrInfo->indexable = indexable;
  107583. pTerm->eOperator = indexable==0 ? 0 : WO_OR;
  107584. /*
  107585. ** chngToIN holds a set of tables that *might* satisfy case 1. But
  107586. ** we have to do some additional checking to see if case 1 really
  107587. ** is satisfied.
  107588. **
  107589. ** chngToIN will hold either 0, 1, or 2 bits. The 0-bit case means
  107590. ** that there is no possibility of transforming the OR clause into an
  107591. ** IN operator because one or more terms in the OR clause contain
  107592. ** something other than == on a column in the single table. The 1-bit
  107593. ** case means that every term of the OR clause is of the form
  107594. ** "table.column=expr" for some single table. The one bit that is set
  107595. ** will correspond to the common table. We still need to check to make
  107596. ** sure the same column is used on all terms. The 2-bit case is when
  107597. ** the all terms are of the form "table1.column=table2.column". It
  107598. ** might be possible to form an IN operator with either table1.column
  107599. ** or table2.column as the LHS if either is common to every term of
  107600. ** the OR clause.
  107601. **
  107602. ** Note that terms of the form "table.column1=table.column2" (the
  107603. ** same table on both sizes of the ==) cannot be optimized.
  107604. */
  107605. if( chngToIN ){
  107606. int okToChngToIN = 0; /* True if the conversion to IN is valid */
  107607. int iColumn = -1; /* Column index on lhs of IN operator */
  107608. int iCursor = -1; /* Table cursor common to all terms */
  107609. int j = 0; /* Loop counter */
  107610. /* Search for a table and column that appears on one side or the
  107611. ** other of the == operator in every subterm. That table and column
  107612. ** will be recorded in iCursor and iColumn. There might not be any
  107613. ** such table and column. Set okToChngToIN if an appropriate table
  107614. ** and column is found but leave okToChngToIN false if not found.
  107615. */
  107616. for(j=0; j<2 && !okToChngToIN; j++){
  107617. pOrTerm = pOrWc->a;
  107618. for(i=pOrWc->nTerm-1; i>=0; i--, pOrTerm++){
  107619. assert( pOrTerm->eOperator & WO_EQ );
  107620. pOrTerm->wtFlags &= ~TERM_OR_OK;
  107621. if( pOrTerm->leftCursor==iCursor ){
  107622. /* This is the 2-bit case and we are on the second iteration and
  107623. ** current term is from the first iteration. So skip this term. */
  107624. assert( j==1 );
  107625. continue;
  107626. }
  107627. if( (chngToIN & getMask(&pWInfo->sMaskSet, pOrTerm->leftCursor))==0 ){
  107628. /* This term must be of the form t1.a==t2.b where t2 is in the
  107629. ** chngToIN set but t1 is not. This term will be either preceded
  107630. ** or follwed by an inverted copy (t2.b==t1.a). Skip this term
  107631. ** and use its inversion. */
  107632. testcase( pOrTerm->wtFlags & TERM_COPIED );
  107633. testcase( pOrTerm->wtFlags & TERM_VIRTUAL );
  107634. assert( pOrTerm->wtFlags & (TERM_COPIED|TERM_VIRTUAL) );
  107635. continue;
  107636. }
  107637. iColumn = pOrTerm->u.leftColumn;
  107638. iCursor = pOrTerm->leftCursor;
  107639. break;
  107640. }
  107641. if( i<0 ){
  107642. /* No candidate table+column was found. This can only occur
  107643. ** on the second iteration */
  107644. assert( j==1 );
  107645. assert( IsPowerOfTwo(chngToIN) );
  107646. assert( chngToIN==getMask(&pWInfo->sMaskSet, iCursor) );
  107647. break;
  107648. }
  107649. testcase( j==1 );
  107650. /* We have found a candidate table and column. Check to see if that
  107651. ** table and column is common to every term in the OR clause */
  107652. okToChngToIN = 1;
  107653. for(; i>=0 && okToChngToIN; i--, pOrTerm++){
  107654. assert( pOrTerm->eOperator & WO_EQ );
  107655. if( pOrTerm->leftCursor!=iCursor ){
  107656. pOrTerm->wtFlags &= ~TERM_OR_OK;
  107657. }else if( pOrTerm->u.leftColumn!=iColumn ){
  107658. okToChngToIN = 0;
  107659. }else{
  107660. int affLeft, affRight;
  107661. /* If the right-hand side is also a column, then the affinities
  107662. ** of both right and left sides must be such that no type
  107663. ** conversions are required on the right. (Ticket #2249)
  107664. */
  107665. affRight = sqlite3ExprAffinity(pOrTerm->pExpr->pRight);
  107666. affLeft = sqlite3ExprAffinity(pOrTerm->pExpr->pLeft);
  107667. if( affRight!=0 && affRight!=affLeft ){
  107668. okToChngToIN = 0;
  107669. }else{
  107670. pOrTerm->wtFlags |= TERM_OR_OK;
  107671. }
  107672. }
  107673. }
  107674. }
  107675. /* At this point, okToChngToIN is true if original pTerm satisfies
  107676. ** case 1. In that case, construct a new virtual term that is
  107677. ** pTerm converted into an IN operator.
  107678. */
  107679. if( okToChngToIN ){
  107680. Expr *pDup; /* A transient duplicate expression */
  107681. ExprList *pList = 0; /* The RHS of the IN operator */
  107682. Expr *pLeft = 0; /* The LHS of the IN operator */
  107683. Expr *pNew; /* The complete IN operator */
  107684. for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0; i--, pOrTerm++){
  107685. if( (pOrTerm->wtFlags & TERM_OR_OK)==0 ) continue;
  107686. assert( pOrTerm->eOperator & WO_EQ );
  107687. assert( pOrTerm->leftCursor==iCursor );
  107688. assert( pOrTerm->u.leftColumn==iColumn );
  107689. pDup = sqlite3ExprDup(db, pOrTerm->pExpr->pRight, 0);
  107690. pList = sqlite3ExprListAppend(pWInfo->pParse, pList, pDup);
  107691. pLeft = pOrTerm->pExpr->pLeft;
  107692. }
  107693. assert( pLeft!=0 );
  107694. pDup = sqlite3ExprDup(db, pLeft, 0);
  107695. pNew = sqlite3PExpr(pParse, TK_IN, pDup, 0, 0);
  107696. if( pNew ){
  107697. int idxNew;
  107698. transferJoinMarkings(pNew, pExpr);
  107699. assert( !ExprHasProperty(pNew, EP_xIsSelect) );
  107700. pNew->x.pList = pList;
  107701. idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
  107702. testcase( idxNew==0 );
  107703. exprAnalyze(pSrc, pWC, idxNew);
  107704. pTerm = &pWC->a[idxTerm];
  107705. markTermAsChild(pWC, idxNew, idxTerm);
  107706. }else{
  107707. sqlite3ExprListDelete(db, pList);
  107708. }
  107709. pTerm->eOperator = WO_NOOP; /* case 1 trumps case 2 */
  107710. }
  107711. }
  107712. }
  107713. #endif /* !SQLITE_OMIT_OR_OPTIMIZATION && !SQLITE_OMIT_SUBQUERY */
  107714. /*
  107715. ** The input to this routine is an WhereTerm structure with only the
  107716. ** "pExpr" field filled in. The job of this routine is to analyze the
  107717. ** subexpression and populate all the other fields of the WhereTerm
  107718. ** structure.
  107719. **
  107720. ** If the expression is of the form "<expr> <op> X" it gets commuted
  107721. ** to the standard form of "X <op> <expr>".
  107722. **
  107723. ** If the expression is of the form "X <op> Y" where both X and Y are
  107724. ** columns, then the original expression is unchanged and a new virtual
  107725. ** term of the form "Y <op> X" is added to the WHERE clause and
  107726. ** analyzed separately. The original term is marked with TERM_COPIED
  107727. ** and the new term is marked with TERM_DYNAMIC (because it's pExpr
  107728. ** needs to be freed with the WhereClause) and TERM_VIRTUAL (because it
  107729. ** is a commuted copy of a prior term.) The original term has nChild=1
  107730. ** and the copy has idxParent set to the index of the original term.
  107731. */
  107732. static void exprAnalyze(
  107733. SrcList *pSrc, /* the FROM clause */
  107734. WhereClause *pWC, /* the WHERE clause */
  107735. int idxTerm /* Index of the term to be analyzed */
  107736. ){
  107737. WhereInfo *pWInfo = pWC->pWInfo; /* WHERE clause processing context */
  107738. WhereTerm *pTerm; /* The term to be analyzed */
  107739. WhereMaskSet *pMaskSet; /* Set of table index masks */
  107740. Expr *pExpr; /* The expression to be analyzed */
  107741. Bitmask prereqLeft; /* Prerequesites of the pExpr->pLeft */
  107742. Bitmask prereqAll; /* Prerequesites of pExpr */
  107743. Bitmask extraRight = 0; /* Extra dependencies on LEFT JOIN */
  107744. Expr *pStr1 = 0; /* RHS of LIKE/GLOB operator */
  107745. int isComplete = 0; /* RHS of LIKE/GLOB ends with wildcard */
  107746. int noCase = 0; /* LIKE/GLOB distinguishes case */
  107747. int op; /* Top-level operator. pExpr->op */
  107748. Parse *pParse = pWInfo->pParse; /* Parsing context */
  107749. sqlite3 *db = pParse->db; /* Database connection */
  107750. if( db->mallocFailed ){
  107751. return;
  107752. }
  107753. pTerm = &pWC->a[idxTerm];
  107754. pMaskSet = &pWInfo->sMaskSet;
  107755. pExpr = pTerm->pExpr;
  107756. assert( pExpr->op!=TK_AS && pExpr->op!=TK_COLLATE );
  107757. prereqLeft = exprTableUsage(pMaskSet, pExpr->pLeft);
  107758. op = pExpr->op;
  107759. if( op==TK_IN ){
  107760. assert( pExpr->pRight==0 );
  107761. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  107762. pTerm->prereqRight = exprSelectTableUsage(pMaskSet, pExpr->x.pSelect);
  107763. }else{
  107764. pTerm->prereqRight = exprListTableUsage(pMaskSet, pExpr->x.pList);
  107765. }
  107766. }else if( op==TK_ISNULL ){
  107767. pTerm->prereqRight = 0;
  107768. }else{
  107769. pTerm->prereqRight = exprTableUsage(pMaskSet, pExpr->pRight);
  107770. }
  107771. prereqAll = exprTableUsage(pMaskSet, pExpr);
  107772. if( ExprHasProperty(pExpr, EP_FromJoin) ){
  107773. Bitmask x = getMask(pMaskSet, pExpr->iRightJoinTable);
  107774. prereqAll |= x;
  107775. extraRight = x-1; /* ON clause terms may not be used with an index
  107776. ** on left table of a LEFT JOIN. Ticket #3015 */
  107777. }
  107778. pTerm->prereqAll = prereqAll;
  107779. pTerm->leftCursor = -1;
  107780. pTerm->iParent = -1;
  107781. pTerm->eOperator = 0;
  107782. if( allowedOp(op) ){
  107783. Expr *pLeft = sqlite3ExprSkipCollate(pExpr->pLeft);
  107784. Expr *pRight = sqlite3ExprSkipCollate(pExpr->pRight);
  107785. u16 opMask = (pTerm->prereqRight & prereqLeft)==0 ? WO_ALL : WO_EQUIV;
  107786. if( pLeft->op==TK_COLUMN ){
  107787. pTerm->leftCursor = pLeft->iTable;
  107788. pTerm->u.leftColumn = pLeft->iColumn;
  107789. pTerm->eOperator = operatorMask(op) & opMask;
  107790. }
  107791. if( pRight && pRight->op==TK_COLUMN ){
  107792. WhereTerm *pNew;
  107793. Expr *pDup;
  107794. u16 eExtraOp = 0; /* Extra bits for pNew->eOperator */
  107795. if( pTerm->leftCursor>=0 ){
  107796. int idxNew;
  107797. pDup = sqlite3ExprDup(db, pExpr, 0);
  107798. if( db->mallocFailed ){
  107799. sqlite3ExprDelete(db, pDup);
  107800. return;
  107801. }
  107802. idxNew = whereClauseInsert(pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC);
  107803. if( idxNew==0 ) return;
  107804. pNew = &pWC->a[idxNew];
  107805. markTermAsChild(pWC, idxNew, idxTerm);
  107806. pTerm = &pWC->a[idxTerm];
  107807. pTerm->wtFlags |= TERM_COPIED;
  107808. if( pExpr->op==TK_EQ
  107809. && !ExprHasProperty(pExpr, EP_FromJoin)
  107810. && OptimizationEnabled(db, SQLITE_Transitive)
  107811. ){
  107812. pTerm->eOperator |= WO_EQUIV;
  107813. eExtraOp = WO_EQUIV;
  107814. }
  107815. }else{
  107816. pDup = pExpr;
  107817. pNew = pTerm;
  107818. }
  107819. exprCommute(pParse, pDup);
  107820. pLeft = sqlite3ExprSkipCollate(pDup->pLeft);
  107821. pNew->leftCursor = pLeft->iTable;
  107822. pNew->u.leftColumn = pLeft->iColumn;
  107823. testcase( (prereqLeft | extraRight) != prereqLeft );
  107824. pNew->prereqRight = prereqLeft | extraRight;
  107825. pNew->prereqAll = prereqAll;
  107826. pNew->eOperator = (operatorMask(pDup->op) + eExtraOp) & opMask;
  107827. }
  107828. }
  107829. #ifndef SQLITE_OMIT_BETWEEN_OPTIMIZATION
  107830. /* If a term is the BETWEEN operator, create two new virtual terms
  107831. ** that define the range that the BETWEEN implements. For example:
  107832. **
  107833. ** a BETWEEN b AND c
  107834. **
  107835. ** is converted into:
  107836. **
  107837. ** (a BETWEEN b AND c) AND (a>=b) AND (a<=c)
  107838. **
  107839. ** The two new terms are added onto the end of the WhereClause object.
  107840. ** The new terms are "dynamic" and are children of the original BETWEEN
  107841. ** term. That means that if the BETWEEN term is coded, the children are
  107842. ** skipped. Or, if the children are satisfied by an index, the original
  107843. ** BETWEEN term is skipped.
  107844. */
  107845. else if( pExpr->op==TK_BETWEEN && pWC->op==TK_AND ){
  107846. ExprList *pList = pExpr->x.pList;
  107847. int i;
  107848. static const u8 ops[] = {TK_GE, TK_LE};
  107849. assert( pList!=0 );
  107850. assert( pList->nExpr==2 );
  107851. for(i=0; i<2; i++){
  107852. Expr *pNewExpr;
  107853. int idxNew;
  107854. pNewExpr = sqlite3PExpr(pParse, ops[i],
  107855. sqlite3ExprDup(db, pExpr->pLeft, 0),
  107856. sqlite3ExprDup(db, pList->a[i].pExpr, 0), 0);
  107857. transferJoinMarkings(pNewExpr, pExpr);
  107858. idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
  107859. testcase( idxNew==0 );
  107860. exprAnalyze(pSrc, pWC, idxNew);
  107861. pTerm = &pWC->a[idxTerm];
  107862. markTermAsChild(pWC, idxNew, idxTerm);
  107863. }
  107864. }
  107865. #endif /* SQLITE_OMIT_BETWEEN_OPTIMIZATION */
  107866. #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
  107867. /* Analyze a term that is composed of two or more subterms connected by
  107868. ** an OR operator.
  107869. */
  107870. else if( pExpr->op==TK_OR ){
  107871. assert( pWC->op==TK_AND );
  107872. exprAnalyzeOrTerm(pSrc, pWC, idxTerm);
  107873. pTerm = &pWC->a[idxTerm];
  107874. }
  107875. #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
  107876. #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
  107877. /* Add constraints to reduce the search space on a LIKE or GLOB
  107878. ** operator.
  107879. **
  107880. ** A like pattern of the form "x LIKE 'abc%'" is changed into constraints
  107881. **
  107882. ** x>='abc' AND x<'abd' AND x LIKE 'abc%'
  107883. **
  107884. ** The last character of the prefix "abc" is incremented to form the
  107885. ** termination condition "abd".
  107886. */
  107887. if( pWC->op==TK_AND
  107888. && isLikeOrGlob(pParse, pExpr, &pStr1, &isComplete, &noCase)
  107889. ){
  107890. Expr *pLeft; /* LHS of LIKE/GLOB operator */
  107891. Expr *pStr2; /* Copy of pStr1 - RHS of LIKE/GLOB operator */
  107892. Expr *pNewExpr1;
  107893. Expr *pNewExpr2;
  107894. int idxNew1;
  107895. int idxNew2;
  107896. Token sCollSeqName; /* Name of collating sequence */
  107897. pLeft = pExpr->x.pList->a[1].pExpr;
  107898. pStr2 = sqlite3ExprDup(db, pStr1, 0);
  107899. if( !db->mallocFailed ){
  107900. u8 c, *pC; /* Last character before the first wildcard */
  107901. pC = (u8*)&pStr2->u.zToken[sqlite3Strlen30(pStr2->u.zToken)-1];
  107902. c = *pC;
  107903. if( noCase ){
  107904. /* The point is to increment the last character before the first
  107905. ** wildcard. But if we increment '@', that will push it into the
  107906. ** alphabetic range where case conversions will mess up the
  107907. ** inequality. To avoid this, make sure to also run the full
  107908. ** LIKE on all candidate expressions by clearing the isComplete flag
  107909. */
  107910. if( c=='A'-1 ) isComplete = 0;
  107911. c = sqlite3UpperToLower[c];
  107912. }
  107913. *pC = c + 1;
  107914. }
  107915. sCollSeqName.z = noCase ? "NOCASE" : "BINARY";
  107916. sCollSeqName.n = 6;
  107917. pNewExpr1 = sqlite3ExprDup(db, pLeft, 0);
  107918. pNewExpr1 = sqlite3PExpr(pParse, TK_GE,
  107919. sqlite3ExprAddCollateToken(pParse,pNewExpr1,&sCollSeqName),
  107920. pStr1, 0);
  107921. transferJoinMarkings(pNewExpr1, pExpr);
  107922. idxNew1 = whereClauseInsert(pWC, pNewExpr1, TERM_VIRTUAL|TERM_DYNAMIC);
  107923. testcase( idxNew1==0 );
  107924. exprAnalyze(pSrc, pWC, idxNew1);
  107925. pNewExpr2 = sqlite3ExprDup(db, pLeft, 0);
  107926. pNewExpr2 = sqlite3PExpr(pParse, TK_LT,
  107927. sqlite3ExprAddCollateToken(pParse,pNewExpr2,&sCollSeqName),
  107928. pStr2, 0);
  107929. transferJoinMarkings(pNewExpr2, pExpr);
  107930. idxNew2 = whereClauseInsert(pWC, pNewExpr2, TERM_VIRTUAL|TERM_DYNAMIC);
  107931. testcase( idxNew2==0 );
  107932. exprAnalyze(pSrc, pWC, idxNew2);
  107933. pTerm = &pWC->a[idxTerm];
  107934. if( isComplete ){
  107935. markTermAsChild(pWC, idxNew1, idxTerm);
  107936. markTermAsChild(pWC, idxNew2, idxTerm);
  107937. }
  107938. }
  107939. #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
  107940. #ifndef SQLITE_OMIT_VIRTUALTABLE
  107941. /* Add a WO_MATCH auxiliary term to the constraint set if the
  107942. ** current expression is of the form: column MATCH expr.
  107943. ** This information is used by the xBestIndex methods of
  107944. ** virtual tables. The native query optimizer does not attempt
  107945. ** to do anything with MATCH functions.
  107946. */
  107947. if( isMatchOfColumn(pExpr) ){
  107948. int idxNew;
  107949. Expr *pRight, *pLeft;
  107950. WhereTerm *pNewTerm;
  107951. Bitmask prereqColumn, prereqExpr;
  107952. pRight = pExpr->x.pList->a[0].pExpr;
  107953. pLeft = pExpr->x.pList->a[1].pExpr;
  107954. prereqExpr = exprTableUsage(pMaskSet, pRight);
  107955. prereqColumn = exprTableUsage(pMaskSet, pLeft);
  107956. if( (prereqExpr & prereqColumn)==0 ){
  107957. Expr *pNewExpr;
  107958. pNewExpr = sqlite3PExpr(pParse, TK_MATCH,
  107959. 0, sqlite3ExprDup(db, pRight, 0), 0);
  107960. idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
  107961. testcase( idxNew==0 );
  107962. pNewTerm = &pWC->a[idxNew];
  107963. pNewTerm->prereqRight = prereqExpr;
  107964. pNewTerm->leftCursor = pLeft->iTable;
  107965. pNewTerm->u.leftColumn = pLeft->iColumn;
  107966. pNewTerm->eOperator = WO_MATCH;
  107967. markTermAsChild(pWC, idxNew, idxTerm);
  107968. pTerm = &pWC->a[idxTerm];
  107969. pTerm->wtFlags |= TERM_COPIED;
  107970. pNewTerm->prereqAll = pTerm->prereqAll;
  107971. }
  107972. }
  107973. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  107974. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  107975. /* When sqlite_stat3 histogram data is available an operator of the
  107976. ** form "x IS NOT NULL" can sometimes be evaluated more efficiently
  107977. ** as "x>NULL" if x is not an INTEGER PRIMARY KEY. So construct a
  107978. ** virtual term of that form.
  107979. **
  107980. ** Note that the virtual term must be tagged with TERM_VNULL. This
  107981. ** TERM_VNULL tag will suppress the not-null check at the beginning
  107982. ** of the loop. Without the TERM_VNULL flag, the not-null check at
  107983. ** the start of the loop will prevent any results from being returned.
  107984. */
  107985. if( pExpr->op==TK_NOTNULL
  107986. && pExpr->pLeft->op==TK_COLUMN
  107987. && pExpr->pLeft->iColumn>=0
  107988. && OptimizationEnabled(db, SQLITE_Stat34)
  107989. ){
  107990. Expr *pNewExpr;
  107991. Expr *pLeft = pExpr->pLeft;
  107992. int idxNew;
  107993. WhereTerm *pNewTerm;
  107994. pNewExpr = sqlite3PExpr(pParse, TK_GT,
  107995. sqlite3ExprDup(db, pLeft, 0),
  107996. sqlite3PExpr(pParse, TK_NULL, 0, 0, 0), 0);
  107997. idxNew = whereClauseInsert(pWC, pNewExpr,
  107998. TERM_VIRTUAL|TERM_DYNAMIC|TERM_VNULL);
  107999. if( idxNew ){
  108000. pNewTerm = &pWC->a[idxNew];
  108001. pNewTerm->prereqRight = 0;
  108002. pNewTerm->leftCursor = pLeft->iTable;
  108003. pNewTerm->u.leftColumn = pLeft->iColumn;
  108004. pNewTerm->eOperator = WO_GT;
  108005. markTermAsChild(pWC, idxNew, idxTerm);
  108006. pTerm = &pWC->a[idxTerm];
  108007. pTerm->wtFlags |= TERM_COPIED;
  108008. pNewTerm->prereqAll = pTerm->prereqAll;
  108009. }
  108010. }
  108011. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  108012. /* Prevent ON clause terms of a LEFT JOIN from being used to drive
  108013. ** an index for tables to the left of the join.
  108014. */
  108015. pTerm->prereqRight |= extraRight;
  108016. }
  108017. /*
  108018. ** This function searches pList for an entry that matches the iCol-th column
  108019. ** of index pIdx.
  108020. **
  108021. ** If such an expression is found, its index in pList->a[] is returned. If
  108022. ** no expression is found, -1 is returned.
  108023. */
  108024. static int findIndexCol(
  108025. Parse *pParse, /* Parse context */
  108026. ExprList *pList, /* Expression list to search */
  108027. int iBase, /* Cursor for table associated with pIdx */
  108028. Index *pIdx, /* Index to match column of */
  108029. int iCol /* Column of index to match */
  108030. ){
  108031. int i;
  108032. const char *zColl = pIdx->azColl[iCol];
  108033. for(i=0; i<pList->nExpr; i++){
  108034. Expr *p = sqlite3ExprSkipCollate(pList->a[i].pExpr);
  108035. if( p->op==TK_COLUMN
  108036. && p->iColumn==pIdx->aiColumn[iCol]
  108037. && p->iTable==iBase
  108038. ){
  108039. CollSeq *pColl = sqlite3ExprCollSeq(pParse, pList->a[i].pExpr);
  108040. if( ALWAYS(pColl) && 0==sqlite3StrICmp(pColl->zName, zColl) ){
  108041. return i;
  108042. }
  108043. }
  108044. }
  108045. return -1;
  108046. }
  108047. /*
  108048. ** Return true if the DISTINCT expression-list passed as the third argument
  108049. ** is redundant.
  108050. **
  108051. ** A DISTINCT list is redundant if the database contains some subset of
  108052. ** columns that are unique and non-null.
  108053. */
  108054. static int isDistinctRedundant(
  108055. Parse *pParse, /* Parsing context */
  108056. SrcList *pTabList, /* The FROM clause */
  108057. WhereClause *pWC, /* The WHERE clause */
  108058. ExprList *pDistinct /* The result set that needs to be DISTINCT */
  108059. ){
  108060. Table *pTab;
  108061. Index *pIdx;
  108062. int i;
  108063. int iBase;
  108064. /* If there is more than one table or sub-select in the FROM clause of
  108065. ** this query, then it will not be possible to show that the DISTINCT
  108066. ** clause is redundant. */
  108067. if( pTabList->nSrc!=1 ) return 0;
  108068. iBase = pTabList->a[0].iCursor;
  108069. pTab = pTabList->a[0].pTab;
  108070. /* If any of the expressions is an IPK column on table iBase, then return
  108071. ** true. Note: The (p->iTable==iBase) part of this test may be false if the
  108072. ** current SELECT is a correlated sub-query.
  108073. */
  108074. for(i=0; i<pDistinct->nExpr; i++){
  108075. Expr *p = sqlite3ExprSkipCollate(pDistinct->a[i].pExpr);
  108076. if( p->op==TK_COLUMN && p->iTable==iBase && p->iColumn<0 ) return 1;
  108077. }
  108078. /* Loop through all indices on the table, checking each to see if it makes
  108079. ** the DISTINCT qualifier redundant. It does so if:
  108080. **
  108081. ** 1. The index is itself UNIQUE, and
  108082. **
  108083. ** 2. All of the columns in the index are either part of the pDistinct
  108084. ** list, or else the WHERE clause contains a term of the form "col=X",
  108085. ** where X is a constant value. The collation sequences of the
  108086. ** comparison and select-list expressions must match those of the index.
  108087. **
  108088. ** 3. All of those index columns for which the WHERE clause does not
  108089. ** contain a "col=X" term are subject to a NOT NULL constraint.
  108090. */
  108091. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  108092. if( !IsUniqueIndex(pIdx) ) continue;
  108093. for(i=0; i<pIdx->nKeyCol; i++){
  108094. i16 iCol = pIdx->aiColumn[i];
  108095. if( 0==findTerm(pWC, iBase, iCol, ~(Bitmask)0, WO_EQ, pIdx) ){
  108096. int iIdxCol = findIndexCol(pParse, pDistinct, iBase, pIdx, i);
  108097. if( iIdxCol<0 || pTab->aCol[iCol].notNull==0 ){
  108098. break;
  108099. }
  108100. }
  108101. }
  108102. if( i==pIdx->nKeyCol ){
  108103. /* This index implies that the DISTINCT qualifier is redundant. */
  108104. return 1;
  108105. }
  108106. }
  108107. return 0;
  108108. }
  108109. /*
  108110. ** Estimate the logarithm of the input value to base 2.
  108111. */
  108112. static LogEst estLog(LogEst N){
  108113. return N<=10 ? 0 : sqlite3LogEst(N) - 33;
  108114. }
  108115. /*
  108116. ** Two routines for printing the content of an sqlite3_index_info
  108117. ** structure. Used for testing and debugging only. If neither
  108118. ** SQLITE_TEST or SQLITE_DEBUG are defined, then these routines
  108119. ** are no-ops.
  108120. */
  108121. #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(WHERETRACE_ENABLED)
  108122. static void TRACE_IDX_INPUTS(sqlite3_index_info *p){
  108123. int i;
  108124. if( !sqlite3WhereTrace ) return;
  108125. for(i=0; i<p->nConstraint; i++){
  108126. sqlite3DebugPrintf(" constraint[%d]: col=%d termid=%d op=%d usabled=%d\n",
  108127. i,
  108128. p->aConstraint[i].iColumn,
  108129. p->aConstraint[i].iTermOffset,
  108130. p->aConstraint[i].op,
  108131. p->aConstraint[i].usable);
  108132. }
  108133. for(i=0; i<p->nOrderBy; i++){
  108134. sqlite3DebugPrintf(" orderby[%d]: col=%d desc=%d\n",
  108135. i,
  108136. p->aOrderBy[i].iColumn,
  108137. p->aOrderBy[i].desc);
  108138. }
  108139. }
  108140. static void TRACE_IDX_OUTPUTS(sqlite3_index_info *p){
  108141. int i;
  108142. if( !sqlite3WhereTrace ) return;
  108143. for(i=0; i<p->nConstraint; i++){
  108144. sqlite3DebugPrintf(" usage[%d]: argvIdx=%d omit=%d\n",
  108145. i,
  108146. p->aConstraintUsage[i].argvIndex,
  108147. p->aConstraintUsage[i].omit);
  108148. }
  108149. sqlite3DebugPrintf(" idxNum=%d\n", p->idxNum);
  108150. sqlite3DebugPrintf(" idxStr=%s\n", p->idxStr);
  108151. sqlite3DebugPrintf(" orderByConsumed=%d\n", p->orderByConsumed);
  108152. sqlite3DebugPrintf(" estimatedCost=%g\n", p->estimatedCost);
  108153. sqlite3DebugPrintf(" estimatedRows=%lld\n", p->estimatedRows);
  108154. }
  108155. #else
  108156. #define TRACE_IDX_INPUTS(A)
  108157. #define TRACE_IDX_OUTPUTS(A)
  108158. #endif
  108159. #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
  108160. /*
  108161. ** Return TRUE if the WHERE clause term pTerm is of a form where it
  108162. ** could be used with an index to access pSrc, assuming an appropriate
  108163. ** index existed.
  108164. */
  108165. static int termCanDriveIndex(
  108166. WhereTerm *pTerm, /* WHERE clause term to check */
  108167. struct SrcList_item *pSrc, /* Table we are trying to access */
  108168. Bitmask notReady /* Tables in outer loops of the join */
  108169. ){
  108170. char aff;
  108171. if( pTerm->leftCursor!=pSrc->iCursor ) return 0;
  108172. if( (pTerm->eOperator & WO_EQ)==0 ) return 0;
  108173. if( (pTerm->prereqRight & notReady)!=0 ) return 0;
  108174. if( pTerm->u.leftColumn<0 ) return 0;
  108175. aff = pSrc->pTab->aCol[pTerm->u.leftColumn].affinity;
  108176. if( !sqlite3IndexAffinityOk(pTerm->pExpr, aff) ) return 0;
  108177. return 1;
  108178. }
  108179. #endif
  108180. #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
  108181. /*
  108182. ** Generate code to construct the Index object for an automatic index
  108183. ** and to set up the WhereLevel object pLevel so that the code generator
  108184. ** makes use of the automatic index.
  108185. */
  108186. static void constructAutomaticIndex(
  108187. Parse *pParse, /* The parsing context */
  108188. WhereClause *pWC, /* The WHERE clause */
  108189. struct SrcList_item *pSrc, /* The FROM clause term to get the next index */
  108190. Bitmask notReady, /* Mask of cursors that are not available */
  108191. WhereLevel *pLevel /* Write new index here */
  108192. ){
  108193. int nKeyCol; /* Number of columns in the constructed index */
  108194. WhereTerm *pTerm; /* A single term of the WHERE clause */
  108195. WhereTerm *pWCEnd; /* End of pWC->a[] */
  108196. Index *pIdx; /* Object describing the transient index */
  108197. Vdbe *v; /* Prepared statement under construction */
  108198. int addrInit; /* Address of the initialization bypass jump */
  108199. Table *pTable; /* The table being indexed */
  108200. int addrTop; /* Top of the index fill loop */
  108201. int regRecord; /* Register holding an index record */
  108202. int n; /* Column counter */
  108203. int i; /* Loop counter */
  108204. int mxBitCol; /* Maximum column in pSrc->colUsed */
  108205. CollSeq *pColl; /* Collating sequence to on a column */
  108206. WhereLoop *pLoop; /* The Loop object */
  108207. char *zNotUsed; /* Extra space on the end of pIdx */
  108208. Bitmask idxCols; /* Bitmap of columns used for indexing */
  108209. Bitmask extraCols; /* Bitmap of additional columns */
  108210. u8 sentWarning = 0; /* True if a warnning has been issued */
  108211. Expr *pPartial = 0; /* Partial Index Expression */
  108212. int iContinue = 0; /* Jump here to skip excluded rows */
  108213. /* Generate code to skip over the creation and initialization of the
  108214. ** transient index on 2nd and subsequent iterations of the loop. */
  108215. v = pParse->pVdbe;
  108216. assert( v!=0 );
  108217. addrInit = sqlite3CodeOnce(pParse); VdbeCoverage(v);
  108218. /* Count the number of columns that will be added to the index
  108219. ** and used to match WHERE clause constraints */
  108220. nKeyCol = 0;
  108221. pTable = pSrc->pTab;
  108222. pWCEnd = &pWC->a[pWC->nTerm];
  108223. pLoop = pLevel->pWLoop;
  108224. idxCols = 0;
  108225. for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
  108226. if( pLoop->prereq==0
  108227. && (pTerm->wtFlags & TERM_VIRTUAL)==0
  108228. && sqlite3ExprIsTableConstant(pTerm->pExpr, pSrc->iCursor) ){
  108229. pPartial = sqlite3ExprAnd(pParse->db, pPartial,
  108230. sqlite3ExprDup(pParse->db, pTerm->pExpr, 0));
  108231. }
  108232. if( termCanDriveIndex(pTerm, pSrc, notReady) ){
  108233. int iCol = pTerm->u.leftColumn;
  108234. Bitmask cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol);
  108235. testcase( iCol==BMS );
  108236. testcase( iCol==BMS-1 );
  108237. if( !sentWarning ){
  108238. sqlite3_log(SQLITE_WARNING_AUTOINDEX,
  108239. "automatic index on %s(%s)", pTable->zName,
  108240. pTable->aCol[iCol].zName);
  108241. sentWarning = 1;
  108242. }
  108243. if( (idxCols & cMask)==0 ){
  108244. if( whereLoopResize(pParse->db, pLoop, nKeyCol+1) ){
  108245. goto end_auto_index_create;
  108246. }
  108247. pLoop->aLTerm[nKeyCol++] = pTerm;
  108248. idxCols |= cMask;
  108249. }
  108250. }
  108251. }
  108252. assert( nKeyCol>0 );
  108253. pLoop->u.btree.nEq = pLoop->nLTerm = nKeyCol;
  108254. pLoop->wsFlags = WHERE_COLUMN_EQ | WHERE_IDX_ONLY | WHERE_INDEXED
  108255. | WHERE_AUTO_INDEX;
  108256. /* Count the number of additional columns needed to create a
  108257. ** covering index. A "covering index" is an index that contains all
  108258. ** columns that are needed by the query. With a covering index, the
  108259. ** original table never needs to be accessed. Automatic indices must
  108260. ** be a covering index because the index will not be updated if the
  108261. ** original table changes and the index and table cannot both be used
  108262. ** if they go out of sync.
  108263. */
  108264. extraCols = pSrc->colUsed & (~idxCols | MASKBIT(BMS-1));
  108265. mxBitCol = (pTable->nCol >= BMS-1) ? BMS-1 : pTable->nCol;
  108266. testcase( pTable->nCol==BMS-1 );
  108267. testcase( pTable->nCol==BMS-2 );
  108268. for(i=0; i<mxBitCol; i++){
  108269. if( extraCols & MASKBIT(i) ) nKeyCol++;
  108270. }
  108271. if( pSrc->colUsed & MASKBIT(BMS-1) ){
  108272. nKeyCol += pTable->nCol - BMS + 1;
  108273. }
  108274. pLoop->wsFlags |= WHERE_COLUMN_EQ | WHERE_IDX_ONLY;
  108275. /* Construct the Index object to describe this index */
  108276. pIdx = sqlite3AllocateIndexObject(pParse->db, nKeyCol+1, 0, &zNotUsed);
  108277. if( pIdx==0 ) goto end_auto_index_create;
  108278. pLoop->u.btree.pIndex = pIdx;
  108279. pIdx->zName = "auto-index";
  108280. pIdx->pTable = pTable;
  108281. n = 0;
  108282. idxCols = 0;
  108283. for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
  108284. if( termCanDriveIndex(pTerm, pSrc, notReady) ){
  108285. int iCol = pTerm->u.leftColumn;
  108286. Bitmask cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol);
  108287. testcase( iCol==BMS-1 );
  108288. testcase( iCol==BMS );
  108289. if( (idxCols & cMask)==0 ){
  108290. Expr *pX = pTerm->pExpr;
  108291. idxCols |= cMask;
  108292. pIdx->aiColumn[n] = pTerm->u.leftColumn;
  108293. pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
  108294. pIdx->azColl[n] = ALWAYS(pColl) ? pColl->zName : "BINARY";
  108295. n++;
  108296. }
  108297. }
  108298. }
  108299. assert( (u32)n==pLoop->u.btree.nEq );
  108300. /* Add additional columns needed to make the automatic index into
  108301. ** a covering index */
  108302. for(i=0; i<mxBitCol; i++){
  108303. if( extraCols & MASKBIT(i) ){
  108304. pIdx->aiColumn[n] = i;
  108305. pIdx->azColl[n] = "BINARY";
  108306. n++;
  108307. }
  108308. }
  108309. if( pSrc->colUsed & MASKBIT(BMS-1) ){
  108310. for(i=BMS-1; i<pTable->nCol; i++){
  108311. pIdx->aiColumn[n] = i;
  108312. pIdx->azColl[n] = "BINARY";
  108313. n++;
  108314. }
  108315. }
  108316. assert( n==nKeyCol );
  108317. pIdx->aiColumn[n] = -1;
  108318. pIdx->azColl[n] = "BINARY";
  108319. /* Create the automatic index */
  108320. assert( pLevel->iIdxCur>=0 );
  108321. pLevel->iIdxCur = pParse->nTab++;
  108322. sqlite3VdbeAddOp2(v, OP_OpenAutoindex, pLevel->iIdxCur, nKeyCol+1);
  108323. sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
  108324. VdbeComment((v, "for %s", pTable->zName));
  108325. /* Fill the automatic index with content */
  108326. sqlite3ExprCachePush(pParse);
  108327. addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, pLevel->iTabCur); VdbeCoverage(v);
  108328. if( pPartial ){
  108329. iContinue = sqlite3VdbeMakeLabel(v);
  108330. sqlite3ExprIfFalse(pParse, pPartial, iContinue, SQLITE_JUMPIFNULL);
  108331. pLoop->wsFlags |= WHERE_PARTIALIDX;
  108332. }
  108333. regRecord = sqlite3GetTempReg(pParse);
  108334. sqlite3GenerateIndexKey(pParse, pIdx, pLevel->iTabCur, regRecord, 0, 0, 0, 0);
  108335. sqlite3VdbeAddOp2(v, OP_IdxInsert, pLevel->iIdxCur, regRecord);
  108336. sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
  108337. if( pPartial ) sqlite3VdbeResolveLabel(v, iContinue);
  108338. sqlite3VdbeAddOp2(v, OP_Next, pLevel->iTabCur, addrTop+1); VdbeCoverage(v);
  108339. sqlite3VdbeChangeP5(v, SQLITE_STMTSTATUS_AUTOINDEX);
  108340. sqlite3VdbeJumpHere(v, addrTop);
  108341. sqlite3ReleaseTempReg(pParse, regRecord);
  108342. sqlite3ExprCachePop(pParse);
  108343. /* Jump here when skipping the initialization */
  108344. sqlite3VdbeJumpHere(v, addrInit);
  108345. end_auto_index_create:
  108346. sqlite3ExprDelete(pParse->db, pPartial);
  108347. }
  108348. #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
  108349. #ifndef SQLITE_OMIT_VIRTUALTABLE
  108350. /*
  108351. ** Allocate and populate an sqlite3_index_info structure. It is the
  108352. ** responsibility of the caller to eventually release the structure
  108353. ** by passing the pointer returned by this function to sqlite3_free().
  108354. */
  108355. static sqlite3_index_info *allocateIndexInfo(
  108356. Parse *pParse,
  108357. WhereClause *pWC,
  108358. struct SrcList_item *pSrc,
  108359. ExprList *pOrderBy
  108360. ){
  108361. int i, j;
  108362. int nTerm;
  108363. struct sqlite3_index_constraint *pIdxCons;
  108364. struct sqlite3_index_orderby *pIdxOrderBy;
  108365. struct sqlite3_index_constraint_usage *pUsage;
  108366. WhereTerm *pTerm;
  108367. int nOrderBy;
  108368. sqlite3_index_info *pIdxInfo;
  108369. /* Count the number of possible WHERE clause constraints referring
  108370. ** to this virtual table */
  108371. for(i=nTerm=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
  108372. if( pTerm->leftCursor != pSrc->iCursor ) continue;
  108373. assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );
  108374. testcase( pTerm->eOperator & WO_IN );
  108375. testcase( pTerm->eOperator & WO_ISNULL );
  108376. testcase( pTerm->eOperator & WO_ALL );
  108377. if( (pTerm->eOperator & ~(WO_ISNULL|WO_EQUIV))==0 ) continue;
  108378. if( pTerm->wtFlags & TERM_VNULL ) continue;
  108379. nTerm++;
  108380. }
  108381. /* If the ORDER BY clause contains only columns in the current
  108382. ** virtual table then allocate space for the aOrderBy part of
  108383. ** the sqlite3_index_info structure.
  108384. */
  108385. nOrderBy = 0;
  108386. if( pOrderBy ){
  108387. int n = pOrderBy->nExpr;
  108388. for(i=0; i<n; i++){
  108389. Expr *pExpr = pOrderBy->a[i].pExpr;
  108390. if( pExpr->op!=TK_COLUMN || pExpr->iTable!=pSrc->iCursor ) break;
  108391. }
  108392. if( i==n){
  108393. nOrderBy = n;
  108394. }
  108395. }
  108396. /* Allocate the sqlite3_index_info structure
  108397. */
  108398. pIdxInfo = sqlite3DbMallocZero(pParse->db, sizeof(*pIdxInfo)
  108399. + (sizeof(*pIdxCons) + sizeof(*pUsage))*nTerm
  108400. + sizeof(*pIdxOrderBy)*nOrderBy );
  108401. if( pIdxInfo==0 ){
  108402. sqlite3ErrorMsg(pParse, "out of memory");
  108403. return 0;
  108404. }
  108405. /* Initialize the structure. The sqlite3_index_info structure contains
  108406. ** many fields that are declared "const" to prevent xBestIndex from
  108407. ** changing them. We have to do some funky casting in order to
  108408. ** initialize those fields.
  108409. */
  108410. pIdxCons = (struct sqlite3_index_constraint*)&pIdxInfo[1];
  108411. pIdxOrderBy = (struct sqlite3_index_orderby*)&pIdxCons[nTerm];
  108412. pUsage = (struct sqlite3_index_constraint_usage*)&pIdxOrderBy[nOrderBy];
  108413. *(int*)&pIdxInfo->nConstraint = nTerm;
  108414. *(int*)&pIdxInfo->nOrderBy = nOrderBy;
  108415. *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint = pIdxCons;
  108416. *(struct sqlite3_index_orderby**)&pIdxInfo->aOrderBy = pIdxOrderBy;
  108417. *(struct sqlite3_index_constraint_usage**)&pIdxInfo->aConstraintUsage =
  108418. pUsage;
  108419. for(i=j=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
  108420. u8 op;
  108421. if( pTerm->leftCursor != pSrc->iCursor ) continue;
  108422. assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );
  108423. testcase( pTerm->eOperator & WO_IN );
  108424. testcase( pTerm->eOperator & WO_ISNULL );
  108425. testcase( pTerm->eOperator & WO_ALL );
  108426. if( (pTerm->eOperator & ~(WO_ISNULL|WO_EQUIV))==0 ) continue;
  108427. if( pTerm->wtFlags & TERM_VNULL ) continue;
  108428. pIdxCons[j].iColumn = pTerm->u.leftColumn;
  108429. pIdxCons[j].iTermOffset = i;
  108430. op = (u8)pTerm->eOperator & WO_ALL;
  108431. if( op==WO_IN ) op = WO_EQ;
  108432. pIdxCons[j].op = op;
  108433. /* The direct assignment in the previous line is possible only because
  108434. ** the WO_ and SQLITE_INDEX_CONSTRAINT_ codes are identical. The
  108435. ** following asserts verify this fact. */
  108436. assert( WO_EQ==SQLITE_INDEX_CONSTRAINT_EQ );
  108437. assert( WO_LT==SQLITE_INDEX_CONSTRAINT_LT );
  108438. assert( WO_LE==SQLITE_INDEX_CONSTRAINT_LE );
  108439. assert( WO_GT==SQLITE_INDEX_CONSTRAINT_GT );
  108440. assert( WO_GE==SQLITE_INDEX_CONSTRAINT_GE );
  108441. assert( WO_MATCH==SQLITE_INDEX_CONSTRAINT_MATCH );
  108442. assert( pTerm->eOperator & (WO_IN|WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE|WO_MATCH) );
  108443. j++;
  108444. }
  108445. for(i=0; i<nOrderBy; i++){
  108446. Expr *pExpr = pOrderBy->a[i].pExpr;
  108447. pIdxOrderBy[i].iColumn = pExpr->iColumn;
  108448. pIdxOrderBy[i].desc = pOrderBy->a[i].sortOrder;
  108449. }
  108450. return pIdxInfo;
  108451. }
  108452. /*
  108453. ** The table object reference passed as the second argument to this function
  108454. ** must represent a virtual table. This function invokes the xBestIndex()
  108455. ** method of the virtual table with the sqlite3_index_info object that
  108456. ** comes in as the 3rd argument to this function.
  108457. **
  108458. ** If an error occurs, pParse is populated with an error message and a
  108459. ** non-zero value is returned. Otherwise, 0 is returned and the output
  108460. ** part of the sqlite3_index_info structure is left populated.
  108461. **
  108462. ** Whether or not an error is returned, it is the responsibility of the
  108463. ** caller to eventually free p->idxStr if p->needToFreeIdxStr indicates
  108464. ** that this is required.
  108465. */
  108466. static int vtabBestIndex(Parse *pParse, Table *pTab, sqlite3_index_info *p){
  108467. sqlite3_vtab *pVtab = sqlite3GetVTable(pParse->db, pTab)->pVtab;
  108468. int i;
  108469. int rc;
  108470. TRACE_IDX_INPUTS(p);
  108471. rc = pVtab->pModule->xBestIndex(pVtab, p);
  108472. TRACE_IDX_OUTPUTS(p);
  108473. if( rc!=SQLITE_OK ){
  108474. if( rc==SQLITE_NOMEM ){
  108475. pParse->db->mallocFailed = 1;
  108476. }else if( !pVtab->zErrMsg ){
  108477. sqlite3ErrorMsg(pParse, "%s", sqlite3ErrStr(rc));
  108478. }else{
  108479. sqlite3ErrorMsg(pParse, "%s", pVtab->zErrMsg);
  108480. }
  108481. }
  108482. sqlite3_free(pVtab->zErrMsg);
  108483. pVtab->zErrMsg = 0;
  108484. for(i=0; i<p->nConstraint; i++){
  108485. if( !p->aConstraint[i].usable && p->aConstraintUsage[i].argvIndex>0 ){
  108486. sqlite3ErrorMsg(pParse,
  108487. "table %s: xBestIndex returned an invalid plan", pTab->zName);
  108488. }
  108489. }
  108490. return pParse->nErr;
  108491. }
  108492. #endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) */
  108493. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  108494. /*
  108495. ** Estimate the location of a particular key among all keys in an
  108496. ** index. Store the results in aStat as follows:
  108497. **
  108498. ** aStat[0] Est. number of rows less than pVal
  108499. ** aStat[1] Est. number of rows equal to pVal
  108500. **
  108501. ** Return SQLITE_OK on success.
  108502. */
  108503. static void whereKeyStats(
  108504. Parse *pParse, /* Database connection */
  108505. Index *pIdx, /* Index to consider domain of */
  108506. UnpackedRecord *pRec, /* Vector of values to consider */
  108507. int roundUp, /* Round up if true. Round down if false */
  108508. tRowcnt *aStat /* OUT: stats written here */
  108509. ){
  108510. IndexSample *aSample = pIdx->aSample;
  108511. int iCol; /* Index of required stats in anEq[] etc. */
  108512. int iMin = 0; /* Smallest sample not yet tested */
  108513. int i = pIdx->nSample; /* Smallest sample larger than or equal to pRec */
  108514. int iTest; /* Next sample to test */
  108515. int res; /* Result of comparison operation */
  108516. #ifndef SQLITE_DEBUG
  108517. UNUSED_PARAMETER( pParse );
  108518. #endif
  108519. assert( pRec!=0 );
  108520. iCol = pRec->nField - 1;
  108521. assert( pIdx->nSample>0 );
  108522. assert( pRec->nField>0 && iCol<pIdx->nSampleCol );
  108523. do{
  108524. iTest = (iMin+i)/2;
  108525. res = sqlite3VdbeRecordCompare(aSample[iTest].n, aSample[iTest].p, pRec);
  108526. if( res<0 ){
  108527. iMin = iTest+1;
  108528. }else{
  108529. i = iTest;
  108530. }
  108531. }while( res && iMin<i );
  108532. #ifdef SQLITE_DEBUG
  108533. /* The following assert statements check that the binary search code
  108534. ** above found the right answer. This block serves no purpose other
  108535. ** than to invoke the asserts. */
  108536. if( res==0 ){
  108537. /* If (res==0) is true, then sample $i must be equal to pRec */
  108538. assert( i<pIdx->nSample );
  108539. assert( 0==sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)
  108540. || pParse->db->mallocFailed );
  108541. }else{
  108542. /* Otherwise, pRec must be smaller than sample $i and larger than
  108543. ** sample ($i-1). */
  108544. assert( i==pIdx->nSample
  108545. || sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)>0
  108546. || pParse->db->mallocFailed );
  108547. assert( i==0
  108548. || sqlite3VdbeRecordCompare(aSample[i-1].n, aSample[i-1].p, pRec)<0
  108549. || pParse->db->mallocFailed );
  108550. }
  108551. #endif /* ifdef SQLITE_DEBUG */
  108552. /* At this point, aSample[i] is the first sample that is greater than
  108553. ** or equal to pVal. Or if i==pIdx->nSample, then all samples are less
  108554. ** than pVal. If aSample[i]==pVal, then res==0.
  108555. */
  108556. if( res==0 ){
  108557. aStat[0] = aSample[i].anLt[iCol];
  108558. aStat[1] = aSample[i].anEq[iCol];
  108559. }else{
  108560. tRowcnt iLower, iUpper, iGap;
  108561. if( i==0 ){
  108562. iLower = 0;
  108563. iUpper = aSample[0].anLt[iCol];
  108564. }else{
  108565. i64 nRow0 = sqlite3LogEstToInt(pIdx->aiRowLogEst[0]);
  108566. iUpper = i>=pIdx->nSample ? nRow0 : aSample[i].anLt[iCol];
  108567. iLower = aSample[i-1].anEq[iCol] + aSample[i-1].anLt[iCol];
  108568. }
  108569. aStat[1] = pIdx->aAvgEq[iCol];
  108570. if( iLower>=iUpper ){
  108571. iGap = 0;
  108572. }else{
  108573. iGap = iUpper - iLower;
  108574. }
  108575. if( roundUp ){
  108576. iGap = (iGap*2)/3;
  108577. }else{
  108578. iGap = iGap/3;
  108579. }
  108580. aStat[0] = iLower + iGap;
  108581. }
  108582. }
  108583. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  108584. /*
  108585. ** If it is not NULL, pTerm is a term that provides an upper or lower
  108586. ** bound on a range scan. Without considering pTerm, it is estimated
  108587. ** that the scan will visit nNew rows. This function returns the number
  108588. ** estimated to be visited after taking pTerm into account.
  108589. **
  108590. ** If the user explicitly specified a likelihood() value for this term,
  108591. ** then the return value is the likelihood multiplied by the number of
  108592. ** input rows. Otherwise, this function assumes that an "IS NOT NULL" term
  108593. ** has a likelihood of 0.50, and any other term a likelihood of 0.25.
  108594. */
  108595. static LogEst whereRangeAdjust(WhereTerm *pTerm, LogEst nNew){
  108596. LogEst nRet = nNew;
  108597. if( pTerm ){
  108598. if( pTerm->truthProb<=0 ){
  108599. nRet += pTerm->truthProb;
  108600. }else if( (pTerm->wtFlags & TERM_VNULL)==0 ){
  108601. nRet -= 20; assert( 20==sqlite3LogEst(4) );
  108602. }
  108603. }
  108604. return nRet;
  108605. }
  108606. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  108607. /*
  108608. ** This function is called to estimate the number of rows visited by a
  108609. ** range-scan on a skip-scan index. For example:
  108610. **
  108611. ** CREATE INDEX i1 ON t1(a, b, c);
  108612. ** SELECT * FROM t1 WHERE a=? AND c BETWEEN ? AND ?;
  108613. **
  108614. ** Value pLoop->nOut is currently set to the estimated number of rows
  108615. ** visited for scanning (a=? AND b=?). This function reduces that estimate
  108616. ** by some factor to account for the (c BETWEEN ? AND ?) expression based
  108617. ** on the stat4 data for the index. this scan will be peformed multiple
  108618. ** times (once for each (a,b) combination that matches a=?) is dealt with
  108619. ** by the caller.
  108620. **
  108621. ** It does this by scanning through all stat4 samples, comparing values
  108622. ** extracted from pLower and pUpper with the corresponding column in each
  108623. ** sample. If L and U are the number of samples found to be less than or
  108624. ** equal to the values extracted from pLower and pUpper respectively, and
  108625. ** N is the total number of samples, the pLoop->nOut value is adjusted
  108626. ** as follows:
  108627. **
  108628. ** nOut = nOut * ( min(U - L, 1) / N )
  108629. **
  108630. ** If pLower is NULL, or a value cannot be extracted from the term, L is
  108631. ** set to zero. If pUpper is NULL, or a value cannot be extracted from it,
  108632. ** U is set to N.
  108633. **
  108634. ** Normally, this function sets *pbDone to 1 before returning. However,
  108635. ** if no value can be extracted from either pLower or pUpper (and so the
  108636. ** estimate of the number of rows delivered remains unchanged), *pbDone
  108637. ** is left as is.
  108638. **
  108639. ** If an error occurs, an SQLite error code is returned. Otherwise,
  108640. ** SQLITE_OK.
  108641. */
  108642. static int whereRangeSkipScanEst(
  108643. Parse *pParse, /* Parsing & code generating context */
  108644. WhereTerm *pLower, /* Lower bound on the range. ex: "x>123" Might be NULL */
  108645. WhereTerm *pUpper, /* Upper bound on the range. ex: "x<455" Might be NULL */
  108646. WhereLoop *pLoop, /* Update the .nOut value of this loop */
  108647. int *pbDone /* Set to true if at least one expr. value extracted */
  108648. ){
  108649. Index *p = pLoop->u.btree.pIndex;
  108650. int nEq = pLoop->u.btree.nEq;
  108651. sqlite3 *db = pParse->db;
  108652. int nLower = -1;
  108653. int nUpper = p->nSample+1;
  108654. int rc = SQLITE_OK;
  108655. int iCol = p->aiColumn[nEq];
  108656. u8 aff = iCol>=0 ? p->pTable->aCol[iCol].affinity : SQLITE_AFF_INTEGER;
  108657. CollSeq *pColl;
  108658. sqlite3_value *p1 = 0; /* Value extracted from pLower */
  108659. sqlite3_value *p2 = 0; /* Value extracted from pUpper */
  108660. sqlite3_value *pVal = 0; /* Value extracted from record */
  108661. pColl = sqlite3LocateCollSeq(pParse, p->azColl[nEq]);
  108662. if( pLower ){
  108663. rc = sqlite3Stat4ValueFromExpr(pParse, pLower->pExpr->pRight, aff, &p1);
  108664. nLower = 0;
  108665. }
  108666. if( pUpper && rc==SQLITE_OK ){
  108667. rc = sqlite3Stat4ValueFromExpr(pParse, pUpper->pExpr->pRight, aff, &p2);
  108668. nUpper = p2 ? 0 : p->nSample;
  108669. }
  108670. if( p1 || p2 ){
  108671. int i;
  108672. int nDiff;
  108673. for(i=0; rc==SQLITE_OK && i<p->nSample; i++){
  108674. rc = sqlite3Stat4Column(db, p->aSample[i].p, p->aSample[i].n, nEq, &pVal);
  108675. if( rc==SQLITE_OK && p1 ){
  108676. int res = sqlite3MemCompare(p1, pVal, pColl);
  108677. if( res>=0 ) nLower++;
  108678. }
  108679. if( rc==SQLITE_OK && p2 ){
  108680. int res = sqlite3MemCompare(p2, pVal, pColl);
  108681. if( res>=0 ) nUpper++;
  108682. }
  108683. }
  108684. nDiff = (nUpper - nLower);
  108685. if( nDiff<=0 ) nDiff = 1;
  108686. /* If there is both an upper and lower bound specified, and the
  108687. ** comparisons indicate that they are close together, use the fallback
  108688. ** method (assume that the scan visits 1/64 of the rows) for estimating
  108689. ** the number of rows visited. Otherwise, estimate the number of rows
  108690. ** using the method described in the header comment for this function. */
  108691. if( nDiff!=1 || pUpper==0 || pLower==0 ){
  108692. int nAdjust = (sqlite3LogEst(p->nSample) - sqlite3LogEst(nDiff));
  108693. pLoop->nOut -= nAdjust;
  108694. *pbDone = 1;
  108695. WHERETRACE(0x10, ("range skip-scan regions: %u..%u adjust=%d est=%d\n",
  108696. nLower, nUpper, nAdjust*-1, pLoop->nOut));
  108697. }
  108698. }else{
  108699. assert( *pbDone==0 );
  108700. }
  108701. sqlite3ValueFree(p1);
  108702. sqlite3ValueFree(p2);
  108703. sqlite3ValueFree(pVal);
  108704. return rc;
  108705. }
  108706. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  108707. /*
  108708. ** This function is used to estimate the number of rows that will be visited
  108709. ** by scanning an index for a range of values. The range may have an upper
  108710. ** bound, a lower bound, or both. The WHERE clause terms that set the upper
  108711. ** and lower bounds are represented by pLower and pUpper respectively. For
  108712. ** example, assuming that index p is on t1(a):
  108713. **
  108714. ** ... FROM t1 WHERE a > ? AND a < ? ...
  108715. ** |_____| |_____|
  108716. ** | |
  108717. ** pLower pUpper
  108718. **
  108719. ** If either of the upper or lower bound is not present, then NULL is passed in
  108720. ** place of the corresponding WhereTerm.
  108721. **
  108722. ** The value in (pBuilder->pNew->u.btree.nEq) is the index of the index
  108723. ** column subject to the range constraint. Or, equivalently, the number of
  108724. ** equality constraints optimized by the proposed index scan. For example,
  108725. ** assuming index p is on t1(a, b), and the SQL query is:
  108726. **
  108727. ** ... FROM t1 WHERE a = ? AND b > ? AND b < ? ...
  108728. **
  108729. ** then nEq is set to 1 (as the range restricted column, b, is the second
  108730. ** left-most column of the index). Or, if the query is:
  108731. **
  108732. ** ... FROM t1 WHERE a > ? AND a < ? ...
  108733. **
  108734. ** then nEq is set to 0.
  108735. **
  108736. ** When this function is called, *pnOut is set to the sqlite3LogEst() of the
  108737. ** number of rows that the index scan is expected to visit without
  108738. ** considering the range constraints. If nEq is 0, this is the number of
  108739. ** rows in the index. Assuming no error occurs, *pnOut is adjusted (reduced)
  108740. ** to account for the range constraints pLower and pUpper.
  108741. **
  108742. ** In the absence of sqlite_stat4 ANALYZE data, or if such data cannot be
  108743. ** used, a single range inequality reduces the search space by a factor of 4.
  108744. ** and a pair of constraints (x>? AND x<?) reduces the expected number of
  108745. ** rows visited by a factor of 64.
  108746. */
  108747. static int whereRangeScanEst(
  108748. Parse *pParse, /* Parsing & code generating context */
  108749. WhereLoopBuilder *pBuilder,
  108750. WhereTerm *pLower, /* Lower bound on the range. ex: "x>123" Might be NULL */
  108751. WhereTerm *pUpper, /* Upper bound on the range. ex: "x<455" Might be NULL */
  108752. WhereLoop *pLoop /* Modify the .nOut and maybe .rRun fields */
  108753. ){
  108754. int rc = SQLITE_OK;
  108755. int nOut = pLoop->nOut;
  108756. LogEst nNew;
  108757. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  108758. Index *p = pLoop->u.btree.pIndex;
  108759. int nEq = pLoop->u.btree.nEq;
  108760. if( p->nSample>0
  108761. && nEq<p->nSampleCol
  108762. ){
  108763. if( nEq==pBuilder->nRecValid ){
  108764. UnpackedRecord *pRec = pBuilder->pRec;
  108765. tRowcnt a[2];
  108766. u8 aff;
  108767. /* Variable iLower will be set to the estimate of the number of rows in
  108768. ** the index that are less than the lower bound of the range query. The
  108769. ** lower bound being the concatenation of $P and $L, where $P is the
  108770. ** key-prefix formed by the nEq values matched against the nEq left-most
  108771. ** columns of the index, and $L is the value in pLower.
  108772. **
  108773. ** Or, if pLower is NULL or $L cannot be extracted from it (because it
  108774. ** is not a simple variable or literal value), the lower bound of the
  108775. ** range is $P. Due to a quirk in the way whereKeyStats() works, even
  108776. ** if $L is available, whereKeyStats() is called for both ($P) and
  108777. ** ($P:$L) and the larger of the two returned values used.
  108778. **
  108779. ** Similarly, iUpper is to be set to the estimate of the number of rows
  108780. ** less than the upper bound of the range query. Where the upper bound
  108781. ** is either ($P) or ($P:$U). Again, even if $U is available, both values
  108782. ** of iUpper are requested of whereKeyStats() and the smaller used.
  108783. */
  108784. tRowcnt iLower;
  108785. tRowcnt iUpper;
  108786. if( pRec ){
  108787. testcase( pRec->nField!=pBuilder->nRecValid );
  108788. pRec->nField = pBuilder->nRecValid;
  108789. }
  108790. if( nEq==p->nKeyCol ){
  108791. aff = SQLITE_AFF_INTEGER;
  108792. }else{
  108793. aff = p->pTable->aCol[p->aiColumn[nEq]].affinity;
  108794. }
  108795. /* Determine iLower and iUpper using ($P) only. */
  108796. if( nEq==0 ){
  108797. iLower = 0;
  108798. iUpper = p->nRowEst0;
  108799. }else{
  108800. /* Note: this call could be optimized away - since the same values must
  108801. ** have been requested when testing key $P in whereEqualScanEst(). */
  108802. whereKeyStats(pParse, p, pRec, 0, a);
  108803. iLower = a[0];
  108804. iUpper = a[0] + a[1];
  108805. }
  108806. assert( pLower==0 || (pLower->eOperator & (WO_GT|WO_GE))!=0 );
  108807. assert( pUpper==0 || (pUpper->eOperator & (WO_LT|WO_LE))!=0 );
  108808. assert( p->aSortOrder!=0 );
  108809. if( p->aSortOrder[nEq] ){
  108810. /* The roles of pLower and pUpper are swapped for a DESC index */
  108811. SWAP(WhereTerm*, pLower, pUpper);
  108812. }
  108813. /* If possible, improve on the iLower estimate using ($P:$L). */
  108814. if( pLower ){
  108815. int bOk; /* True if value is extracted from pExpr */
  108816. Expr *pExpr = pLower->pExpr->pRight;
  108817. rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, aff, nEq, &bOk);
  108818. if( rc==SQLITE_OK && bOk ){
  108819. tRowcnt iNew;
  108820. whereKeyStats(pParse, p, pRec, 0, a);
  108821. iNew = a[0] + ((pLower->eOperator & (WO_GT|WO_LE)) ? a[1] : 0);
  108822. if( iNew>iLower ) iLower = iNew;
  108823. nOut--;
  108824. pLower = 0;
  108825. }
  108826. }
  108827. /* If possible, improve on the iUpper estimate using ($P:$U). */
  108828. if( pUpper ){
  108829. int bOk; /* True if value is extracted from pExpr */
  108830. Expr *pExpr = pUpper->pExpr->pRight;
  108831. rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, aff, nEq, &bOk);
  108832. if( rc==SQLITE_OK && bOk ){
  108833. tRowcnt iNew;
  108834. whereKeyStats(pParse, p, pRec, 1, a);
  108835. iNew = a[0] + ((pUpper->eOperator & (WO_GT|WO_LE)) ? a[1] : 0);
  108836. if( iNew<iUpper ) iUpper = iNew;
  108837. nOut--;
  108838. pUpper = 0;
  108839. }
  108840. }
  108841. pBuilder->pRec = pRec;
  108842. if( rc==SQLITE_OK ){
  108843. if( iUpper>iLower ){
  108844. nNew = sqlite3LogEst(iUpper - iLower);
  108845. }else{
  108846. nNew = 10; assert( 10==sqlite3LogEst(2) );
  108847. }
  108848. if( nNew<nOut ){
  108849. nOut = nNew;
  108850. }
  108851. WHERETRACE(0x10, ("STAT4 range scan: %u..%u est=%d\n",
  108852. (u32)iLower, (u32)iUpper, nOut));
  108853. }
  108854. }else{
  108855. int bDone = 0;
  108856. rc = whereRangeSkipScanEst(pParse, pLower, pUpper, pLoop, &bDone);
  108857. if( bDone ) return rc;
  108858. }
  108859. }
  108860. #else
  108861. UNUSED_PARAMETER(pParse);
  108862. UNUSED_PARAMETER(pBuilder);
  108863. assert( pLower || pUpper );
  108864. #endif
  108865. assert( pUpper==0 || (pUpper->wtFlags & TERM_VNULL)==0 );
  108866. nNew = whereRangeAdjust(pLower, nOut);
  108867. nNew = whereRangeAdjust(pUpper, nNew);
  108868. /* TUNING: If there is both an upper and lower limit and neither limit
  108869. ** has an application-defined likelihood(), assume the range is
  108870. ** reduced by an additional 75%. This means that, by default, an open-ended
  108871. ** range query (e.g. col > ?) is assumed to match 1/4 of the rows in the
  108872. ** index. While a closed range (e.g. col BETWEEN ? AND ?) is estimated to
  108873. ** match 1/64 of the index. */
  108874. if( pLower && pLower->truthProb>0 && pUpper && pUpper->truthProb>0 ){
  108875. nNew -= 20;
  108876. }
  108877. nOut -= (pLower!=0) + (pUpper!=0);
  108878. if( nNew<10 ) nNew = 10;
  108879. if( nNew<nOut ) nOut = nNew;
  108880. #if defined(WHERETRACE_ENABLED)
  108881. if( pLoop->nOut>nOut ){
  108882. WHERETRACE(0x10,("Range scan lowers nOut from %d to %d\n",
  108883. pLoop->nOut, nOut));
  108884. }
  108885. #endif
  108886. pLoop->nOut = (LogEst)nOut;
  108887. return rc;
  108888. }
  108889. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  108890. /*
  108891. ** Estimate the number of rows that will be returned based on
  108892. ** an equality constraint x=VALUE and where that VALUE occurs in
  108893. ** the histogram data. This only works when x is the left-most
  108894. ** column of an index and sqlite_stat3 histogram data is available
  108895. ** for that index. When pExpr==NULL that means the constraint is
  108896. ** "x IS NULL" instead of "x=VALUE".
  108897. **
  108898. ** Write the estimated row count into *pnRow and return SQLITE_OK.
  108899. ** If unable to make an estimate, leave *pnRow unchanged and return
  108900. ** non-zero.
  108901. **
  108902. ** This routine can fail if it is unable to load a collating sequence
  108903. ** required for string comparison, or if unable to allocate memory
  108904. ** for a UTF conversion required for comparison. The error is stored
  108905. ** in the pParse structure.
  108906. */
  108907. static int whereEqualScanEst(
  108908. Parse *pParse, /* Parsing & code generating context */
  108909. WhereLoopBuilder *pBuilder,
  108910. Expr *pExpr, /* Expression for VALUE in the x=VALUE constraint */
  108911. tRowcnt *pnRow /* Write the revised row estimate here */
  108912. ){
  108913. Index *p = pBuilder->pNew->u.btree.pIndex;
  108914. int nEq = pBuilder->pNew->u.btree.nEq;
  108915. UnpackedRecord *pRec = pBuilder->pRec;
  108916. u8 aff; /* Column affinity */
  108917. int rc; /* Subfunction return code */
  108918. tRowcnt a[2]; /* Statistics */
  108919. int bOk;
  108920. assert( nEq>=1 );
  108921. assert( nEq<=p->nColumn );
  108922. assert( p->aSample!=0 );
  108923. assert( p->nSample>0 );
  108924. assert( pBuilder->nRecValid<nEq );
  108925. /* If values are not available for all fields of the index to the left
  108926. ** of this one, no estimate can be made. Return SQLITE_NOTFOUND. */
  108927. if( pBuilder->nRecValid<(nEq-1) ){
  108928. return SQLITE_NOTFOUND;
  108929. }
  108930. /* This is an optimization only. The call to sqlite3Stat4ProbeSetValue()
  108931. ** below would return the same value. */
  108932. if( nEq>=p->nColumn ){
  108933. *pnRow = 1;
  108934. return SQLITE_OK;
  108935. }
  108936. aff = p->pTable->aCol[p->aiColumn[nEq-1]].affinity;
  108937. rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, aff, nEq-1, &bOk);
  108938. pBuilder->pRec = pRec;
  108939. if( rc!=SQLITE_OK ) return rc;
  108940. if( bOk==0 ) return SQLITE_NOTFOUND;
  108941. pBuilder->nRecValid = nEq;
  108942. whereKeyStats(pParse, p, pRec, 0, a);
  108943. WHERETRACE(0x10,("equality scan regions: %d\n", (int)a[1]));
  108944. *pnRow = a[1];
  108945. return rc;
  108946. }
  108947. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  108948. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  108949. /*
  108950. ** Estimate the number of rows that will be returned based on
  108951. ** an IN constraint where the right-hand side of the IN operator
  108952. ** is a list of values. Example:
  108953. **
  108954. ** WHERE x IN (1,2,3,4)
  108955. **
  108956. ** Write the estimated row count into *pnRow and return SQLITE_OK.
  108957. ** If unable to make an estimate, leave *pnRow unchanged and return
  108958. ** non-zero.
  108959. **
  108960. ** This routine can fail if it is unable to load a collating sequence
  108961. ** required for string comparison, or if unable to allocate memory
  108962. ** for a UTF conversion required for comparison. The error is stored
  108963. ** in the pParse structure.
  108964. */
  108965. static int whereInScanEst(
  108966. Parse *pParse, /* Parsing & code generating context */
  108967. WhereLoopBuilder *pBuilder,
  108968. ExprList *pList, /* The value list on the RHS of "x IN (v1,v2,v3,...)" */
  108969. tRowcnt *pnRow /* Write the revised row estimate here */
  108970. ){
  108971. Index *p = pBuilder->pNew->u.btree.pIndex;
  108972. i64 nRow0 = sqlite3LogEstToInt(p->aiRowLogEst[0]);
  108973. int nRecValid = pBuilder->nRecValid;
  108974. int rc = SQLITE_OK; /* Subfunction return code */
  108975. tRowcnt nEst; /* Number of rows for a single term */
  108976. tRowcnt nRowEst = 0; /* New estimate of the number of rows */
  108977. int i; /* Loop counter */
  108978. assert( p->aSample!=0 );
  108979. for(i=0; rc==SQLITE_OK && i<pList->nExpr; i++){
  108980. nEst = nRow0;
  108981. rc = whereEqualScanEst(pParse, pBuilder, pList->a[i].pExpr, &nEst);
  108982. nRowEst += nEst;
  108983. pBuilder->nRecValid = nRecValid;
  108984. }
  108985. if( rc==SQLITE_OK ){
  108986. if( nRowEst > nRow0 ) nRowEst = nRow0;
  108987. *pnRow = nRowEst;
  108988. WHERETRACE(0x10,("IN row estimate: est=%d\n", nRowEst));
  108989. }
  108990. assert( pBuilder->nRecValid==nRecValid );
  108991. return rc;
  108992. }
  108993. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  108994. /*
  108995. ** Disable a term in the WHERE clause. Except, do not disable the term
  108996. ** if it controls a LEFT OUTER JOIN and it did not originate in the ON
  108997. ** or USING clause of that join.
  108998. **
  108999. ** Consider the term t2.z='ok' in the following queries:
  109000. **
  109001. ** (1) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok'
  109002. ** (2) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok'
  109003. ** (3) SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok'
  109004. **
  109005. ** The t2.z='ok' is disabled in the in (2) because it originates
  109006. ** in the ON clause. The term is disabled in (3) because it is not part
  109007. ** of a LEFT OUTER JOIN. In (1), the term is not disabled.
  109008. **
  109009. ** Disabling a term causes that term to not be tested in the inner loop
  109010. ** of the join. Disabling is an optimization. When terms are satisfied
  109011. ** by indices, we disable them to prevent redundant tests in the inner
  109012. ** loop. We would get the correct results if nothing were ever disabled,
  109013. ** but joins might run a little slower. The trick is to disable as much
  109014. ** as we can without disabling too much. If we disabled in (1), we'd get
  109015. ** the wrong answer. See ticket #813.
  109016. */
  109017. static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){
  109018. if( pTerm
  109019. && (pTerm->wtFlags & TERM_CODED)==0
  109020. && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin))
  109021. && (pLevel->notReady & pTerm->prereqAll)==0
  109022. ){
  109023. pTerm->wtFlags |= TERM_CODED;
  109024. if( pTerm->iParent>=0 ){
  109025. WhereTerm *pOther = &pTerm->pWC->a[pTerm->iParent];
  109026. if( (--pOther->nChild)==0 ){
  109027. disableTerm(pLevel, pOther);
  109028. }
  109029. }
  109030. }
  109031. }
  109032. /*
  109033. ** Code an OP_Affinity opcode to apply the column affinity string zAff
  109034. ** to the n registers starting at base.
  109035. **
  109036. ** As an optimization, SQLITE_AFF_NONE entries (which are no-ops) at the
  109037. ** beginning and end of zAff are ignored. If all entries in zAff are
  109038. ** SQLITE_AFF_NONE, then no code gets generated.
  109039. **
  109040. ** This routine makes its own copy of zAff so that the caller is free
  109041. ** to modify zAff after this routine returns.
  109042. */
  109043. static void codeApplyAffinity(Parse *pParse, int base, int n, char *zAff){
  109044. Vdbe *v = pParse->pVdbe;
  109045. if( zAff==0 ){
  109046. assert( pParse->db->mallocFailed );
  109047. return;
  109048. }
  109049. assert( v!=0 );
  109050. /* Adjust base and n to skip over SQLITE_AFF_NONE entries at the beginning
  109051. ** and end of the affinity string.
  109052. */
  109053. while( n>0 && zAff[0]==SQLITE_AFF_NONE ){
  109054. n--;
  109055. base++;
  109056. zAff++;
  109057. }
  109058. while( n>1 && zAff[n-1]==SQLITE_AFF_NONE ){
  109059. n--;
  109060. }
  109061. /* Code the OP_Affinity opcode if there is anything left to do. */
  109062. if( n>0 ){
  109063. sqlite3VdbeAddOp2(v, OP_Affinity, base, n);
  109064. sqlite3VdbeChangeP4(v, -1, zAff, n);
  109065. sqlite3ExprCacheAffinityChange(pParse, base, n);
  109066. }
  109067. }
  109068. /*
  109069. ** Generate code for a single equality term of the WHERE clause. An equality
  109070. ** term can be either X=expr or X IN (...). pTerm is the term to be
  109071. ** coded.
  109072. **
  109073. ** The current value for the constraint is left in register iReg.
  109074. **
  109075. ** For a constraint of the form X=expr, the expression is evaluated and its
  109076. ** result is left on the stack. For constraints of the form X IN (...)
  109077. ** this routine sets up a loop that will iterate over all values of X.
  109078. */
  109079. static int codeEqualityTerm(
  109080. Parse *pParse, /* The parsing context */
  109081. WhereTerm *pTerm, /* The term of the WHERE clause to be coded */
  109082. WhereLevel *pLevel, /* The level of the FROM clause we are working on */
  109083. int iEq, /* Index of the equality term within this level */
  109084. int bRev, /* True for reverse-order IN operations */
  109085. int iTarget /* Attempt to leave results in this register */
  109086. ){
  109087. Expr *pX = pTerm->pExpr;
  109088. Vdbe *v = pParse->pVdbe;
  109089. int iReg; /* Register holding results */
  109090. assert( iTarget>0 );
  109091. if( pX->op==TK_EQ ){
  109092. iReg = sqlite3ExprCodeTarget(pParse, pX->pRight, iTarget);
  109093. }else if( pX->op==TK_ISNULL ){
  109094. iReg = iTarget;
  109095. sqlite3VdbeAddOp2(v, OP_Null, 0, iReg);
  109096. #ifndef SQLITE_OMIT_SUBQUERY
  109097. }else{
  109098. int eType;
  109099. int iTab;
  109100. struct InLoop *pIn;
  109101. WhereLoop *pLoop = pLevel->pWLoop;
  109102. if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0
  109103. && pLoop->u.btree.pIndex!=0
  109104. && pLoop->u.btree.pIndex->aSortOrder[iEq]
  109105. ){
  109106. testcase( iEq==0 );
  109107. testcase( bRev );
  109108. bRev = !bRev;
  109109. }
  109110. assert( pX->op==TK_IN );
  109111. iReg = iTarget;
  109112. eType = sqlite3FindInIndex(pParse, pX, IN_INDEX_LOOP, 0);
  109113. if( eType==IN_INDEX_INDEX_DESC ){
  109114. testcase( bRev );
  109115. bRev = !bRev;
  109116. }
  109117. iTab = pX->iTable;
  109118. sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iTab, 0);
  109119. VdbeCoverageIf(v, bRev);
  109120. VdbeCoverageIf(v, !bRev);
  109121. assert( (pLoop->wsFlags & WHERE_MULTI_OR)==0 );
  109122. pLoop->wsFlags |= WHERE_IN_ABLE;
  109123. if( pLevel->u.in.nIn==0 ){
  109124. pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
  109125. }
  109126. pLevel->u.in.nIn++;
  109127. pLevel->u.in.aInLoop =
  109128. sqlite3DbReallocOrFree(pParse->db, pLevel->u.in.aInLoop,
  109129. sizeof(pLevel->u.in.aInLoop[0])*pLevel->u.in.nIn);
  109130. pIn = pLevel->u.in.aInLoop;
  109131. if( pIn ){
  109132. pIn += pLevel->u.in.nIn - 1;
  109133. pIn->iCur = iTab;
  109134. if( eType==IN_INDEX_ROWID ){
  109135. pIn->addrInTop = sqlite3VdbeAddOp2(v, OP_Rowid, iTab, iReg);
  109136. }else{
  109137. pIn->addrInTop = sqlite3VdbeAddOp3(v, OP_Column, iTab, 0, iReg);
  109138. }
  109139. pIn->eEndLoopOp = bRev ? OP_PrevIfOpen : OP_NextIfOpen;
  109140. sqlite3VdbeAddOp1(v, OP_IsNull, iReg); VdbeCoverage(v);
  109141. }else{
  109142. pLevel->u.in.nIn = 0;
  109143. }
  109144. #endif
  109145. }
  109146. disableTerm(pLevel, pTerm);
  109147. return iReg;
  109148. }
  109149. /*
  109150. ** Generate code that will evaluate all == and IN constraints for an
  109151. ** index scan.
  109152. **
  109153. ** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c).
  109154. ** Suppose the WHERE clause is this: a==5 AND b IN (1,2,3) AND c>5 AND c<10
  109155. ** The index has as many as three equality constraints, but in this
  109156. ** example, the third "c" value is an inequality. So only two
  109157. ** constraints are coded. This routine will generate code to evaluate
  109158. ** a==5 and b IN (1,2,3). The current values for a and b will be stored
  109159. ** in consecutive registers and the index of the first register is returned.
  109160. **
  109161. ** In the example above nEq==2. But this subroutine works for any value
  109162. ** of nEq including 0. If nEq==0, this routine is nearly a no-op.
  109163. ** The only thing it does is allocate the pLevel->iMem memory cell and
  109164. ** compute the affinity string.
  109165. **
  109166. ** The nExtraReg parameter is 0 or 1. It is 0 if all WHERE clause constraints
  109167. ** are == or IN and are covered by the nEq. nExtraReg is 1 if there is
  109168. ** an inequality constraint (such as the "c>=5 AND c<10" in the example) that
  109169. ** occurs after the nEq quality constraints.
  109170. **
  109171. ** This routine allocates a range of nEq+nExtraReg memory cells and returns
  109172. ** the index of the first memory cell in that range. The code that
  109173. ** calls this routine will use that memory range to store keys for
  109174. ** start and termination conditions of the loop.
  109175. ** key value of the loop. If one or more IN operators appear, then
  109176. ** this routine allocates an additional nEq memory cells for internal
  109177. ** use.
  109178. **
  109179. ** Before returning, *pzAff is set to point to a buffer containing a
  109180. ** copy of the column affinity string of the index allocated using
  109181. ** sqlite3DbMalloc(). Except, entries in the copy of the string associated
  109182. ** with equality constraints that use NONE affinity are set to
  109183. ** SQLITE_AFF_NONE. This is to deal with SQL such as the following:
  109184. **
  109185. ** CREATE TABLE t1(a TEXT PRIMARY KEY, b);
  109186. ** SELECT ... FROM t1 AS t2, t1 WHERE t1.a = t2.b;
  109187. **
  109188. ** In the example above, the index on t1(a) has TEXT affinity. But since
  109189. ** the right hand side of the equality constraint (t2.b) has NONE affinity,
  109190. ** no conversion should be attempted before using a t2.b value as part of
  109191. ** a key to search the index. Hence the first byte in the returned affinity
  109192. ** string in this example would be set to SQLITE_AFF_NONE.
  109193. */
  109194. static int codeAllEqualityTerms(
  109195. Parse *pParse, /* Parsing context */
  109196. WhereLevel *pLevel, /* Which nested loop of the FROM we are coding */
  109197. int bRev, /* Reverse the order of IN operators */
  109198. int nExtraReg, /* Number of extra registers to allocate */
  109199. char **pzAff /* OUT: Set to point to affinity string */
  109200. ){
  109201. u16 nEq; /* The number of == or IN constraints to code */
  109202. u16 nSkip; /* Number of left-most columns to skip */
  109203. Vdbe *v = pParse->pVdbe; /* The vm under construction */
  109204. Index *pIdx; /* The index being used for this loop */
  109205. WhereTerm *pTerm; /* A single constraint term */
  109206. WhereLoop *pLoop; /* The WhereLoop object */
  109207. int j; /* Loop counter */
  109208. int regBase; /* Base register */
  109209. int nReg; /* Number of registers to allocate */
  109210. char *zAff; /* Affinity string to return */
  109211. /* This module is only called on query plans that use an index. */
  109212. pLoop = pLevel->pWLoop;
  109213. assert( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 );
  109214. nEq = pLoop->u.btree.nEq;
  109215. nSkip = pLoop->nSkip;
  109216. pIdx = pLoop->u.btree.pIndex;
  109217. assert( pIdx!=0 );
  109218. /* Figure out how many memory cells we will need then allocate them.
  109219. */
  109220. regBase = pParse->nMem + 1;
  109221. nReg = pLoop->u.btree.nEq + nExtraReg;
  109222. pParse->nMem += nReg;
  109223. zAff = sqlite3DbStrDup(pParse->db, sqlite3IndexAffinityStr(v, pIdx));
  109224. if( !zAff ){
  109225. pParse->db->mallocFailed = 1;
  109226. }
  109227. if( nSkip ){
  109228. int iIdxCur = pLevel->iIdxCur;
  109229. sqlite3VdbeAddOp1(v, (bRev?OP_Last:OP_Rewind), iIdxCur);
  109230. VdbeCoverageIf(v, bRev==0);
  109231. VdbeCoverageIf(v, bRev!=0);
  109232. VdbeComment((v, "begin skip-scan on %s", pIdx->zName));
  109233. j = sqlite3VdbeAddOp0(v, OP_Goto);
  109234. pLevel->addrSkip = sqlite3VdbeAddOp4Int(v, (bRev?OP_SeekLT:OP_SeekGT),
  109235. iIdxCur, 0, regBase, nSkip);
  109236. VdbeCoverageIf(v, bRev==0);
  109237. VdbeCoverageIf(v, bRev!=0);
  109238. sqlite3VdbeJumpHere(v, j);
  109239. for(j=0; j<nSkip; j++){
  109240. sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, j, regBase+j);
  109241. assert( pIdx->aiColumn[j]>=0 );
  109242. VdbeComment((v, "%s", pIdx->pTable->aCol[pIdx->aiColumn[j]].zName));
  109243. }
  109244. }
  109245. /* Evaluate the equality constraints
  109246. */
  109247. assert( zAff==0 || (int)strlen(zAff)>=nEq );
  109248. for(j=nSkip; j<nEq; j++){
  109249. int r1;
  109250. pTerm = pLoop->aLTerm[j];
  109251. assert( pTerm!=0 );
  109252. /* The following testcase is true for indices with redundant columns.
  109253. ** Ex: CREATE INDEX i1 ON t1(a,b,a); SELECT * FROM t1 WHERE a=0 AND b=0; */
  109254. testcase( (pTerm->wtFlags & TERM_CODED)!=0 );
  109255. testcase( pTerm->wtFlags & TERM_VIRTUAL );
  109256. r1 = codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, regBase+j);
  109257. if( r1!=regBase+j ){
  109258. if( nReg==1 ){
  109259. sqlite3ReleaseTempReg(pParse, regBase);
  109260. regBase = r1;
  109261. }else{
  109262. sqlite3VdbeAddOp2(v, OP_SCopy, r1, regBase+j);
  109263. }
  109264. }
  109265. testcase( pTerm->eOperator & WO_ISNULL );
  109266. testcase( pTerm->eOperator & WO_IN );
  109267. if( (pTerm->eOperator & (WO_ISNULL|WO_IN))==0 ){
  109268. Expr *pRight = pTerm->pExpr->pRight;
  109269. if( sqlite3ExprCanBeNull(pRight) ){
  109270. sqlite3VdbeAddOp2(v, OP_IsNull, regBase+j, pLevel->addrBrk);
  109271. VdbeCoverage(v);
  109272. }
  109273. if( zAff ){
  109274. if( sqlite3CompareAffinity(pRight, zAff[j])==SQLITE_AFF_NONE ){
  109275. zAff[j] = SQLITE_AFF_NONE;
  109276. }
  109277. if( sqlite3ExprNeedsNoAffinityChange(pRight, zAff[j]) ){
  109278. zAff[j] = SQLITE_AFF_NONE;
  109279. }
  109280. }
  109281. }
  109282. }
  109283. *pzAff = zAff;
  109284. return regBase;
  109285. }
  109286. #ifndef SQLITE_OMIT_EXPLAIN
  109287. /*
  109288. ** This routine is a helper for explainIndexRange() below
  109289. **
  109290. ** pStr holds the text of an expression that we are building up one term
  109291. ** at a time. This routine adds a new term to the end of the expression.
  109292. ** Terms are separated by AND so add the "AND" text for second and subsequent
  109293. ** terms only.
  109294. */
  109295. static void explainAppendTerm(
  109296. StrAccum *pStr, /* The text expression being built */
  109297. int iTerm, /* Index of this term. First is zero */
  109298. const char *zColumn, /* Name of the column */
  109299. const char *zOp /* Name of the operator */
  109300. ){
  109301. if( iTerm ) sqlite3StrAccumAppend(pStr, " AND ", 5);
  109302. sqlite3StrAccumAppendAll(pStr, zColumn);
  109303. sqlite3StrAccumAppend(pStr, zOp, 1);
  109304. sqlite3StrAccumAppend(pStr, "?", 1);
  109305. }
  109306. /*
  109307. ** Argument pLevel describes a strategy for scanning table pTab. This
  109308. ** function appends text to pStr that describes the subset of table
  109309. ** rows scanned by the strategy in the form of an SQL expression.
  109310. **
  109311. ** For example, if the query:
  109312. **
  109313. ** SELECT * FROM t1 WHERE a=1 AND b>2;
  109314. **
  109315. ** is run and there is an index on (a, b), then this function returns a
  109316. ** string similar to:
  109317. **
  109318. ** "a=? AND b>?"
  109319. */
  109320. static void explainIndexRange(StrAccum *pStr, WhereLoop *pLoop, Table *pTab){
  109321. Index *pIndex = pLoop->u.btree.pIndex;
  109322. u16 nEq = pLoop->u.btree.nEq;
  109323. u16 nSkip = pLoop->nSkip;
  109324. int i, j;
  109325. Column *aCol = pTab->aCol;
  109326. i16 *aiColumn = pIndex->aiColumn;
  109327. if( nEq==0 && (pLoop->wsFlags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))==0 ) return;
  109328. sqlite3StrAccumAppend(pStr, " (", 2);
  109329. for(i=0; i<nEq; i++){
  109330. char *z = aiColumn[i] < 0 ? "rowid" : aCol[aiColumn[i]].zName;
  109331. if( i>=nSkip ){
  109332. explainAppendTerm(pStr, i, z, "=");
  109333. }else{
  109334. if( i ) sqlite3StrAccumAppend(pStr, " AND ", 5);
  109335. sqlite3XPrintf(pStr, 0, "ANY(%s)", z);
  109336. }
  109337. }
  109338. j = i;
  109339. if( pLoop->wsFlags&WHERE_BTM_LIMIT ){
  109340. char *z = aiColumn[j] < 0 ? "rowid" : aCol[aiColumn[j]].zName;
  109341. explainAppendTerm(pStr, i++, z, ">");
  109342. }
  109343. if( pLoop->wsFlags&WHERE_TOP_LIMIT ){
  109344. char *z = aiColumn[j] < 0 ? "rowid" : aCol[aiColumn[j]].zName;
  109345. explainAppendTerm(pStr, i, z, "<");
  109346. }
  109347. sqlite3StrAccumAppend(pStr, ")", 1);
  109348. }
  109349. /*
  109350. ** This function is a no-op unless currently processing an EXPLAIN QUERY PLAN
  109351. ** command. If the query being compiled is an EXPLAIN QUERY PLAN, a single
  109352. ** record is added to the output to describe the table scan strategy in
  109353. ** pLevel.
  109354. */
  109355. static void explainOneScan(
  109356. Parse *pParse, /* Parse context */
  109357. SrcList *pTabList, /* Table list this loop refers to */
  109358. WhereLevel *pLevel, /* Scan to write OP_Explain opcode for */
  109359. int iLevel, /* Value for "level" column of output */
  109360. int iFrom, /* Value for "from" column of output */
  109361. u16 wctrlFlags /* Flags passed to sqlite3WhereBegin() */
  109362. ){
  109363. #ifndef SQLITE_DEBUG
  109364. if( pParse->explain==2 )
  109365. #endif
  109366. {
  109367. struct SrcList_item *pItem = &pTabList->a[pLevel->iFrom];
  109368. Vdbe *v = pParse->pVdbe; /* VM being constructed */
  109369. sqlite3 *db = pParse->db; /* Database handle */
  109370. int iId = pParse->iSelectId; /* Select id (left-most output column) */
  109371. int isSearch; /* True for a SEARCH. False for SCAN. */
  109372. WhereLoop *pLoop; /* The controlling WhereLoop object */
  109373. u32 flags; /* Flags that describe this loop */
  109374. char *zMsg; /* Text to add to EQP output */
  109375. StrAccum str; /* EQP output string */
  109376. char zBuf[100]; /* Initial space for EQP output string */
  109377. pLoop = pLevel->pWLoop;
  109378. flags = pLoop->wsFlags;
  109379. if( (flags&WHERE_MULTI_OR) || (wctrlFlags&WHERE_ONETABLE_ONLY) ) return;
  109380. isSearch = (flags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0
  109381. || ((flags&WHERE_VIRTUALTABLE)==0 && (pLoop->u.btree.nEq>0))
  109382. || (wctrlFlags&(WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX));
  109383. sqlite3StrAccumInit(&str, zBuf, sizeof(zBuf), SQLITE_MAX_LENGTH);
  109384. str.db = db;
  109385. sqlite3StrAccumAppendAll(&str, isSearch ? "SEARCH" : "SCAN");
  109386. if( pItem->pSelect ){
  109387. sqlite3XPrintf(&str, 0, " SUBQUERY %d", pItem->iSelectId);
  109388. }else{
  109389. sqlite3XPrintf(&str, 0, " TABLE %s", pItem->zName);
  109390. }
  109391. if( pItem->zAlias ){
  109392. sqlite3XPrintf(&str, 0, " AS %s", pItem->zAlias);
  109393. }
  109394. if( (flags & (WHERE_IPK|WHERE_VIRTUALTABLE))==0 ){
  109395. const char *zFmt = 0;
  109396. Index *pIdx;
  109397. assert( pLoop->u.btree.pIndex!=0 );
  109398. pIdx = pLoop->u.btree.pIndex;
  109399. assert( !(flags&WHERE_AUTO_INDEX) || (flags&WHERE_IDX_ONLY) );
  109400. if( !HasRowid(pItem->pTab) && IsPrimaryKeyIndex(pIdx) ){
  109401. if( isSearch ){
  109402. zFmt = "PRIMARY KEY";
  109403. }
  109404. }else if( flags & WHERE_PARTIALIDX ){
  109405. zFmt = "AUTOMATIC PARTIAL COVERING INDEX";
  109406. }else if( flags & WHERE_AUTO_INDEX ){
  109407. zFmt = "AUTOMATIC COVERING INDEX";
  109408. }else if( flags & WHERE_IDX_ONLY ){
  109409. zFmt = "COVERING INDEX %s";
  109410. }else{
  109411. zFmt = "INDEX %s";
  109412. }
  109413. if( zFmt ){
  109414. sqlite3StrAccumAppend(&str, " USING ", 7);
  109415. sqlite3XPrintf(&str, 0, zFmt, pIdx->zName);
  109416. explainIndexRange(&str, pLoop, pItem->pTab);
  109417. }
  109418. }else if( (flags & WHERE_IPK)!=0 && (flags & WHERE_CONSTRAINT)!=0 ){
  109419. const char *zRange;
  109420. if( flags&(WHERE_COLUMN_EQ|WHERE_COLUMN_IN) ){
  109421. zRange = "(rowid=?)";
  109422. }else if( (flags&WHERE_BOTH_LIMIT)==WHERE_BOTH_LIMIT ){
  109423. zRange = "(rowid>? AND rowid<?)";
  109424. }else if( flags&WHERE_BTM_LIMIT ){
  109425. zRange = "(rowid>?)";
  109426. }else{
  109427. assert( flags&WHERE_TOP_LIMIT);
  109428. zRange = "(rowid<?)";
  109429. }
  109430. sqlite3StrAccumAppendAll(&str, " USING INTEGER PRIMARY KEY ");
  109431. sqlite3StrAccumAppendAll(&str, zRange);
  109432. }
  109433. #ifndef SQLITE_OMIT_VIRTUALTABLE
  109434. else if( (flags & WHERE_VIRTUALTABLE)!=0 ){
  109435. sqlite3XPrintf(&str, 0, " VIRTUAL TABLE INDEX %d:%s",
  109436. pLoop->u.vtab.idxNum, pLoop->u.vtab.idxStr);
  109437. }
  109438. #endif
  109439. #ifdef SQLITE_EXPLAIN_ESTIMATED_ROWS
  109440. if( pLoop->nOut>=10 ){
  109441. sqlite3XPrintf(&str, 0, " (~%llu rows)", sqlite3LogEstToInt(pLoop->nOut));
  109442. }else{
  109443. sqlite3StrAccumAppend(&str, " (~1 row)", 9);
  109444. }
  109445. #endif
  109446. zMsg = sqlite3StrAccumFinish(&str);
  109447. sqlite3VdbeAddOp4(v, OP_Explain, iId, iLevel, iFrom, zMsg, P4_DYNAMIC);
  109448. }
  109449. }
  109450. #else
  109451. # define explainOneScan(u,v,w,x,y,z)
  109452. #endif /* SQLITE_OMIT_EXPLAIN */
  109453. /*
  109454. ** Generate code for the start of the iLevel-th loop in the WHERE clause
  109455. ** implementation described by pWInfo.
  109456. */
  109457. static Bitmask codeOneLoopStart(
  109458. WhereInfo *pWInfo, /* Complete information about the WHERE clause */
  109459. int iLevel, /* Which level of pWInfo->a[] should be coded */
  109460. Bitmask notReady /* Which tables are currently available */
  109461. ){
  109462. int j, k; /* Loop counters */
  109463. int iCur; /* The VDBE cursor for the table */
  109464. int addrNxt; /* Where to jump to continue with the next IN case */
  109465. int omitTable; /* True if we use the index only */
  109466. int bRev; /* True if we need to scan in reverse order */
  109467. WhereLevel *pLevel; /* The where level to be coded */
  109468. WhereLoop *pLoop; /* The WhereLoop object being coded */
  109469. WhereClause *pWC; /* Decomposition of the entire WHERE clause */
  109470. WhereTerm *pTerm; /* A WHERE clause term */
  109471. Parse *pParse; /* Parsing context */
  109472. sqlite3 *db; /* Database connection */
  109473. Vdbe *v; /* The prepared stmt under constructions */
  109474. struct SrcList_item *pTabItem; /* FROM clause term being coded */
  109475. int addrBrk; /* Jump here to break out of the loop */
  109476. int addrCont; /* Jump here to continue with next cycle */
  109477. int iRowidReg = 0; /* Rowid is stored in this register, if not zero */
  109478. int iReleaseReg = 0; /* Temp register to free before returning */
  109479. pParse = pWInfo->pParse;
  109480. v = pParse->pVdbe;
  109481. pWC = &pWInfo->sWC;
  109482. db = pParse->db;
  109483. pLevel = &pWInfo->a[iLevel];
  109484. pLoop = pLevel->pWLoop;
  109485. pTabItem = &pWInfo->pTabList->a[pLevel->iFrom];
  109486. iCur = pTabItem->iCursor;
  109487. pLevel->notReady = notReady & ~getMask(&pWInfo->sMaskSet, iCur);
  109488. bRev = (pWInfo->revMask>>iLevel)&1;
  109489. omitTable = (pLoop->wsFlags & WHERE_IDX_ONLY)!=0
  109490. && (pWInfo->wctrlFlags & WHERE_FORCE_TABLE)==0;
  109491. VdbeModuleComment((v, "Begin WHERE-loop%d: %s",iLevel,pTabItem->pTab->zName));
  109492. /* Create labels for the "break" and "continue" instructions
  109493. ** for the current loop. Jump to addrBrk to break out of a loop.
  109494. ** Jump to cont to go immediately to the next iteration of the
  109495. ** loop.
  109496. **
  109497. ** When there is an IN operator, we also have a "addrNxt" label that
  109498. ** means to continue with the next IN value combination. When
  109499. ** there are no IN operators in the constraints, the "addrNxt" label
  109500. ** is the same as "addrBrk".
  109501. */
  109502. addrBrk = pLevel->addrBrk = pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
  109503. addrCont = pLevel->addrCont = sqlite3VdbeMakeLabel(v);
  109504. /* If this is the right table of a LEFT OUTER JOIN, allocate and
  109505. ** initialize a memory cell that records if this table matches any
  109506. ** row of the left table of the join.
  109507. */
  109508. if( pLevel->iFrom>0 && (pTabItem[0].jointype & JT_LEFT)!=0 ){
  109509. pLevel->iLeftJoin = ++pParse->nMem;
  109510. sqlite3VdbeAddOp2(v, OP_Integer, 0, pLevel->iLeftJoin);
  109511. VdbeComment((v, "init LEFT JOIN no-match flag"));
  109512. }
  109513. /* Special case of a FROM clause subquery implemented as a co-routine */
  109514. if( pTabItem->viaCoroutine ){
  109515. int regYield = pTabItem->regReturn;
  109516. sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, pTabItem->addrFillSub);
  109517. pLevel->p2 = sqlite3VdbeAddOp2(v, OP_Yield, regYield, addrBrk);
  109518. VdbeCoverage(v);
  109519. VdbeComment((v, "next row of \"%s\"", pTabItem->pTab->zName));
  109520. pLevel->op = OP_Goto;
  109521. }else
  109522. #ifndef SQLITE_OMIT_VIRTUALTABLE
  109523. if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){
  109524. /* Case 1: The table is a virtual-table. Use the VFilter and VNext
  109525. ** to access the data.
  109526. */
  109527. int iReg; /* P3 Value for OP_VFilter */
  109528. int addrNotFound;
  109529. int nConstraint = pLoop->nLTerm;
  109530. sqlite3ExprCachePush(pParse);
  109531. iReg = sqlite3GetTempRange(pParse, nConstraint+2);
  109532. addrNotFound = pLevel->addrBrk;
  109533. for(j=0; j<nConstraint; j++){
  109534. int iTarget = iReg+j+2;
  109535. pTerm = pLoop->aLTerm[j];
  109536. if( pTerm==0 ) continue;
  109537. if( pTerm->eOperator & WO_IN ){
  109538. codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, iTarget);
  109539. addrNotFound = pLevel->addrNxt;
  109540. }else{
  109541. sqlite3ExprCode(pParse, pTerm->pExpr->pRight, iTarget);
  109542. }
  109543. }
  109544. sqlite3VdbeAddOp2(v, OP_Integer, pLoop->u.vtab.idxNum, iReg);
  109545. sqlite3VdbeAddOp2(v, OP_Integer, nConstraint, iReg+1);
  109546. sqlite3VdbeAddOp4(v, OP_VFilter, iCur, addrNotFound, iReg,
  109547. pLoop->u.vtab.idxStr,
  109548. pLoop->u.vtab.needFree ? P4_MPRINTF : P4_STATIC);
  109549. VdbeCoverage(v);
  109550. pLoop->u.vtab.needFree = 0;
  109551. for(j=0; j<nConstraint && j<16; j++){
  109552. if( (pLoop->u.vtab.omitMask>>j)&1 ){
  109553. disableTerm(pLevel, pLoop->aLTerm[j]);
  109554. }
  109555. }
  109556. pLevel->op = OP_VNext;
  109557. pLevel->p1 = iCur;
  109558. pLevel->p2 = sqlite3VdbeCurrentAddr(v);
  109559. sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2);
  109560. sqlite3ExprCachePop(pParse);
  109561. }else
  109562. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  109563. if( (pLoop->wsFlags & WHERE_IPK)!=0
  109564. && (pLoop->wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_EQ))!=0
  109565. ){
  109566. /* Case 2: We can directly reference a single row using an
  109567. ** equality comparison against the ROWID field. Or
  109568. ** we reference multiple rows using a "rowid IN (...)"
  109569. ** construct.
  109570. */
  109571. assert( pLoop->u.btree.nEq==1 );
  109572. pTerm = pLoop->aLTerm[0];
  109573. assert( pTerm!=0 );
  109574. assert( pTerm->pExpr!=0 );
  109575. assert( omitTable==0 );
  109576. testcase( pTerm->wtFlags & TERM_VIRTUAL );
  109577. iReleaseReg = ++pParse->nMem;
  109578. iRowidReg = codeEqualityTerm(pParse, pTerm, pLevel, 0, bRev, iReleaseReg);
  109579. if( iRowidReg!=iReleaseReg ) sqlite3ReleaseTempReg(pParse, iReleaseReg);
  109580. addrNxt = pLevel->addrNxt;
  109581. sqlite3VdbeAddOp2(v, OP_MustBeInt, iRowidReg, addrNxt); VdbeCoverage(v);
  109582. sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addrNxt, iRowidReg);
  109583. VdbeCoverage(v);
  109584. sqlite3ExprCacheAffinityChange(pParse, iRowidReg, 1);
  109585. sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
  109586. VdbeComment((v, "pk"));
  109587. pLevel->op = OP_Noop;
  109588. }else if( (pLoop->wsFlags & WHERE_IPK)!=0
  109589. && (pLoop->wsFlags & WHERE_COLUMN_RANGE)!=0
  109590. ){
  109591. /* Case 3: We have an inequality comparison against the ROWID field.
  109592. */
  109593. int testOp = OP_Noop;
  109594. int start;
  109595. int memEndValue = 0;
  109596. WhereTerm *pStart, *pEnd;
  109597. assert( omitTable==0 );
  109598. j = 0;
  109599. pStart = pEnd = 0;
  109600. if( pLoop->wsFlags & WHERE_BTM_LIMIT ) pStart = pLoop->aLTerm[j++];
  109601. if( pLoop->wsFlags & WHERE_TOP_LIMIT ) pEnd = pLoop->aLTerm[j++];
  109602. assert( pStart!=0 || pEnd!=0 );
  109603. if( bRev ){
  109604. pTerm = pStart;
  109605. pStart = pEnd;
  109606. pEnd = pTerm;
  109607. }
  109608. if( pStart ){
  109609. Expr *pX; /* The expression that defines the start bound */
  109610. int r1, rTemp; /* Registers for holding the start boundary */
  109611. /* The following constant maps TK_xx codes into corresponding
  109612. ** seek opcodes. It depends on a particular ordering of TK_xx
  109613. */
  109614. const u8 aMoveOp[] = {
  109615. /* TK_GT */ OP_SeekGT,
  109616. /* TK_LE */ OP_SeekLE,
  109617. /* TK_LT */ OP_SeekLT,
  109618. /* TK_GE */ OP_SeekGE
  109619. };
  109620. assert( TK_LE==TK_GT+1 ); /* Make sure the ordering.. */
  109621. assert( TK_LT==TK_GT+2 ); /* ... of the TK_xx values... */
  109622. assert( TK_GE==TK_GT+3 ); /* ... is correcct. */
  109623. assert( (pStart->wtFlags & TERM_VNULL)==0 );
  109624. testcase( pStart->wtFlags & TERM_VIRTUAL );
  109625. pX = pStart->pExpr;
  109626. assert( pX!=0 );
  109627. testcase( pStart->leftCursor!=iCur ); /* transitive constraints */
  109628. r1 = sqlite3ExprCodeTemp(pParse, pX->pRight, &rTemp);
  109629. sqlite3VdbeAddOp3(v, aMoveOp[pX->op-TK_GT], iCur, addrBrk, r1);
  109630. VdbeComment((v, "pk"));
  109631. VdbeCoverageIf(v, pX->op==TK_GT);
  109632. VdbeCoverageIf(v, pX->op==TK_LE);
  109633. VdbeCoverageIf(v, pX->op==TK_LT);
  109634. VdbeCoverageIf(v, pX->op==TK_GE);
  109635. sqlite3ExprCacheAffinityChange(pParse, r1, 1);
  109636. sqlite3ReleaseTempReg(pParse, rTemp);
  109637. disableTerm(pLevel, pStart);
  109638. }else{
  109639. sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iCur, addrBrk);
  109640. VdbeCoverageIf(v, bRev==0);
  109641. VdbeCoverageIf(v, bRev!=0);
  109642. }
  109643. if( pEnd ){
  109644. Expr *pX;
  109645. pX = pEnd->pExpr;
  109646. assert( pX!=0 );
  109647. assert( (pEnd->wtFlags & TERM_VNULL)==0 );
  109648. testcase( pEnd->leftCursor!=iCur ); /* Transitive constraints */
  109649. testcase( pEnd->wtFlags & TERM_VIRTUAL );
  109650. memEndValue = ++pParse->nMem;
  109651. sqlite3ExprCode(pParse, pX->pRight, memEndValue);
  109652. if( pX->op==TK_LT || pX->op==TK_GT ){
  109653. testOp = bRev ? OP_Le : OP_Ge;
  109654. }else{
  109655. testOp = bRev ? OP_Lt : OP_Gt;
  109656. }
  109657. disableTerm(pLevel, pEnd);
  109658. }
  109659. start = sqlite3VdbeCurrentAddr(v);
  109660. pLevel->op = bRev ? OP_Prev : OP_Next;
  109661. pLevel->p1 = iCur;
  109662. pLevel->p2 = start;
  109663. assert( pLevel->p5==0 );
  109664. if( testOp!=OP_Noop ){
  109665. iRowidReg = ++pParse->nMem;
  109666. sqlite3VdbeAddOp2(v, OP_Rowid, iCur, iRowidReg);
  109667. sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
  109668. sqlite3VdbeAddOp3(v, testOp, memEndValue, addrBrk, iRowidReg);
  109669. VdbeCoverageIf(v, testOp==OP_Le);
  109670. VdbeCoverageIf(v, testOp==OP_Lt);
  109671. VdbeCoverageIf(v, testOp==OP_Ge);
  109672. VdbeCoverageIf(v, testOp==OP_Gt);
  109673. sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC | SQLITE_JUMPIFNULL);
  109674. }
  109675. }else if( pLoop->wsFlags & WHERE_INDEXED ){
  109676. /* Case 4: A scan using an index.
  109677. **
  109678. ** The WHERE clause may contain zero or more equality
  109679. ** terms ("==" or "IN" operators) that refer to the N
  109680. ** left-most columns of the index. It may also contain
  109681. ** inequality constraints (>, <, >= or <=) on the indexed
  109682. ** column that immediately follows the N equalities. Only
  109683. ** the right-most column can be an inequality - the rest must
  109684. ** use the "==" and "IN" operators. For example, if the
  109685. ** index is on (x,y,z), then the following clauses are all
  109686. ** optimized:
  109687. **
  109688. ** x=5
  109689. ** x=5 AND y=10
  109690. ** x=5 AND y<10
  109691. ** x=5 AND y>5 AND y<10
  109692. ** x=5 AND y=5 AND z<=10
  109693. **
  109694. ** The z<10 term of the following cannot be used, only
  109695. ** the x=5 term:
  109696. **
  109697. ** x=5 AND z<10
  109698. **
  109699. ** N may be zero if there are inequality constraints.
  109700. ** If there are no inequality constraints, then N is at
  109701. ** least one.
  109702. **
  109703. ** This case is also used when there are no WHERE clause
  109704. ** constraints but an index is selected anyway, in order
  109705. ** to force the output order to conform to an ORDER BY.
  109706. */
  109707. static const u8 aStartOp[] = {
  109708. 0,
  109709. 0,
  109710. OP_Rewind, /* 2: (!start_constraints && startEq && !bRev) */
  109711. OP_Last, /* 3: (!start_constraints && startEq && bRev) */
  109712. OP_SeekGT, /* 4: (start_constraints && !startEq && !bRev) */
  109713. OP_SeekLT, /* 5: (start_constraints && !startEq && bRev) */
  109714. OP_SeekGE, /* 6: (start_constraints && startEq && !bRev) */
  109715. OP_SeekLE /* 7: (start_constraints && startEq && bRev) */
  109716. };
  109717. static const u8 aEndOp[] = {
  109718. OP_IdxGE, /* 0: (end_constraints && !bRev && !endEq) */
  109719. OP_IdxGT, /* 1: (end_constraints && !bRev && endEq) */
  109720. OP_IdxLE, /* 2: (end_constraints && bRev && !endEq) */
  109721. OP_IdxLT, /* 3: (end_constraints && bRev && endEq) */
  109722. };
  109723. u16 nEq = pLoop->u.btree.nEq; /* Number of == or IN terms */
  109724. int regBase; /* Base register holding constraint values */
  109725. WhereTerm *pRangeStart = 0; /* Inequality constraint at range start */
  109726. WhereTerm *pRangeEnd = 0; /* Inequality constraint at range end */
  109727. int startEq; /* True if range start uses ==, >= or <= */
  109728. int endEq; /* True if range end uses ==, >= or <= */
  109729. int start_constraints; /* Start of range is constrained */
  109730. int nConstraint; /* Number of constraint terms */
  109731. Index *pIdx; /* The index we will be using */
  109732. int iIdxCur; /* The VDBE cursor for the index */
  109733. int nExtraReg = 0; /* Number of extra registers needed */
  109734. int op; /* Instruction opcode */
  109735. char *zStartAff; /* Affinity for start of range constraint */
  109736. char cEndAff = 0; /* Affinity for end of range constraint */
  109737. u8 bSeekPastNull = 0; /* True to seek past initial nulls */
  109738. u8 bStopAtNull = 0; /* Add condition to terminate at NULLs */
  109739. pIdx = pLoop->u.btree.pIndex;
  109740. iIdxCur = pLevel->iIdxCur;
  109741. assert( nEq>=pLoop->nSkip );
  109742. /* If this loop satisfies a sort order (pOrderBy) request that
  109743. ** was passed to this function to implement a "SELECT min(x) ..."
  109744. ** query, then the caller will only allow the loop to run for
  109745. ** a single iteration. This means that the first row returned
  109746. ** should not have a NULL value stored in 'x'. If column 'x' is
  109747. ** the first one after the nEq equality constraints in the index,
  109748. ** this requires some special handling.
  109749. */
  109750. assert( pWInfo->pOrderBy==0
  109751. || pWInfo->pOrderBy->nExpr==1
  109752. || (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)==0 );
  109753. if( (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)!=0
  109754. && pWInfo->nOBSat>0
  109755. && (pIdx->nKeyCol>nEq)
  109756. ){
  109757. assert( pLoop->nSkip==0 );
  109758. bSeekPastNull = 1;
  109759. nExtraReg = 1;
  109760. }
  109761. /* Find any inequality constraint terms for the start and end
  109762. ** of the range.
  109763. */
  109764. j = nEq;
  109765. if( pLoop->wsFlags & WHERE_BTM_LIMIT ){
  109766. pRangeStart = pLoop->aLTerm[j++];
  109767. nExtraReg = 1;
  109768. }
  109769. if( pLoop->wsFlags & WHERE_TOP_LIMIT ){
  109770. pRangeEnd = pLoop->aLTerm[j++];
  109771. nExtraReg = 1;
  109772. if( pRangeStart==0
  109773. && (j = pIdx->aiColumn[nEq])>=0
  109774. && pIdx->pTable->aCol[j].notNull==0
  109775. ){
  109776. bSeekPastNull = 1;
  109777. }
  109778. }
  109779. assert( pRangeEnd==0 || (pRangeEnd->wtFlags & TERM_VNULL)==0 );
  109780. /* Generate code to evaluate all constraint terms using == or IN
  109781. ** and store the values of those terms in an array of registers
  109782. ** starting at regBase.
  109783. */
  109784. regBase = codeAllEqualityTerms(pParse,pLevel,bRev,nExtraReg,&zStartAff);
  109785. assert( zStartAff==0 || sqlite3Strlen30(zStartAff)>=nEq );
  109786. if( zStartAff ) cEndAff = zStartAff[nEq];
  109787. addrNxt = pLevel->addrNxt;
  109788. /* If we are doing a reverse order scan on an ascending index, or
  109789. ** a forward order scan on a descending index, interchange the
  109790. ** start and end terms (pRangeStart and pRangeEnd).
  109791. */
  109792. if( (nEq<pIdx->nKeyCol && bRev==(pIdx->aSortOrder[nEq]==SQLITE_SO_ASC))
  109793. || (bRev && pIdx->nKeyCol==nEq)
  109794. ){
  109795. SWAP(WhereTerm *, pRangeEnd, pRangeStart);
  109796. SWAP(u8, bSeekPastNull, bStopAtNull);
  109797. }
  109798. testcase( pRangeStart && (pRangeStart->eOperator & WO_LE)!=0 );
  109799. testcase( pRangeStart && (pRangeStart->eOperator & WO_GE)!=0 );
  109800. testcase( pRangeEnd && (pRangeEnd->eOperator & WO_LE)!=0 );
  109801. testcase( pRangeEnd && (pRangeEnd->eOperator & WO_GE)!=0 );
  109802. startEq = !pRangeStart || pRangeStart->eOperator & (WO_LE|WO_GE);
  109803. endEq = !pRangeEnd || pRangeEnd->eOperator & (WO_LE|WO_GE);
  109804. start_constraints = pRangeStart || nEq>0;
  109805. /* Seek the index cursor to the start of the range. */
  109806. nConstraint = nEq;
  109807. if( pRangeStart ){
  109808. Expr *pRight = pRangeStart->pExpr->pRight;
  109809. sqlite3ExprCode(pParse, pRight, regBase+nEq);
  109810. if( (pRangeStart->wtFlags & TERM_VNULL)==0
  109811. && sqlite3ExprCanBeNull(pRight)
  109812. ){
  109813. sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt);
  109814. VdbeCoverage(v);
  109815. }
  109816. if( zStartAff ){
  109817. if( sqlite3CompareAffinity(pRight, zStartAff[nEq])==SQLITE_AFF_NONE){
  109818. /* Since the comparison is to be performed with no conversions
  109819. ** applied to the operands, set the affinity to apply to pRight to
  109820. ** SQLITE_AFF_NONE. */
  109821. zStartAff[nEq] = SQLITE_AFF_NONE;
  109822. }
  109823. if( sqlite3ExprNeedsNoAffinityChange(pRight, zStartAff[nEq]) ){
  109824. zStartAff[nEq] = SQLITE_AFF_NONE;
  109825. }
  109826. }
  109827. nConstraint++;
  109828. testcase( pRangeStart->wtFlags & TERM_VIRTUAL );
  109829. }else if( bSeekPastNull ){
  109830. sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
  109831. nConstraint++;
  109832. startEq = 0;
  109833. start_constraints = 1;
  109834. }
  109835. codeApplyAffinity(pParse, regBase, nConstraint - bSeekPastNull, zStartAff);
  109836. op = aStartOp[(start_constraints<<2) + (startEq<<1) + bRev];
  109837. assert( op!=0 );
  109838. sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
  109839. VdbeCoverage(v);
  109840. VdbeCoverageIf(v, op==OP_Rewind); testcase( op==OP_Rewind );
  109841. VdbeCoverageIf(v, op==OP_Last); testcase( op==OP_Last );
  109842. VdbeCoverageIf(v, op==OP_SeekGT); testcase( op==OP_SeekGT );
  109843. VdbeCoverageIf(v, op==OP_SeekGE); testcase( op==OP_SeekGE );
  109844. VdbeCoverageIf(v, op==OP_SeekLE); testcase( op==OP_SeekLE );
  109845. VdbeCoverageIf(v, op==OP_SeekLT); testcase( op==OP_SeekLT );
  109846. /* Load the value for the inequality constraint at the end of the
  109847. ** range (if any).
  109848. */
  109849. nConstraint = nEq;
  109850. if( pRangeEnd ){
  109851. Expr *pRight = pRangeEnd->pExpr->pRight;
  109852. sqlite3ExprCacheRemove(pParse, regBase+nEq, 1);
  109853. sqlite3ExprCode(pParse, pRight, regBase+nEq);
  109854. if( (pRangeEnd->wtFlags & TERM_VNULL)==0
  109855. && sqlite3ExprCanBeNull(pRight)
  109856. ){
  109857. sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt);
  109858. VdbeCoverage(v);
  109859. }
  109860. if( sqlite3CompareAffinity(pRight, cEndAff)!=SQLITE_AFF_NONE
  109861. && !sqlite3ExprNeedsNoAffinityChange(pRight, cEndAff)
  109862. ){
  109863. codeApplyAffinity(pParse, regBase+nEq, 1, &cEndAff);
  109864. }
  109865. nConstraint++;
  109866. testcase( pRangeEnd->wtFlags & TERM_VIRTUAL );
  109867. }else if( bStopAtNull ){
  109868. sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
  109869. endEq = 0;
  109870. nConstraint++;
  109871. }
  109872. sqlite3DbFree(db, zStartAff);
  109873. /* Top of the loop body */
  109874. pLevel->p2 = sqlite3VdbeCurrentAddr(v);
  109875. /* Check if the index cursor is past the end of the range. */
  109876. if( nConstraint ){
  109877. op = aEndOp[bRev*2 + endEq];
  109878. sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
  109879. testcase( op==OP_IdxGT ); VdbeCoverageIf(v, op==OP_IdxGT );
  109880. testcase( op==OP_IdxGE ); VdbeCoverageIf(v, op==OP_IdxGE );
  109881. testcase( op==OP_IdxLT ); VdbeCoverageIf(v, op==OP_IdxLT );
  109882. testcase( op==OP_IdxLE ); VdbeCoverageIf(v, op==OP_IdxLE );
  109883. }
  109884. /* Seek the table cursor, if required */
  109885. disableTerm(pLevel, pRangeStart);
  109886. disableTerm(pLevel, pRangeEnd);
  109887. if( omitTable ){
  109888. /* pIdx is a covering index. No need to access the main table. */
  109889. }else if( HasRowid(pIdx->pTable) ){
  109890. iRowidReg = ++pParse->nMem;
  109891. sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, iRowidReg);
  109892. sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
  109893. sqlite3VdbeAddOp2(v, OP_Seek, iCur, iRowidReg); /* Deferred seek */
  109894. }else if( iCur!=iIdxCur ){
  109895. Index *pPk = sqlite3PrimaryKeyIndex(pIdx->pTable);
  109896. iRowidReg = sqlite3GetTempRange(pParse, pPk->nKeyCol);
  109897. for(j=0; j<pPk->nKeyCol; j++){
  109898. k = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[j]);
  109899. sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, k, iRowidReg+j);
  109900. }
  109901. sqlite3VdbeAddOp4Int(v, OP_NotFound, iCur, addrCont,
  109902. iRowidReg, pPk->nKeyCol); VdbeCoverage(v);
  109903. }
  109904. /* Record the instruction used to terminate the loop. Disable
  109905. ** WHERE clause terms made redundant by the index range scan.
  109906. */
  109907. if( pLoop->wsFlags & WHERE_ONEROW ){
  109908. pLevel->op = OP_Noop;
  109909. }else if( bRev ){
  109910. pLevel->op = OP_Prev;
  109911. }else{
  109912. pLevel->op = OP_Next;
  109913. }
  109914. pLevel->p1 = iIdxCur;
  109915. pLevel->p3 = (pLoop->wsFlags&WHERE_UNQ_WANTED)!=0 ? 1:0;
  109916. if( (pLoop->wsFlags & WHERE_CONSTRAINT)==0 ){
  109917. pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
  109918. }else{
  109919. assert( pLevel->p5==0 );
  109920. }
  109921. }else
  109922. #ifndef SQLITE_OMIT_OR_OPTIMIZATION
  109923. if( pLoop->wsFlags & WHERE_MULTI_OR ){
  109924. /* Case 5: Two or more separately indexed terms connected by OR
  109925. **
  109926. ** Example:
  109927. **
  109928. ** CREATE TABLE t1(a,b,c,d);
  109929. ** CREATE INDEX i1 ON t1(a);
  109930. ** CREATE INDEX i2 ON t1(b);
  109931. ** CREATE INDEX i3 ON t1(c);
  109932. **
  109933. ** SELECT * FROM t1 WHERE a=5 OR b=7 OR (c=11 AND d=13)
  109934. **
  109935. ** In the example, there are three indexed terms connected by OR.
  109936. ** The top of the loop looks like this:
  109937. **
  109938. ** Null 1 # Zero the rowset in reg 1
  109939. **
  109940. ** Then, for each indexed term, the following. The arguments to
  109941. ** RowSetTest are such that the rowid of the current row is inserted
  109942. ** into the RowSet. If it is already present, control skips the
  109943. ** Gosub opcode and jumps straight to the code generated by WhereEnd().
  109944. **
  109945. ** sqlite3WhereBegin(<term>)
  109946. ** RowSetTest # Insert rowid into rowset
  109947. ** Gosub 2 A
  109948. ** sqlite3WhereEnd()
  109949. **
  109950. ** Following the above, code to terminate the loop. Label A, the target
  109951. ** of the Gosub above, jumps to the instruction right after the Goto.
  109952. **
  109953. ** Null 1 # Zero the rowset in reg 1
  109954. ** Goto B # The loop is finished.
  109955. **
  109956. ** A: <loop body> # Return data, whatever.
  109957. **
  109958. ** Return 2 # Jump back to the Gosub
  109959. **
  109960. ** B: <after the loop>
  109961. **
  109962. ** Added 2014-05-26: If the table is a WITHOUT ROWID table, then
  109963. ** use an ephemeral index instead of a RowSet to record the primary
  109964. ** keys of the rows we have already seen.
  109965. **
  109966. */
  109967. WhereClause *pOrWc; /* The OR-clause broken out into subterms */
  109968. SrcList *pOrTab; /* Shortened table list or OR-clause generation */
  109969. Index *pCov = 0; /* Potential covering index (or NULL) */
  109970. int iCovCur = pParse->nTab++; /* Cursor used for index scans (if any) */
  109971. int regReturn = ++pParse->nMem; /* Register used with OP_Gosub */
  109972. int regRowset = 0; /* Register for RowSet object */
  109973. int regRowid = 0; /* Register holding rowid */
  109974. int iLoopBody = sqlite3VdbeMakeLabel(v); /* Start of loop body */
  109975. int iRetInit; /* Address of regReturn init */
  109976. int untestedTerms = 0; /* Some terms not completely tested */
  109977. int ii; /* Loop counter */
  109978. u16 wctrlFlags; /* Flags for sub-WHERE clause */
  109979. Expr *pAndExpr = 0; /* An ".. AND (...)" expression */
  109980. Table *pTab = pTabItem->pTab;
  109981. pTerm = pLoop->aLTerm[0];
  109982. assert( pTerm!=0 );
  109983. assert( pTerm->eOperator & WO_OR );
  109984. assert( (pTerm->wtFlags & TERM_ORINFO)!=0 );
  109985. pOrWc = &pTerm->u.pOrInfo->wc;
  109986. pLevel->op = OP_Return;
  109987. pLevel->p1 = regReturn;
  109988. /* Set up a new SrcList in pOrTab containing the table being scanned
  109989. ** by this loop in the a[0] slot and all notReady tables in a[1..] slots.
  109990. ** This becomes the SrcList in the recursive call to sqlite3WhereBegin().
  109991. */
  109992. if( pWInfo->nLevel>1 ){
  109993. int nNotReady; /* The number of notReady tables */
  109994. struct SrcList_item *origSrc; /* Original list of tables */
  109995. nNotReady = pWInfo->nLevel - iLevel - 1;
  109996. pOrTab = sqlite3StackAllocRaw(db,
  109997. sizeof(*pOrTab)+ nNotReady*sizeof(pOrTab->a[0]));
  109998. if( pOrTab==0 ) return notReady;
  109999. pOrTab->nAlloc = (u8)(nNotReady + 1);
  110000. pOrTab->nSrc = pOrTab->nAlloc;
  110001. memcpy(pOrTab->a, pTabItem, sizeof(*pTabItem));
  110002. origSrc = pWInfo->pTabList->a;
  110003. for(k=1; k<=nNotReady; k++){
  110004. memcpy(&pOrTab->a[k], &origSrc[pLevel[k].iFrom], sizeof(pOrTab->a[k]));
  110005. }
  110006. }else{
  110007. pOrTab = pWInfo->pTabList;
  110008. }
  110009. /* Initialize the rowset register to contain NULL. An SQL NULL is
  110010. ** equivalent to an empty rowset. Or, create an ephemeral index
  110011. ** capable of holding primary keys in the case of a WITHOUT ROWID.
  110012. **
  110013. ** Also initialize regReturn to contain the address of the instruction
  110014. ** immediately following the OP_Return at the bottom of the loop. This
  110015. ** is required in a few obscure LEFT JOIN cases where control jumps
  110016. ** over the top of the loop into the body of it. In this case the
  110017. ** correct response for the end-of-loop code (the OP_Return) is to
  110018. ** fall through to the next instruction, just as an OP_Next does if
  110019. ** called on an uninitialized cursor.
  110020. */
  110021. if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
  110022. if( HasRowid(pTab) ){
  110023. regRowset = ++pParse->nMem;
  110024. sqlite3VdbeAddOp2(v, OP_Null, 0, regRowset);
  110025. }else{
  110026. Index *pPk = sqlite3PrimaryKeyIndex(pTab);
  110027. regRowset = pParse->nTab++;
  110028. sqlite3VdbeAddOp2(v, OP_OpenEphemeral, regRowset, pPk->nKeyCol);
  110029. sqlite3VdbeSetP4KeyInfo(pParse, pPk);
  110030. }
  110031. regRowid = ++pParse->nMem;
  110032. }
  110033. iRetInit = sqlite3VdbeAddOp2(v, OP_Integer, 0, regReturn);
  110034. /* If the original WHERE clause is z of the form: (x1 OR x2 OR ...) AND y
  110035. ** Then for every term xN, evaluate as the subexpression: xN AND z
  110036. ** That way, terms in y that are factored into the disjunction will
  110037. ** be picked up by the recursive calls to sqlite3WhereBegin() below.
  110038. **
  110039. ** Actually, each subexpression is converted to "xN AND w" where w is
  110040. ** the "interesting" terms of z - terms that did not originate in the
  110041. ** ON or USING clause of a LEFT JOIN, and terms that are usable as
  110042. ** indices.
  110043. **
  110044. ** This optimization also only applies if the (x1 OR x2 OR ...) term
  110045. ** is not contained in the ON clause of a LEFT JOIN.
  110046. ** See ticket http://www.sqlite.org/src/info/f2369304e4
  110047. */
  110048. if( pWC->nTerm>1 ){
  110049. int iTerm;
  110050. for(iTerm=0; iTerm<pWC->nTerm; iTerm++){
  110051. Expr *pExpr = pWC->a[iTerm].pExpr;
  110052. if( &pWC->a[iTerm] == pTerm ) continue;
  110053. if( ExprHasProperty(pExpr, EP_FromJoin) ) continue;
  110054. testcase( pWC->a[iTerm].wtFlags & TERM_ORINFO );
  110055. testcase( pWC->a[iTerm].wtFlags & TERM_VIRTUAL );
  110056. if( pWC->a[iTerm].wtFlags & (TERM_ORINFO|TERM_VIRTUAL) ) continue;
  110057. if( (pWC->a[iTerm].eOperator & WO_ALL)==0 ) continue;
  110058. pExpr = sqlite3ExprDup(db, pExpr, 0);
  110059. pAndExpr = sqlite3ExprAnd(db, pAndExpr, pExpr);
  110060. }
  110061. if( pAndExpr ){
  110062. pAndExpr = sqlite3PExpr(pParse, TK_AND, 0, pAndExpr, 0);
  110063. }
  110064. }
  110065. /* Run a separate WHERE clause for each term of the OR clause. After
  110066. ** eliminating duplicates from other WHERE clauses, the action for each
  110067. ** sub-WHERE clause is to to invoke the main loop body as a subroutine.
  110068. */
  110069. wctrlFlags = WHERE_OMIT_OPEN_CLOSE
  110070. | WHERE_FORCE_TABLE
  110071. | WHERE_ONETABLE_ONLY;
  110072. for(ii=0; ii<pOrWc->nTerm; ii++){
  110073. WhereTerm *pOrTerm = &pOrWc->a[ii];
  110074. if( pOrTerm->leftCursor==iCur || (pOrTerm->eOperator & WO_AND)!=0 ){
  110075. WhereInfo *pSubWInfo; /* Info for single OR-term scan */
  110076. Expr *pOrExpr = pOrTerm->pExpr; /* Current OR clause term */
  110077. int j1 = 0; /* Address of jump operation */
  110078. if( pAndExpr && !ExprHasProperty(pOrExpr, EP_FromJoin) ){
  110079. pAndExpr->pLeft = pOrExpr;
  110080. pOrExpr = pAndExpr;
  110081. }
  110082. /* Loop through table entries that match term pOrTerm. */
  110083. WHERETRACE(0xffff, ("Subplan for OR-clause:\n"));
  110084. pSubWInfo = sqlite3WhereBegin(pParse, pOrTab, pOrExpr, 0, 0,
  110085. wctrlFlags, iCovCur);
  110086. assert( pSubWInfo || pParse->nErr || db->mallocFailed );
  110087. if( pSubWInfo ){
  110088. WhereLoop *pSubLoop;
  110089. explainOneScan(
  110090. pParse, pOrTab, &pSubWInfo->a[0], iLevel, pLevel->iFrom, 0
  110091. );
  110092. /* This is the sub-WHERE clause body. First skip over
  110093. ** duplicate rows from prior sub-WHERE clauses, and record the
  110094. ** rowid (or PRIMARY KEY) for the current row so that the same
  110095. ** row will be skipped in subsequent sub-WHERE clauses.
  110096. */
  110097. if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
  110098. int r;
  110099. int iSet = ((ii==pOrWc->nTerm-1)?-1:ii);
  110100. if( HasRowid(pTab) ){
  110101. r = sqlite3ExprCodeGetColumn(pParse, pTab, -1, iCur, regRowid, 0);
  110102. j1 = sqlite3VdbeAddOp4Int(v, OP_RowSetTest, regRowset, 0, r,iSet);
  110103. VdbeCoverage(v);
  110104. }else{
  110105. Index *pPk = sqlite3PrimaryKeyIndex(pTab);
  110106. int nPk = pPk->nKeyCol;
  110107. int iPk;
  110108. /* Read the PK into an array of temp registers. */
  110109. r = sqlite3GetTempRange(pParse, nPk);
  110110. for(iPk=0; iPk<nPk; iPk++){
  110111. int iCol = pPk->aiColumn[iPk];
  110112. sqlite3ExprCodeGetColumn(pParse, pTab, iCol, iCur, r+iPk, 0);
  110113. }
  110114. /* Check if the temp table already contains this key. If so,
  110115. ** the row has already been included in the result set and
  110116. ** can be ignored (by jumping past the Gosub below). Otherwise,
  110117. ** insert the key into the temp table and proceed with processing
  110118. ** the row.
  110119. **
  110120. ** Use some of the same optimizations as OP_RowSetTest: If iSet
  110121. ** is zero, assume that the key cannot already be present in
  110122. ** the temp table. And if iSet is -1, assume that there is no
  110123. ** need to insert the key into the temp table, as it will never
  110124. ** be tested for. */
  110125. if( iSet ){
  110126. j1 = sqlite3VdbeAddOp4Int(v, OP_Found, regRowset, 0, r, nPk);
  110127. VdbeCoverage(v);
  110128. }
  110129. if( iSet>=0 ){
  110130. sqlite3VdbeAddOp3(v, OP_MakeRecord, r, nPk, regRowid);
  110131. sqlite3VdbeAddOp3(v, OP_IdxInsert, regRowset, regRowid, 0);
  110132. if( iSet ) sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
  110133. }
  110134. /* Release the array of temp registers */
  110135. sqlite3ReleaseTempRange(pParse, r, nPk);
  110136. }
  110137. }
  110138. /* Invoke the main loop body as a subroutine */
  110139. sqlite3VdbeAddOp2(v, OP_Gosub, regReturn, iLoopBody);
  110140. /* Jump here (skipping the main loop body subroutine) if the
  110141. ** current sub-WHERE row is a duplicate from prior sub-WHEREs. */
  110142. if( j1 ) sqlite3VdbeJumpHere(v, j1);
  110143. /* The pSubWInfo->untestedTerms flag means that this OR term
  110144. ** contained one or more AND term from a notReady table. The
  110145. ** terms from the notReady table could not be tested and will
  110146. ** need to be tested later.
  110147. */
  110148. if( pSubWInfo->untestedTerms ) untestedTerms = 1;
  110149. /* If all of the OR-connected terms are optimized using the same
  110150. ** index, and the index is opened using the same cursor number
  110151. ** by each call to sqlite3WhereBegin() made by this loop, it may
  110152. ** be possible to use that index as a covering index.
  110153. **
  110154. ** If the call to sqlite3WhereBegin() above resulted in a scan that
  110155. ** uses an index, and this is either the first OR-connected term
  110156. ** processed or the index is the same as that used by all previous
  110157. ** terms, set pCov to the candidate covering index. Otherwise, set
  110158. ** pCov to NULL to indicate that no candidate covering index will
  110159. ** be available.
  110160. */
  110161. pSubLoop = pSubWInfo->a[0].pWLoop;
  110162. assert( (pSubLoop->wsFlags & WHERE_AUTO_INDEX)==0 );
  110163. if( (pSubLoop->wsFlags & WHERE_INDEXED)!=0
  110164. && (ii==0 || pSubLoop->u.btree.pIndex==pCov)
  110165. && (HasRowid(pTab) || !IsPrimaryKeyIndex(pSubLoop->u.btree.pIndex))
  110166. ){
  110167. assert( pSubWInfo->a[0].iIdxCur==iCovCur );
  110168. pCov = pSubLoop->u.btree.pIndex;
  110169. wctrlFlags |= WHERE_REOPEN_IDX;
  110170. }else{
  110171. pCov = 0;
  110172. }
  110173. /* Finish the loop through table entries that match term pOrTerm. */
  110174. sqlite3WhereEnd(pSubWInfo);
  110175. }
  110176. }
  110177. }
  110178. pLevel->u.pCovidx = pCov;
  110179. if( pCov ) pLevel->iIdxCur = iCovCur;
  110180. if( pAndExpr ){
  110181. pAndExpr->pLeft = 0;
  110182. sqlite3ExprDelete(db, pAndExpr);
  110183. }
  110184. sqlite3VdbeChangeP1(v, iRetInit, sqlite3VdbeCurrentAddr(v));
  110185. sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrBrk);
  110186. sqlite3VdbeResolveLabel(v, iLoopBody);
  110187. if( pWInfo->nLevel>1 ) sqlite3StackFree(db, pOrTab);
  110188. if( !untestedTerms ) disableTerm(pLevel, pTerm);
  110189. }else
  110190. #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
  110191. {
  110192. /* Case 6: There is no usable index. We must do a complete
  110193. ** scan of the entire table.
  110194. */
  110195. static const u8 aStep[] = { OP_Next, OP_Prev };
  110196. static const u8 aStart[] = { OP_Rewind, OP_Last };
  110197. assert( bRev==0 || bRev==1 );
  110198. if( pTabItem->isRecursive ){
  110199. /* Tables marked isRecursive have only a single row that is stored in
  110200. ** a pseudo-cursor. No need to Rewind or Next such cursors. */
  110201. pLevel->op = OP_Noop;
  110202. }else{
  110203. pLevel->op = aStep[bRev];
  110204. pLevel->p1 = iCur;
  110205. pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, aStart[bRev], iCur, addrBrk);
  110206. VdbeCoverageIf(v, bRev==0);
  110207. VdbeCoverageIf(v, bRev!=0);
  110208. pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
  110209. }
  110210. }
  110211. /* Insert code to test every subexpression that can be completely
  110212. ** computed using the current set of tables.
  110213. */
  110214. for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
  110215. Expr *pE;
  110216. testcase( pTerm->wtFlags & TERM_VIRTUAL );
  110217. testcase( pTerm->wtFlags & TERM_CODED );
  110218. if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
  110219. if( (pTerm->prereqAll & pLevel->notReady)!=0 ){
  110220. testcase( pWInfo->untestedTerms==0
  110221. && (pWInfo->wctrlFlags & WHERE_ONETABLE_ONLY)!=0 );
  110222. pWInfo->untestedTerms = 1;
  110223. continue;
  110224. }
  110225. pE = pTerm->pExpr;
  110226. assert( pE!=0 );
  110227. if( pLevel->iLeftJoin && !ExprHasProperty(pE, EP_FromJoin) ){
  110228. continue;
  110229. }
  110230. sqlite3ExprIfFalse(pParse, pE, addrCont, SQLITE_JUMPIFNULL);
  110231. pTerm->wtFlags |= TERM_CODED;
  110232. }
  110233. /* Insert code to test for implied constraints based on transitivity
  110234. ** of the "==" operator.
  110235. **
  110236. ** Example: If the WHERE clause contains "t1.a=t2.b" and "t2.b=123"
  110237. ** and we are coding the t1 loop and the t2 loop has not yet coded,
  110238. ** then we cannot use the "t1.a=t2.b" constraint, but we can code
  110239. ** the implied "t1.a=123" constraint.
  110240. */
  110241. for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
  110242. Expr *pE, *pEAlt;
  110243. WhereTerm *pAlt;
  110244. if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
  110245. if( pTerm->eOperator!=(WO_EQUIV|WO_EQ) ) continue;
  110246. if( pTerm->leftCursor!=iCur ) continue;
  110247. if( pLevel->iLeftJoin ) continue;
  110248. pE = pTerm->pExpr;
  110249. assert( !ExprHasProperty(pE, EP_FromJoin) );
  110250. assert( (pTerm->prereqRight & pLevel->notReady)!=0 );
  110251. pAlt = findTerm(pWC, iCur, pTerm->u.leftColumn, notReady, WO_EQ|WO_IN, 0);
  110252. if( pAlt==0 ) continue;
  110253. if( pAlt->wtFlags & (TERM_CODED) ) continue;
  110254. testcase( pAlt->eOperator & WO_EQ );
  110255. testcase( pAlt->eOperator & WO_IN );
  110256. VdbeModuleComment((v, "begin transitive constraint"));
  110257. pEAlt = sqlite3StackAllocRaw(db, sizeof(*pEAlt));
  110258. if( pEAlt ){
  110259. *pEAlt = *pAlt->pExpr;
  110260. pEAlt->pLeft = pE->pLeft;
  110261. sqlite3ExprIfFalse(pParse, pEAlt, addrCont, SQLITE_JUMPIFNULL);
  110262. sqlite3StackFree(db, pEAlt);
  110263. }
  110264. }
  110265. /* For a LEFT OUTER JOIN, generate code that will record the fact that
  110266. ** at least one row of the right table has matched the left table.
  110267. */
  110268. if( pLevel->iLeftJoin ){
  110269. pLevel->addrFirst = sqlite3VdbeCurrentAddr(v);
  110270. sqlite3VdbeAddOp2(v, OP_Integer, 1, pLevel->iLeftJoin);
  110271. VdbeComment((v, "record LEFT JOIN hit"));
  110272. sqlite3ExprCacheClear(pParse);
  110273. for(pTerm=pWC->a, j=0; j<pWC->nTerm; j++, pTerm++){
  110274. testcase( pTerm->wtFlags & TERM_VIRTUAL );
  110275. testcase( pTerm->wtFlags & TERM_CODED );
  110276. if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
  110277. if( (pTerm->prereqAll & pLevel->notReady)!=0 ){
  110278. assert( pWInfo->untestedTerms );
  110279. continue;
  110280. }
  110281. assert( pTerm->pExpr );
  110282. sqlite3ExprIfFalse(pParse, pTerm->pExpr, addrCont, SQLITE_JUMPIFNULL);
  110283. pTerm->wtFlags |= TERM_CODED;
  110284. }
  110285. }
  110286. return pLevel->notReady;
  110287. }
  110288. #ifdef WHERETRACE_ENABLED
  110289. /*
  110290. ** Print the content of a WhereTerm object
  110291. */
  110292. static void whereTermPrint(WhereTerm *pTerm, int iTerm){
  110293. if( pTerm==0 ){
  110294. sqlite3DebugPrintf("TERM-%-3d NULL\n", iTerm);
  110295. }else{
  110296. char zType[4];
  110297. memcpy(zType, "...", 4);
  110298. if( pTerm->wtFlags & TERM_VIRTUAL ) zType[0] = 'V';
  110299. if( pTerm->eOperator & WO_EQUIV ) zType[1] = 'E';
  110300. if( ExprHasProperty(pTerm->pExpr, EP_FromJoin) ) zType[2] = 'L';
  110301. sqlite3DebugPrintf("TERM-%-3d %p %s cursor=%-3d prob=%-3d op=0x%03x\n",
  110302. iTerm, pTerm, zType, pTerm->leftCursor, pTerm->truthProb,
  110303. pTerm->eOperator);
  110304. sqlite3TreeViewExpr(0, pTerm->pExpr, 0);
  110305. }
  110306. }
  110307. #endif
  110308. #ifdef WHERETRACE_ENABLED
  110309. /*
  110310. ** Print a WhereLoop object for debugging purposes
  110311. */
  110312. static void whereLoopPrint(WhereLoop *p, WhereClause *pWC){
  110313. WhereInfo *pWInfo = pWC->pWInfo;
  110314. int nb = 1+(pWInfo->pTabList->nSrc+7)/8;
  110315. struct SrcList_item *pItem = pWInfo->pTabList->a + p->iTab;
  110316. Table *pTab = pItem->pTab;
  110317. sqlite3DebugPrintf("%c%2d.%0*llx.%0*llx", p->cId,
  110318. p->iTab, nb, p->maskSelf, nb, p->prereq);
  110319. sqlite3DebugPrintf(" %12s",
  110320. pItem->zAlias ? pItem->zAlias : pTab->zName);
  110321. if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){
  110322. const char *zName;
  110323. if( p->u.btree.pIndex && (zName = p->u.btree.pIndex->zName)!=0 ){
  110324. if( strncmp(zName, "sqlite_autoindex_", 17)==0 ){
  110325. int i = sqlite3Strlen30(zName) - 1;
  110326. while( zName[i]!='_' ) i--;
  110327. zName += i;
  110328. }
  110329. sqlite3DebugPrintf(".%-16s %2d", zName, p->u.btree.nEq);
  110330. }else{
  110331. sqlite3DebugPrintf("%20s","");
  110332. }
  110333. }else{
  110334. char *z;
  110335. if( p->u.vtab.idxStr ){
  110336. z = sqlite3_mprintf("(%d,\"%s\",%x)",
  110337. p->u.vtab.idxNum, p->u.vtab.idxStr, p->u.vtab.omitMask);
  110338. }else{
  110339. z = sqlite3_mprintf("(%d,%x)", p->u.vtab.idxNum, p->u.vtab.omitMask);
  110340. }
  110341. sqlite3DebugPrintf(" %-19s", z);
  110342. sqlite3_free(z);
  110343. }
  110344. if( p->wsFlags & WHERE_SKIPSCAN ){
  110345. sqlite3DebugPrintf(" f %05x %d-%d", p->wsFlags, p->nLTerm,p->nSkip);
  110346. }else{
  110347. sqlite3DebugPrintf(" f %05x N %d", p->wsFlags, p->nLTerm);
  110348. }
  110349. sqlite3DebugPrintf(" cost %d,%d,%d\n", p->rSetup, p->rRun, p->nOut);
  110350. if( p->nLTerm && (sqlite3WhereTrace & 0x100)!=0 ){
  110351. int i;
  110352. for(i=0; i<p->nLTerm; i++){
  110353. whereTermPrint(p->aLTerm[i], i);
  110354. }
  110355. }
  110356. }
  110357. #endif
  110358. /*
  110359. ** Convert bulk memory into a valid WhereLoop that can be passed
  110360. ** to whereLoopClear harmlessly.
  110361. */
  110362. static void whereLoopInit(WhereLoop *p){
  110363. p->aLTerm = p->aLTermSpace;
  110364. p->nLTerm = 0;
  110365. p->nLSlot = ArraySize(p->aLTermSpace);
  110366. p->wsFlags = 0;
  110367. }
  110368. /*
  110369. ** Clear the WhereLoop.u union. Leave WhereLoop.pLTerm intact.
  110370. */
  110371. static void whereLoopClearUnion(sqlite3 *db, WhereLoop *p){
  110372. if( p->wsFlags & (WHERE_VIRTUALTABLE|WHERE_AUTO_INDEX) ){
  110373. if( (p->wsFlags & WHERE_VIRTUALTABLE)!=0 && p->u.vtab.needFree ){
  110374. sqlite3_free(p->u.vtab.idxStr);
  110375. p->u.vtab.needFree = 0;
  110376. p->u.vtab.idxStr = 0;
  110377. }else if( (p->wsFlags & WHERE_AUTO_INDEX)!=0 && p->u.btree.pIndex!=0 ){
  110378. sqlite3DbFree(db, p->u.btree.pIndex->zColAff);
  110379. sqlite3KeyInfoUnref(p->u.btree.pIndex->pKeyInfo);
  110380. sqlite3DbFree(db, p->u.btree.pIndex);
  110381. p->u.btree.pIndex = 0;
  110382. }
  110383. }
  110384. }
  110385. /*
  110386. ** Deallocate internal memory used by a WhereLoop object
  110387. */
  110388. static void whereLoopClear(sqlite3 *db, WhereLoop *p){
  110389. if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFree(db, p->aLTerm);
  110390. whereLoopClearUnion(db, p);
  110391. whereLoopInit(p);
  110392. }
  110393. /*
  110394. ** Increase the memory allocation for pLoop->aLTerm[] to be at least n.
  110395. */
  110396. static int whereLoopResize(sqlite3 *db, WhereLoop *p, int n){
  110397. WhereTerm **paNew;
  110398. if( p->nLSlot>=n ) return SQLITE_OK;
  110399. n = (n+7)&~7;
  110400. paNew = sqlite3DbMallocRaw(db, sizeof(p->aLTerm[0])*n);
  110401. if( paNew==0 ) return SQLITE_NOMEM;
  110402. memcpy(paNew, p->aLTerm, sizeof(p->aLTerm[0])*p->nLSlot);
  110403. if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFree(db, p->aLTerm);
  110404. p->aLTerm = paNew;
  110405. p->nLSlot = n;
  110406. return SQLITE_OK;
  110407. }
  110408. /*
  110409. ** Transfer content from the second pLoop into the first.
  110410. */
  110411. static int whereLoopXfer(sqlite3 *db, WhereLoop *pTo, WhereLoop *pFrom){
  110412. whereLoopClearUnion(db, pTo);
  110413. if( whereLoopResize(db, pTo, pFrom->nLTerm) ){
  110414. memset(&pTo->u, 0, sizeof(pTo->u));
  110415. return SQLITE_NOMEM;
  110416. }
  110417. memcpy(pTo, pFrom, WHERE_LOOP_XFER_SZ);
  110418. memcpy(pTo->aLTerm, pFrom->aLTerm, pTo->nLTerm*sizeof(pTo->aLTerm[0]));
  110419. if( pFrom->wsFlags & WHERE_VIRTUALTABLE ){
  110420. pFrom->u.vtab.needFree = 0;
  110421. }else if( (pFrom->wsFlags & WHERE_AUTO_INDEX)!=0 ){
  110422. pFrom->u.btree.pIndex = 0;
  110423. }
  110424. return SQLITE_OK;
  110425. }
  110426. /*
  110427. ** Delete a WhereLoop object
  110428. */
  110429. static void whereLoopDelete(sqlite3 *db, WhereLoop *p){
  110430. whereLoopClear(db, p);
  110431. sqlite3DbFree(db, p);
  110432. }
  110433. /*
  110434. ** Free a WhereInfo structure
  110435. */
  110436. static void whereInfoFree(sqlite3 *db, WhereInfo *pWInfo){
  110437. if( ALWAYS(pWInfo) ){
  110438. whereClauseClear(&pWInfo->sWC);
  110439. while( pWInfo->pLoops ){
  110440. WhereLoop *p = pWInfo->pLoops;
  110441. pWInfo->pLoops = p->pNextLoop;
  110442. whereLoopDelete(db, p);
  110443. }
  110444. sqlite3DbFree(db, pWInfo);
  110445. }
  110446. }
  110447. /*
  110448. ** Return TRUE if both of the following are true:
  110449. **
  110450. ** (1) X has the same or lower cost that Y
  110451. ** (2) X is a proper subset of Y
  110452. **
  110453. ** By "proper subset" we mean that X uses fewer WHERE clause terms
  110454. ** than Y and that every WHERE clause term used by X is also used
  110455. ** by Y.
  110456. **
  110457. ** If X is a proper subset of Y then Y is a better choice and ought
  110458. ** to have a lower cost. This routine returns TRUE when that cost
  110459. ** relationship is inverted and needs to be adjusted.
  110460. */
  110461. static int whereLoopCheaperProperSubset(
  110462. const WhereLoop *pX, /* First WhereLoop to compare */
  110463. const WhereLoop *pY /* Compare against this WhereLoop */
  110464. ){
  110465. int i, j;
  110466. if( pX->nLTerm-pX->nSkip >= pY->nLTerm-pY->nSkip ){
  110467. return 0; /* X is not a subset of Y */
  110468. }
  110469. if( pX->rRun >= pY->rRun ){
  110470. if( pX->rRun > pY->rRun ) return 0; /* X costs more than Y */
  110471. if( pX->nOut > pY->nOut ) return 0; /* X costs more than Y */
  110472. }
  110473. for(i=pX->nLTerm-1; i>=0; i--){
  110474. if( pX->aLTerm[i]==0 ) continue;
  110475. for(j=pY->nLTerm-1; j>=0; j--){
  110476. if( pY->aLTerm[j]==pX->aLTerm[i] ) break;
  110477. }
  110478. if( j<0 ) return 0; /* X not a subset of Y since term X[i] not used by Y */
  110479. }
  110480. return 1; /* All conditions meet */
  110481. }
  110482. /*
  110483. ** Try to adjust the cost of WhereLoop pTemplate upwards or downwards so
  110484. ** that:
  110485. **
  110486. ** (1) pTemplate costs less than any other WhereLoops that are a proper
  110487. ** subset of pTemplate
  110488. **
  110489. ** (2) pTemplate costs more than any other WhereLoops for which pTemplate
  110490. ** is a proper subset.
  110491. **
  110492. ** To say "WhereLoop X is a proper subset of Y" means that X uses fewer
  110493. ** WHERE clause terms than Y and that every WHERE clause term used by X is
  110494. ** also used by Y.
  110495. */
  110496. static void whereLoopAdjustCost(const WhereLoop *p, WhereLoop *pTemplate){
  110497. if( (pTemplate->wsFlags & WHERE_INDEXED)==0 ) return;
  110498. for(; p; p=p->pNextLoop){
  110499. if( p->iTab!=pTemplate->iTab ) continue;
  110500. if( (p->wsFlags & WHERE_INDEXED)==0 ) continue;
  110501. if( whereLoopCheaperProperSubset(p, pTemplate) ){
  110502. /* Adjust pTemplate cost downward so that it is cheaper than its
  110503. ** subset p. Except, do not adjust the cost estimate downward for
  110504. ** a loop that skips more columns. */
  110505. if( pTemplate->nSkip>p->nSkip ) continue;
  110506. WHERETRACE(0x80,("subset cost adjustment %d,%d to %d,%d\n",
  110507. pTemplate->rRun, pTemplate->nOut, p->rRun, p->nOut-1));
  110508. pTemplate->rRun = p->rRun;
  110509. pTemplate->nOut = p->nOut - 1;
  110510. }else if( whereLoopCheaperProperSubset(pTemplate, p) ){
  110511. /* Adjust pTemplate cost upward so that it is costlier than p since
  110512. ** pTemplate is a proper subset of p */
  110513. WHERETRACE(0x80,("subset cost adjustment %d,%d to %d,%d\n",
  110514. pTemplate->rRun, pTemplate->nOut, p->rRun, p->nOut+1));
  110515. pTemplate->rRun = p->rRun;
  110516. pTemplate->nOut = p->nOut + 1;
  110517. }
  110518. }
  110519. }
  110520. /*
  110521. ** Search the list of WhereLoops in *ppPrev looking for one that can be
  110522. ** supplanted by pTemplate.
  110523. **
  110524. ** Return NULL if the WhereLoop list contains an entry that can supplant
  110525. ** pTemplate, in other words if pTemplate does not belong on the list.
  110526. **
  110527. ** If pX is a WhereLoop that pTemplate can supplant, then return the
  110528. ** link that points to pX.
  110529. **
  110530. ** If pTemplate cannot supplant any existing element of the list but needs
  110531. ** to be added to the list, then return a pointer to the tail of the list.
  110532. */
  110533. static WhereLoop **whereLoopFindLesser(
  110534. WhereLoop **ppPrev,
  110535. const WhereLoop *pTemplate
  110536. ){
  110537. WhereLoop *p;
  110538. for(p=(*ppPrev); p; ppPrev=&p->pNextLoop, p=*ppPrev){
  110539. if( p->iTab!=pTemplate->iTab || p->iSortIdx!=pTemplate->iSortIdx ){
  110540. /* If either the iTab or iSortIdx values for two WhereLoop are different
  110541. ** then those WhereLoops need to be considered separately. Neither is
  110542. ** a candidate to replace the other. */
  110543. continue;
  110544. }
  110545. /* In the current implementation, the rSetup value is either zero
  110546. ** or the cost of building an automatic index (NlogN) and the NlogN
  110547. ** is the same for compatible WhereLoops. */
  110548. assert( p->rSetup==0 || pTemplate->rSetup==0
  110549. || p->rSetup==pTemplate->rSetup );
  110550. /* whereLoopAddBtree() always generates and inserts the automatic index
  110551. ** case first. Hence compatible candidate WhereLoops never have a larger
  110552. ** rSetup. Call this SETUP-INVARIANT */
  110553. assert( p->rSetup>=pTemplate->rSetup );
  110554. /* Any loop using an appliation-defined index (or PRIMARY KEY or
  110555. ** UNIQUE constraint) with one or more == constraints is better
  110556. ** than an automatic index. */
  110557. if( (p->wsFlags & WHERE_AUTO_INDEX)!=0
  110558. && (pTemplate->wsFlags & WHERE_INDEXED)!=0
  110559. && (pTemplate->wsFlags & WHERE_COLUMN_EQ)!=0
  110560. && (p->prereq & pTemplate->prereq)==pTemplate->prereq
  110561. ){
  110562. break;
  110563. }
  110564. /* If existing WhereLoop p is better than pTemplate, pTemplate can be
  110565. ** discarded. WhereLoop p is better if:
  110566. ** (1) p has no more dependencies than pTemplate, and
  110567. ** (2) p has an equal or lower cost than pTemplate
  110568. */
  110569. if( (p->prereq & pTemplate->prereq)==p->prereq /* (1) */
  110570. && p->rSetup<=pTemplate->rSetup /* (2a) */
  110571. && p->rRun<=pTemplate->rRun /* (2b) */
  110572. && p->nOut<=pTemplate->nOut /* (2c) */
  110573. ){
  110574. return 0; /* Discard pTemplate */
  110575. }
  110576. /* If pTemplate is always better than p, then cause p to be overwritten
  110577. ** with pTemplate. pTemplate is better than p if:
  110578. ** (1) pTemplate has no more dependences than p, and
  110579. ** (2) pTemplate has an equal or lower cost than p.
  110580. */
  110581. if( (p->prereq & pTemplate->prereq)==pTemplate->prereq /* (1) */
  110582. && p->rRun>=pTemplate->rRun /* (2a) */
  110583. && p->nOut>=pTemplate->nOut /* (2b) */
  110584. ){
  110585. assert( p->rSetup>=pTemplate->rSetup ); /* SETUP-INVARIANT above */
  110586. break; /* Cause p to be overwritten by pTemplate */
  110587. }
  110588. }
  110589. return ppPrev;
  110590. }
  110591. /*
  110592. ** Insert or replace a WhereLoop entry using the template supplied.
  110593. **
  110594. ** An existing WhereLoop entry might be overwritten if the new template
  110595. ** is better and has fewer dependencies. Or the template will be ignored
  110596. ** and no insert will occur if an existing WhereLoop is faster and has
  110597. ** fewer dependencies than the template. Otherwise a new WhereLoop is
  110598. ** added based on the template.
  110599. **
  110600. ** If pBuilder->pOrSet is not NULL then we care about only the
  110601. ** prerequisites and rRun and nOut costs of the N best loops. That
  110602. ** information is gathered in the pBuilder->pOrSet object. This special
  110603. ** processing mode is used only for OR clause processing.
  110604. **
  110605. ** When accumulating multiple loops (when pBuilder->pOrSet is NULL) we
  110606. ** still might overwrite similar loops with the new template if the
  110607. ** new template is better. Loops may be overwritten if the following
  110608. ** conditions are met:
  110609. **
  110610. ** (1) They have the same iTab.
  110611. ** (2) They have the same iSortIdx.
  110612. ** (3) The template has same or fewer dependencies than the current loop
  110613. ** (4) The template has the same or lower cost than the current loop
  110614. */
  110615. static int whereLoopInsert(WhereLoopBuilder *pBuilder, WhereLoop *pTemplate){
  110616. WhereLoop **ppPrev, *p;
  110617. WhereInfo *pWInfo = pBuilder->pWInfo;
  110618. sqlite3 *db = pWInfo->pParse->db;
  110619. /* If pBuilder->pOrSet is defined, then only keep track of the costs
  110620. ** and prereqs.
  110621. */
  110622. if( pBuilder->pOrSet!=0 ){
  110623. #if WHERETRACE_ENABLED
  110624. u16 n = pBuilder->pOrSet->n;
  110625. int x =
  110626. #endif
  110627. whereOrInsert(pBuilder->pOrSet, pTemplate->prereq, pTemplate->rRun,
  110628. pTemplate->nOut);
  110629. #if WHERETRACE_ENABLED /* 0x8 */
  110630. if( sqlite3WhereTrace & 0x8 ){
  110631. sqlite3DebugPrintf(x?" or-%d: ":" or-X: ", n);
  110632. whereLoopPrint(pTemplate, pBuilder->pWC);
  110633. }
  110634. #endif
  110635. return SQLITE_OK;
  110636. }
  110637. /* Look for an existing WhereLoop to replace with pTemplate
  110638. */
  110639. whereLoopAdjustCost(pWInfo->pLoops, pTemplate);
  110640. ppPrev = whereLoopFindLesser(&pWInfo->pLoops, pTemplate);
  110641. if( ppPrev==0 ){
  110642. /* There already exists a WhereLoop on the list that is better
  110643. ** than pTemplate, so just ignore pTemplate */
  110644. #if WHERETRACE_ENABLED /* 0x8 */
  110645. if( sqlite3WhereTrace & 0x8 ){
  110646. sqlite3DebugPrintf(" skip: ");
  110647. whereLoopPrint(pTemplate, pBuilder->pWC);
  110648. }
  110649. #endif
  110650. return SQLITE_OK;
  110651. }else{
  110652. p = *ppPrev;
  110653. }
  110654. /* If we reach this point it means that either p[] should be overwritten
  110655. ** with pTemplate[] if p[] exists, or if p==NULL then allocate a new
  110656. ** WhereLoop and insert it.
  110657. */
  110658. #if WHERETRACE_ENABLED /* 0x8 */
  110659. if( sqlite3WhereTrace & 0x8 ){
  110660. if( p!=0 ){
  110661. sqlite3DebugPrintf("replace: ");
  110662. whereLoopPrint(p, pBuilder->pWC);
  110663. }
  110664. sqlite3DebugPrintf(" add: ");
  110665. whereLoopPrint(pTemplate, pBuilder->pWC);
  110666. }
  110667. #endif
  110668. if( p==0 ){
  110669. /* Allocate a new WhereLoop to add to the end of the list */
  110670. *ppPrev = p = sqlite3DbMallocRaw(db, sizeof(WhereLoop));
  110671. if( p==0 ) return SQLITE_NOMEM;
  110672. whereLoopInit(p);
  110673. p->pNextLoop = 0;
  110674. }else{
  110675. /* We will be overwriting WhereLoop p[]. But before we do, first
  110676. ** go through the rest of the list and delete any other entries besides
  110677. ** p[] that are also supplated by pTemplate */
  110678. WhereLoop **ppTail = &p->pNextLoop;
  110679. WhereLoop *pToDel;
  110680. while( *ppTail ){
  110681. ppTail = whereLoopFindLesser(ppTail, pTemplate);
  110682. if( ppTail==0 ) break;
  110683. pToDel = *ppTail;
  110684. if( pToDel==0 ) break;
  110685. *ppTail = pToDel->pNextLoop;
  110686. #if WHERETRACE_ENABLED /* 0x8 */
  110687. if( sqlite3WhereTrace & 0x8 ){
  110688. sqlite3DebugPrintf(" delete: ");
  110689. whereLoopPrint(pToDel, pBuilder->pWC);
  110690. }
  110691. #endif
  110692. whereLoopDelete(db, pToDel);
  110693. }
  110694. }
  110695. whereLoopXfer(db, p, pTemplate);
  110696. if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){
  110697. Index *pIndex = p->u.btree.pIndex;
  110698. if( pIndex && pIndex->tnum==0 ){
  110699. p->u.btree.pIndex = 0;
  110700. }
  110701. }
  110702. return SQLITE_OK;
  110703. }
  110704. /*
  110705. ** Adjust the WhereLoop.nOut value downward to account for terms of the
  110706. ** WHERE clause that reference the loop but which are not used by an
  110707. ** index.
  110708. **
  110709. ** In the current implementation, the first extra WHERE clause term reduces
  110710. ** the number of output rows by a factor of 10 and each additional term
  110711. ** reduces the number of output rows by sqrt(2).
  110712. */
  110713. static void whereLoopOutputAdjust(
  110714. WhereClause *pWC, /* The WHERE clause */
  110715. WhereLoop *pLoop, /* The loop to adjust downward */
  110716. LogEst nRow /* Number of rows in the entire table */
  110717. ){
  110718. WhereTerm *pTerm, *pX;
  110719. Bitmask notAllowed = ~(pLoop->prereq|pLoop->maskSelf);
  110720. int i, j;
  110721. int nEq = 0; /* Number of = constraints not within likely()/unlikely() */
  110722. for(i=pWC->nTerm, pTerm=pWC->a; i>0; i--, pTerm++){
  110723. if( (pTerm->wtFlags & TERM_VIRTUAL)!=0 ) break;
  110724. if( (pTerm->prereqAll & pLoop->maskSelf)==0 ) continue;
  110725. if( (pTerm->prereqAll & notAllowed)!=0 ) continue;
  110726. for(j=pLoop->nLTerm-1; j>=0; j--){
  110727. pX = pLoop->aLTerm[j];
  110728. if( pX==0 ) continue;
  110729. if( pX==pTerm ) break;
  110730. if( pX->iParent>=0 && (&pWC->a[pX->iParent])==pTerm ) break;
  110731. }
  110732. if( j<0 ){
  110733. if( pTerm->truthProb<=0 ){
  110734. pLoop->nOut += pTerm->truthProb;
  110735. }else{
  110736. pLoop->nOut--;
  110737. if( pTerm->eOperator&WO_EQ ) nEq++;
  110738. }
  110739. }
  110740. }
  110741. /* TUNING: If there is at least one equality constraint in the WHERE
  110742. ** clause that does not have a likelihood() explicitly assigned to it
  110743. ** then do not let the estimated number of output rows exceed half
  110744. ** the number of rows in the table. */
  110745. if( nEq && pLoop->nOut>nRow-10 ){
  110746. pLoop->nOut = nRow - 10;
  110747. }
  110748. }
  110749. /*
  110750. ** Adjust the cost C by the costMult facter T. This only occurs if
  110751. ** compiled with -DSQLITE_ENABLE_COSTMULT
  110752. */
  110753. #ifdef SQLITE_ENABLE_COSTMULT
  110754. # define ApplyCostMultiplier(C,T) C += T
  110755. #else
  110756. # define ApplyCostMultiplier(C,T)
  110757. #endif
  110758. /*
  110759. ** We have so far matched pBuilder->pNew->u.btree.nEq terms of the
  110760. ** index pIndex. Try to match one more.
  110761. **
  110762. ** When this function is called, pBuilder->pNew->nOut contains the
  110763. ** number of rows expected to be visited by filtering using the nEq
  110764. ** terms only. If it is modified, this value is restored before this
  110765. ** function returns.
  110766. **
  110767. ** If pProbe->tnum==0, that means pIndex is a fake index used for the
  110768. ** INTEGER PRIMARY KEY.
  110769. */
  110770. static int whereLoopAddBtreeIndex(
  110771. WhereLoopBuilder *pBuilder, /* The WhereLoop factory */
  110772. struct SrcList_item *pSrc, /* FROM clause term being analyzed */
  110773. Index *pProbe, /* An index on pSrc */
  110774. LogEst nInMul /* log(Number of iterations due to IN) */
  110775. ){
  110776. WhereInfo *pWInfo = pBuilder->pWInfo; /* WHERE analyse context */
  110777. Parse *pParse = pWInfo->pParse; /* Parsing context */
  110778. sqlite3 *db = pParse->db; /* Database connection malloc context */
  110779. WhereLoop *pNew; /* Template WhereLoop under construction */
  110780. WhereTerm *pTerm; /* A WhereTerm under consideration */
  110781. int opMask; /* Valid operators for constraints */
  110782. WhereScan scan; /* Iterator for WHERE terms */
  110783. Bitmask saved_prereq; /* Original value of pNew->prereq */
  110784. u16 saved_nLTerm; /* Original value of pNew->nLTerm */
  110785. u16 saved_nEq; /* Original value of pNew->u.btree.nEq */
  110786. u16 saved_nSkip; /* Original value of pNew->nSkip */
  110787. u32 saved_wsFlags; /* Original value of pNew->wsFlags */
  110788. LogEst saved_nOut; /* Original value of pNew->nOut */
  110789. int iCol; /* Index of the column in the table */
  110790. int rc = SQLITE_OK; /* Return code */
  110791. LogEst rSize; /* Number of rows in the table */
  110792. LogEst rLogSize; /* Logarithm of table size */
  110793. WhereTerm *pTop = 0, *pBtm = 0; /* Top and bottom range constraints */
  110794. pNew = pBuilder->pNew;
  110795. if( db->mallocFailed ) return SQLITE_NOMEM;
  110796. assert( (pNew->wsFlags & WHERE_VIRTUALTABLE)==0 );
  110797. assert( (pNew->wsFlags & WHERE_TOP_LIMIT)==0 );
  110798. if( pNew->wsFlags & WHERE_BTM_LIMIT ){
  110799. opMask = WO_LT|WO_LE;
  110800. }else if( pProbe->tnum<=0 || (pSrc->jointype & JT_LEFT)!=0 ){
  110801. opMask = WO_EQ|WO_IN|WO_GT|WO_GE|WO_LT|WO_LE;
  110802. }else{
  110803. opMask = WO_EQ|WO_IN|WO_ISNULL|WO_GT|WO_GE|WO_LT|WO_LE;
  110804. }
  110805. if( pProbe->bUnordered ) opMask &= ~(WO_GT|WO_GE|WO_LT|WO_LE);
  110806. assert( pNew->u.btree.nEq<pProbe->nColumn );
  110807. iCol = pProbe->aiColumn[pNew->u.btree.nEq];
  110808. pTerm = whereScanInit(&scan, pBuilder->pWC, pSrc->iCursor, iCol,
  110809. opMask, pProbe);
  110810. saved_nEq = pNew->u.btree.nEq;
  110811. saved_nSkip = pNew->nSkip;
  110812. saved_nLTerm = pNew->nLTerm;
  110813. saved_wsFlags = pNew->wsFlags;
  110814. saved_prereq = pNew->prereq;
  110815. saved_nOut = pNew->nOut;
  110816. pNew->rSetup = 0;
  110817. rSize = pProbe->aiRowLogEst[0];
  110818. rLogSize = estLog(rSize);
  110819. for(; rc==SQLITE_OK && pTerm!=0; pTerm = whereScanNext(&scan)){
  110820. u16 eOp = pTerm->eOperator; /* Shorthand for pTerm->eOperator */
  110821. LogEst rCostIdx;
  110822. LogEst nOutUnadjusted; /* nOut before IN() and WHERE adjustments */
  110823. int nIn = 0;
  110824. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  110825. int nRecValid = pBuilder->nRecValid;
  110826. #endif
  110827. if( (eOp==WO_ISNULL || (pTerm->wtFlags&TERM_VNULL)!=0)
  110828. && (iCol<0 || pSrc->pTab->aCol[iCol].notNull)
  110829. ){
  110830. continue; /* ignore IS [NOT] NULL constraints on NOT NULL columns */
  110831. }
  110832. if( pTerm->prereqRight & pNew->maskSelf ) continue;
  110833. pNew->wsFlags = saved_wsFlags;
  110834. pNew->u.btree.nEq = saved_nEq;
  110835. pNew->nLTerm = saved_nLTerm;
  110836. if( whereLoopResize(db, pNew, pNew->nLTerm+1) ) break; /* OOM */
  110837. pNew->aLTerm[pNew->nLTerm++] = pTerm;
  110838. pNew->prereq = (saved_prereq | pTerm->prereqRight) & ~pNew->maskSelf;
  110839. assert( nInMul==0
  110840. || (pNew->wsFlags & WHERE_COLUMN_NULL)!=0
  110841. || (pNew->wsFlags & WHERE_COLUMN_IN)!=0
  110842. || (pNew->wsFlags & WHERE_SKIPSCAN)!=0
  110843. );
  110844. if( eOp & WO_IN ){
  110845. Expr *pExpr = pTerm->pExpr;
  110846. pNew->wsFlags |= WHERE_COLUMN_IN;
  110847. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  110848. /* "x IN (SELECT ...)": TUNING: the SELECT returns 25 rows */
  110849. nIn = 46; assert( 46==sqlite3LogEst(25) );
  110850. }else if( ALWAYS(pExpr->x.pList && pExpr->x.pList->nExpr) ){
  110851. /* "x IN (value, value, ...)" */
  110852. nIn = sqlite3LogEst(pExpr->x.pList->nExpr);
  110853. }
  110854. assert( nIn>0 ); /* RHS always has 2 or more terms... The parser
  110855. ** changes "x IN (?)" into "x=?". */
  110856. }else if( eOp & (WO_EQ) ){
  110857. pNew->wsFlags |= WHERE_COLUMN_EQ;
  110858. if( iCol<0 || (nInMul==0 && pNew->u.btree.nEq==pProbe->nKeyCol-1) ){
  110859. if( iCol>=0 && !IsUniqueIndex(pProbe) ){
  110860. pNew->wsFlags |= WHERE_UNQ_WANTED;
  110861. }else{
  110862. pNew->wsFlags |= WHERE_ONEROW;
  110863. }
  110864. }
  110865. }else if( eOp & WO_ISNULL ){
  110866. pNew->wsFlags |= WHERE_COLUMN_NULL;
  110867. }else if( eOp & (WO_GT|WO_GE) ){
  110868. testcase( eOp & WO_GT );
  110869. testcase( eOp & WO_GE );
  110870. pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_BTM_LIMIT;
  110871. pBtm = pTerm;
  110872. pTop = 0;
  110873. }else{
  110874. assert( eOp & (WO_LT|WO_LE) );
  110875. testcase( eOp & WO_LT );
  110876. testcase( eOp & WO_LE );
  110877. pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_TOP_LIMIT;
  110878. pTop = pTerm;
  110879. pBtm = (pNew->wsFlags & WHERE_BTM_LIMIT)!=0 ?
  110880. pNew->aLTerm[pNew->nLTerm-2] : 0;
  110881. }
  110882. /* At this point pNew->nOut is set to the number of rows expected to
  110883. ** be visited by the index scan before considering term pTerm, or the
  110884. ** values of nIn and nInMul. In other words, assuming that all
  110885. ** "x IN(...)" terms are replaced with "x = ?". This block updates
  110886. ** the value of pNew->nOut to account for pTerm (but not nIn/nInMul). */
  110887. assert( pNew->nOut==saved_nOut );
  110888. if( pNew->wsFlags & WHERE_COLUMN_RANGE ){
  110889. /* Adjust nOut using stat3/stat4 data. Or, if there is no stat3/stat4
  110890. ** data, using some other estimate. */
  110891. whereRangeScanEst(pParse, pBuilder, pBtm, pTop, pNew);
  110892. }else{
  110893. int nEq = ++pNew->u.btree.nEq;
  110894. assert( eOp & (WO_ISNULL|WO_EQ|WO_IN) );
  110895. assert( pNew->nOut==saved_nOut );
  110896. if( pTerm->truthProb<=0 && iCol>=0 ){
  110897. assert( (eOp & WO_IN) || nIn==0 );
  110898. testcase( eOp & WO_IN );
  110899. pNew->nOut += pTerm->truthProb;
  110900. pNew->nOut -= nIn;
  110901. }else{
  110902. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  110903. tRowcnt nOut = 0;
  110904. if( nInMul==0
  110905. && pProbe->nSample
  110906. && pNew->u.btree.nEq<=pProbe->nSampleCol
  110907. && ((eOp & WO_IN)==0 || !ExprHasProperty(pTerm->pExpr, EP_xIsSelect))
  110908. ){
  110909. Expr *pExpr = pTerm->pExpr;
  110910. if( (eOp & (WO_EQ|WO_ISNULL))!=0 ){
  110911. testcase( eOp & WO_EQ );
  110912. testcase( eOp & WO_ISNULL );
  110913. rc = whereEqualScanEst(pParse, pBuilder, pExpr->pRight, &nOut);
  110914. }else{
  110915. rc = whereInScanEst(pParse, pBuilder, pExpr->x.pList, &nOut);
  110916. }
  110917. if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
  110918. if( rc!=SQLITE_OK ) break; /* Jump out of the pTerm loop */
  110919. if( nOut ){
  110920. pNew->nOut = sqlite3LogEst(nOut);
  110921. if( pNew->nOut>saved_nOut ) pNew->nOut = saved_nOut;
  110922. pNew->nOut -= nIn;
  110923. }
  110924. }
  110925. if( nOut==0 )
  110926. #endif
  110927. {
  110928. pNew->nOut += (pProbe->aiRowLogEst[nEq] - pProbe->aiRowLogEst[nEq-1]);
  110929. if( eOp & WO_ISNULL ){
  110930. /* TUNING: If there is no likelihood() value, assume that a
  110931. ** "col IS NULL" expression matches twice as many rows
  110932. ** as (col=?). */
  110933. pNew->nOut += 10;
  110934. }
  110935. }
  110936. }
  110937. }
  110938. /* Set rCostIdx to the cost of visiting selected rows in index. Add
  110939. ** it to pNew->rRun, which is currently set to the cost of the index
  110940. ** seek only. Then, if this is a non-covering index, add the cost of
  110941. ** visiting the rows in the main table. */
  110942. rCostIdx = pNew->nOut + 1 + (15*pProbe->szIdxRow)/pSrc->pTab->szTabRow;
  110943. pNew->rRun = sqlite3LogEstAdd(rLogSize, rCostIdx);
  110944. if( (pNew->wsFlags & (WHERE_IDX_ONLY|WHERE_IPK))==0 ){
  110945. pNew->rRun = sqlite3LogEstAdd(pNew->rRun, pNew->nOut + 16);
  110946. }
  110947. ApplyCostMultiplier(pNew->rRun, pProbe->pTable->costMult);
  110948. nOutUnadjusted = pNew->nOut;
  110949. pNew->rRun += nInMul + nIn;
  110950. pNew->nOut += nInMul + nIn;
  110951. whereLoopOutputAdjust(pBuilder->pWC, pNew, rSize);
  110952. rc = whereLoopInsert(pBuilder, pNew);
  110953. if( pNew->wsFlags & WHERE_COLUMN_RANGE ){
  110954. pNew->nOut = saved_nOut;
  110955. }else{
  110956. pNew->nOut = nOutUnadjusted;
  110957. }
  110958. if( (pNew->wsFlags & WHERE_TOP_LIMIT)==0
  110959. && pNew->u.btree.nEq<pProbe->nColumn
  110960. ){
  110961. whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, nInMul+nIn);
  110962. }
  110963. pNew->nOut = saved_nOut;
  110964. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  110965. pBuilder->nRecValid = nRecValid;
  110966. #endif
  110967. }
  110968. pNew->prereq = saved_prereq;
  110969. pNew->u.btree.nEq = saved_nEq;
  110970. pNew->nSkip = saved_nSkip;
  110971. pNew->wsFlags = saved_wsFlags;
  110972. pNew->nOut = saved_nOut;
  110973. pNew->nLTerm = saved_nLTerm;
  110974. /* Consider using a skip-scan if there are no WHERE clause constraints
  110975. ** available for the left-most terms of the index, and if the average
  110976. ** number of repeats in the left-most terms is at least 18.
  110977. **
  110978. ** The magic number 18 is selected on the basis that scanning 17 rows
  110979. ** is almost always quicker than an index seek (even though if the index
  110980. ** contains fewer than 2^17 rows we assume otherwise in other parts of
  110981. ** the code). And, even if it is not, it should not be too much slower.
  110982. ** On the other hand, the extra seeks could end up being significantly
  110983. ** more expensive. */
  110984. assert( 42==sqlite3LogEst(18) );
  110985. if( saved_nEq==saved_nSkip
  110986. && saved_nEq+1<pProbe->nKeyCol
  110987. && pProbe->aiRowLogEst[saved_nEq+1]>=42 /* TUNING: Minimum for skip-scan */
  110988. && (rc = whereLoopResize(db, pNew, pNew->nLTerm+1))==SQLITE_OK
  110989. ){
  110990. LogEst nIter;
  110991. pNew->u.btree.nEq++;
  110992. pNew->nSkip++;
  110993. pNew->aLTerm[pNew->nLTerm++] = 0;
  110994. pNew->wsFlags |= WHERE_SKIPSCAN;
  110995. nIter = pProbe->aiRowLogEst[saved_nEq] - pProbe->aiRowLogEst[saved_nEq+1];
  110996. pNew->nOut -= nIter;
  110997. /* TUNING: Because uncertainties in the estimates for skip-scan queries,
  110998. ** add a 1.375 fudge factor to make skip-scan slightly less likely. */
  110999. nIter += 5;
  111000. whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, nIter + nInMul);
  111001. pNew->nOut = saved_nOut;
  111002. pNew->u.btree.nEq = saved_nEq;
  111003. pNew->nSkip = saved_nSkip;
  111004. pNew->wsFlags = saved_wsFlags;
  111005. }
  111006. return rc;
  111007. }
  111008. /*
  111009. ** Return True if it is possible that pIndex might be useful in
  111010. ** implementing the ORDER BY clause in pBuilder.
  111011. **
  111012. ** Return False if pBuilder does not contain an ORDER BY clause or
  111013. ** if there is no way for pIndex to be useful in implementing that
  111014. ** ORDER BY clause.
  111015. */
  111016. static int indexMightHelpWithOrderBy(
  111017. WhereLoopBuilder *pBuilder,
  111018. Index *pIndex,
  111019. int iCursor
  111020. ){
  111021. ExprList *pOB;
  111022. int ii, jj;
  111023. if( pIndex->bUnordered ) return 0;
  111024. if( (pOB = pBuilder->pWInfo->pOrderBy)==0 ) return 0;
  111025. for(ii=0; ii<pOB->nExpr; ii++){
  111026. Expr *pExpr = sqlite3ExprSkipCollate(pOB->a[ii].pExpr);
  111027. if( pExpr->op!=TK_COLUMN ) return 0;
  111028. if( pExpr->iTable==iCursor ){
  111029. if( pExpr->iColumn<0 ) return 1;
  111030. for(jj=0; jj<pIndex->nKeyCol; jj++){
  111031. if( pExpr->iColumn==pIndex->aiColumn[jj] ) return 1;
  111032. }
  111033. }
  111034. }
  111035. return 0;
  111036. }
  111037. /*
  111038. ** Return a bitmask where 1s indicate that the corresponding column of
  111039. ** the table is used by an index. Only the first 63 columns are considered.
  111040. */
  111041. static Bitmask columnsInIndex(Index *pIdx){
  111042. Bitmask m = 0;
  111043. int j;
  111044. for(j=pIdx->nColumn-1; j>=0; j--){
  111045. int x = pIdx->aiColumn[j];
  111046. if( x>=0 ){
  111047. testcase( x==BMS-1 );
  111048. testcase( x==BMS-2 );
  111049. if( x<BMS-1 ) m |= MASKBIT(x);
  111050. }
  111051. }
  111052. return m;
  111053. }
  111054. /* Check to see if a partial index with pPartIndexWhere can be used
  111055. ** in the current query. Return true if it can be and false if not.
  111056. */
  111057. static int whereUsablePartialIndex(int iTab, WhereClause *pWC, Expr *pWhere){
  111058. int i;
  111059. WhereTerm *pTerm;
  111060. for(i=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
  111061. if( sqlite3ExprImpliesExpr(pTerm->pExpr, pWhere, iTab) ) return 1;
  111062. }
  111063. return 0;
  111064. }
  111065. /*
  111066. ** Add all WhereLoop objects for a single table of the join where the table
  111067. ** is idenfied by pBuilder->pNew->iTab. That table is guaranteed to be
  111068. ** a b-tree table, not a virtual table.
  111069. **
  111070. ** The costs (WhereLoop.rRun) of the b-tree loops added by this function
  111071. ** are calculated as follows:
  111072. **
  111073. ** For a full scan, assuming the table (or index) contains nRow rows:
  111074. **
  111075. ** cost = nRow * 3.0 // full-table scan
  111076. ** cost = nRow * K // scan of covering index
  111077. ** cost = nRow * (K+3.0) // scan of non-covering index
  111078. **
  111079. ** where K is a value between 1.1 and 3.0 set based on the relative
  111080. ** estimated average size of the index and table records.
  111081. **
  111082. ** For an index scan, where nVisit is the number of index rows visited
  111083. ** by the scan, and nSeek is the number of seek operations required on
  111084. ** the index b-tree:
  111085. **
  111086. ** cost = nSeek * (log(nRow) + K * nVisit) // covering index
  111087. ** cost = nSeek * (log(nRow) + (K+3.0) * nVisit) // non-covering index
  111088. **
  111089. ** Normally, nSeek is 1. nSeek values greater than 1 come about if the
  111090. ** WHERE clause includes "x IN (....)" terms used in place of "x=?". Or when
  111091. ** implicit "x IN (SELECT x FROM tbl)" terms are added for skip-scans.
  111092. **
  111093. ** The estimated values (nRow, nVisit, nSeek) often contain a large amount
  111094. ** of uncertainty. For this reason, scoring is designed to pick plans that
  111095. ** "do the least harm" if the estimates are inaccurate. For example, a
  111096. ** log(nRow) factor is omitted from a non-covering index scan in order to
  111097. ** bias the scoring in favor of using an index, since the worst-case
  111098. ** performance of using an index is far better than the worst-case performance
  111099. ** of a full table scan.
  111100. */
  111101. static int whereLoopAddBtree(
  111102. WhereLoopBuilder *pBuilder, /* WHERE clause information */
  111103. Bitmask mExtra /* Extra prerequesites for using this table */
  111104. ){
  111105. WhereInfo *pWInfo; /* WHERE analysis context */
  111106. Index *pProbe; /* An index we are evaluating */
  111107. Index sPk; /* A fake index object for the primary key */
  111108. LogEst aiRowEstPk[2]; /* The aiRowLogEst[] value for the sPk index */
  111109. i16 aiColumnPk = -1; /* The aColumn[] value for the sPk index */
  111110. SrcList *pTabList; /* The FROM clause */
  111111. struct SrcList_item *pSrc; /* The FROM clause btree term to add */
  111112. WhereLoop *pNew; /* Template WhereLoop object */
  111113. int rc = SQLITE_OK; /* Return code */
  111114. int iSortIdx = 1; /* Index number */
  111115. int b; /* A boolean value */
  111116. LogEst rSize; /* number of rows in the table */
  111117. LogEst rLogSize; /* Logarithm of the number of rows in the table */
  111118. WhereClause *pWC; /* The parsed WHERE clause */
  111119. Table *pTab; /* Table being queried */
  111120. pNew = pBuilder->pNew;
  111121. pWInfo = pBuilder->pWInfo;
  111122. pTabList = pWInfo->pTabList;
  111123. pSrc = pTabList->a + pNew->iTab;
  111124. pTab = pSrc->pTab;
  111125. pWC = pBuilder->pWC;
  111126. assert( !IsVirtual(pSrc->pTab) );
  111127. if( pSrc->pIndex ){
  111128. /* An INDEXED BY clause specifies a particular index to use */
  111129. pProbe = pSrc->pIndex;
  111130. }else if( !HasRowid(pTab) ){
  111131. pProbe = pTab->pIndex;
  111132. }else{
  111133. /* There is no INDEXED BY clause. Create a fake Index object in local
  111134. ** variable sPk to represent the rowid primary key index. Make this
  111135. ** fake index the first in a chain of Index objects with all of the real
  111136. ** indices to follow */
  111137. Index *pFirst; /* First of real indices on the table */
  111138. memset(&sPk, 0, sizeof(Index));
  111139. sPk.nKeyCol = 1;
  111140. sPk.nColumn = 1;
  111141. sPk.aiColumn = &aiColumnPk;
  111142. sPk.aiRowLogEst = aiRowEstPk;
  111143. sPk.onError = OE_Replace;
  111144. sPk.pTable = pTab;
  111145. sPk.szIdxRow = pTab->szTabRow;
  111146. aiRowEstPk[0] = pTab->nRowLogEst;
  111147. aiRowEstPk[1] = 0;
  111148. pFirst = pSrc->pTab->pIndex;
  111149. if( pSrc->notIndexed==0 ){
  111150. /* The real indices of the table are only considered if the
  111151. ** NOT INDEXED qualifier is omitted from the FROM clause */
  111152. sPk.pNext = pFirst;
  111153. }
  111154. pProbe = &sPk;
  111155. }
  111156. rSize = pTab->nRowLogEst;
  111157. rLogSize = estLog(rSize);
  111158. #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
  111159. /* Automatic indexes */
  111160. if( !pBuilder->pOrSet
  111161. && (pWInfo->pParse->db->flags & SQLITE_AutoIndex)!=0
  111162. && pSrc->pIndex==0
  111163. && !pSrc->viaCoroutine
  111164. && !pSrc->notIndexed
  111165. && HasRowid(pTab)
  111166. && !pSrc->isCorrelated
  111167. && !pSrc->isRecursive
  111168. ){
  111169. /* Generate auto-index WhereLoops */
  111170. WhereTerm *pTerm;
  111171. WhereTerm *pWCEnd = pWC->a + pWC->nTerm;
  111172. for(pTerm=pWC->a; rc==SQLITE_OK && pTerm<pWCEnd; pTerm++){
  111173. if( pTerm->prereqRight & pNew->maskSelf ) continue;
  111174. if( termCanDriveIndex(pTerm, pSrc, 0) ){
  111175. pNew->u.btree.nEq = 1;
  111176. pNew->nSkip = 0;
  111177. pNew->u.btree.pIndex = 0;
  111178. pNew->nLTerm = 1;
  111179. pNew->aLTerm[0] = pTerm;
  111180. /* TUNING: One-time cost for computing the automatic index is
  111181. ** estimated to be X*N*log2(N) where N is the number of rows in
  111182. ** the table being indexed and where X is 7 (LogEst=28) for normal
  111183. ** tables or 1.375 (LogEst=4) for views and subqueries. The value
  111184. ** of X is smaller for views and subqueries so that the query planner
  111185. ** will be more aggressive about generating automatic indexes for
  111186. ** those objects, since there is no opportunity to add schema
  111187. ** indexes on subqueries and views. */
  111188. pNew->rSetup = rLogSize + rSize + 4;
  111189. if( pTab->pSelect==0 && (pTab->tabFlags & TF_Ephemeral)==0 ){
  111190. pNew->rSetup += 24;
  111191. }
  111192. ApplyCostMultiplier(pNew->rSetup, pTab->costMult);
  111193. /* TUNING: Each index lookup yields 20 rows in the table. This
  111194. ** is more than the usual guess of 10 rows, since we have no way
  111195. ** of knowing how selective the index will ultimately be. It would
  111196. ** not be unreasonable to make this value much larger. */
  111197. pNew->nOut = 43; assert( 43==sqlite3LogEst(20) );
  111198. pNew->rRun = sqlite3LogEstAdd(rLogSize,pNew->nOut);
  111199. pNew->wsFlags = WHERE_AUTO_INDEX;
  111200. pNew->prereq = mExtra | pTerm->prereqRight;
  111201. rc = whereLoopInsert(pBuilder, pNew);
  111202. }
  111203. }
  111204. }
  111205. #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
  111206. /* Loop over all indices
  111207. */
  111208. for(; rc==SQLITE_OK && pProbe; pProbe=pProbe->pNext, iSortIdx++){
  111209. if( pProbe->pPartIdxWhere!=0
  111210. && !whereUsablePartialIndex(pSrc->iCursor, pWC, pProbe->pPartIdxWhere) ){
  111211. testcase( pNew->iTab!=pSrc->iCursor ); /* See ticket [98d973b8f5] */
  111212. continue; /* Partial index inappropriate for this query */
  111213. }
  111214. rSize = pProbe->aiRowLogEst[0];
  111215. pNew->u.btree.nEq = 0;
  111216. pNew->nSkip = 0;
  111217. pNew->nLTerm = 0;
  111218. pNew->iSortIdx = 0;
  111219. pNew->rSetup = 0;
  111220. pNew->prereq = mExtra;
  111221. pNew->nOut = rSize;
  111222. pNew->u.btree.pIndex = pProbe;
  111223. b = indexMightHelpWithOrderBy(pBuilder, pProbe, pSrc->iCursor);
  111224. /* The ONEPASS_DESIRED flags never occurs together with ORDER BY */
  111225. assert( (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || b==0 );
  111226. if( pProbe->tnum<=0 ){
  111227. /* Integer primary key index */
  111228. pNew->wsFlags = WHERE_IPK;
  111229. /* Full table scan */
  111230. pNew->iSortIdx = b ? iSortIdx : 0;
  111231. /* TUNING: Cost of full table scan is (N*3.0). */
  111232. pNew->rRun = rSize + 16;
  111233. ApplyCostMultiplier(pNew->rRun, pTab->costMult);
  111234. whereLoopOutputAdjust(pWC, pNew, rSize);
  111235. rc = whereLoopInsert(pBuilder, pNew);
  111236. pNew->nOut = rSize;
  111237. if( rc ) break;
  111238. }else{
  111239. Bitmask m;
  111240. if( pProbe->isCovering ){
  111241. pNew->wsFlags = WHERE_IDX_ONLY | WHERE_INDEXED;
  111242. m = 0;
  111243. }else{
  111244. m = pSrc->colUsed & ~columnsInIndex(pProbe);
  111245. pNew->wsFlags = (m==0) ? (WHERE_IDX_ONLY|WHERE_INDEXED) : WHERE_INDEXED;
  111246. }
  111247. /* Full scan via index */
  111248. if( b
  111249. || !HasRowid(pTab)
  111250. || ( m==0
  111251. && pProbe->bUnordered==0
  111252. && (pProbe->szIdxRow<pTab->szTabRow)
  111253. && (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0
  111254. && sqlite3GlobalConfig.bUseCis
  111255. && OptimizationEnabled(pWInfo->pParse->db, SQLITE_CoverIdxScan)
  111256. )
  111257. ){
  111258. pNew->iSortIdx = b ? iSortIdx : 0;
  111259. /* The cost of visiting the index rows is N*K, where K is
  111260. ** between 1.1 and 3.0, depending on the relative sizes of the
  111261. ** index and table rows. If this is a non-covering index scan,
  111262. ** also add the cost of visiting table rows (N*3.0). */
  111263. pNew->rRun = rSize + 1 + (15*pProbe->szIdxRow)/pTab->szTabRow;
  111264. if( m!=0 ){
  111265. pNew->rRun = sqlite3LogEstAdd(pNew->rRun, rSize+16);
  111266. }
  111267. ApplyCostMultiplier(pNew->rRun, pTab->costMult);
  111268. whereLoopOutputAdjust(pWC, pNew, rSize);
  111269. rc = whereLoopInsert(pBuilder, pNew);
  111270. pNew->nOut = rSize;
  111271. if( rc ) break;
  111272. }
  111273. }
  111274. rc = whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, 0);
  111275. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  111276. sqlite3Stat4ProbeFree(pBuilder->pRec);
  111277. pBuilder->nRecValid = 0;
  111278. pBuilder->pRec = 0;
  111279. #endif
  111280. /* If there was an INDEXED BY clause, then only that one index is
  111281. ** considered. */
  111282. if( pSrc->pIndex ) break;
  111283. }
  111284. return rc;
  111285. }
  111286. #ifndef SQLITE_OMIT_VIRTUALTABLE
  111287. /*
  111288. ** Add all WhereLoop objects for a table of the join identified by
  111289. ** pBuilder->pNew->iTab. That table is guaranteed to be a virtual table.
  111290. */
  111291. static int whereLoopAddVirtual(
  111292. WhereLoopBuilder *pBuilder, /* WHERE clause information */
  111293. Bitmask mExtra
  111294. ){
  111295. WhereInfo *pWInfo; /* WHERE analysis context */
  111296. Parse *pParse; /* The parsing context */
  111297. WhereClause *pWC; /* The WHERE clause */
  111298. struct SrcList_item *pSrc; /* The FROM clause term to search */
  111299. Table *pTab;
  111300. sqlite3 *db;
  111301. sqlite3_index_info *pIdxInfo;
  111302. struct sqlite3_index_constraint *pIdxCons;
  111303. struct sqlite3_index_constraint_usage *pUsage;
  111304. WhereTerm *pTerm;
  111305. int i, j;
  111306. int iTerm, mxTerm;
  111307. int nConstraint;
  111308. int seenIn = 0; /* True if an IN operator is seen */
  111309. int seenVar = 0; /* True if a non-constant constraint is seen */
  111310. int iPhase; /* 0: const w/o IN, 1: const, 2: no IN, 2: IN */
  111311. WhereLoop *pNew;
  111312. int rc = SQLITE_OK;
  111313. pWInfo = pBuilder->pWInfo;
  111314. pParse = pWInfo->pParse;
  111315. db = pParse->db;
  111316. pWC = pBuilder->pWC;
  111317. pNew = pBuilder->pNew;
  111318. pSrc = &pWInfo->pTabList->a[pNew->iTab];
  111319. pTab = pSrc->pTab;
  111320. assert( IsVirtual(pTab) );
  111321. pIdxInfo = allocateIndexInfo(pParse, pWC, pSrc, pBuilder->pOrderBy);
  111322. if( pIdxInfo==0 ) return SQLITE_NOMEM;
  111323. pNew->prereq = 0;
  111324. pNew->rSetup = 0;
  111325. pNew->wsFlags = WHERE_VIRTUALTABLE;
  111326. pNew->nLTerm = 0;
  111327. pNew->u.vtab.needFree = 0;
  111328. pUsage = pIdxInfo->aConstraintUsage;
  111329. nConstraint = pIdxInfo->nConstraint;
  111330. if( whereLoopResize(db, pNew, nConstraint) ){
  111331. sqlite3DbFree(db, pIdxInfo);
  111332. return SQLITE_NOMEM;
  111333. }
  111334. for(iPhase=0; iPhase<=3; iPhase++){
  111335. if( !seenIn && (iPhase&1)!=0 ){
  111336. iPhase++;
  111337. if( iPhase>3 ) break;
  111338. }
  111339. if( !seenVar && iPhase>1 ) break;
  111340. pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
  111341. for(i=0; i<pIdxInfo->nConstraint; i++, pIdxCons++){
  111342. j = pIdxCons->iTermOffset;
  111343. pTerm = &pWC->a[j];
  111344. switch( iPhase ){
  111345. case 0: /* Constants without IN operator */
  111346. pIdxCons->usable = 0;
  111347. if( (pTerm->eOperator & WO_IN)!=0 ){
  111348. seenIn = 1;
  111349. }
  111350. if( pTerm->prereqRight!=0 ){
  111351. seenVar = 1;
  111352. }else if( (pTerm->eOperator & WO_IN)==0 ){
  111353. pIdxCons->usable = 1;
  111354. }
  111355. break;
  111356. case 1: /* Constants with IN operators */
  111357. assert( seenIn );
  111358. pIdxCons->usable = (pTerm->prereqRight==0);
  111359. break;
  111360. case 2: /* Variables without IN */
  111361. assert( seenVar );
  111362. pIdxCons->usable = (pTerm->eOperator & WO_IN)==0;
  111363. break;
  111364. default: /* Variables with IN */
  111365. assert( seenVar && seenIn );
  111366. pIdxCons->usable = 1;
  111367. break;
  111368. }
  111369. }
  111370. memset(pUsage, 0, sizeof(pUsage[0])*pIdxInfo->nConstraint);
  111371. if( pIdxInfo->needToFreeIdxStr ) sqlite3_free(pIdxInfo->idxStr);
  111372. pIdxInfo->idxStr = 0;
  111373. pIdxInfo->idxNum = 0;
  111374. pIdxInfo->needToFreeIdxStr = 0;
  111375. pIdxInfo->orderByConsumed = 0;
  111376. pIdxInfo->estimatedCost = SQLITE_BIG_DBL / (double)2;
  111377. pIdxInfo->estimatedRows = 25;
  111378. rc = vtabBestIndex(pParse, pTab, pIdxInfo);
  111379. if( rc ) goto whereLoopAddVtab_exit;
  111380. pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
  111381. pNew->prereq = mExtra;
  111382. mxTerm = -1;
  111383. assert( pNew->nLSlot>=nConstraint );
  111384. for(i=0; i<nConstraint; i++) pNew->aLTerm[i] = 0;
  111385. pNew->u.vtab.omitMask = 0;
  111386. for(i=0; i<nConstraint; i++, pIdxCons++){
  111387. if( (iTerm = pUsage[i].argvIndex - 1)>=0 ){
  111388. j = pIdxCons->iTermOffset;
  111389. if( iTerm>=nConstraint
  111390. || j<0
  111391. || j>=pWC->nTerm
  111392. || pNew->aLTerm[iTerm]!=0
  111393. ){
  111394. rc = SQLITE_ERROR;
  111395. sqlite3ErrorMsg(pParse, "%s.xBestIndex() malfunction", pTab->zName);
  111396. goto whereLoopAddVtab_exit;
  111397. }
  111398. testcase( iTerm==nConstraint-1 );
  111399. testcase( j==0 );
  111400. testcase( j==pWC->nTerm-1 );
  111401. pTerm = &pWC->a[j];
  111402. pNew->prereq |= pTerm->prereqRight;
  111403. assert( iTerm<pNew->nLSlot );
  111404. pNew->aLTerm[iTerm] = pTerm;
  111405. if( iTerm>mxTerm ) mxTerm = iTerm;
  111406. testcase( iTerm==15 );
  111407. testcase( iTerm==16 );
  111408. if( iTerm<16 && pUsage[i].omit ) pNew->u.vtab.omitMask |= 1<<iTerm;
  111409. if( (pTerm->eOperator & WO_IN)!=0 ){
  111410. if( pUsage[i].omit==0 ){
  111411. /* Do not attempt to use an IN constraint if the virtual table
  111412. ** says that the equivalent EQ constraint cannot be safely omitted.
  111413. ** If we do attempt to use such a constraint, some rows might be
  111414. ** repeated in the output. */
  111415. break;
  111416. }
  111417. /* A virtual table that is constrained by an IN clause may not
  111418. ** consume the ORDER BY clause because (1) the order of IN terms
  111419. ** is not necessarily related to the order of output terms and
  111420. ** (2) Multiple outputs from a single IN value will not merge
  111421. ** together. */
  111422. pIdxInfo->orderByConsumed = 0;
  111423. }
  111424. }
  111425. }
  111426. if( i>=nConstraint ){
  111427. pNew->nLTerm = mxTerm+1;
  111428. assert( pNew->nLTerm<=pNew->nLSlot );
  111429. pNew->u.vtab.idxNum = pIdxInfo->idxNum;
  111430. pNew->u.vtab.needFree = pIdxInfo->needToFreeIdxStr;
  111431. pIdxInfo->needToFreeIdxStr = 0;
  111432. pNew->u.vtab.idxStr = pIdxInfo->idxStr;
  111433. pNew->u.vtab.isOrdered = (i8)(pIdxInfo->orderByConsumed ?
  111434. pIdxInfo->nOrderBy : 0);
  111435. pNew->rSetup = 0;
  111436. pNew->rRun = sqlite3LogEstFromDouble(pIdxInfo->estimatedCost);
  111437. pNew->nOut = sqlite3LogEst(pIdxInfo->estimatedRows);
  111438. whereLoopInsert(pBuilder, pNew);
  111439. if( pNew->u.vtab.needFree ){
  111440. sqlite3_free(pNew->u.vtab.idxStr);
  111441. pNew->u.vtab.needFree = 0;
  111442. }
  111443. }
  111444. }
  111445. whereLoopAddVtab_exit:
  111446. if( pIdxInfo->needToFreeIdxStr ) sqlite3_free(pIdxInfo->idxStr);
  111447. sqlite3DbFree(db, pIdxInfo);
  111448. return rc;
  111449. }
  111450. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  111451. /*
  111452. ** Add WhereLoop entries to handle OR terms. This works for either
  111453. ** btrees or virtual tables.
  111454. */
  111455. static int whereLoopAddOr(WhereLoopBuilder *pBuilder, Bitmask mExtra){
  111456. WhereInfo *pWInfo = pBuilder->pWInfo;
  111457. WhereClause *pWC;
  111458. WhereLoop *pNew;
  111459. WhereTerm *pTerm, *pWCEnd;
  111460. int rc = SQLITE_OK;
  111461. int iCur;
  111462. WhereClause tempWC;
  111463. WhereLoopBuilder sSubBuild;
  111464. WhereOrSet sSum, sCur;
  111465. struct SrcList_item *pItem;
  111466. pWC = pBuilder->pWC;
  111467. pWCEnd = pWC->a + pWC->nTerm;
  111468. pNew = pBuilder->pNew;
  111469. memset(&sSum, 0, sizeof(sSum));
  111470. pItem = pWInfo->pTabList->a + pNew->iTab;
  111471. iCur = pItem->iCursor;
  111472. for(pTerm=pWC->a; pTerm<pWCEnd && rc==SQLITE_OK; pTerm++){
  111473. if( (pTerm->eOperator & WO_OR)!=0
  111474. && (pTerm->u.pOrInfo->indexable & pNew->maskSelf)!=0
  111475. ){
  111476. WhereClause * const pOrWC = &pTerm->u.pOrInfo->wc;
  111477. WhereTerm * const pOrWCEnd = &pOrWC->a[pOrWC->nTerm];
  111478. WhereTerm *pOrTerm;
  111479. int once = 1;
  111480. int i, j;
  111481. sSubBuild = *pBuilder;
  111482. sSubBuild.pOrderBy = 0;
  111483. sSubBuild.pOrSet = &sCur;
  111484. WHERETRACE(0x200, ("Begin processing OR-clause %p\n", pTerm));
  111485. for(pOrTerm=pOrWC->a; pOrTerm<pOrWCEnd; pOrTerm++){
  111486. if( (pOrTerm->eOperator & WO_AND)!=0 ){
  111487. sSubBuild.pWC = &pOrTerm->u.pAndInfo->wc;
  111488. }else if( pOrTerm->leftCursor==iCur ){
  111489. tempWC.pWInfo = pWC->pWInfo;
  111490. tempWC.pOuter = pWC;
  111491. tempWC.op = TK_AND;
  111492. tempWC.nTerm = 1;
  111493. tempWC.a = pOrTerm;
  111494. sSubBuild.pWC = &tempWC;
  111495. }else{
  111496. continue;
  111497. }
  111498. sCur.n = 0;
  111499. #ifdef WHERETRACE_ENABLED
  111500. WHERETRACE(0x200, ("OR-term %d of %p has %d subterms:\n",
  111501. (int)(pOrTerm-pOrWC->a), pTerm, sSubBuild.pWC->nTerm));
  111502. if( sqlite3WhereTrace & 0x400 ){
  111503. for(i=0; i<sSubBuild.pWC->nTerm; i++){
  111504. whereTermPrint(&sSubBuild.pWC->a[i], i);
  111505. }
  111506. }
  111507. #endif
  111508. #ifndef SQLITE_OMIT_VIRTUALTABLE
  111509. if( IsVirtual(pItem->pTab) ){
  111510. rc = whereLoopAddVirtual(&sSubBuild, mExtra);
  111511. }else
  111512. #endif
  111513. {
  111514. rc = whereLoopAddBtree(&sSubBuild, mExtra);
  111515. }
  111516. if( rc==SQLITE_OK ){
  111517. rc = whereLoopAddOr(&sSubBuild, mExtra);
  111518. }
  111519. assert( rc==SQLITE_OK || sCur.n==0 );
  111520. if( sCur.n==0 ){
  111521. sSum.n = 0;
  111522. break;
  111523. }else if( once ){
  111524. whereOrMove(&sSum, &sCur);
  111525. once = 0;
  111526. }else{
  111527. WhereOrSet sPrev;
  111528. whereOrMove(&sPrev, &sSum);
  111529. sSum.n = 0;
  111530. for(i=0; i<sPrev.n; i++){
  111531. for(j=0; j<sCur.n; j++){
  111532. whereOrInsert(&sSum, sPrev.a[i].prereq | sCur.a[j].prereq,
  111533. sqlite3LogEstAdd(sPrev.a[i].rRun, sCur.a[j].rRun),
  111534. sqlite3LogEstAdd(sPrev.a[i].nOut, sCur.a[j].nOut));
  111535. }
  111536. }
  111537. }
  111538. }
  111539. pNew->nLTerm = 1;
  111540. pNew->aLTerm[0] = pTerm;
  111541. pNew->wsFlags = WHERE_MULTI_OR;
  111542. pNew->rSetup = 0;
  111543. pNew->iSortIdx = 0;
  111544. memset(&pNew->u, 0, sizeof(pNew->u));
  111545. for(i=0; rc==SQLITE_OK && i<sSum.n; i++){
  111546. /* TUNING: Currently sSum.a[i].rRun is set to the sum of the costs
  111547. ** of all sub-scans required by the OR-scan. However, due to rounding
  111548. ** errors, it may be that the cost of the OR-scan is equal to its
  111549. ** most expensive sub-scan. Add the smallest possible penalty
  111550. ** (equivalent to multiplying the cost by 1.07) to ensure that
  111551. ** this does not happen. Otherwise, for WHERE clauses such as the
  111552. ** following where there is an index on "y":
  111553. **
  111554. ** WHERE likelihood(x=?, 0.99) OR y=?
  111555. **
  111556. ** the planner may elect to "OR" together a full-table scan and an
  111557. ** index lookup. And other similarly odd results. */
  111558. pNew->rRun = sSum.a[i].rRun + 1;
  111559. pNew->nOut = sSum.a[i].nOut;
  111560. pNew->prereq = sSum.a[i].prereq;
  111561. rc = whereLoopInsert(pBuilder, pNew);
  111562. }
  111563. WHERETRACE(0x200, ("End processing OR-clause %p\n", pTerm));
  111564. }
  111565. }
  111566. return rc;
  111567. }
  111568. /*
  111569. ** Add all WhereLoop objects for all tables
  111570. */
  111571. static int whereLoopAddAll(WhereLoopBuilder *pBuilder){
  111572. WhereInfo *pWInfo = pBuilder->pWInfo;
  111573. Bitmask mExtra = 0;
  111574. Bitmask mPrior = 0;
  111575. int iTab;
  111576. SrcList *pTabList = pWInfo->pTabList;
  111577. struct SrcList_item *pItem;
  111578. sqlite3 *db = pWInfo->pParse->db;
  111579. int nTabList = pWInfo->nLevel;
  111580. int rc = SQLITE_OK;
  111581. u8 priorJoinType = 0;
  111582. WhereLoop *pNew;
  111583. /* Loop over the tables in the join, from left to right */
  111584. pNew = pBuilder->pNew;
  111585. whereLoopInit(pNew);
  111586. for(iTab=0, pItem=pTabList->a; iTab<nTabList; iTab++, pItem++){
  111587. pNew->iTab = iTab;
  111588. pNew->maskSelf = getMask(&pWInfo->sMaskSet, pItem->iCursor);
  111589. if( ((pItem->jointype|priorJoinType) & (JT_LEFT|JT_CROSS))!=0 ){
  111590. mExtra = mPrior;
  111591. }
  111592. priorJoinType = pItem->jointype;
  111593. if( IsVirtual(pItem->pTab) ){
  111594. rc = whereLoopAddVirtual(pBuilder, mExtra);
  111595. }else{
  111596. rc = whereLoopAddBtree(pBuilder, mExtra);
  111597. }
  111598. if( rc==SQLITE_OK ){
  111599. rc = whereLoopAddOr(pBuilder, mExtra);
  111600. }
  111601. mPrior |= pNew->maskSelf;
  111602. if( rc || db->mallocFailed ) break;
  111603. }
  111604. whereLoopClear(db, pNew);
  111605. return rc;
  111606. }
  111607. /*
  111608. ** Examine a WherePath (with the addition of the extra WhereLoop of the 5th
  111609. ** parameters) to see if it outputs rows in the requested ORDER BY
  111610. ** (or GROUP BY) without requiring a separate sort operation. Return N:
  111611. **
  111612. ** N>0: N terms of the ORDER BY clause are satisfied
  111613. ** N==0: No terms of the ORDER BY clause are satisfied
  111614. ** N<0: Unknown yet how many terms of ORDER BY might be satisfied.
  111615. **
  111616. ** Note that processing for WHERE_GROUPBY and WHERE_DISTINCTBY is not as
  111617. ** strict. With GROUP BY and DISTINCT the only requirement is that
  111618. ** equivalent rows appear immediately adjacent to one another. GROUP BY
  111619. ** and DISTINCT do not require rows to appear in any particular order as long
  111620. ** as equivalent rows are grouped together. Thus for GROUP BY and DISTINCT
  111621. ** the pOrderBy terms can be matched in any order. With ORDER BY, the
  111622. ** pOrderBy terms must be matched in strict left-to-right order.
  111623. */
  111624. static i8 wherePathSatisfiesOrderBy(
  111625. WhereInfo *pWInfo, /* The WHERE clause */
  111626. ExprList *pOrderBy, /* ORDER BY or GROUP BY or DISTINCT clause to check */
  111627. WherePath *pPath, /* The WherePath to check */
  111628. u16 wctrlFlags, /* Might contain WHERE_GROUPBY or WHERE_DISTINCTBY */
  111629. u16 nLoop, /* Number of entries in pPath->aLoop[] */
  111630. WhereLoop *pLast, /* Add this WhereLoop to the end of pPath->aLoop[] */
  111631. Bitmask *pRevMask /* OUT: Mask of WhereLoops to run in reverse order */
  111632. ){
  111633. u8 revSet; /* True if rev is known */
  111634. u8 rev; /* Composite sort order */
  111635. u8 revIdx; /* Index sort order */
  111636. u8 isOrderDistinct; /* All prior WhereLoops are order-distinct */
  111637. u8 distinctColumns; /* True if the loop has UNIQUE NOT NULL columns */
  111638. u8 isMatch; /* iColumn matches a term of the ORDER BY clause */
  111639. u16 nKeyCol; /* Number of key columns in pIndex */
  111640. u16 nColumn; /* Total number of ordered columns in the index */
  111641. u16 nOrderBy; /* Number terms in the ORDER BY clause */
  111642. int iLoop; /* Index of WhereLoop in pPath being processed */
  111643. int i, j; /* Loop counters */
  111644. int iCur; /* Cursor number for current WhereLoop */
  111645. int iColumn; /* A column number within table iCur */
  111646. WhereLoop *pLoop = 0; /* Current WhereLoop being processed. */
  111647. WhereTerm *pTerm; /* A single term of the WHERE clause */
  111648. Expr *pOBExpr; /* An expression from the ORDER BY clause */
  111649. CollSeq *pColl; /* COLLATE function from an ORDER BY clause term */
  111650. Index *pIndex; /* The index associated with pLoop */
  111651. sqlite3 *db = pWInfo->pParse->db; /* Database connection */
  111652. Bitmask obSat = 0; /* Mask of ORDER BY terms satisfied so far */
  111653. Bitmask obDone; /* Mask of all ORDER BY terms */
  111654. Bitmask orderDistinctMask; /* Mask of all well-ordered loops */
  111655. Bitmask ready; /* Mask of inner loops */
  111656. /*
  111657. ** We say the WhereLoop is "one-row" if it generates no more than one
  111658. ** row of output. A WhereLoop is one-row if all of the following are true:
  111659. ** (a) All index columns match with WHERE_COLUMN_EQ.
  111660. ** (b) The index is unique
  111661. ** Any WhereLoop with an WHERE_COLUMN_EQ constraint on the rowid is one-row.
  111662. ** Every one-row WhereLoop will have the WHERE_ONEROW bit set in wsFlags.
  111663. **
  111664. ** We say the WhereLoop is "order-distinct" if the set of columns from
  111665. ** that WhereLoop that are in the ORDER BY clause are different for every
  111666. ** row of the WhereLoop. Every one-row WhereLoop is automatically
  111667. ** order-distinct. A WhereLoop that has no columns in the ORDER BY clause
  111668. ** is not order-distinct. To be order-distinct is not quite the same as being
  111669. ** UNIQUE since a UNIQUE column or index can have multiple rows that
  111670. ** are NULL and NULL values are equivalent for the purpose of order-distinct.
  111671. ** To be order-distinct, the columns must be UNIQUE and NOT NULL.
  111672. **
  111673. ** The rowid for a table is always UNIQUE and NOT NULL so whenever the
  111674. ** rowid appears in the ORDER BY clause, the corresponding WhereLoop is
  111675. ** automatically order-distinct.
  111676. */
  111677. assert( pOrderBy!=0 );
  111678. if( nLoop && OptimizationDisabled(db, SQLITE_OrderByIdxJoin) ) return 0;
  111679. nOrderBy = pOrderBy->nExpr;
  111680. testcase( nOrderBy==BMS-1 );
  111681. if( nOrderBy>BMS-1 ) return 0; /* Cannot optimize overly large ORDER BYs */
  111682. isOrderDistinct = 1;
  111683. obDone = MASKBIT(nOrderBy)-1;
  111684. orderDistinctMask = 0;
  111685. ready = 0;
  111686. for(iLoop=0; isOrderDistinct && obSat<obDone && iLoop<=nLoop; iLoop++){
  111687. if( iLoop>0 ) ready |= pLoop->maskSelf;
  111688. pLoop = iLoop<nLoop ? pPath->aLoop[iLoop] : pLast;
  111689. if( pLoop->wsFlags & WHERE_VIRTUALTABLE ){
  111690. if( pLoop->u.vtab.isOrdered ) obSat = obDone;
  111691. break;
  111692. }
  111693. iCur = pWInfo->pTabList->a[pLoop->iTab].iCursor;
  111694. /* Mark off any ORDER BY term X that is a column in the table of
  111695. ** the current loop for which there is term in the WHERE
  111696. ** clause of the form X IS NULL or X=? that reference only outer
  111697. ** loops.
  111698. */
  111699. for(i=0; i<nOrderBy; i++){
  111700. if( MASKBIT(i) & obSat ) continue;
  111701. pOBExpr = sqlite3ExprSkipCollate(pOrderBy->a[i].pExpr);
  111702. if( pOBExpr->op!=TK_COLUMN ) continue;
  111703. if( pOBExpr->iTable!=iCur ) continue;
  111704. pTerm = findTerm(&pWInfo->sWC, iCur, pOBExpr->iColumn,
  111705. ~ready, WO_EQ|WO_ISNULL, 0);
  111706. if( pTerm==0 ) continue;
  111707. if( (pTerm->eOperator&WO_EQ)!=0 && pOBExpr->iColumn>=0 ){
  111708. const char *z1, *z2;
  111709. pColl = sqlite3ExprCollSeq(pWInfo->pParse, pOrderBy->a[i].pExpr);
  111710. if( !pColl ) pColl = db->pDfltColl;
  111711. z1 = pColl->zName;
  111712. pColl = sqlite3ExprCollSeq(pWInfo->pParse, pTerm->pExpr);
  111713. if( !pColl ) pColl = db->pDfltColl;
  111714. z2 = pColl->zName;
  111715. if( sqlite3StrICmp(z1, z2)!=0 ) continue;
  111716. }
  111717. obSat |= MASKBIT(i);
  111718. }
  111719. if( (pLoop->wsFlags & WHERE_ONEROW)==0 ){
  111720. if( pLoop->wsFlags & WHERE_IPK ){
  111721. pIndex = 0;
  111722. nKeyCol = 0;
  111723. nColumn = 1;
  111724. }else if( (pIndex = pLoop->u.btree.pIndex)==0 || pIndex->bUnordered ){
  111725. return 0;
  111726. }else{
  111727. nKeyCol = pIndex->nKeyCol;
  111728. nColumn = pIndex->nColumn;
  111729. assert( nColumn==nKeyCol+1 || !HasRowid(pIndex->pTable) );
  111730. assert( pIndex->aiColumn[nColumn-1]==(-1) || !HasRowid(pIndex->pTable));
  111731. isOrderDistinct = IsUniqueIndex(pIndex);
  111732. }
  111733. /* Loop through all columns of the index and deal with the ones
  111734. ** that are not constrained by == or IN.
  111735. */
  111736. rev = revSet = 0;
  111737. distinctColumns = 0;
  111738. for(j=0; j<nColumn; j++){
  111739. u8 bOnce; /* True to run the ORDER BY search loop */
  111740. /* Skip over == and IS NULL terms */
  111741. if( j<pLoop->u.btree.nEq
  111742. && pLoop->nSkip==0
  111743. && ((i = pLoop->aLTerm[j]->eOperator) & (WO_EQ|WO_ISNULL))!=0
  111744. ){
  111745. if( i & WO_ISNULL ){
  111746. testcase( isOrderDistinct );
  111747. isOrderDistinct = 0;
  111748. }
  111749. continue;
  111750. }
  111751. /* Get the column number in the table (iColumn) and sort order
  111752. ** (revIdx) for the j-th column of the index.
  111753. */
  111754. if( pIndex ){
  111755. iColumn = pIndex->aiColumn[j];
  111756. revIdx = pIndex->aSortOrder[j];
  111757. if( iColumn==pIndex->pTable->iPKey ) iColumn = -1;
  111758. }else{
  111759. iColumn = -1;
  111760. revIdx = 0;
  111761. }
  111762. /* An unconstrained column that might be NULL means that this
  111763. ** WhereLoop is not well-ordered
  111764. */
  111765. if( isOrderDistinct
  111766. && iColumn>=0
  111767. && j>=pLoop->u.btree.nEq
  111768. && pIndex->pTable->aCol[iColumn].notNull==0
  111769. ){
  111770. isOrderDistinct = 0;
  111771. }
  111772. /* Find the ORDER BY term that corresponds to the j-th column
  111773. ** of the index and mark that ORDER BY term off
  111774. */
  111775. bOnce = 1;
  111776. isMatch = 0;
  111777. for(i=0; bOnce && i<nOrderBy; i++){
  111778. if( MASKBIT(i) & obSat ) continue;
  111779. pOBExpr = sqlite3ExprSkipCollate(pOrderBy->a[i].pExpr);
  111780. testcase( wctrlFlags & WHERE_GROUPBY );
  111781. testcase( wctrlFlags & WHERE_DISTINCTBY );
  111782. if( (wctrlFlags & (WHERE_GROUPBY|WHERE_DISTINCTBY))==0 ) bOnce = 0;
  111783. if( pOBExpr->op!=TK_COLUMN ) continue;
  111784. if( pOBExpr->iTable!=iCur ) continue;
  111785. if( pOBExpr->iColumn!=iColumn ) continue;
  111786. if( iColumn>=0 ){
  111787. pColl = sqlite3ExprCollSeq(pWInfo->pParse, pOrderBy->a[i].pExpr);
  111788. if( !pColl ) pColl = db->pDfltColl;
  111789. if( sqlite3StrICmp(pColl->zName, pIndex->azColl[j])!=0 ) continue;
  111790. }
  111791. isMatch = 1;
  111792. break;
  111793. }
  111794. if( isMatch && (wctrlFlags & WHERE_GROUPBY)==0 ){
  111795. /* Make sure the sort order is compatible in an ORDER BY clause.
  111796. ** Sort order is irrelevant for a GROUP BY clause. */
  111797. if( revSet ){
  111798. if( (rev ^ revIdx)!=pOrderBy->a[i].sortOrder ) isMatch = 0;
  111799. }else{
  111800. rev = revIdx ^ pOrderBy->a[i].sortOrder;
  111801. if( rev ) *pRevMask |= MASKBIT(iLoop);
  111802. revSet = 1;
  111803. }
  111804. }
  111805. if( isMatch ){
  111806. if( iColumn<0 ){
  111807. testcase( distinctColumns==0 );
  111808. distinctColumns = 1;
  111809. }
  111810. obSat |= MASKBIT(i);
  111811. }else{
  111812. /* No match found */
  111813. if( j==0 || j<nKeyCol ){
  111814. testcase( isOrderDistinct!=0 );
  111815. isOrderDistinct = 0;
  111816. }
  111817. break;
  111818. }
  111819. } /* end Loop over all index columns */
  111820. if( distinctColumns ){
  111821. testcase( isOrderDistinct==0 );
  111822. isOrderDistinct = 1;
  111823. }
  111824. } /* end-if not one-row */
  111825. /* Mark off any other ORDER BY terms that reference pLoop */
  111826. if( isOrderDistinct ){
  111827. orderDistinctMask |= pLoop->maskSelf;
  111828. for(i=0; i<nOrderBy; i++){
  111829. Expr *p;
  111830. Bitmask mTerm;
  111831. if( MASKBIT(i) & obSat ) continue;
  111832. p = pOrderBy->a[i].pExpr;
  111833. mTerm = exprTableUsage(&pWInfo->sMaskSet,p);
  111834. if( mTerm==0 && !sqlite3ExprIsConstant(p) ) continue;
  111835. if( (mTerm&~orderDistinctMask)==0 ){
  111836. obSat |= MASKBIT(i);
  111837. }
  111838. }
  111839. }
  111840. } /* End the loop over all WhereLoops from outer-most down to inner-most */
  111841. if( obSat==obDone ) return (i8)nOrderBy;
  111842. if( !isOrderDistinct ){
  111843. for(i=nOrderBy-1; i>0; i--){
  111844. Bitmask m = MASKBIT(i) - 1;
  111845. if( (obSat&m)==m ) return i;
  111846. }
  111847. return 0;
  111848. }
  111849. return -1;
  111850. }
  111851. /*
  111852. ** If the WHERE_GROUPBY flag is set in the mask passed to sqlite3WhereBegin(),
  111853. ** the planner assumes that the specified pOrderBy list is actually a GROUP
  111854. ** BY clause - and so any order that groups rows as required satisfies the
  111855. ** request.
  111856. **
  111857. ** Normally, in this case it is not possible for the caller to determine
  111858. ** whether or not the rows are really being delivered in sorted order, or
  111859. ** just in some other order that provides the required grouping. However,
  111860. ** if the WHERE_SORTBYGROUP flag is also passed to sqlite3WhereBegin(), then
  111861. ** this function may be called on the returned WhereInfo object. It returns
  111862. ** true if the rows really will be sorted in the specified order, or false
  111863. ** otherwise.
  111864. **
  111865. ** For example, assuming:
  111866. **
  111867. ** CREATE INDEX i1 ON t1(x, Y);
  111868. **
  111869. ** then
  111870. **
  111871. ** SELECT * FROM t1 GROUP BY x,y ORDER BY x,y; -- IsSorted()==1
  111872. ** SELECT * FROM t1 GROUP BY y,x ORDER BY y,x; -- IsSorted()==0
  111873. */
  111874. SQLITE_PRIVATE int sqlite3WhereIsSorted(WhereInfo *pWInfo){
  111875. assert( pWInfo->wctrlFlags & WHERE_GROUPBY );
  111876. assert( pWInfo->wctrlFlags & WHERE_SORTBYGROUP );
  111877. return pWInfo->sorted;
  111878. }
  111879. #ifdef WHERETRACE_ENABLED
  111880. /* For debugging use only: */
  111881. static const char *wherePathName(WherePath *pPath, int nLoop, WhereLoop *pLast){
  111882. static char zName[65];
  111883. int i;
  111884. for(i=0; i<nLoop; i++){ zName[i] = pPath->aLoop[i]->cId; }
  111885. if( pLast ) zName[i++] = pLast->cId;
  111886. zName[i] = 0;
  111887. return zName;
  111888. }
  111889. #endif
  111890. /*
  111891. ** Return the cost of sorting nRow rows, assuming that the keys have
  111892. ** nOrderby columns and that the first nSorted columns are already in
  111893. ** order.
  111894. */
  111895. static LogEst whereSortingCost(
  111896. WhereInfo *pWInfo,
  111897. LogEst nRow,
  111898. int nOrderBy,
  111899. int nSorted
  111900. ){
  111901. /* TUNING: Estimated cost of a full external sort, where N is
  111902. ** the number of rows to sort is:
  111903. **
  111904. ** cost = (3.0 * N * log(N)).
  111905. **
  111906. ** Or, if the order-by clause has X terms but only the last Y
  111907. ** terms are out of order, then block-sorting will reduce the
  111908. ** sorting cost to:
  111909. **
  111910. ** cost = (3.0 * N * log(N)) * (Y/X)
  111911. **
  111912. ** The (Y/X) term is implemented using stack variable rScale
  111913. ** below. */
  111914. LogEst rScale, rSortCost;
  111915. assert( nOrderBy>0 && 66==sqlite3LogEst(100) );
  111916. rScale = sqlite3LogEst((nOrderBy-nSorted)*100/nOrderBy) - 66;
  111917. rSortCost = nRow + estLog(nRow) + rScale + 16;
  111918. /* TUNING: The cost of implementing DISTINCT using a B-TREE is
  111919. ** similar but with a larger constant of proportionality.
  111920. ** Multiply by an additional factor of 3.0. */
  111921. if( pWInfo->wctrlFlags & WHERE_WANT_DISTINCT ){
  111922. rSortCost += 16;
  111923. }
  111924. return rSortCost;
  111925. }
  111926. /*
  111927. ** Given the list of WhereLoop objects at pWInfo->pLoops, this routine
  111928. ** attempts to find the lowest cost path that visits each WhereLoop
  111929. ** once. This path is then loaded into the pWInfo->a[].pWLoop fields.
  111930. **
  111931. ** Assume that the total number of output rows that will need to be sorted
  111932. ** will be nRowEst (in the 10*log2 representation). Or, ignore sorting
  111933. ** costs if nRowEst==0.
  111934. **
  111935. ** Return SQLITE_OK on success or SQLITE_NOMEM of a memory allocation
  111936. ** error occurs.
  111937. */
  111938. static int wherePathSolver(WhereInfo *pWInfo, LogEst nRowEst){
  111939. int mxChoice; /* Maximum number of simultaneous paths tracked */
  111940. int nLoop; /* Number of terms in the join */
  111941. Parse *pParse; /* Parsing context */
  111942. sqlite3 *db; /* The database connection */
  111943. int iLoop; /* Loop counter over the terms of the join */
  111944. int ii, jj; /* Loop counters */
  111945. int mxI = 0; /* Index of next entry to replace */
  111946. int nOrderBy; /* Number of ORDER BY clause terms */
  111947. LogEst mxCost = 0; /* Maximum cost of a set of paths */
  111948. LogEst mxUnsorted = 0; /* Maximum unsorted cost of a set of path */
  111949. int nTo, nFrom; /* Number of valid entries in aTo[] and aFrom[] */
  111950. WherePath *aFrom; /* All nFrom paths at the previous level */
  111951. WherePath *aTo; /* The nTo best paths at the current level */
  111952. WherePath *pFrom; /* An element of aFrom[] that we are working on */
  111953. WherePath *pTo; /* An element of aTo[] that we are working on */
  111954. WhereLoop *pWLoop; /* One of the WhereLoop objects */
  111955. WhereLoop **pX; /* Used to divy up the pSpace memory */
  111956. LogEst *aSortCost = 0; /* Sorting and partial sorting costs */
  111957. char *pSpace; /* Temporary memory used by this routine */
  111958. int nSpace; /* Bytes of space allocated at pSpace */
  111959. pParse = pWInfo->pParse;
  111960. db = pParse->db;
  111961. nLoop = pWInfo->nLevel;
  111962. /* TUNING: For simple queries, only the best path is tracked.
  111963. ** For 2-way joins, the 5 best paths are followed.
  111964. ** For joins of 3 or more tables, track the 10 best paths */
  111965. mxChoice = (nLoop<=1) ? 1 : (nLoop==2 ? 5 : 10);
  111966. assert( nLoop<=pWInfo->pTabList->nSrc );
  111967. WHERETRACE(0x002, ("---- begin solver. (nRowEst=%d)\n", nRowEst));
  111968. /* If nRowEst is zero and there is an ORDER BY clause, ignore it. In this
  111969. ** case the purpose of this call is to estimate the number of rows returned
  111970. ** by the overall query. Once this estimate has been obtained, the caller
  111971. ** will invoke this function a second time, passing the estimate as the
  111972. ** nRowEst parameter. */
  111973. if( pWInfo->pOrderBy==0 || nRowEst==0 ){
  111974. nOrderBy = 0;
  111975. }else{
  111976. nOrderBy = pWInfo->pOrderBy->nExpr;
  111977. }
  111978. /* Allocate and initialize space for aTo, aFrom and aSortCost[] */
  111979. nSpace = (sizeof(WherePath)+sizeof(WhereLoop*)*nLoop)*mxChoice*2;
  111980. nSpace += sizeof(LogEst) * nOrderBy;
  111981. pSpace = sqlite3DbMallocRaw(db, nSpace);
  111982. if( pSpace==0 ) return SQLITE_NOMEM;
  111983. aTo = (WherePath*)pSpace;
  111984. aFrom = aTo+mxChoice;
  111985. memset(aFrom, 0, sizeof(aFrom[0]));
  111986. pX = (WhereLoop**)(aFrom+mxChoice);
  111987. for(ii=mxChoice*2, pFrom=aTo; ii>0; ii--, pFrom++, pX += nLoop){
  111988. pFrom->aLoop = pX;
  111989. }
  111990. if( nOrderBy ){
  111991. /* If there is an ORDER BY clause and it is not being ignored, set up
  111992. ** space for the aSortCost[] array. Each element of the aSortCost array
  111993. ** is either zero - meaning it has not yet been initialized - or the
  111994. ** cost of sorting nRowEst rows of data where the first X terms of
  111995. ** the ORDER BY clause are already in order, where X is the array
  111996. ** index. */
  111997. aSortCost = (LogEst*)pX;
  111998. memset(aSortCost, 0, sizeof(LogEst) * nOrderBy);
  111999. }
  112000. assert( aSortCost==0 || &pSpace[nSpace]==(char*)&aSortCost[nOrderBy] );
  112001. assert( aSortCost!=0 || &pSpace[nSpace]==(char*)pX );
  112002. /* Seed the search with a single WherePath containing zero WhereLoops.
  112003. **
  112004. ** TUNING: Do not let the number of iterations go above 25. If the cost
  112005. ** of computing an automatic index is not paid back within the first 25
  112006. ** rows, then do not use the automatic index. */
  112007. aFrom[0].nRow = MIN(pParse->nQueryLoop, 46); assert( 46==sqlite3LogEst(25) );
  112008. nFrom = 1;
  112009. assert( aFrom[0].isOrdered==0 );
  112010. if( nOrderBy ){
  112011. /* If nLoop is zero, then there are no FROM terms in the query. Since
  112012. ** in this case the query may return a maximum of one row, the results
  112013. ** are already in the requested order. Set isOrdered to nOrderBy to
  112014. ** indicate this. Or, if nLoop is greater than zero, set isOrdered to
  112015. ** -1, indicating that the result set may or may not be ordered,
  112016. ** depending on the loops added to the current plan. */
  112017. aFrom[0].isOrdered = nLoop>0 ? -1 : nOrderBy;
  112018. }
  112019. /* Compute successively longer WherePaths using the previous generation
  112020. ** of WherePaths as the basis for the next. Keep track of the mxChoice
  112021. ** best paths at each generation */
  112022. for(iLoop=0; iLoop<nLoop; iLoop++){
  112023. nTo = 0;
  112024. for(ii=0, pFrom=aFrom; ii<nFrom; ii++, pFrom++){
  112025. for(pWLoop=pWInfo->pLoops; pWLoop; pWLoop=pWLoop->pNextLoop){
  112026. LogEst nOut; /* Rows visited by (pFrom+pWLoop) */
  112027. LogEst rCost; /* Cost of path (pFrom+pWLoop) */
  112028. LogEst rUnsorted; /* Unsorted cost of (pFrom+pWLoop) */
  112029. i8 isOrdered = pFrom->isOrdered; /* isOrdered for (pFrom+pWLoop) */
  112030. Bitmask maskNew; /* Mask of src visited by (..) */
  112031. Bitmask revMask = 0; /* Mask of rev-order loops for (..) */
  112032. if( (pWLoop->prereq & ~pFrom->maskLoop)!=0 ) continue;
  112033. if( (pWLoop->maskSelf & pFrom->maskLoop)!=0 ) continue;
  112034. /* At this point, pWLoop is a candidate to be the next loop.
  112035. ** Compute its cost */
  112036. rUnsorted = sqlite3LogEstAdd(pWLoop->rSetup,pWLoop->rRun + pFrom->nRow);
  112037. rUnsorted = sqlite3LogEstAdd(rUnsorted, pFrom->rUnsorted);
  112038. nOut = pFrom->nRow + pWLoop->nOut;
  112039. maskNew = pFrom->maskLoop | pWLoop->maskSelf;
  112040. if( isOrdered<0 ){
  112041. isOrdered = wherePathSatisfiesOrderBy(pWInfo,
  112042. pWInfo->pOrderBy, pFrom, pWInfo->wctrlFlags,
  112043. iLoop, pWLoop, &revMask);
  112044. }else{
  112045. revMask = pFrom->revLoop;
  112046. }
  112047. if( isOrdered>=0 && isOrdered<nOrderBy ){
  112048. if( aSortCost[isOrdered]==0 ){
  112049. aSortCost[isOrdered] = whereSortingCost(
  112050. pWInfo, nRowEst, nOrderBy, isOrdered
  112051. );
  112052. }
  112053. rCost = sqlite3LogEstAdd(rUnsorted, aSortCost[isOrdered]);
  112054. WHERETRACE(0x002,
  112055. ("---- sort cost=%-3d (%d/%d) increases cost %3d to %-3d\n",
  112056. aSortCost[isOrdered], (nOrderBy-isOrdered), nOrderBy,
  112057. rUnsorted, rCost));
  112058. }else{
  112059. rCost = rUnsorted;
  112060. }
  112061. /* Check to see if pWLoop should be added to the set of
  112062. ** mxChoice best-so-far paths.
  112063. **
  112064. ** First look for an existing path among best-so-far paths
  112065. ** that covers the same set of loops and has the same isOrdered
  112066. ** setting as the current path candidate.
  112067. **
  112068. ** The term "((pTo->isOrdered^isOrdered)&0x80)==0" is equivalent
  112069. ** to (pTo->isOrdered==(-1))==(isOrdered==(-1))" for the range
  112070. ** of legal values for isOrdered, -1..64.
  112071. */
  112072. for(jj=0, pTo=aTo; jj<nTo; jj++, pTo++){
  112073. if( pTo->maskLoop==maskNew
  112074. && ((pTo->isOrdered^isOrdered)&0x80)==0
  112075. ){
  112076. testcase( jj==nTo-1 );
  112077. break;
  112078. }
  112079. }
  112080. if( jj>=nTo ){
  112081. /* None of the existing best-so-far paths match the candidate. */
  112082. if( nTo>=mxChoice
  112083. && (rCost>mxCost || (rCost==mxCost && rUnsorted>=mxUnsorted))
  112084. ){
  112085. /* The current candidate is no better than any of the mxChoice
  112086. ** paths currently in the best-so-far buffer. So discard
  112087. ** this candidate as not viable. */
  112088. #ifdef WHERETRACE_ENABLED /* 0x4 */
  112089. if( sqlite3WhereTrace&0x4 ){
  112090. sqlite3DebugPrintf("Skip %s cost=%-3d,%3d order=%c\n",
  112091. wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
  112092. isOrdered>=0 ? isOrdered+'0' : '?');
  112093. }
  112094. #endif
  112095. continue;
  112096. }
  112097. /* If we reach this points it means that the new candidate path
  112098. ** needs to be added to the set of best-so-far paths. */
  112099. if( nTo<mxChoice ){
  112100. /* Increase the size of the aTo set by one */
  112101. jj = nTo++;
  112102. }else{
  112103. /* New path replaces the prior worst to keep count below mxChoice */
  112104. jj = mxI;
  112105. }
  112106. pTo = &aTo[jj];
  112107. #ifdef WHERETRACE_ENABLED /* 0x4 */
  112108. if( sqlite3WhereTrace&0x4 ){
  112109. sqlite3DebugPrintf("New %s cost=%-3d,%3d order=%c\n",
  112110. wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
  112111. isOrdered>=0 ? isOrdered+'0' : '?');
  112112. }
  112113. #endif
  112114. }else{
  112115. /* Control reaches here if best-so-far path pTo=aTo[jj] covers the
  112116. ** same set of loops and has the sam isOrdered setting as the
  112117. ** candidate path. Check to see if the candidate should replace
  112118. ** pTo or if the candidate should be skipped */
  112119. if( pTo->rCost<rCost || (pTo->rCost==rCost && pTo->nRow<=nOut) ){
  112120. #ifdef WHERETRACE_ENABLED /* 0x4 */
  112121. if( sqlite3WhereTrace&0x4 ){
  112122. sqlite3DebugPrintf(
  112123. "Skip %s cost=%-3d,%3d order=%c",
  112124. wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
  112125. isOrdered>=0 ? isOrdered+'0' : '?');
  112126. sqlite3DebugPrintf(" vs %s cost=%-3d,%d order=%c\n",
  112127. wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
  112128. pTo->isOrdered>=0 ? pTo->isOrdered+'0' : '?');
  112129. }
  112130. #endif
  112131. /* Discard the candidate path from further consideration */
  112132. testcase( pTo->rCost==rCost );
  112133. continue;
  112134. }
  112135. testcase( pTo->rCost==rCost+1 );
  112136. /* Control reaches here if the candidate path is better than the
  112137. ** pTo path. Replace pTo with the candidate. */
  112138. #ifdef WHERETRACE_ENABLED /* 0x4 */
  112139. if( sqlite3WhereTrace&0x4 ){
  112140. sqlite3DebugPrintf(
  112141. "Update %s cost=%-3d,%3d order=%c",
  112142. wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
  112143. isOrdered>=0 ? isOrdered+'0' : '?');
  112144. sqlite3DebugPrintf(" was %s cost=%-3d,%3d order=%c\n",
  112145. wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
  112146. pTo->isOrdered>=0 ? pTo->isOrdered+'0' : '?');
  112147. }
  112148. #endif
  112149. }
  112150. /* pWLoop is a winner. Add it to the set of best so far */
  112151. pTo->maskLoop = pFrom->maskLoop | pWLoop->maskSelf;
  112152. pTo->revLoop = revMask;
  112153. pTo->nRow = nOut;
  112154. pTo->rCost = rCost;
  112155. pTo->rUnsorted = rUnsorted;
  112156. pTo->isOrdered = isOrdered;
  112157. memcpy(pTo->aLoop, pFrom->aLoop, sizeof(WhereLoop*)*iLoop);
  112158. pTo->aLoop[iLoop] = pWLoop;
  112159. if( nTo>=mxChoice ){
  112160. mxI = 0;
  112161. mxCost = aTo[0].rCost;
  112162. mxUnsorted = aTo[0].nRow;
  112163. for(jj=1, pTo=&aTo[1]; jj<mxChoice; jj++, pTo++){
  112164. if( pTo->rCost>mxCost
  112165. || (pTo->rCost==mxCost && pTo->rUnsorted>mxUnsorted)
  112166. ){
  112167. mxCost = pTo->rCost;
  112168. mxUnsorted = pTo->rUnsorted;
  112169. mxI = jj;
  112170. }
  112171. }
  112172. }
  112173. }
  112174. }
  112175. #ifdef WHERETRACE_ENABLED /* >=2 */
  112176. if( sqlite3WhereTrace & 0x02 ){
  112177. sqlite3DebugPrintf("---- after round %d ----\n", iLoop);
  112178. for(ii=0, pTo=aTo; ii<nTo; ii++, pTo++){
  112179. sqlite3DebugPrintf(" %s cost=%-3d nrow=%-3d order=%c",
  112180. wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
  112181. pTo->isOrdered>=0 ? (pTo->isOrdered+'0') : '?');
  112182. if( pTo->isOrdered>0 ){
  112183. sqlite3DebugPrintf(" rev=0x%llx\n", pTo->revLoop);
  112184. }else{
  112185. sqlite3DebugPrintf("\n");
  112186. }
  112187. }
  112188. }
  112189. #endif
  112190. /* Swap the roles of aFrom and aTo for the next generation */
  112191. pFrom = aTo;
  112192. aTo = aFrom;
  112193. aFrom = pFrom;
  112194. nFrom = nTo;
  112195. }
  112196. if( nFrom==0 ){
  112197. sqlite3ErrorMsg(pParse, "no query solution");
  112198. sqlite3DbFree(db, pSpace);
  112199. return SQLITE_ERROR;
  112200. }
  112201. /* Find the lowest cost path. pFrom will be left pointing to that path */
  112202. pFrom = aFrom;
  112203. for(ii=1; ii<nFrom; ii++){
  112204. if( pFrom->rCost>aFrom[ii].rCost ) pFrom = &aFrom[ii];
  112205. }
  112206. assert( pWInfo->nLevel==nLoop );
  112207. /* Load the lowest cost path into pWInfo */
  112208. for(iLoop=0; iLoop<nLoop; iLoop++){
  112209. WhereLevel *pLevel = pWInfo->a + iLoop;
  112210. pLevel->pWLoop = pWLoop = pFrom->aLoop[iLoop];
  112211. pLevel->iFrom = pWLoop->iTab;
  112212. pLevel->iTabCur = pWInfo->pTabList->a[pLevel->iFrom].iCursor;
  112213. }
  112214. if( (pWInfo->wctrlFlags & WHERE_WANT_DISTINCT)!=0
  112215. && (pWInfo->wctrlFlags & WHERE_DISTINCTBY)==0
  112216. && pWInfo->eDistinct==WHERE_DISTINCT_NOOP
  112217. && nRowEst
  112218. ){
  112219. Bitmask notUsed;
  112220. int rc = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pResultSet, pFrom,
  112221. WHERE_DISTINCTBY, nLoop-1, pFrom->aLoop[nLoop-1], &notUsed);
  112222. if( rc==pWInfo->pResultSet->nExpr ){
  112223. pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
  112224. }
  112225. }
  112226. if( pWInfo->pOrderBy ){
  112227. if( pWInfo->wctrlFlags & WHERE_DISTINCTBY ){
  112228. if( pFrom->isOrdered==pWInfo->pOrderBy->nExpr ){
  112229. pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
  112230. }
  112231. }else{
  112232. pWInfo->nOBSat = pFrom->isOrdered;
  112233. if( pWInfo->nOBSat<0 ) pWInfo->nOBSat = 0;
  112234. pWInfo->revMask = pFrom->revLoop;
  112235. }
  112236. if( (pWInfo->wctrlFlags & WHERE_SORTBYGROUP)
  112237. && pWInfo->nOBSat==pWInfo->pOrderBy->nExpr
  112238. ){
  112239. Bitmask revMask = 0;
  112240. int nOrder = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pOrderBy,
  112241. pFrom, 0, nLoop-1, pFrom->aLoop[nLoop-1], &revMask
  112242. );
  112243. assert( pWInfo->sorted==0 );
  112244. if( nOrder==pWInfo->pOrderBy->nExpr ){
  112245. pWInfo->sorted = 1;
  112246. pWInfo->revMask = revMask;
  112247. }
  112248. }
  112249. }
  112250. pWInfo->nRowOut = pFrom->nRow;
  112251. /* Free temporary memory and return success */
  112252. sqlite3DbFree(db, pSpace);
  112253. return SQLITE_OK;
  112254. }
  112255. /*
  112256. ** Most queries use only a single table (they are not joins) and have
  112257. ** simple == constraints against indexed fields. This routine attempts
  112258. ** to plan those simple cases using much less ceremony than the
  112259. ** general-purpose query planner, and thereby yield faster sqlite3_prepare()
  112260. ** times for the common case.
  112261. **
  112262. ** Return non-zero on success, if this query can be handled by this
  112263. ** no-frills query planner. Return zero if this query needs the
  112264. ** general-purpose query planner.
  112265. */
  112266. static int whereShortCut(WhereLoopBuilder *pBuilder){
  112267. WhereInfo *pWInfo;
  112268. struct SrcList_item *pItem;
  112269. WhereClause *pWC;
  112270. WhereTerm *pTerm;
  112271. WhereLoop *pLoop;
  112272. int iCur;
  112273. int j;
  112274. Table *pTab;
  112275. Index *pIdx;
  112276. pWInfo = pBuilder->pWInfo;
  112277. if( pWInfo->wctrlFlags & WHERE_FORCE_TABLE ) return 0;
  112278. assert( pWInfo->pTabList->nSrc>=1 );
  112279. pItem = pWInfo->pTabList->a;
  112280. pTab = pItem->pTab;
  112281. if( IsVirtual(pTab) ) return 0;
  112282. if( pItem->zIndex ) return 0;
  112283. iCur = pItem->iCursor;
  112284. pWC = &pWInfo->sWC;
  112285. pLoop = pBuilder->pNew;
  112286. pLoop->wsFlags = 0;
  112287. pLoop->nSkip = 0;
  112288. pTerm = findTerm(pWC, iCur, -1, 0, WO_EQ, 0);
  112289. if( pTerm ){
  112290. pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_IPK|WHERE_ONEROW;
  112291. pLoop->aLTerm[0] = pTerm;
  112292. pLoop->nLTerm = 1;
  112293. pLoop->u.btree.nEq = 1;
  112294. /* TUNING: Cost of a rowid lookup is 10 */
  112295. pLoop->rRun = 33; /* 33==sqlite3LogEst(10) */
  112296. }else{
  112297. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  112298. assert( pLoop->aLTermSpace==pLoop->aLTerm );
  112299. if( !IsUniqueIndex(pIdx)
  112300. || pIdx->pPartIdxWhere!=0
  112301. || pIdx->nKeyCol>ArraySize(pLoop->aLTermSpace)
  112302. ) continue;
  112303. for(j=0; j<pIdx->nKeyCol; j++){
  112304. pTerm = findTerm(pWC, iCur, pIdx->aiColumn[j], 0, WO_EQ, pIdx);
  112305. if( pTerm==0 ) break;
  112306. pLoop->aLTerm[j] = pTerm;
  112307. }
  112308. if( j!=pIdx->nKeyCol ) continue;
  112309. pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_ONEROW|WHERE_INDEXED;
  112310. if( pIdx->isCovering || (pItem->colUsed & ~columnsInIndex(pIdx))==0 ){
  112311. pLoop->wsFlags |= WHERE_IDX_ONLY;
  112312. }
  112313. pLoop->nLTerm = j;
  112314. pLoop->u.btree.nEq = j;
  112315. pLoop->u.btree.pIndex = pIdx;
  112316. /* TUNING: Cost of a unique index lookup is 15 */
  112317. pLoop->rRun = 39; /* 39==sqlite3LogEst(15) */
  112318. break;
  112319. }
  112320. }
  112321. if( pLoop->wsFlags ){
  112322. pLoop->nOut = (LogEst)1;
  112323. pWInfo->a[0].pWLoop = pLoop;
  112324. pLoop->maskSelf = getMask(&pWInfo->sMaskSet, iCur);
  112325. pWInfo->a[0].iTabCur = iCur;
  112326. pWInfo->nRowOut = 1;
  112327. if( pWInfo->pOrderBy ) pWInfo->nOBSat = pWInfo->pOrderBy->nExpr;
  112328. if( pWInfo->wctrlFlags & WHERE_WANT_DISTINCT ){
  112329. pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
  112330. }
  112331. #ifdef SQLITE_DEBUG
  112332. pLoop->cId = '0';
  112333. #endif
  112334. return 1;
  112335. }
  112336. return 0;
  112337. }
  112338. /*
  112339. ** Generate the beginning of the loop used for WHERE clause processing.
  112340. ** The return value is a pointer to an opaque structure that contains
  112341. ** information needed to terminate the loop. Later, the calling routine
  112342. ** should invoke sqlite3WhereEnd() with the return value of this function
  112343. ** in order to complete the WHERE clause processing.
  112344. **
  112345. ** If an error occurs, this routine returns NULL.
  112346. **
  112347. ** The basic idea is to do a nested loop, one loop for each table in
  112348. ** the FROM clause of a select. (INSERT and UPDATE statements are the
  112349. ** same as a SELECT with only a single table in the FROM clause.) For
  112350. ** example, if the SQL is this:
  112351. **
  112352. ** SELECT * FROM t1, t2, t3 WHERE ...;
  112353. **
  112354. ** Then the code generated is conceptually like the following:
  112355. **
  112356. ** foreach row1 in t1 do \ Code generated
  112357. ** foreach row2 in t2 do |-- by sqlite3WhereBegin()
  112358. ** foreach row3 in t3 do /
  112359. ** ...
  112360. ** end \ Code generated
  112361. ** end |-- by sqlite3WhereEnd()
  112362. ** end /
  112363. **
  112364. ** Note that the loops might not be nested in the order in which they
  112365. ** appear in the FROM clause if a different order is better able to make
  112366. ** use of indices. Note also that when the IN operator appears in
  112367. ** the WHERE clause, it might result in additional nested loops for
  112368. ** scanning through all values on the right-hand side of the IN.
  112369. **
  112370. ** There are Btree cursors associated with each table. t1 uses cursor
  112371. ** number pTabList->a[0].iCursor. t2 uses the cursor pTabList->a[1].iCursor.
  112372. ** And so forth. This routine generates code to open those VDBE cursors
  112373. ** and sqlite3WhereEnd() generates the code to close them.
  112374. **
  112375. ** The code that sqlite3WhereBegin() generates leaves the cursors named
  112376. ** in pTabList pointing at their appropriate entries. The [...] code
  112377. ** can use OP_Column and OP_Rowid opcodes on these cursors to extract
  112378. ** data from the various tables of the loop.
  112379. **
  112380. ** If the WHERE clause is empty, the foreach loops must each scan their
  112381. ** entire tables. Thus a three-way join is an O(N^3) operation. But if
  112382. ** the tables have indices and there are terms in the WHERE clause that
  112383. ** refer to those indices, a complete table scan can be avoided and the
  112384. ** code will run much faster. Most of the work of this routine is checking
  112385. ** to see if there are indices that can be used to speed up the loop.
  112386. **
  112387. ** Terms of the WHERE clause are also used to limit which rows actually
  112388. ** make it to the "..." in the middle of the loop. After each "foreach",
  112389. ** terms of the WHERE clause that use only terms in that loop and outer
  112390. ** loops are evaluated and if false a jump is made around all subsequent
  112391. ** inner loops (or around the "..." if the test occurs within the inner-
  112392. ** most loop)
  112393. **
  112394. ** OUTER JOINS
  112395. **
  112396. ** An outer join of tables t1 and t2 is conceptally coded as follows:
  112397. **
  112398. ** foreach row1 in t1 do
  112399. ** flag = 0
  112400. ** foreach row2 in t2 do
  112401. ** start:
  112402. ** ...
  112403. ** flag = 1
  112404. ** end
  112405. ** if flag==0 then
  112406. ** move the row2 cursor to a null row
  112407. ** goto start
  112408. ** fi
  112409. ** end
  112410. **
  112411. ** ORDER BY CLAUSE PROCESSING
  112412. **
  112413. ** pOrderBy is a pointer to the ORDER BY clause (or the GROUP BY clause
  112414. ** if the WHERE_GROUPBY flag is set in wctrlFlags) of a SELECT statement
  112415. ** if there is one. If there is no ORDER BY clause or if this routine
  112416. ** is called from an UPDATE or DELETE statement, then pOrderBy is NULL.
  112417. **
  112418. ** The iIdxCur parameter is the cursor number of an index. If
  112419. ** WHERE_ONETABLE_ONLY is set, iIdxCur is the cursor number of an index
  112420. ** to use for OR clause processing. The WHERE clause should use this
  112421. ** specific cursor. If WHERE_ONEPASS_DESIRED is set, then iIdxCur is
  112422. ** the first cursor in an array of cursors for all indices. iIdxCur should
  112423. ** be used to compute the appropriate cursor depending on which index is
  112424. ** used.
  112425. */
  112426. SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(
  112427. Parse *pParse, /* The parser context */
  112428. SrcList *pTabList, /* FROM clause: A list of all tables to be scanned */
  112429. Expr *pWhere, /* The WHERE clause */
  112430. ExprList *pOrderBy, /* An ORDER BY (or GROUP BY) clause, or NULL */
  112431. ExprList *pResultSet, /* Result set of the query */
  112432. u16 wctrlFlags, /* One of the WHERE_* flags defined in sqliteInt.h */
  112433. int iIdxCur /* If WHERE_ONETABLE_ONLY is set, index cursor number */
  112434. ){
  112435. int nByteWInfo; /* Num. bytes allocated for WhereInfo struct */
  112436. int nTabList; /* Number of elements in pTabList */
  112437. WhereInfo *pWInfo; /* Will become the return value of this function */
  112438. Vdbe *v = pParse->pVdbe; /* The virtual database engine */
  112439. Bitmask notReady; /* Cursors that are not yet positioned */
  112440. WhereLoopBuilder sWLB; /* The WhereLoop builder */
  112441. WhereMaskSet *pMaskSet; /* The expression mask set */
  112442. WhereLevel *pLevel; /* A single level in pWInfo->a[] */
  112443. WhereLoop *pLoop; /* Pointer to a single WhereLoop object */
  112444. int ii; /* Loop counter */
  112445. sqlite3 *db; /* Database connection */
  112446. int rc; /* Return code */
  112447. /* Variable initialization */
  112448. db = pParse->db;
  112449. memset(&sWLB, 0, sizeof(sWLB));
  112450. /* An ORDER/GROUP BY clause of more than 63 terms cannot be optimized */
  112451. testcase( pOrderBy && pOrderBy->nExpr==BMS-1 );
  112452. if( pOrderBy && pOrderBy->nExpr>=BMS ) pOrderBy = 0;
  112453. sWLB.pOrderBy = pOrderBy;
  112454. /* Disable the DISTINCT optimization if SQLITE_DistinctOpt is set via
  112455. ** sqlite3_test_ctrl(SQLITE_TESTCTRL_OPTIMIZATIONS,...) */
  112456. if( OptimizationDisabled(db, SQLITE_DistinctOpt) ){
  112457. wctrlFlags &= ~WHERE_WANT_DISTINCT;
  112458. }
  112459. /* The number of tables in the FROM clause is limited by the number of
  112460. ** bits in a Bitmask
  112461. */
  112462. testcase( pTabList->nSrc==BMS );
  112463. if( pTabList->nSrc>BMS ){
  112464. sqlite3ErrorMsg(pParse, "at most %d tables in a join", BMS);
  112465. return 0;
  112466. }
  112467. /* This function normally generates a nested loop for all tables in
  112468. ** pTabList. But if the WHERE_ONETABLE_ONLY flag is set, then we should
  112469. ** only generate code for the first table in pTabList and assume that
  112470. ** any cursors associated with subsequent tables are uninitialized.
  112471. */
  112472. nTabList = (wctrlFlags & WHERE_ONETABLE_ONLY) ? 1 : pTabList->nSrc;
  112473. /* Allocate and initialize the WhereInfo structure that will become the
  112474. ** return value. A single allocation is used to store the WhereInfo
  112475. ** struct, the contents of WhereInfo.a[], the WhereClause structure
  112476. ** and the WhereMaskSet structure. Since WhereClause contains an 8-byte
  112477. ** field (type Bitmask) it must be aligned on an 8-byte boundary on
  112478. ** some architectures. Hence the ROUND8() below.
  112479. */
  112480. nByteWInfo = ROUND8(sizeof(WhereInfo)+(nTabList-1)*sizeof(WhereLevel));
  112481. pWInfo = sqlite3DbMallocZero(db, nByteWInfo + sizeof(WhereLoop));
  112482. if( db->mallocFailed ){
  112483. sqlite3DbFree(db, pWInfo);
  112484. pWInfo = 0;
  112485. goto whereBeginError;
  112486. }
  112487. pWInfo->aiCurOnePass[0] = pWInfo->aiCurOnePass[1] = -1;
  112488. pWInfo->nLevel = nTabList;
  112489. pWInfo->pParse = pParse;
  112490. pWInfo->pTabList = pTabList;
  112491. pWInfo->pOrderBy = pOrderBy;
  112492. pWInfo->pResultSet = pResultSet;
  112493. pWInfo->iBreak = pWInfo->iContinue = sqlite3VdbeMakeLabel(v);
  112494. pWInfo->wctrlFlags = wctrlFlags;
  112495. pWInfo->savedNQueryLoop = pParse->nQueryLoop;
  112496. pMaskSet = &pWInfo->sMaskSet;
  112497. sWLB.pWInfo = pWInfo;
  112498. sWLB.pWC = &pWInfo->sWC;
  112499. sWLB.pNew = (WhereLoop*)(((char*)pWInfo)+nByteWInfo);
  112500. assert( EIGHT_BYTE_ALIGNMENT(sWLB.pNew) );
  112501. whereLoopInit(sWLB.pNew);
  112502. #ifdef SQLITE_DEBUG
  112503. sWLB.pNew->cId = '*';
  112504. #endif
  112505. /* Split the WHERE clause into separate subexpressions where each
  112506. ** subexpression is separated by an AND operator.
  112507. */
  112508. initMaskSet(pMaskSet);
  112509. whereClauseInit(&pWInfo->sWC, pWInfo);
  112510. whereSplit(&pWInfo->sWC, pWhere, TK_AND);
  112511. /* Special case: a WHERE clause that is constant. Evaluate the
  112512. ** expression and either jump over all of the code or fall thru.
  112513. */
  112514. for(ii=0; ii<sWLB.pWC->nTerm; ii++){
  112515. if( nTabList==0 || sqlite3ExprIsConstantNotJoin(sWLB.pWC->a[ii].pExpr) ){
  112516. sqlite3ExprIfFalse(pParse, sWLB.pWC->a[ii].pExpr, pWInfo->iBreak,
  112517. SQLITE_JUMPIFNULL);
  112518. sWLB.pWC->a[ii].wtFlags |= TERM_CODED;
  112519. }
  112520. }
  112521. /* Special case: No FROM clause
  112522. */
  112523. if( nTabList==0 ){
  112524. if( pOrderBy ) pWInfo->nOBSat = pOrderBy->nExpr;
  112525. if( wctrlFlags & WHERE_WANT_DISTINCT ){
  112526. pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
  112527. }
  112528. }
  112529. /* Assign a bit from the bitmask to every term in the FROM clause.
  112530. **
  112531. ** When assigning bitmask values to FROM clause cursors, it must be
  112532. ** the case that if X is the bitmask for the N-th FROM clause term then
  112533. ** the bitmask for all FROM clause terms to the left of the N-th term
  112534. ** is (X-1). An expression from the ON clause of a LEFT JOIN can use
  112535. ** its Expr.iRightJoinTable value to find the bitmask of the right table
  112536. ** of the join. Subtracting one from the right table bitmask gives a
  112537. ** bitmask for all tables to the left of the join. Knowing the bitmask
  112538. ** for all tables to the left of a left join is important. Ticket #3015.
  112539. **
  112540. ** Note that bitmasks are created for all pTabList->nSrc tables in
  112541. ** pTabList, not just the first nTabList tables. nTabList is normally
  112542. ** equal to pTabList->nSrc but might be shortened to 1 if the
  112543. ** WHERE_ONETABLE_ONLY flag is set.
  112544. */
  112545. for(ii=0; ii<pTabList->nSrc; ii++){
  112546. createMask(pMaskSet, pTabList->a[ii].iCursor);
  112547. }
  112548. #ifndef NDEBUG
  112549. {
  112550. Bitmask toTheLeft = 0;
  112551. for(ii=0; ii<pTabList->nSrc; ii++){
  112552. Bitmask m = getMask(pMaskSet, pTabList->a[ii].iCursor);
  112553. assert( (m-1)==toTheLeft );
  112554. toTheLeft |= m;
  112555. }
  112556. }
  112557. #endif
  112558. /* Analyze all of the subexpressions. Note that exprAnalyze() might
  112559. ** add new virtual terms onto the end of the WHERE clause. We do not
  112560. ** want to analyze these virtual terms, so start analyzing at the end
  112561. ** and work forward so that the added virtual terms are never processed.
  112562. */
  112563. exprAnalyzeAll(pTabList, &pWInfo->sWC);
  112564. if( db->mallocFailed ){
  112565. goto whereBeginError;
  112566. }
  112567. if( wctrlFlags & WHERE_WANT_DISTINCT ){
  112568. if( isDistinctRedundant(pParse, pTabList, &pWInfo->sWC, pResultSet) ){
  112569. /* The DISTINCT marking is pointless. Ignore it. */
  112570. pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
  112571. }else if( pOrderBy==0 ){
  112572. /* Try to ORDER BY the result set to make distinct processing easier */
  112573. pWInfo->wctrlFlags |= WHERE_DISTINCTBY;
  112574. pWInfo->pOrderBy = pResultSet;
  112575. }
  112576. }
  112577. /* Construct the WhereLoop objects */
  112578. WHERETRACE(0xffff,("*** Optimizer Start ***\n"));
  112579. #if defined(WHERETRACE_ENABLED)
  112580. /* Display all terms of the WHERE clause */
  112581. if( sqlite3WhereTrace & 0x100 ){
  112582. int i;
  112583. for(i=0; i<sWLB.pWC->nTerm; i++){
  112584. whereTermPrint(&sWLB.pWC->a[i], i);
  112585. }
  112586. }
  112587. #endif
  112588. if( nTabList!=1 || whereShortCut(&sWLB)==0 ){
  112589. rc = whereLoopAddAll(&sWLB);
  112590. if( rc ) goto whereBeginError;
  112591. /* Display all of the WhereLoop objects if wheretrace is enabled */
  112592. #ifdef WHERETRACE_ENABLED /* !=0 */
  112593. if( sqlite3WhereTrace ){
  112594. WhereLoop *p;
  112595. int i;
  112596. static char zLabel[] = "0123456789abcdefghijklmnopqrstuvwyxz"
  112597. "ABCDEFGHIJKLMNOPQRSTUVWYXZ";
  112598. for(p=pWInfo->pLoops, i=0; p; p=p->pNextLoop, i++){
  112599. p->cId = zLabel[i%sizeof(zLabel)];
  112600. whereLoopPrint(p, sWLB.pWC);
  112601. }
  112602. }
  112603. #endif
  112604. wherePathSolver(pWInfo, 0);
  112605. if( db->mallocFailed ) goto whereBeginError;
  112606. if( pWInfo->pOrderBy ){
  112607. wherePathSolver(pWInfo, pWInfo->nRowOut+1);
  112608. if( db->mallocFailed ) goto whereBeginError;
  112609. }
  112610. }
  112611. if( pWInfo->pOrderBy==0 && (db->flags & SQLITE_ReverseOrder)!=0 ){
  112612. pWInfo->revMask = (Bitmask)(-1);
  112613. }
  112614. if( pParse->nErr || NEVER(db->mallocFailed) ){
  112615. goto whereBeginError;
  112616. }
  112617. #ifdef WHERETRACE_ENABLED /* !=0 */
  112618. if( sqlite3WhereTrace ){
  112619. int ii;
  112620. sqlite3DebugPrintf("---- Solution nRow=%d", pWInfo->nRowOut);
  112621. if( pWInfo->nOBSat>0 ){
  112622. sqlite3DebugPrintf(" ORDERBY=%d,0x%llx", pWInfo->nOBSat, pWInfo->revMask);
  112623. }
  112624. switch( pWInfo->eDistinct ){
  112625. case WHERE_DISTINCT_UNIQUE: {
  112626. sqlite3DebugPrintf(" DISTINCT=unique");
  112627. break;
  112628. }
  112629. case WHERE_DISTINCT_ORDERED: {
  112630. sqlite3DebugPrintf(" DISTINCT=ordered");
  112631. break;
  112632. }
  112633. case WHERE_DISTINCT_UNORDERED: {
  112634. sqlite3DebugPrintf(" DISTINCT=unordered");
  112635. break;
  112636. }
  112637. }
  112638. sqlite3DebugPrintf("\n");
  112639. for(ii=0; ii<pWInfo->nLevel; ii++){
  112640. whereLoopPrint(pWInfo->a[ii].pWLoop, sWLB.pWC);
  112641. }
  112642. }
  112643. #endif
  112644. /* Attempt to omit tables from the join that do not effect the result */
  112645. if( pWInfo->nLevel>=2
  112646. && pResultSet!=0
  112647. && OptimizationEnabled(db, SQLITE_OmitNoopJoin)
  112648. ){
  112649. Bitmask tabUsed = exprListTableUsage(pMaskSet, pResultSet);
  112650. if( sWLB.pOrderBy ) tabUsed |= exprListTableUsage(pMaskSet, sWLB.pOrderBy);
  112651. while( pWInfo->nLevel>=2 ){
  112652. WhereTerm *pTerm, *pEnd;
  112653. pLoop = pWInfo->a[pWInfo->nLevel-1].pWLoop;
  112654. if( (pWInfo->pTabList->a[pLoop->iTab].jointype & JT_LEFT)==0 ) break;
  112655. if( (wctrlFlags & WHERE_WANT_DISTINCT)==0
  112656. && (pLoop->wsFlags & WHERE_ONEROW)==0
  112657. ){
  112658. break;
  112659. }
  112660. if( (tabUsed & pLoop->maskSelf)!=0 ) break;
  112661. pEnd = sWLB.pWC->a + sWLB.pWC->nTerm;
  112662. for(pTerm=sWLB.pWC->a; pTerm<pEnd; pTerm++){
  112663. if( (pTerm->prereqAll & pLoop->maskSelf)!=0
  112664. && !ExprHasProperty(pTerm->pExpr, EP_FromJoin)
  112665. ){
  112666. break;
  112667. }
  112668. }
  112669. if( pTerm<pEnd ) break;
  112670. WHERETRACE(0xffff, ("-> drop loop %c not used\n", pLoop->cId));
  112671. pWInfo->nLevel--;
  112672. nTabList--;
  112673. }
  112674. }
  112675. WHERETRACE(0xffff,("*** Optimizer Finished ***\n"));
  112676. pWInfo->pParse->nQueryLoop += pWInfo->nRowOut;
  112677. /* If the caller is an UPDATE or DELETE statement that is requesting
  112678. ** to use a one-pass algorithm, determine if this is appropriate.
  112679. ** The one-pass algorithm only works if the WHERE clause constrains
  112680. ** the statement to update a single row.
  112681. */
  112682. assert( (wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || pWInfo->nLevel==1 );
  112683. if( (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0
  112684. && (pWInfo->a[0].pWLoop->wsFlags & WHERE_ONEROW)!=0 ){
  112685. pWInfo->okOnePass = 1;
  112686. if( HasRowid(pTabList->a[0].pTab) ){
  112687. pWInfo->a[0].pWLoop->wsFlags &= ~WHERE_IDX_ONLY;
  112688. }
  112689. }
  112690. /* Open all tables in the pTabList and any indices selected for
  112691. ** searching those tables.
  112692. */
  112693. notReady = ~(Bitmask)0;
  112694. for(ii=0, pLevel=pWInfo->a; ii<nTabList; ii++, pLevel++){
  112695. Table *pTab; /* Table to open */
  112696. int iDb; /* Index of database containing table/index */
  112697. struct SrcList_item *pTabItem;
  112698. pTabItem = &pTabList->a[pLevel->iFrom];
  112699. pTab = pTabItem->pTab;
  112700. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  112701. pLoop = pLevel->pWLoop;
  112702. if( (pTab->tabFlags & TF_Ephemeral)!=0 || pTab->pSelect ){
  112703. /* Do nothing */
  112704. }else
  112705. #ifndef SQLITE_OMIT_VIRTUALTABLE
  112706. if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){
  112707. const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
  112708. int iCur = pTabItem->iCursor;
  112709. sqlite3VdbeAddOp4(v, OP_VOpen, iCur, 0, 0, pVTab, P4_VTAB);
  112710. }else if( IsVirtual(pTab) ){
  112711. /* noop */
  112712. }else
  112713. #endif
  112714. if( (pLoop->wsFlags & WHERE_IDX_ONLY)==0
  112715. && (wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0 ){
  112716. int op = OP_OpenRead;
  112717. if( pWInfo->okOnePass ){
  112718. op = OP_OpenWrite;
  112719. pWInfo->aiCurOnePass[0] = pTabItem->iCursor;
  112720. };
  112721. sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, op);
  112722. assert( pTabItem->iCursor==pLevel->iTabCur );
  112723. testcase( !pWInfo->okOnePass && pTab->nCol==BMS-1 );
  112724. testcase( !pWInfo->okOnePass && pTab->nCol==BMS );
  112725. if( !pWInfo->okOnePass && pTab->nCol<BMS && HasRowid(pTab) ){
  112726. Bitmask b = pTabItem->colUsed;
  112727. int n = 0;
  112728. for(; b; b=b>>1, n++){}
  112729. sqlite3VdbeChangeP4(v, sqlite3VdbeCurrentAddr(v)-1,
  112730. SQLITE_INT_TO_PTR(n), P4_INT32);
  112731. assert( n<=pTab->nCol );
  112732. }
  112733. }else{
  112734. sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
  112735. }
  112736. if( pLoop->wsFlags & WHERE_INDEXED ){
  112737. Index *pIx = pLoop->u.btree.pIndex;
  112738. int iIndexCur;
  112739. int op = OP_OpenRead;
  112740. /* iIdxCur is always set if to a positive value if ONEPASS is possible */
  112741. assert( iIdxCur!=0 || (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 );
  112742. if( !HasRowid(pTab) && IsPrimaryKeyIndex(pIx)
  112743. && (wctrlFlags & WHERE_ONETABLE_ONLY)!=0
  112744. ){
  112745. /* This is one term of an OR-optimization using the PRIMARY KEY of a
  112746. ** WITHOUT ROWID table. No need for a separate index */
  112747. iIndexCur = pLevel->iTabCur;
  112748. op = 0;
  112749. }else if( pWInfo->okOnePass ){
  112750. Index *pJ = pTabItem->pTab->pIndex;
  112751. iIndexCur = iIdxCur;
  112752. assert( wctrlFlags & WHERE_ONEPASS_DESIRED );
  112753. while( ALWAYS(pJ) && pJ!=pIx ){
  112754. iIndexCur++;
  112755. pJ = pJ->pNext;
  112756. }
  112757. op = OP_OpenWrite;
  112758. pWInfo->aiCurOnePass[1] = iIndexCur;
  112759. }else if( iIdxCur && (wctrlFlags & WHERE_ONETABLE_ONLY)!=0 ){
  112760. iIndexCur = iIdxCur;
  112761. if( wctrlFlags & WHERE_REOPEN_IDX ) op = OP_ReopenIdx;
  112762. }else{
  112763. iIndexCur = pParse->nTab++;
  112764. }
  112765. pLevel->iIdxCur = iIndexCur;
  112766. assert( pIx->pSchema==pTab->pSchema );
  112767. assert( iIndexCur>=0 );
  112768. if( op ){
  112769. sqlite3VdbeAddOp3(v, op, iIndexCur, pIx->tnum, iDb);
  112770. sqlite3VdbeSetP4KeyInfo(pParse, pIx);
  112771. VdbeComment((v, "%s", pIx->zName));
  112772. }
  112773. }
  112774. if( iDb>=0 ) sqlite3CodeVerifySchema(pParse, iDb);
  112775. notReady &= ~getMask(&pWInfo->sMaskSet, pTabItem->iCursor);
  112776. }
  112777. pWInfo->iTop = sqlite3VdbeCurrentAddr(v);
  112778. if( db->mallocFailed ) goto whereBeginError;
  112779. /* Generate the code to do the search. Each iteration of the for
  112780. ** loop below generates code for a single nested loop of the VM
  112781. ** program.
  112782. */
  112783. notReady = ~(Bitmask)0;
  112784. for(ii=0; ii<nTabList; ii++){
  112785. pLevel = &pWInfo->a[ii];
  112786. #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
  112787. if( (pLevel->pWLoop->wsFlags & WHERE_AUTO_INDEX)!=0 ){
  112788. constructAutomaticIndex(pParse, &pWInfo->sWC,
  112789. &pTabList->a[pLevel->iFrom], notReady, pLevel);
  112790. if( db->mallocFailed ) goto whereBeginError;
  112791. }
  112792. #endif
  112793. explainOneScan(pParse, pTabList, pLevel, ii, pLevel->iFrom, wctrlFlags);
  112794. pLevel->addrBody = sqlite3VdbeCurrentAddr(v);
  112795. notReady = codeOneLoopStart(pWInfo, ii, notReady);
  112796. pWInfo->iContinue = pLevel->addrCont;
  112797. }
  112798. /* Done. */
  112799. VdbeModuleComment((v, "Begin WHERE-core"));
  112800. return pWInfo;
  112801. /* Jump here if malloc fails */
  112802. whereBeginError:
  112803. if( pWInfo ){
  112804. pParse->nQueryLoop = pWInfo->savedNQueryLoop;
  112805. whereInfoFree(db, pWInfo);
  112806. }
  112807. return 0;
  112808. }
  112809. /*
  112810. ** Generate the end of the WHERE loop. See comments on
  112811. ** sqlite3WhereBegin() for additional information.
  112812. */
  112813. SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){
  112814. Parse *pParse = pWInfo->pParse;
  112815. Vdbe *v = pParse->pVdbe;
  112816. int i;
  112817. WhereLevel *pLevel;
  112818. WhereLoop *pLoop;
  112819. SrcList *pTabList = pWInfo->pTabList;
  112820. sqlite3 *db = pParse->db;
  112821. /* Generate loop termination code.
  112822. */
  112823. VdbeModuleComment((v, "End WHERE-core"));
  112824. sqlite3ExprCacheClear(pParse);
  112825. for(i=pWInfo->nLevel-1; i>=0; i--){
  112826. int addr;
  112827. pLevel = &pWInfo->a[i];
  112828. pLoop = pLevel->pWLoop;
  112829. sqlite3VdbeResolveLabel(v, pLevel->addrCont);
  112830. if( pLevel->op!=OP_Noop ){
  112831. sqlite3VdbeAddOp3(v, pLevel->op, pLevel->p1, pLevel->p2, pLevel->p3);
  112832. sqlite3VdbeChangeP5(v, pLevel->p5);
  112833. VdbeCoverage(v);
  112834. VdbeCoverageIf(v, pLevel->op==OP_Next);
  112835. VdbeCoverageIf(v, pLevel->op==OP_Prev);
  112836. VdbeCoverageIf(v, pLevel->op==OP_VNext);
  112837. }
  112838. if( pLoop->wsFlags & WHERE_IN_ABLE && pLevel->u.in.nIn>0 ){
  112839. struct InLoop *pIn;
  112840. int j;
  112841. sqlite3VdbeResolveLabel(v, pLevel->addrNxt);
  112842. for(j=pLevel->u.in.nIn, pIn=&pLevel->u.in.aInLoop[j-1]; j>0; j--, pIn--){
  112843. sqlite3VdbeJumpHere(v, pIn->addrInTop+1);
  112844. sqlite3VdbeAddOp2(v, pIn->eEndLoopOp, pIn->iCur, pIn->addrInTop);
  112845. VdbeCoverage(v);
  112846. VdbeCoverageIf(v, pIn->eEndLoopOp==OP_PrevIfOpen);
  112847. VdbeCoverageIf(v, pIn->eEndLoopOp==OP_NextIfOpen);
  112848. sqlite3VdbeJumpHere(v, pIn->addrInTop-1);
  112849. }
  112850. sqlite3DbFree(db, pLevel->u.in.aInLoop);
  112851. }
  112852. sqlite3VdbeResolveLabel(v, pLevel->addrBrk);
  112853. if( pLevel->addrSkip ){
  112854. sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrSkip);
  112855. VdbeComment((v, "next skip-scan on %s", pLoop->u.btree.pIndex->zName));
  112856. sqlite3VdbeJumpHere(v, pLevel->addrSkip);
  112857. sqlite3VdbeJumpHere(v, pLevel->addrSkip-2);
  112858. }
  112859. if( pLevel->iLeftJoin ){
  112860. addr = sqlite3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin); VdbeCoverage(v);
  112861. assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0
  112862. || (pLoop->wsFlags & WHERE_INDEXED)!=0 );
  112863. if( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 ){
  112864. sqlite3VdbeAddOp1(v, OP_NullRow, pTabList->a[i].iCursor);
  112865. }
  112866. if( pLoop->wsFlags & WHERE_INDEXED ){
  112867. sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur);
  112868. }
  112869. if( pLevel->op==OP_Return ){
  112870. sqlite3VdbeAddOp2(v, OP_Gosub, pLevel->p1, pLevel->addrFirst);
  112871. }else{
  112872. sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrFirst);
  112873. }
  112874. sqlite3VdbeJumpHere(v, addr);
  112875. }
  112876. VdbeModuleComment((v, "End WHERE-loop%d: %s", i,
  112877. pWInfo->pTabList->a[pLevel->iFrom].pTab->zName));
  112878. }
  112879. /* The "break" point is here, just past the end of the outer loop.
  112880. ** Set it.
  112881. */
  112882. sqlite3VdbeResolveLabel(v, pWInfo->iBreak);
  112883. assert( pWInfo->nLevel<=pTabList->nSrc );
  112884. for(i=0, pLevel=pWInfo->a; i<pWInfo->nLevel; i++, pLevel++){
  112885. int k, last;
  112886. VdbeOp *pOp;
  112887. Index *pIdx = 0;
  112888. struct SrcList_item *pTabItem = &pTabList->a[pLevel->iFrom];
  112889. Table *pTab = pTabItem->pTab;
  112890. assert( pTab!=0 );
  112891. pLoop = pLevel->pWLoop;
  112892. /* For a co-routine, change all OP_Column references to the table of
  112893. ** the co-routine into OP_SCopy of result contained in a register.
  112894. ** OP_Rowid becomes OP_Null.
  112895. */
  112896. if( pTabItem->viaCoroutine && !db->mallocFailed ){
  112897. last = sqlite3VdbeCurrentAddr(v);
  112898. k = pLevel->addrBody;
  112899. pOp = sqlite3VdbeGetOp(v, k);
  112900. for(; k<last; k++, pOp++){
  112901. if( pOp->p1!=pLevel->iTabCur ) continue;
  112902. if( pOp->opcode==OP_Column ){
  112903. pOp->opcode = OP_Copy;
  112904. pOp->p1 = pOp->p2 + pTabItem->regResult;
  112905. pOp->p2 = pOp->p3;
  112906. pOp->p3 = 0;
  112907. }else if( pOp->opcode==OP_Rowid ){
  112908. pOp->opcode = OP_Null;
  112909. pOp->p1 = 0;
  112910. pOp->p3 = 0;
  112911. }
  112912. }
  112913. continue;
  112914. }
  112915. /* Close all of the cursors that were opened by sqlite3WhereBegin.
  112916. ** Except, do not close cursors that will be reused by the OR optimization
  112917. ** (WHERE_OMIT_OPEN_CLOSE). And do not close the OP_OpenWrite cursors
  112918. ** created for the ONEPASS optimization.
  112919. */
  112920. if( (pTab->tabFlags & TF_Ephemeral)==0
  112921. && pTab->pSelect==0
  112922. && (pWInfo->wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0
  112923. ){
  112924. int ws = pLoop->wsFlags;
  112925. if( !pWInfo->okOnePass && (ws & WHERE_IDX_ONLY)==0 ){
  112926. sqlite3VdbeAddOp1(v, OP_Close, pTabItem->iCursor);
  112927. }
  112928. if( (ws & WHERE_INDEXED)!=0
  112929. && (ws & (WHERE_IPK|WHERE_AUTO_INDEX))==0
  112930. && pLevel->iIdxCur!=pWInfo->aiCurOnePass[1]
  112931. ){
  112932. sqlite3VdbeAddOp1(v, OP_Close, pLevel->iIdxCur);
  112933. }
  112934. }
  112935. /* If this scan uses an index, make VDBE code substitutions to read data
  112936. ** from the index instead of from the table where possible. In some cases
  112937. ** this optimization prevents the table from ever being read, which can
  112938. ** yield a significant performance boost.
  112939. **
  112940. ** Calls to the code generator in between sqlite3WhereBegin and
  112941. ** sqlite3WhereEnd will have created code that references the table
  112942. ** directly. This loop scans all that code looking for opcodes
  112943. ** that reference the table and converts them into opcodes that
  112944. ** reference the index.
  112945. */
  112946. if( pLoop->wsFlags & (WHERE_INDEXED|WHERE_IDX_ONLY) ){
  112947. pIdx = pLoop->u.btree.pIndex;
  112948. }else if( pLoop->wsFlags & WHERE_MULTI_OR ){
  112949. pIdx = pLevel->u.pCovidx;
  112950. }
  112951. if( pIdx && !db->mallocFailed ){
  112952. last = sqlite3VdbeCurrentAddr(v);
  112953. k = pLevel->addrBody;
  112954. pOp = sqlite3VdbeGetOp(v, k);
  112955. for(; k<last; k++, pOp++){
  112956. if( pOp->p1!=pLevel->iTabCur ) continue;
  112957. if( pOp->opcode==OP_Column ){
  112958. int x = pOp->p2;
  112959. assert( pIdx->pTable==pTab );
  112960. if( !HasRowid(pTab) ){
  112961. Index *pPk = sqlite3PrimaryKeyIndex(pTab);
  112962. x = pPk->aiColumn[x];
  112963. }
  112964. x = sqlite3ColumnOfIndex(pIdx, x);
  112965. if( x>=0 ){
  112966. pOp->p2 = x;
  112967. pOp->p1 = pLevel->iIdxCur;
  112968. }
  112969. assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 || x>=0 );
  112970. }else if( pOp->opcode==OP_Rowid ){
  112971. pOp->p1 = pLevel->iIdxCur;
  112972. pOp->opcode = OP_IdxRowid;
  112973. }
  112974. }
  112975. }
  112976. }
  112977. /* Final cleanup
  112978. */
  112979. pParse->nQueryLoop = pWInfo->savedNQueryLoop;
  112980. whereInfoFree(db, pWInfo);
  112981. return;
  112982. }
  112983. /************** End of where.c ***********************************************/
  112984. /************** Begin file parse.c *******************************************/
  112985. /* Driver template for the LEMON parser generator.
  112986. ** The author disclaims copyright to this source code.
  112987. **
  112988. ** This version of "lempar.c" is modified, slightly, for use by SQLite.
  112989. ** The only modifications are the addition of a couple of NEVER()
  112990. ** macros to disable tests that are needed in the case of a general
  112991. ** LALR(1) grammar but which are always false in the
  112992. ** specific grammar used by SQLite.
  112993. */
  112994. /* First off, code is included that follows the "include" declaration
  112995. ** in the input grammar file. */
  112996. /* #include <stdio.h> */
  112997. /*
  112998. ** Disable all error recovery processing in the parser push-down
  112999. ** automaton.
  113000. */
  113001. #define YYNOERRORRECOVERY 1
  113002. /*
  113003. ** Make yytestcase() the same as testcase()
  113004. */
  113005. #define yytestcase(X) testcase(X)
  113006. /*
  113007. ** An instance of this structure holds information about the
  113008. ** LIMIT clause of a SELECT statement.
  113009. */
  113010. struct LimitVal {
  113011. Expr *pLimit; /* The LIMIT expression. NULL if there is no limit */
  113012. Expr *pOffset; /* The OFFSET expression. NULL if there is none */
  113013. };
  113014. /*
  113015. ** An instance of this structure is used to store the LIKE,
  113016. ** GLOB, NOT LIKE, and NOT GLOB operators.
  113017. */
  113018. struct LikeOp {
  113019. Token eOperator; /* "like" or "glob" or "regexp" */
  113020. int bNot; /* True if the NOT keyword is present */
  113021. };
  113022. /*
  113023. ** An instance of the following structure describes the event of a
  113024. ** TRIGGER. "a" is the event type, one of TK_UPDATE, TK_INSERT,
  113025. ** TK_DELETE, or TK_INSTEAD. If the event is of the form
  113026. **
  113027. ** UPDATE ON (a,b,c)
  113028. **
  113029. ** Then the "b" IdList records the list "a,b,c".
  113030. */
  113031. struct TrigEvent { int a; IdList * b; };
  113032. /*
  113033. ** An instance of this structure holds the ATTACH key and the key type.
  113034. */
  113035. struct AttachKey { int type; Token key; };
  113036. /* This is a utility routine used to set the ExprSpan.zStart and
  113037. ** ExprSpan.zEnd values of pOut so that the span covers the complete
  113038. ** range of text beginning with pStart and going to the end of pEnd.
  113039. */
  113040. static void spanSet(ExprSpan *pOut, Token *pStart, Token *pEnd){
  113041. pOut->zStart = pStart->z;
  113042. pOut->zEnd = &pEnd->z[pEnd->n];
  113043. }
  113044. /* Construct a new Expr object from a single identifier. Use the
  113045. ** new Expr to populate pOut. Set the span of pOut to be the identifier
  113046. ** that created the expression.
  113047. */
  113048. static void spanExpr(ExprSpan *pOut, Parse *pParse, int op, Token *pValue){
  113049. pOut->pExpr = sqlite3PExpr(pParse, op, 0, 0, pValue);
  113050. pOut->zStart = pValue->z;
  113051. pOut->zEnd = &pValue->z[pValue->n];
  113052. }
  113053. /* This routine constructs a binary expression node out of two ExprSpan
  113054. ** objects and uses the result to populate a new ExprSpan object.
  113055. */
  113056. static void spanBinaryExpr(
  113057. ExprSpan *pOut, /* Write the result here */
  113058. Parse *pParse, /* The parsing context. Errors accumulate here */
  113059. int op, /* The binary operation */
  113060. ExprSpan *pLeft, /* The left operand */
  113061. ExprSpan *pRight /* The right operand */
  113062. ){
  113063. pOut->pExpr = sqlite3PExpr(pParse, op, pLeft->pExpr, pRight->pExpr, 0);
  113064. pOut->zStart = pLeft->zStart;
  113065. pOut->zEnd = pRight->zEnd;
  113066. }
  113067. /* Construct an expression node for a unary postfix operator
  113068. */
  113069. static void spanUnaryPostfix(
  113070. ExprSpan *pOut, /* Write the new expression node here */
  113071. Parse *pParse, /* Parsing context to record errors */
  113072. int op, /* The operator */
  113073. ExprSpan *pOperand, /* The operand */
  113074. Token *pPostOp /* The operand token for setting the span */
  113075. ){
  113076. pOut->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0, 0);
  113077. pOut->zStart = pOperand->zStart;
  113078. pOut->zEnd = &pPostOp->z[pPostOp->n];
  113079. }
  113080. /* A routine to convert a binary TK_IS or TK_ISNOT expression into a
  113081. ** unary TK_ISNULL or TK_NOTNULL expression. */
  113082. static void binaryToUnaryIfNull(Parse *pParse, Expr *pY, Expr *pA, int op){
  113083. sqlite3 *db = pParse->db;
  113084. if( pY && pA && pY->op==TK_NULL ){
  113085. pA->op = (u8)op;
  113086. sqlite3ExprDelete(db, pA->pRight);
  113087. pA->pRight = 0;
  113088. }
  113089. }
  113090. /* Construct an expression node for a unary prefix operator
  113091. */
  113092. static void spanUnaryPrefix(
  113093. ExprSpan *pOut, /* Write the new expression node here */
  113094. Parse *pParse, /* Parsing context to record errors */
  113095. int op, /* The operator */
  113096. ExprSpan *pOperand, /* The operand */
  113097. Token *pPreOp /* The operand token for setting the span */
  113098. ){
  113099. pOut->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0, 0);
  113100. pOut->zStart = pPreOp->z;
  113101. pOut->zEnd = pOperand->zEnd;
  113102. }
  113103. /* Next is all token values, in a form suitable for use by makeheaders.
  113104. ** This section will be null unless lemon is run with the -m switch.
  113105. */
  113106. /*
  113107. ** These constants (all generated automatically by the parser generator)
  113108. ** specify the various kinds of tokens (terminals) that the parser
  113109. ** understands.
  113110. **
  113111. ** Each symbol here is a terminal symbol in the grammar.
  113112. */
  113113. /* Make sure the INTERFACE macro is defined.
  113114. */
  113115. #ifndef INTERFACE
  113116. # define INTERFACE 1
  113117. #endif
  113118. /* The next thing included is series of defines which control
  113119. ** various aspects of the generated parser.
  113120. ** YYCODETYPE is the data type used for storing terminal
  113121. ** and nonterminal numbers. "unsigned char" is
  113122. ** used if there are fewer than 250 terminals
  113123. ** and nonterminals. "int" is used otherwise.
  113124. ** YYNOCODE is a number of type YYCODETYPE which corresponds
  113125. ** to no legal terminal or nonterminal number. This
  113126. ** number is used to fill in empty slots of the hash
  113127. ** table.
  113128. ** YYFALLBACK If defined, this indicates that one or more tokens
  113129. ** have fall-back values which should be used if the
  113130. ** original value of the token will not parse.
  113131. ** YYACTIONTYPE is the data type used for storing terminal
  113132. ** and nonterminal numbers. "unsigned char" is
  113133. ** used if there are fewer than 250 rules and
  113134. ** states combined. "int" is used otherwise.
  113135. ** sqlite3ParserTOKENTYPE is the data type used for minor tokens given
  113136. ** directly to the parser from the tokenizer.
  113137. ** YYMINORTYPE is the data type used for all minor tokens.
  113138. ** This is typically a union of many types, one of
  113139. ** which is sqlite3ParserTOKENTYPE. The entry in the union
  113140. ** for base tokens is called "yy0".
  113141. ** YYSTACKDEPTH is the maximum depth of the parser's stack. If
  113142. ** zero the stack is dynamically sized using realloc()
  113143. ** sqlite3ParserARG_SDECL A static variable declaration for the %extra_argument
  113144. ** sqlite3ParserARG_PDECL A parameter declaration for the %extra_argument
  113145. ** sqlite3ParserARG_STORE Code to store %extra_argument into yypParser
  113146. ** sqlite3ParserARG_FETCH Code to extract %extra_argument from yypParser
  113147. ** YYNSTATE the combined number of states.
  113148. ** YYNRULE the number of rules in the grammar
  113149. ** YYERRORSYMBOL is the code number of the error symbol. If not
  113150. ** defined, then do no error processing.
  113151. */
  113152. #define YYCODETYPE unsigned char
  113153. #define YYNOCODE 254
  113154. #define YYACTIONTYPE unsigned short int
  113155. #define YYWILDCARD 70
  113156. #define sqlite3ParserTOKENTYPE Token
  113157. typedef union {
  113158. int yyinit;
  113159. sqlite3ParserTOKENTYPE yy0;
  113160. Select* yy3;
  113161. ExprList* yy14;
  113162. With* yy59;
  113163. SrcList* yy65;
  113164. struct LikeOp yy96;
  113165. Expr* yy132;
  113166. u8 yy186;
  113167. int yy328;
  113168. ExprSpan yy346;
  113169. struct TrigEvent yy378;
  113170. u16 yy381;
  113171. IdList* yy408;
  113172. struct {int value; int mask;} yy429;
  113173. TriggerStep* yy473;
  113174. struct LimitVal yy476;
  113175. } YYMINORTYPE;
  113176. #ifndef YYSTACKDEPTH
  113177. #define YYSTACKDEPTH 100
  113178. #endif
  113179. #define sqlite3ParserARG_SDECL Parse *pParse;
  113180. #define sqlite3ParserARG_PDECL ,Parse *pParse
  113181. #define sqlite3ParserARG_FETCH Parse *pParse = yypParser->pParse
  113182. #define sqlite3ParserARG_STORE yypParser->pParse = pParse
  113183. #define YYNSTATE 642
  113184. #define YYNRULE 327
  113185. #define YYFALLBACK 1
  113186. #define YY_NO_ACTION (YYNSTATE+YYNRULE+2)
  113187. #define YY_ACCEPT_ACTION (YYNSTATE+YYNRULE+1)
  113188. #define YY_ERROR_ACTION (YYNSTATE+YYNRULE)
  113189. /* The yyzerominor constant is used to initialize instances of
  113190. ** YYMINORTYPE objects to zero. */
  113191. static const YYMINORTYPE yyzerominor = { 0 };
  113192. /* Define the yytestcase() macro to be a no-op if is not already defined
  113193. ** otherwise.
  113194. **
  113195. ** Applications can choose to define yytestcase() in the %include section
  113196. ** to a macro that can assist in verifying code coverage. For production
  113197. ** code the yytestcase() macro should be turned off. But it is useful
  113198. ** for testing.
  113199. */
  113200. #ifndef yytestcase
  113201. # define yytestcase(X)
  113202. #endif
  113203. /* Next are the tables used to determine what action to take based on the
  113204. ** current state and lookahead token. These tables are used to implement
  113205. ** functions that take a state number and lookahead value and return an
  113206. ** action integer.
  113207. **
  113208. ** Suppose the action integer is N. Then the action is determined as
  113209. ** follows
  113210. **
  113211. ** 0 <= N < YYNSTATE Shift N. That is, push the lookahead
  113212. ** token onto the stack and goto state N.
  113213. **
  113214. ** YYNSTATE <= N < YYNSTATE+YYNRULE Reduce by rule N-YYNSTATE.
  113215. **
  113216. ** N == YYNSTATE+YYNRULE A syntax error has occurred.
  113217. **
  113218. ** N == YYNSTATE+YYNRULE+1 The parser accepts its input.
  113219. **
  113220. ** N == YYNSTATE+YYNRULE+2 No such action. Denotes unused
  113221. ** slots in the yy_action[] table.
  113222. **
  113223. ** The action table is constructed as a single large table named yy_action[].
  113224. ** Given state S and lookahead X, the action is computed as
  113225. **
  113226. ** yy_action[ yy_shift_ofst[S] + X ]
  113227. **
  113228. ** If the index value yy_shift_ofst[S]+X is out of range or if the value
  113229. ** yy_lookahead[yy_shift_ofst[S]+X] is not equal to X or if yy_shift_ofst[S]
  113230. ** is equal to YY_SHIFT_USE_DFLT, it means that the action is not in the table
  113231. ** and that yy_default[S] should be used instead.
  113232. **
  113233. ** The formula above is for computing the action when the lookahead is
  113234. ** a terminal symbol. If the lookahead is a non-terminal (as occurs after
  113235. ** a reduce action) then the yy_reduce_ofst[] array is used in place of
  113236. ** the yy_shift_ofst[] array and YY_REDUCE_USE_DFLT is used in place of
  113237. ** YY_SHIFT_USE_DFLT.
  113238. **
  113239. ** The following are the tables generated in this section:
  113240. **
  113241. ** yy_action[] A single table containing all actions.
  113242. ** yy_lookahead[] A table containing the lookahead for each entry in
  113243. ** yy_action. Used to detect hash collisions.
  113244. ** yy_shift_ofst[] For each state, the offset into yy_action for
  113245. ** shifting terminals.
  113246. ** yy_reduce_ofst[] For each state, the offset into yy_action for
  113247. ** shifting non-terminals after a reduce.
  113248. ** yy_default[] Default action for each state.
  113249. */
  113250. #define YY_ACTTAB_COUNT (1497)
  113251. static const YYACTIONTYPE yy_action[] = {
  113252. /* 0 */ 306, 212, 432, 955, 639, 191, 955, 295, 559, 88,
  113253. /* 10 */ 88, 88, 88, 81, 86, 86, 86, 86, 85, 85,
  113254. /* 20 */ 84, 84, 84, 83, 330, 185, 184, 183, 635, 635,
  113255. /* 30 */ 292, 606, 606, 88, 88, 88, 88, 683, 86, 86,
  113256. /* 40 */ 86, 86, 85, 85, 84, 84, 84, 83, 330, 16,
  113257. /* 50 */ 436, 597, 89, 90, 80, 600, 599, 601, 601, 87,
  113258. /* 60 */ 87, 88, 88, 88, 88, 684, 86, 86, 86, 86,
  113259. /* 70 */ 85, 85, 84, 84, 84, 83, 330, 306, 559, 84,
  113260. /* 80 */ 84, 84, 83, 330, 65, 86, 86, 86, 86, 85,
  113261. /* 90 */ 85, 84, 84, 84, 83, 330, 635, 635, 634, 633,
  113262. /* 100 */ 182, 682, 550, 379, 376, 375, 17, 322, 606, 606,
  113263. /* 110 */ 371, 198, 479, 91, 374, 82, 79, 165, 85, 85,
  113264. /* 120 */ 84, 84, 84, 83, 330, 598, 635, 635, 107, 89,
  113265. /* 130 */ 90, 80, 600, 599, 601, 601, 87, 87, 88, 88,
  113266. /* 140 */ 88, 88, 186, 86, 86, 86, 86, 85, 85, 84,
  113267. /* 150 */ 84, 84, 83, 330, 306, 594, 594, 142, 328, 327,
  113268. /* 160 */ 484, 249, 344, 238, 635, 635, 634, 633, 585, 448,
  113269. /* 170 */ 526, 525, 229, 388, 1, 394, 450, 584, 449, 635,
  113270. /* 180 */ 635, 635, 635, 319, 395, 606, 606, 199, 157, 273,
  113271. /* 190 */ 382, 268, 381, 187, 635, 635, 634, 633, 311, 555,
  113272. /* 200 */ 266, 593, 593, 266, 347, 588, 89, 90, 80, 600,
  113273. /* 210 */ 599, 601, 601, 87, 87, 88, 88, 88, 88, 478,
  113274. /* 220 */ 86, 86, 86, 86, 85, 85, 84, 84, 84, 83,
  113275. /* 230 */ 330, 306, 272, 536, 634, 633, 146, 610, 197, 310,
  113276. /* 240 */ 575, 182, 482, 271, 379, 376, 375, 506, 21, 634,
  113277. /* 250 */ 633, 634, 633, 635, 635, 374, 611, 574, 548, 440,
  113278. /* 260 */ 111, 563, 606, 606, 634, 633, 324, 479, 608, 608,
  113279. /* 270 */ 608, 300, 435, 573, 119, 407, 210, 162, 562, 883,
  113280. /* 280 */ 592, 592, 306, 89, 90, 80, 600, 599, 601, 601,
  113281. /* 290 */ 87, 87, 88, 88, 88, 88, 506, 86, 86, 86,
  113282. /* 300 */ 86, 85, 85, 84, 84, 84, 83, 330, 620, 111,
  113283. /* 310 */ 635, 635, 361, 606, 606, 358, 249, 349, 248, 433,
  113284. /* 320 */ 243, 479, 586, 634, 633, 195, 611, 93, 119, 221,
  113285. /* 330 */ 575, 497, 534, 534, 89, 90, 80, 600, 599, 601,
  113286. /* 340 */ 601, 87, 87, 88, 88, 88, 88, 574, 86, 86,
  113287. /* 350 */ 86, 86, 85, 85, 84, 84, 84, 83, 330, 306,
  113288. /* 360 */ 77, 429, 638, 573, 589, 530, 240, 230, 242, 105,
  113289. /* 370 */ 249, 349, 248, 515, 588, 208, 460, 529, 564, 173,
  113290. /* 380 */ 634, 633, 970, 144, 430, 2, 424, 228, 380, 557,
  113291. /* 390 */ 606, 606, 190, 153, 159, 158, 514, 51, 632, 631,
  113292. /* 400 */ 630, 71, 536, 432, 954, 196, 610, 954, 614, 45,
  113293. /* 410 */ 18, 89, 90, 80, 600, 599, 601, 601, 87, 87,
  113294. /* 420 */ 88, 88, 88, 88, 261, 86, 86, 86, 86, 85,
  113295. /* 430 */ 85, 84, 84, 84, 83, 330, 306, 608, 608, 608,
  113296. /* 440 */ 542, 424, 402, 385, 241, 506, 451, 320, 211, 543,
  113297. /* 450 */ 164, 436, 386, 293, 451, 587, 108, 496, 111, 334,
  113298. /* 460 */ 391, 591, 424, 614, 27, 452, 453, 606, 606, 72,
  113299. /* 470 */ 257, 70, 259, 452, 339, 342, 564, 582, 68, 415,
  113300. /* 480 */ 469, 328, 327, 62, 614, 45, 110, 393, 89, 90,
  113301. /* 490 */ 80, 600, 599, 601, 601, 87, 87, 88, 88, 88,
  113302. /* 500 */ 88, 152, 86, 86, 86, 86, 85, 85, 84, 84,
  113303. /* 510 */ 84, 83, 330, 306, 110, 499, 520, 538, 402, 389,
  113304. /* 520 */ 424, 110, 566, 500, 593, 593, 454, 82, 79, 165,
  113305. /* 530 */ 424, 591, 384, 564, 340, 615, 188, 162, 424, 350,
  113306. /* 540 */ 616, 424, 614, 44, 606, 606, 445, 582, 300, 434,
  113307. /* 550 */ 151, 19, 614, 9, 568, 580, 348, 615, 469, 567,
  113308. /* 560 */ 614, 26, 616, 614, 45, 89, 90, 80, 600, 599,
  113309. /* 570 */ 601, 601, 87, 87, 88, 88, 88, 88, 411, 86,
  113310. /* 580 */ 86, 86, 86, 85, 85, 84, 84, 84, 83, 330,
  113311. /* 590 */ 306, 579, 110, 578, 521, 282, 433, 398, 400, 255,
  113312. /* 600 */ 486, 82, 79, 165, 487, 164, 82, 79, 165, 488,
  113313. /* 610 */ 488, 364, 387, 424, 544, 544, 509, 350, 362, 155,
  113314. /* 620 */ 191, 606, 606, 559, 642, 640, 333, 82, 79, 165,
  113315. /* 630 */ 305, 564, 507, 312, 357, 614, 45, 329, 596, 595,
  113316. /* 640 */ 194, 337, 89, 90, 80, 600, 599, 601, 601, 87,
  113317. /* 650 */ 87, 88, 88, 88, 88, 424, 86, 86, 86, 86,
  113318. /* 660 */ 85, 85, 84, 84, 84, 83, 330, 306, 20, 323,
  113319. /* 670 */ 150, 263, 211, 543, 421, 596, 595, 614, 22, 424,
  113320. /* 680 */ 193, 424, 284, 424, 391, 424, 509, 424, 577, 424,
  113321. /* 690 */ 186, 335, 424, 559, 424, 313, 120, 546, 606, 606,
  113322. /* 700 */ 67, 614, 47, 614, 50, 614, 48, 614, 100, 614,
  113323. /* 710 */ 99, 614, 101, 576, 614, 102, 614, 109, 326, 89,
  113324. /* 720 */ 90, 80, 600, 599, 601, 601, 87, 87, 88, 88,
  113325. /* 730 */ 88, 88, 424, 86, 86, 86, 86, 85, 85, 84,
  113326. /* 740 */ 84, 84, 83, 330, 306, 424, 311, 424, 585, 54,
  113327. /* 750 */ 424, 516, 517, 590, 614, 112, 424, 584, 424, 572,
  113328. /* 760 */ 424, 195, 424, 571, 424, 67, 424, 614, 94, 614,
  113329. /* 770 */ 98, 424, 614, 97, 264, 606, 606, 195, 614, 46,
  113330. /* 780 */ 614, 96, 614, 30, 614, 49, 614, 115, 614, 114,
  113331. /* 790 */ 418, 229, 388, 614, 113, 306, 89, 90, 80, 600,
  113332. /* 800 */ 599, 601, 601, 87, 87, 88, 88, 88, 88, 424,
  113333. /* 810 */ 86, 86, 86, 86, 85, 85, 84, 84, 84, 83,
  113334. /* 820 */ 330, 119, 424, 590, 110, 372, 606, 606, 195, 53,
  113335. /* 830 */ 250, 614, 29, 195, 472, 438, 729, 190, 302, 498,
  113336. /* 840 */ 14, 523, 641, 2, 614, 43, 306, 89, 90, 80,
  113337. /* 850 */ 600, 599, 601, 601, 87, 87, 88, 88, 88, 88,
  113338. /* 860 */ 424, 86, 86, 86, 86, 85, 85, 84, 84, 84,
  113339. /* 870 */ 83, 330, 424, 613, 964, 964, 354, 606, 606, 420,
  113340. /* 880 */ 312, 64, 614, 42, 391, 355, 283, 437, 301, 255,
  113341. /* 890 */ 414, 410, 495, 492, 614, 28, 471, 306, 89, 90,
  113342. /* 900 */ 80, 600, 599, 601, 601, 87, 87, 88, 88, 88,
  113343. /* 910 */ 88, 424, 86, 86, 86, 86, 85, 85, 84, 84,
  113344. /* 920 */ 84, 83, 330, 424, 110, 110, 110, 110, 606, 606,
  113345. /* 930 */ 110, 254, 13, 614, 41, 532, 531, 283, 481, 531,
  113346. /* 940 */ 457, 284, 119, 561, 356, 614, 40, 284, 306, 89,
  113347. /* 950 */ 78, 80, 600, 599, 601, 601, 87, 87, 88, 88,
  113348. /* 960 */ 88, 88, 424, 86, 86, 86, 86, 85, 85, 84,
  113349. /* 970 */ 84, 84, 83, 330, 110, 424, 341, 220, 555, 606,
  113350. /* 980 */ 606, 351, 555, 318, 614, 95, 413, 255, 83, 330,
  113351. /* 990 */ 284, 284, 255, 640, 333, 356, 255, 614, 39, 306,
  113352. /* 1000 */ 356, 90, 80, 600, 599, 601, 601, 87, 87, 88,
  113353. /* 1010 */ 88, 88, 88, 424, 86, 86, 86, 86, 85, 85,
  113354. /* 1020 */ 84, 84, 84, 83, 330, 424, 317, 316, 141, 465,
  113355. /* 1030 */ 606, 606, 219, 619, 463, 614, 10, 417, 462, 255,
  113356. /* 1040 */ 189, 510, 553, 351, 207, 363, 161, 614, 38, 315,
  113357. /* 1050 */ 218, 255, 255, 80, 600, 599, 601, 601, 87, 87,
  113358. /* 1060 */ 88, 88, 88, 88, 424, 86, 86, 86, 86, 85,
  113359. /* 1070 */ 85, 84, 84, 84, 83, 330, 76, 419, 255, 3,
  113360. /* 1080 */ 878, 461, 424, 247, 331, 331, 614, 37, 217, 76,
  113361. /* 1090 */ 419, 390, 3, 216, 215, 422, 4, 331, 331, 424,
  113362. /* 1100 */ 547, 12, 424, 545, 614, 36, 424, 541, 422, 424,
  113363. /* 1110 */ 540, 424, 214, 424, 408, 424, 539, 403, 605, 605,
  113364. /* 1120 */ 237, 614, 25, 119, 614, 24, 588, 408, 614, 45,
  113365. /* 1130 */ 118, 614, 35, 614, 34, 614, 33, 614, 23, 588,
  113366. /* 1140 */ 60, 223, 603, 602, 513, 378, 73, 74, 140, 139,
  113367. /* 1150 */ 424, 110, 265, 75, 426, 425, 59, 424, 610, 73,
  113368. /* 1160 */ 74, 549, 402, 404, 424, 373, 75, 426, 425, 604,
  113369. /* 1170 */ 138, 610, 614, 11, 392, 76, 419, 181, 3, 614,
  113370. /* 1180 */ 32, 271, 369, 331, 331, 493, 614, 31, 149, 608,
  113371. /* 1190 */ 608, 608, 607, 15, 422, 365, 614, 8, 137, 489,
  113372. /* 1200 */ 136, 190, 608, 608, 608, 607, 15, 485, 176, 135,
  113373. /* 1210 */ 7, 252, 477, 408, 174, 133, 175, 474, 57, 56,
  113374. /* 1220 */ 132, 130, 119, 76, 419, 588, 3, 468, 245, 464,
  113375. /* 1230 */ 171, 331, 331, 125, 123, 456, 447, 122, 446, 104,
  113376. /* 1240 */ 336, 231, 422, 166, 154, 73, 74, 332, 116, 431,
  113377. /* 1250 */ 121, 309, 75, 426, 425, 222, 106, 610, 308, 637,
  113378. /* 1260 */ 204, 408, 629, 627, 628, 6, 200, 428, 427, 290,
  113379. /* 1270 */ 203, 622, 201, 588, 62, 63, 289, 66, 419, 399,
  113380. /* 1280 */ 3, 401, 288, 92, 143, 331, 331, 287, 608, 608,
  113381. /* 1290 */ 608, 607, 15, 73, 74, 227, 422, 325, 69, 416,
  113382. /* 1300 */ 75, 426, 425, 612, 412, 610, 192, 61, 569, 209,
  113383. /* 1310 */ 396, 226, 278, 225, 383, 408, 527, 558, 276, 533,
  113384. /* 1320 */ 552, 528, 321, 523, 370, 508, 180, 588, 494, 179,
  113385. /* 1330 */ 366, 117, 253, 269, 522, 503, 608, 608, 608, 607,
  113386. /* 1340 */ 15, 551, 502, 58, 274, 524, 178, 73, 74, 304,
  113387. /* 1350 */ 501, 368, 303, 206, 75, 426, 425, 491, 360, 610,
  113388. /* 1360 */ 213, 177, 483, 131, 345, 298, 297, 296, 202, 294,
  113389. /* 1370 */ 480, 490, 466, 134, 172, 129, 444, 346, 470, 128,
  113390. /* 1380 */ 314, 459, 103, 127, 126, 148, 124, 167, 443, 235,
  113391. /* 1390 */ 608, 608, 608, 607, 15, 442, 439, 623, 234, 299,
  113392. /* 1400 */ 145, 583, 291, 377, 581, 160, 119, 156, 270, 636,
  113393. /* 1410 */ 971, 169, 279, 626, 520, 625, 473, 624, 170, 621,
  113394. /* 1420 */ 618, 119, 168, 55, 409, 423, 537, 609, 286, 285,
  113395. /* 1430 */ 405, 570, 560, 556, 5, 52, 458, 554, 147, 267,
  113396. /* 1440 */ 519, 504, 518, 406, 262, 239, 260, 512, 343, 511,
  113397. /* 1450 */ 258, 353, 565, 256, 224, 251, 359, 277, 275, 476,
  113398. /* 1460 */ 475, 246, 352, 244, 467, 455, 236, 233, 232, 307,
  113399. /* 1470 */ 441, 281, 205, 163, 397, 280, 535, 505, 330, 617,
  113400. /* 1480 */ 971, 971, 971, 971, 367, 971, 971, 971, 971, 971,
  113401. /* 1490 */ 971, 971, 971, 971, 971, 971, 338,
  113402. };
  113403. static const YYCODETYPE yy_lookahead[] = {
  113404. /* 0 */ 19, 22, 22, 23, 1, 24, 26, 15, 27, 80,
  113405. /* 10 */ 81, 82, 83, 84, 85, 86, 87, 88, 89, 90,
  113406. /* 20 */ 91, 92, 93, 94, 95, 108, 109, 110, 27, 28,
  113407. /* 30 */ 23, 50, 51, 80, 81, 82, 83, 122, 85, 86,
  113408. /* 40 */ 87, 88, 89, 90, 91, 92, 93, 94, 95, 22,
  113409. /* 50 */ 70, 23, 71, 72, 73, 74, 75, 76, 77, 78,
  113410. /* 60 */ 79, 80, 81, 82, 83, 122, 85, 86, 87, 88,
  113411. /* 70 */ 89, 90, 91, 92, 93, 94, 95, 19, 97, 91,
  113412. /* 80 */ 92, 93, 94, 95, 26, 85, 86, 87, 88, 89,
  113413. /* 90 */ 90, 91, 92, 93, 94, 95, 27, 28, 97, 98,
  113414. /* 100 */ 99, 122, 211, 102, 103, 104, 79, 19, 50, 51,
  113415. /* 110 */ 19, 122, 59, 55, 113, 224, 225, 226, 89, 90,
  113416. /* 120 */ 91, 92, 93, 94, 95, 23, 27, 28, 26, 71,
  113417. /* 130 */ 72, 73, 74, 75, 76, 77, 78, 79, 80, 81,
  113418. /* 140 */ 82, 83, 51, 85, 86, 87, 88, 89, 90, 91,
  113419. /* 150 */ 92, 93, 94, 95, 19, 132, 133, 58, 89, 90,
  113420. /* 160 */ 21, 108, 109, 110, 27, 28, 97, 98, 33, 100,
  113421. /* 170 */ 7, 8, 119, 120, 22, 19, 107, 42, 109, 27,
  113422. /* 180 */ 28, 27, 28, 95, 28, 50, 51, 99, 100, 101,
  113423. /* 190 */ 102, 103, 104, 105, 27, 28, 97, 98, 107, 152,
  113424. /* 200 */ 112, 132, 133, 112, 65, 69, 71, 72, 73, 74,
  113425. /* 210 */ 75, 76, 77, 78, 79, 80, 81, 82, 83, 11,
  113426. /* 220 */ 85, 86, 87, 88, 89, 90, 91, 92, 93, 94,
  113427. /* 230 */ 95, 19, 101, 97, 97, 98, 24, 101, 122, 157,
  113428. /* 240 */ 12, 99, 103, 112, 102, 103, 104, 152, 22, 97,
  113429. /* 250 */ 98, 97, 98, 27, 28, 113, 27, 29, 91, 164,
  113430. /* 260 */ 165, 124, 50, 51, 97, 98, 219, 59, 132, 133,
  113431. /* 270 */ 134, 22, 23, 45, 66, 47, 212, 213, 124, 140,
  113432. /* 280 */ 132, 133, 19, 71, 72, 73, 74, 75, 76, 77,
  113433. /* 290 */ 78, 79, 80, 81, 82, 83, 152, 85, 86, 87,
  113434. /* 300 */ 88, 89, 90, 91, 92, 93, 94, 95, 164, 165,
  113435. /* 310 */ 27, 28, 230, 50, 51, 233, 108, 109, 110, 70,
  113436. /* 320 */ 16, 59, 23, 97, 98, 26, 97, 22, 66, 185,
  113437. /* 330 */ 12, 187, 27, 28, 71, 72, 73, 74, 75, 76,
  113438. /* 340 */ 77, 78, 79, 80, 81, 82, 83, 29, 85, 86,
  113439. /* 350 */ 87, 88, 89, 90, 91, 92, 93, 94, 95, 19,
  113440. /* 360 */ 22, 148, 149, 45, 23, 47, 62, 154, 64, 156,
  113441. /* 370 */ 108, 109, 110, 37, 69, 23, 163, 59, 26, 26,
  113442. /* 380 */ 97, 98, 144, 145, 146, 147, 152, 200, 52, 23,
  113443. /* 390 */ 50, 51, 26, 22, 89, 90, 60, 210, 7, 8,
  113444. /* 400 */ 9, 138, 97, 22, 23, 26, 101, 26, 174, 175,
  113445. /* 410 */ 197, 71, 72, 73, 74, 75, 76, 77, 78, 79,
  113446. /* 420 */ 80, 81, 82, 83, 16, 85, 86, 87, 88, 89,
  113447. /* 430 */ 90, 91, 92, 93, 94, 95, 19, 132, 133, 134,
  113448. /* 440 */ 23, 152, 208, 209, 140, 152, 152, 111, 195, 196,
  113449. /* 450 */ 98, 70, 163, 160, 152, 23, 22, 164, 165, 246,
  113450. /* 460 */ 207, 27, 152, 174, 175, 171, 172, 50, 51, 137,
  113451. /* 470 */ 62, 139, 64, 171, 172, 222, 124, 27, 138, 24,
  113452. /* 480 */ 163, 89, 90, 130, 174, 175, 197, 163, 71, 72,
  113453. /* 490 */ 73, 74, 75, 76, 77, 78, 79, 80, 81, 82,
  113454. /* 500 */ 83, 22, 85, 86, 87, 88, 89, 90, 91, 92,
  113455. /* 510 */ 93, 94, 95, 19, 197, 181, 182, 23, 208, 209,
  113456. /* 520 */ 152, 197, 26, 189, 132, 133, 232, 224, 225, 226,
  113457. /* 530 */ 152, 97, 91, 26, 232, 116, 212, 213, 152, 222,
  113458. /* 540 */ 121, 152, 174, 175, 50, 51, 243, 97, 22, 23,
  113459. /* 550 */ 22, 234, 174, 175, 177, 23, 239, 116, 163, 177,
  113460. /* 560 */ 174, 175, 121, 174, 175, 71, 72, 73, 74, 75,
  113461. /* 570 */ 76, 77, 78, 79, 80, 81, 82, 83, 24, 85,
  113462. /* 580 */ 86, 87, 88, 89, 90, 91, 92, 93, 94, 95,
  113463. /* 590 */ 19, 23, 197, 11, 23, 227, 70, 208, 220, 152,
  113464. /* 600 */ 31, 224, 225, 226, 35, 98, 224, 225, 226, 108,
  113465. /* 610 */ 109, 110, 115, 152, 117, 118, 27, 222, 49, 123,
  113466. /* 620 */ 24, 50, 51, 27, 0, 1, 2, 224, 225, 226,
  113467. /* 630 */ 166, 124, 168, 169, 239, 174, 175, 170, 171, 172,
  113468. /* 640 */ 22, 194, 71, 72, 73, 74, 75, 76, 77, 78,
  113469. /* 650 */ 79, 80, 81, 82, 83, 152, 85, 86, 87, 88,
  113470. /* 660 */ 89, 90, 91, 92, 93, 94, 95, 19, 22, 208,
  113471. /* 670 */ 24, 23, 195, 196, 170, 171, 172, 174, 175, 152,
  113472. /* 680 */ 26, 152, 152, 152, 207, 152, 97, 152, 23, 152,
  113473. /* 690 */ 51, 244, 152, 97, 152, 247, 248, 23, 50, 51,
  113474. /* 700 */ 26, 174, 175, 174, 175, 174, 175, 174, 175, 174,
  113475. /* 710 */ 175, 174, 175, 23, 174, 175, 174, 175, 188, 71,
  113476. /* 720 */ 72, 73, 74, 75, 76, 77, 78, 79, 80, 81,
  113477. /* 730 */ 82, 83, 152, 85, 86, 87, 88, 89, 90, 91,
  113478. /* 740 */ 92, 93, 94, 95, 19, 152, 107, 152, 33, 24,
  113479. /* 750 */ 152, 100, 101, 27, 174, 175, 152, 42, 152, 23,
  113480. /* 760 */ 152, 26, 152, 23, 152, 26, 152, 174, 175, 174,
  113481. /* 770 */ 175, 152, 174, 175, 23, 50, 51, 26, 174, 175,
  113482. /* 780 */ 174, 175, 174, 175, 174, 175, 174, 175, 174, 175,
  113483. /* 790 */ 163, 119, 120, 174, 175, 19, 71, 72, 73, 74,
  113484. /* 800 */ 75, 76, 77, 78, 79, 80, 81, 82, 83, 152,
  113485. /* 810 */ 85, 86, 87, 88, 89, 90, 91, 92, 93, 94,
  113486. /* 820 */ 95, 66, 152, 97, 197, 23, 50, 51, 26, 53,
  113487. /* 830 */ 23, 174, 175, 26, 23, 23, 23, 26, 26, 26,
  113488. /* 840 */ 36, 106, 146, 147, 174, 175, 19, 71, 72, 73,
  113489. /* 850 */ 74, 75, 76, 77, 78, 79, 80, 81, 82, 83,
  113490. /* 860 */ 152, 85, 86, 87, 88, 89, 90, 91, 92, 93,
  113491. /* 870 */ 94, 95, 152, 196, 119, 120, 19, 50, 51, 168,
  113492. /* 880 */ 169, 26, 174, 175, 207, 28, 152, 249, 250, 152,
  113493. /* 890 */ 163, 163, 163, 163, 174, 175, 163, 19, 71, 72,
  113494. /* 900 */ 73, 74, 75, 76, 77, 78, 79, 80, 81, 82,
  113495. /* 910 */ 83, 152, 85, 86, 87, 88, 89, 90, 91, 92,
  113496. /* 920 */ 93, 94, 95, 152, 197, 197, 197, 197, 50, 51,
  113497. /* 930 */ 197, 194, 36, 174, 175, 191, 192, 152, 191, 192,
  113498. /* 940 */ 163, 152, 66, 124, 152, 174, 175, 152, 19, 71,
  113499. /* 950 */ 72, 73, 74, 75, 76, 77, 78, 79, 80, 81,
  113500. /* 960 */ 82, 83, 152, 85, 86, 87, 88, 89, 90, 91,
  113501. /* 970 */ 92, 93, 94, 95, 197, 152, 100, 188, 152, 50,
  113502. /* 980 */ 51, 152, 152, 188, 174, 175, 252, 152, 94, 95,
  113503. /* 990 */ 152, 152, 152, 1, 2, 152, 152, 174, 175, 19,
  113504. /* 1000 */ 152, 72, 73, 74, 75, 76, 77, 78, 79, 80,
  113505. /* 1010 */ 81, 82, 83, 152, 85, 86, 87, 88, 89, 90,
  113506. /* 1020 */ 91, 92, 93, 94, 95, 152, 188, 188, 22, 194,
  113507. /* 1030 */ 50, 51, 240, 173, 194, 174, 175, 252, 194, 152,
  113508. /* 1040 */ 36, 181, 28, 152, 23, 219, 122, 174, 175, 219,
  113509. /* 1050 */ 221, 152, 152, 73, 74, 75, 76, 77, 78, 79,
  113510. /* 1060 */ 80, 81, 82, 83, 152, 85, 86, 87, 88, 89,
  113511. /* 1070 */ 90, 91, 92, 93, 94, 95, 19, 20, 152, 22,
  113512. /* 1080 */ 23, 194, 152, 240, 27, 28, 174, 175, 240, 19,
  113513. /* 1090 */ 20, 26, 22, 194, 194, 38, 22, 27, 28, 152,
  113514. /* 1100 */ 23, 22, 152, 116, 174, 175, 152, 23, 38, 152,
  113515. /* 1110 */ 23, 152, 221, 152, 57, 152, 23, 163, 50, 51,
  113516. /* 1120 */ 194, 174, 175, 66, 174, 175, 69, 57, 174, 175,
  113517. /* 1130 */ 40, 174, 175, 174, 175, 174, 175, 174, 175, 69,
  113518. /* 1140 */ 22, 53, 74, 75, 30, 53, 89, 90, 22, 22,
  113519. /* 1150 */ 152, 197, 23, 96, 97, 98, 22, 152, 101, 89,
  113520. /* 1160 */ 90, 91, 208, 209, 152, 53, 96, 97, 98, 101,
  113521. /* 1170 */ 22, 101, 174, 175, 152, 19, 20, 105, 22, 174,
  113522. /* 1180 */ 175, 112, 19, 27, 28, 20, 174, 175, 24, 132,
  113523. /* 1190 */ 133, 134, 135, 136, 38, 44, 174, 175, 107, 61,
  113524. /* 1200 */ 54, 26, 132, 133, 134, 135, 136, 54, 107, 22,
  113525. /* 1210 */ 5, 140, 1, 57, 36, 111, 122, 28, 79, 79,
  113526. /* 1220 */ 131, 123, 66, 19, 20, 69, 22, 1, 16, 20,
  113527. /* 1230 */ 125, 27, 28, 123, 111, 120, 23, 131, 23, 16,
  113528. /* 1240 */ 68, 142, 38, 15, 22, 89, 90, 3, 167, 4,
  113529. /* 1250 */ 248, 251, 96, 97, 98, 180, 180, 101, 251, 151,
  113530. /* 1260 */ 6, 57, 151, 13, 151, 26, 25, 151, 161, 202,
  113531. /* 1270 */ 153, 162, 153, 69, 130, 128, 203, 19, 20, 127,
  113532. /* 1280 */ 22, 126, 204, 129, 22, 27, 28, 205, 132, 133,
  113533. /* 1290 */ 134, 135, 136, 89, 90, 231, 38, 95, 137, 179,
  113534. /* 1300 */ 96, 97, 98, 206, 179, 101, 122, 107, 159, 159,
  113535. /* 1310 */ 125, 231, 216, 228, 107, 57, 184, 217, 216, 176,
  113536. /* 1320 */ 217, 176, 48, 106, 18, 184, 158, 69, 159, 158,
  113537. /* 1330 */ 46, 71, 237, 176, 176, 176, 132, 133, 134, 135,
  113538. /* 1340 */ 136, 217, 176, 137, 216, 178, 158, 89, 90, 179,
  113539. /* 1350 */ 176, 159, 179, 159, 96, 97, 98, 159, 159, 101,
  113540. /* 1360 */ 5, 158, 202, 22, 18, 10, 11, 12, 13, 14,
  113541. /* 1370 */ 190, 238, 17, 190, 158, 193, 41, 159, 202, 193,
  113542. /* 1380 */ 159, 202, 245, 193, 193, 223, 190, 32, 159, 34,
  113543. /* 1390 */ 132, 133, 134, 135, 136, 159, 39, 155, 43, 150,
  113544. /* 1400 */ 223, 177, 201, 178, 177, 186, 66, 199, 177, 152,
  113545. /* 1410 */ 253, 56, 215, 152, 182, 152, 202, 152, 63, 152,
  113546. /* 1420 */ 152, 66, 67, 242, 229, 152, 174, 152, 152, 152,
  113547. /* 1430 */ 152, 152, 152, 152, 199, 242, 202, 152, 198, 152,
  113548. /* 1440 */ 152, 152, 183, 192, 152, 215, 152, 183, 215, 183,
  113549. /* 1450 */ 152, 241, 214, 152, 211, 152, 152, 211, 211, 152,
  113550. /* 1460 */ 152, 241, 152, 152, 152, 152, 152, 152, 152, 114,
  113551. /* 1470 */ 152, 152, 235, 152, 152, 152, 174, 187, 95, 174,
  113552. /* 1480 */ 253, 253, 253, 253, 236, 253, 253, 253, 253, 253,
  113553. /* 1490 */ 253, 253, 253, 253, 253, 253, 141,
  113554. };
  113555. #define YY_SHIFT_USE_DFLT (-86)
  113556. #define YY_SHIFT_COUNT (429)
  113557. #define YY_SHIFT_MIN (-85)
  113558. #define YY_SHIFT_MAX (1383)
  113559. static const short yy_shift_ofst[] = {
  113560. /* 0 */ 992, 1057, 1355, 1156, 1204, 1204, 1, 262, -19, 135,
  113561. /* 10 */ 135, 776, 1204, 1204, 1204, 1204, 69, 69, 53, 208,
  113562. /* 20 */ 283, 755, 58, 725, 648, 571, 494, 417, 340, 263,
  113563. /* 30 */ 212, 827, 827, 827, 827, 827, 827, 827, 827, 827,
  113564. /* 40 */ 827, 827, 827, 827, 827, 827, 878, 827, 929, 980,
  113565. /* 50 */ 980, 1070, 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204,
  113566. /* 60 */ 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204,
  113567. /* 70 */ 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204,
  113568. /* 80 */ 1258, 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204,
  113569. /* 90 */ 1204, 1204, 1204, 1204, -71, -47, -47, -47, -47, -47,
  113570. /* 100 */ 0, 29, -12, 283, 283, 139, 91, 392, 392, 894,
  113571. /* 110 */ 672, 726, 1383, -86, -86, -86, 88, 318, 318, 99,
  113572. /* 120 */ 381, -20, 283, 283, 283, 283, 283, 283, 283, 283,
  113573. /* 130 */ 283, 283, 283, 283, 283, 283, 283, 283, 283, 283,
  113574. /* 140 */ 283, 283, 283, 283, 624, 876, 726, 672, 1340, 1340,
  113575. /* 150 */ 1340, 1340, 1340, 1340, -86, -86, -86, 305, 136, 136,
  113576. /* 160 */ 142, 167, 226, 154, 137, 152, 283, 283, 283, 283,
  113577. /* 170 */ 283, 283, 283, 283, 283, 283, 283, 283, 283, 283,
  113578. /* 180 */ 283, 283, 283, 336, 336, 336, 283, 283, 352, 283,
  113579. /* 190 */ 283, 283, 283, 283, 228, 283, 283, 283, 283, 283,
  113580. /* 200 */ 283, 283, 283, 283, 283, 501, 569, 596, 596, 596,
  113581. /* 210 */ 507, 497, 441, 391, 353, 156, 156, 857, 353, 857,
  113582. /* 220 */ 735, 813, 639, 715, 156, 332, 715, 715, 496, 419,
  113583. /* 230 */ 646, 1357, 1184, 1184, 1335, 1335, 1184, 1341, 1260, 1144,
  113584. /* 240 */ 1346, 1346, 1346, 1346, 1184, 1306, 1144, 1341, 1260, 1260,
  113585. /* 250 */ 1144, 1184, 1306, 1206, 1284, 1184, 1184, 1306, 1184, 1306,
  113586. /* 260 */ 1184, 1306, 1262, 1207, 1207, 1207, 1274, 1262, 1207, 1217,
  113587. /* 270 */ 1207, 1274, 1207, 1207, 1185, 1200, 1185, 1200, 1185, 1200,
  113588. /* 280 */ 1184, 1184, 1161, 1262, 1202, 1202, 1262, 1154, 1155, 1147,
  113589. /* 290 */ 1152, 1144, 1241, 1239, 1250, 1250, 1254, 1254, 1254, 1254,
  113590. /* 300 */ -86, -86, -86, -86, -86, -86, 1068, 304, 526, 249,
  113591. /* 310 */ 408, -83, 434, 812, 27, 811, 807, 802, 751, 589,
  113592. /* 320 */ 651, 163, 131, 674, 366, 450, 299, 148, 23, 102,
  113593. /* 330 */ 229, -21, 1245, 1244, 1222, 1099, 1228, 1172, 1223, 1215,
  113594. /* 340 */ 1213, 1115, 1106, 1123, 1110, 1209, 1105, 1212, 1226, 1098,
  113595. /* 350 */ 1089, 1140, 1139, 1104, 1189, 1178, 1094, 1211, 1205, 1187,
  113596. /* 360 */ 1101, 1071, 1153, 1175, 1146, 1138, 1151, 1091, 1164, 1165,
  113597. /* 370 */ 1163, 1069, 1072, 1148, 1112, 1134, 1127, 1129, 1126, 1092,
  113598. /* 380 */ 1114, 1118, 1088, 1090, 1093, 1087, 1084, 987, 1079, 1077,
  113599. /* 390 */ 1074, 1065, 924, 1021, 1014, 1004, 1006, 819, 739, 896,
  113600. /* 400 */ 855, 804, 739, 740, 736, 690, 654, 665, 618, 582,
  113601. /* 410 */ 568, 528, 554, 379, 532, 479, 455, 379, 432, 371,
  113602. /* 420 */ 341, 28, 338, 116, -11, -57, -85, 7, -8, 3,
  113603. };
  113604. #define YY_REDUCE_USE_DFLT (-110)
  113605. #define YY_REDUCE_COUNT (305)
  113606. #define YY_REDUCE_MIN (-109)
  113607. #define YY_REDUCE_MAX (1323)
  113608. static const short yy_reduce_ofst[] = {
  113609. /* 0 */ 238, 954, 213, 289, 310, 234, 144, 317, -109, 382,
  113610. /* 10 */ 377, 303, 461, 389, 378, 368, 302, 294, 253, 395,
  113611. /* 20 */ 293, 324, 403, 403, 403, 403, 403, 403, 403, 403,
  113612. /* 30 */ 403, 403, 403, 403, 403, 403, 403, 403, 403, 403,
  113613. /* 40 */ 403, 403, 403, 403, 403, 403, 403, 403, 403, 403,
  113614. /* 50 */ 403, 1022, 1012, 1005, 998, 963, 961, 959, 957, 950,
  113615. /* 60 */ 947, 930, 912, 873, 861, 823, 810, 771, 759, 720,
  113616. /* 70 */ 708, 670, 657, 619, 614, 612, 610, 608, 606, 604,
  113617. /* 80 */ 598, 595, 593, 580, 542, 540, 537, 535, 533, 531,
  113618. /* 90 */ 529, 527, 503, 386, 403, 403, 403, 403, 403, 403,
  113619. /* 100 */ 403, 403, 403, 95, 447, 82, 334, 504, 467, 403,
  113620. /* 110 */ 477, 464, 403, 403, 403, 403, 860, 747, 744, 785,
  113621. /* 120 */ 638, 638, 926, 891, 900, 899, 887, 844, 840, 835,
  113622. /* 130 */ 848, 830, 843, 829, 792, 839, 826, 737, 838, 795,
  113623. /* 140 */ 789, 47, 734, 530, 696, 777, 711, 677, 733, 730,
  113624. /* 150 */ 729, 728, 727, 627, 448, 64, 187, 1305, 1302, 1252,
  113625. /* 160 */ 1290, 1273, 1323, 1322, 1321, 1319, 1318, 1316, 1315, 1314,
  113626. /* 170 */ 1313, 1312, 1311, 1310, 1308, 1307, 1304, 1303, 1301, 1298,
  113627. /* 180 */ 1294, 1292, 1289, 1266, 1264, 1259, 1288, 1287, 1238, 1285,
  113628. /* 190 */ 1281, 1280, 1279, 1278, 1251, 1277, 1276, 1275, 1273, 1268,
  113629. /* 200 */ 1267, 1265, 1263, 1261, 1257, 1248, 1237, 1247, 1246, 1243,
  113630. /* 210 */ 1238, 1240, 1235, 1249, 1234, 1233, 1230, 1220, 1214, 1210,
  113631. /* 220 */ 1225, 1219, 1232, 1231, 1197, 1195, 1227, 1224, 1201, 1208,
  113632. /* 230 */ 1242, 1137, 1236, 1229, 1193, 1181, 1221, 1177, 1196, 1179,
  113633. /* 240 */ 1191, 1190, 1186, 1182, 1218, 1216, 1176, 1162, 1183, 1180,
  113634. /* 250 */ 1160, 1199, 1203, 1133, 1095, 1198, 1194, 1188, 1192, 1171,
  113635. /* 260 */ 1169, 1168, 1173, 1174, 1166, 1159, 1141, 1170, 1158, 1167,
  113636. /* 270 */ 1157, 1132, 1145, 1143, 1124, 1128, 1103, 1102, 1100, 1096,
  113637. /* 280 */ 1150, 1149, 1085, 1125, 1080, 1064, 1120, 1097, 1082, 1078,
  113638. /* 290 */ 1073, 1067, 1109, 1107, 1119, 1117, 1116, 1113, 1111, 1108,
  113639. /* 300 */ 1007, 1000, 1002, 1076, 1075, 1081,
  113640. };
  113641. static const YYACTIONTYPE yy_default[] = {
  113642. /* 0 */ 647, 964, 964, 964, 878, 878, 969, 964, 774, 802,
  113643. /* 10 */ 802, 938, 969, 969, 969, 876, 969, 969, 969, 964,
  113644. /* 20 */ 969, 778, 808, 969, 969, 969, 969, 969, 969, 969,
  113645. /* 30 */ 969, 937, 939, 816, 815, 918, 789, 813, 806, 810,
  113646. /* 40 */ 879, 872, 873, 871, 875, 880, 969, 809, 841, 856,
  113647. /* 50 */ 840, 969, 969, 969, 969, 969, 969, 969, 969, 969,
  113648. /* 60 */ 969, 969, 969, 969, 969, 969, 969, 969, 969, 969,
  113649. /* 70 */ 969, 969, 969, 969, 969, 969, 969, 969, 969, 969,
  113650. /* 80 */ 969, 969, 969, 969, 969, 969, 969, 969, 969, 969,
  113651. /* 90 */ 969, 969, 969, 969, 850, 855, 862, 854, 851, 843,
  113652. /* 100 */ 842, 844, 845, 969, 969, 673, 739, 969, 969, 846,
  113653. /* 110 */ 969, 685, 847, 859, 858, 857, 680, 969, 969, 969,
  113654. /* 120 */ 969, 969, 969, 969, 969, 969, 969, 969, 969, 969,
  113655. /* 130 */ 969, 969, 969, 969, 969, 969, 969, 969, 969, 969,
  113656. /* 140 */ 969, 969, 969, 969, 647, 964, 969, 969, 964, 964,
  113657. /* 150 */ 964, 964, 964, 964, 956, 778, 768, 969, 969, 969,
  113658. /* 160 */ 969, 969, 969, 969, 969, 969, 969, 944, 942, 969,
  113659. /* 170 */ 891, 969, 969, 969, 969, 969, 969, 969, 969, 969,
  113660. /* 180 */ 969, 969, 969, 969, 969, 969, 969, 969, 969, 969,
  113661. /* 190 */ 969, 969, 969, 969, 969, 969, 969, 969, 969, 969,
  113662. /* 200 */ 969, 969, 969, 969, 653, 969, 911, 774, 774, 774,
  113663. /* 210 */ 776, 754, 766, 655, 812, 791, 791, 923, 812, 923,
  113664. /* 220 */ 710, 733, 707, 802, 791, 874, 802, 802, 775, 766,
  113665. /* 230 */ 969, 949, 782, 782, 941, 941, 782, 821, 743, 812,
  113666. /* 240 */ 750, 750, 750, 750, 782, 670, 812, 821, 743, 743,
  113667. /* 250 */ 812, 782, 670, 917, 915, 782, 782, 670, 782, 670,
  113668. /* 260 */ 782, 670, 884, 741, 741, 741, 725, 884, 741, 710,
  113669. /* 270 */ 741, 725, 741, 741, 795, 790, 795, 790, 795, 790,
  113670. /* 280 */ 782, 782, 969, 884, 888, 888, 884, 807, 796, 805,
  113671. /* 290 */ 803, 812, 676, 728, 663, 663, 652, 652, 652, 652,
  113672. /* 300 */ 961, 961, 956, 712, 712, 695, 969, 969, 969, 969,
  113673. /* 310 */ 969, 969, 687, 969, 893, 969, 969, 969, 969, 969,
  113674. /* 320 */ 969, 969, 969, 969, 969, 969, 969, 969, 969, 969,
  113675. /* 330 */ 969, 828, 969, 648, 951, 969, 969, 948, 969, 969,
  113676. /* 340 */ 969, 969, 969, 969, 969, 969, 969, 969, 969, 969,
  113677. /* 350 */ 969, 969, 969, 969, 969, 969, 921, 969, 969, 969,
  113678. /* 360 */ 969, 969, 969, 914, 913, 969, 969, 969, 969, 969,
  113679. /* 370 */ 969, 969, 969, 969, 969, 969, 969, 969, 969, 969,
  113680. /* 380 */ 969, 969, 969, 969, 969, 969, 969, 757, 969, 969,
  113681. /* 390 */ 969, 761, 969, 969, 969, 969, 969, 969, 804, 969,
  113682. /* 400 */ 797, 969, 877, 969, 969, 969, 969, 969, 969, 969,
  113683. /* 410 */ 969, 969, 969, 966, 969, 969, 969, 965, 969, 969,
  113684. /* 420 */ 969, 969, 969, 830, 969, 829, 833, 969, 661, 969,
  113685. /* 430 */ 644, 649, 960, 963, 962, 959, 958, 957, 952, 950,
  113686. /* 440 */ 947, 946, 945, 943, 940, 936, 897, 895, 902, 901,
  113687. /* 450 */ 900, 899, 898, 896, 894, 892, 818, 817, 814, 811,
  113688. /* 460 */ 753, 935, 890, 752, 749, 748, 669, 953, 920, 929,
  113689. /* 470 */ 928, 927, 822, 926, 925, 924, 922, 919, 906, 820,
  113690. /* 480 */ 819, 744, 882, 881, 672, 910, 909, 908, 912, 916,
  113691. /* 490 */ 907, 784, 751, 671, 668, 675, 679, 731, 732, 740,
  113692. /* 500 */ 738, 737, 736, 735, 734, 730, 681, 686, 724, 709,
  113693. /* 510 */ 708, 717, 716, 722, 721, 720, 719, 718, 715, 714,
  113694. /* 520 */ 713, 706, 705, 711, 704, 727, 726, 723, 703, 747,
  113695. /* 530 */ 746, 745, 742, 702, 701, 700, 833, 699, 698, 838,
  113696. /* 540 */ 837, 866, 826, 755, 759, 758, 762, 763, 771, 770,
  113697. /* 550 */ 769, 780, 781, 793, 792, 824, 823, 794, 779, 773,
  113698. /* 560 */ 772, 788, 787, 786, 785, 777, 767, 799, 798, 868,
  113699. /* 570 */ 783, 867, 865, 934, 933, 932, 931, 930, 870, 967,
  113700. /* 580 */ 968, 887, 889, 886, 801, 800, 885, 869, 839, 836,
  113701. /* 590 */ 690, 691, 905, 904, 903, 693, 692, 689, 688, 863,
  113702. /* 600 */ 860, 852, 864, 861, 853, 849, 848, 834, 832, 831,
  113703. /* 610 */ 827, 835, 760, 756, 825, 765, 764, 697, 696, 694,
  113704. /* 620 */ 678, 677, 674, 667, 665, 664, 666, 662, 660, 659,
  113705. /* 630 */ 658, 657, 656, 684, 683, 682, 654, 651, 650, 646,
  113706. /* 640 */ 645, 643,
  113707. };
  113708. /* The next table maps tokens into fallback tokens. If a construct
  113709. ** like the following:
  113710. **
  113711. ** %fallback ID X Y Z.
  113712. **
  113713. ** appears in the grammar, then ID becomes a fallback token for X, Y,
  113714. ** and Z. Whenever one of the tokens X, Y, or Z is input to the parser
  113715. ** but it does not parse, the type of the token is changed to ID and
  113716. ** the parse is retried before an error is thrown.
  113717. */
  113718. #ifdef YYFALLBACK
  113719. static const YYCODETYPE yyFallback[] = {
  113720. 0, /* $ => nothing */
  113721. 0, /* SEMI => nothing */
  113722. 27, /* EXPLAIN => ID */
  113723. 27, /* QUERY => ID */
  113724. 27, /* PLAN => ID */
  113725. 27, /* BEGIN => ID */
  113726. 0, /* TRANSACTION => nothing */
  113727. 27, /* DEFERRED => ID */
  113728. 27, /* IMMEDIATE => ID */
  113729. 27, /* EXCLUSIVE => ID */
  113730. 0, /* COMMIT => nothing */
  113731. 27, /* END => ID */
  113732. 27, /* ROLLBACK => ID */
  113733. 27, /* SAVEPOINT => ID */
  113734. 27, /* RELEASE => ID */
  113735. 0, /* TO => nothing */
  113736. 0, /* TABLE => nothing */
  113737. 0, /* CREATE => nothing */
  113738. 27, /* IF => ID */
  113739. 0, /* NOT => nothing */
  113740. 0, /* EXISTS => nothing */
  113741. 27, /* TEMP => ID */
  113742. 0, /* LP => nothing */
  113743. 0, /* RP => nothing */
  113744. 0, /* AS => nothing */
  113745. 27, /* WITHOUT => ID */
  113746. 0, /* COMMA => nothing */
  113747. 0, /* ID => nothing */
  113748. 0, /* INDEXED => nothing */
  113749. 27, /* ABORT => ID */
  113750. 27, /* ACTION => ID */
  113751. 27, /* AFTER => ID */
  113752. 27, /* ANALYZE => ID */
  113753. 27, /* ASC => ID */
  113754. 27, /* ATTACH => ID */
  113755. 27, /* BEFORE => ID */
  113756. 27, /* BY => ID */
  113757. 27, /* CASCADE => ID */
  113758. 27, /* CAST => ID */
  113759. 27, /* COLUMNKW => ID */
  113760. 27, /* CONFLICT => ID */
  113761. 27, /* DATABASE => ID */
  113762. 27, /* DESC => ID */
  113763. 27, /* DETACH => ID */
  113764. 27, /* EACH => ID */
  113765. 27, /* FAIL => ID */
  113766. 27, /* FOR => ID */
  113767. 27, /* IGNORE => ID */
  113768. 27, /* INITIALLY => ID */
  113769. 27, /* INSTEAD => ID */
  113770. 27, /* LIKE_KW => ID */
  113771. 27, /* MATCH => ID */
  113772. 27, /* NO => ID */
  113773. 27, /* KEY => ID */
  113774. 27, /* OF => ID */
  113775. 27, /* OFFSET => ID */
  113776. 27, /* PRAGMA => ID */
  113777. 27, /* RAISE => ID */
  113778. 27, /* RECURSIVE => ID */
  113779. 27, /* REPLACE => ID */
  113780. 27, /* RESTRICT => ID */
  113781. 27, /* ROW => ID */
  113782. 27, /* TRIGGER => ID */
  113783. 27, /* VACUUM => ID */
  113784. 27, /* VIEW => ID */
  113785. 27, /* VIRTUAL => ID */
  113786. 27, /* WITH => ID */
  113787. 27, /* REINDEX => ID */
  113788. 27, /* RENAME => ID */
  113789. 27, /* CTIME_KW => ID */
  113790. };
  113791. #endif /* YYFALLBACK */
  113792. /* The following structure represents a single element of the
  113793. ** parser's stack. Information stored includes:
  113794. **
  113795. ** + The state number for the parser at this level of the stack.
  113796. **
  113797. ** + The value of the token stored at this level of the stack.
  113798. ** (In other words, the "major" token.)
  113799. **
  113800. ** + The semantic value stored at this level of the stack. This is
  113801. ** the information used by the action routines in the grammar.
  113802. ** It is sometimes called the "minor" token.
  113803. */
  113804. struct yyStackEntry {
  113805. YYACTIONTYPE stateno; /* The state-number */
  113806. YYCODETYPE major; /* The major token value. This is the code
  113807. ** number for the token at this stack level */
  113808. YYMINORTYPE minor; /* The user-supplied minor token value. This
  113809. ** is the value of the token */
  113810. };
  113811. typedef struct yyStackEntry yyStackEntry;
  113812. /* The state of the parser is completely contained in an instance of
  113813. ** the following structure */
  113814. struct yyParser {
  113815. int yyidx; /* Index of top element in stack */
  113816. #ifdef YYTRACKMAXSTACKDEPTH
  113817. int yyidxMax; /* Maximum value of yyidx */
  113818. #endif
  113819. int yyerrcnt; /* Shifts left before out of the error */
  113820. sqlite3ParserARG_SDECL /* A place to hold %extra_argument */
  113821. #if YYSTACKDEPTH<=0
  113822. int yystksz; /* Current side of the stack */
  113823. yyStackEntry *yystack; /* The parser's stack */
  113824. #else
  113825. yyStackEntry yystack[YYSTACKDEPTH]; /* The parser's stack */
  113826. #endif
  113827. };
  113828. typedef struct yyParser yyParser;
  113829. #ifndef NDEBUG
  113830. /* #include <stdio.h> */
  113831. static FILE *yyTraceFILE = 0;
  113832. static char *yyTracePrompt = 0;
  113833. #endif /* NDEBUG */
  113834. #ifndef NDEBUG
  113835. /*
  113836. ** Turn parser tracing on by giving a stream to which to write the trace
  113837. ** and a prompt to preface each trace message. Tracing is turned off
  113838. ** by making either argument NULL
  113839. **
  113840. ** Inputs:
  113841. ** <ul>
  113842. ** <li> A FILE* to which trace output should be written.
  113843. ** If NULL, then tracing is turned off.
  113844. ** <li> A prefix string written at the beginning of every
  113845. ** line of trace output. If NULL, then tracing is
  113846. ** turned off.
  113847. ** </ul>
  113848. **
  113849. ** Outputs:
  113850. ** None.
  113851. */
  113852. SQLITE_PRIVATE void sqlite3ParserTrace(FILE *TraceFILE, char *zTracePrompt){
  113853. yyTraceFILE = TraceFILE;
  113854. yyTracePrompt = zTracePrompt;
  113855. if( yyTraceFILE==0 ) yyTracePrompt = 0;
  113856. else if( yyTracePrompt==0 ) yyTraceFILE = 0;
  113857. }
  113858. #endif /* NDEBUG */
  113859. #ifndef NDEBUG
  113860. /* For tracing shifts, the names of all terminals and nonterminals
  113861. ** are required. The following table supplies these names */
  113862. static const char *const yyTokenName[] = {
  113863. "$", "SEMI", "EXPLAIN", "QUERY",
  113864. "PLAN", "BEGIN", "TRANSACTION", "DEFERRED",
  113865. "IMMEDIATE", "EXCLUSIVE", "COMMIT", "END",
  113866. "ROLLBACK", "SAVEPOINT", "RELEASE", "TO",
  113867. "TABLE", "CREATE", "IF", "NOT",
  113868. "EXISTS", "TEMP", "LP", "RP",
  113869. "AS", "WITHOUT", "COMMA", "ID",
  113870. "INDEXED", "ABORT", "ACTION", "AFTER",
  113871. "ANALYZE", "ASC", "ATTACH", "BEFORE",
  113872. "BY", "CASCADE", "CAST", "COLUMNKW",
  113873. "CONFLICT", "DATABASE", "DESC", "DETACH",
  113874. "EACH", "FAIL", "FOR", "IGNORE",
  113875. "INITIALLY", "INSTEAD", "LIKE_KW", "MATCH",
  113876. "NO", "KEY", "OF", "OFFSET",
  113877. "PRAGMA", "RAISE", "RECURSIVE", "REPLACE",
  113878. "RESTRICT", "ROW", "TRIGGER", "VACUUM",
  113879. "VIEW", "VIRTUAL", "WITH", "REINDEX",
  113880. "RENAME", "CTIME_KW", "ANY", "OR",
  113881. "AND", "IS", "BETWEEN", "IN",
  113882. "ISNULL", "NOTNULL", "NE", "EQ",
  113883. "GT", "LE", "LT", "GE",
  113884. "ESCAPE", "BITAND", "BITOR", "LSHIFT",
  113885. "RSHIFT", "PLUS", "MINUS", "STAR",
  113886. "SLASH", "REM", "CONCAT", "COLLATE",
  113887. "BITNOT", "STRING", "JOIN_KW", "CONSTRAINT",
  113888. "DEFAULT", "NULL", "PRIMARY", "UNIQUE",
  113889. "CHECK", "REFERENCES", "AUTOINCR", "ON",
  113890. "INSERT", "DELETE", "UPDATE", "SET",
  113891. "DEFERRABLE", "FOREIGN", "DROP", "UNION",
  113892. "ALL", "EXCEPT", "INTERSECT", "SELECT",
  113893. "VALUES", "DISTINCT", "DOT", "FROM",
  113894. "JOIN", "USING", "ORDER", "GROUP",
  113895. "HAVING", "LIMIT", "WHERE", "INTO",
  113896. "INTEGER", "FLOAT", "BLOB", "VARIABLE",
  113897. "CASE", "WHEN", "THEN", "ELSE",
  113898. "INDEX", "ALTER", "ADD", "error",
  113899. "input", "cmdlist", "ecmd", "explain",
  113900. "cmdx", "cmd", "transtype", "trans_opt",
  113901. "nm", "savepoint_opt", "create_table", "create_table_args",
  113902. "createkw", "temp", "ifnotexists", "dbnm",
  113903. "columnlist", "conslist_opt", "table_options", "select",
  113904. "column", "columnid", "type", "carglist",
  113905. "typetoken", "typename", "signed", "plus_num",
  113906. "minus_num", "ccons", "term", "expr",
  113907. "onconf", "sortorder", "autoinc", "idxlist_opt",
  113908. "refargs", "defer_subclause", "refarg", "refact",
  113909. "init_deferred_pred_opt", "conslist", "tconscomma", "tcons",
  113910. "idxlist", "defer_subclause_opt", "orconf", "resolvetype",
  113911. "raisetype", "ifexists", "fullname", "selectnowith",
  113912. "oneselect", "with", "multiselect_op", "distinct",
  113913. "selcollist", "from", "where_opt", "groupby_opt",
  113914. "having_opt", "orderby_opt", "limit_opt", "values",
  113915. "nexprlist", "exprlist", "sclp", "as",
  113916. "seltablist", "stl_prefix", "joinop", "indexed_opt",
  113917. "on_opt", "using_opt", "joinop2", "idlist",
  113918. "sortlist", "setlist", "insert_cmd", "inscollist_opt",
  113919. "likeop", "between_op", "in_op", "case_operand",
  113920. "case_exprlist", "case_else", "uniqueflag", "collate",
  113921. "nmnum", "trigger_decl", "trigger_cmd_list", "trigger_time",
  113922. "trigger_event", "foreach_clause", "when_clause", "trigger_cmd",
  113923. "trnm", "tridxby", "database_kw_opt", "key_opt",
  113924. "add_column_fullname", "kwcolumn_opt", "create_vtab", "vtabarglist",
  113925. "vtabarg", "vtabargtoken", "lp", "anylist",
  113926. "wqlist",
  113927. };
  113928. #endif /* NDEBUG */
  113929. #ifndef NDEBUG
  113930. /* For tracing reduce actions, the names of all rules are required.
  113931. */
  113932. static const char *const yyRuleName[] = {
  113933. /* 0 */ "input ::= cmdlist",
  113934. /* 1 */ "cmdlist ::= cmdlist ecmd",
  113935. /* 2 */ "cmdlist ::= ecmd",
  113936. /* 3 */ "ecmd ::= SEMI",
  113937. /* 4 */ "ecmd ::= explain cmdx SEMI",
  113938. /* 5 */ "explain ::=",
  113939. /* 6 */ "explain ::= EXPLAIN",
  113940. /* 7 */ "explain ::= EXPLAIN QUERY PLAN",
  113941. /* 8 */ "cmdx ::= cmd",
  113942. /* 9 */ "cmd ::= BEGIN transtype trans_opt",
  113943. /* 10 */ "trans_opt ::=",
  113944. /* 11 */ "trans_opt ::= TRANSACTION",
  113945. /* 12 */ "trans_opt ::= TRANSACTION nm",
  113946. /* 13 */ "transtype ::=",
  113947. /* 14 */ "transtype ::= DEFERRED",
  113948. /* 15 */ "transtype ::= IMMEDIATE",
  113949. /* 16 */ "transtype ::= EXCLUSIVE",
  113950. /* 17 */ "cmd ::= COMMIT trans_opt",
  113951. /* 18 */ "cmd ::= END trans_opt",
  113952. /* 19 */ "cmd ::= ROLLBACK trans_opt",
  113953. /* 20 */ "savepoint_opt ::= SAVEPOINT",
  113954. /* 21 */ "savepoint_opt ::=",
  113955. /* 22 */ "cmd ::= SAVEPOINT nm",
  113956. /* 23 */ "cmd ::= RELEASE savepoint_opt nm",
  113957. /* 24 */ "cmd ::= ROLLBACK trans_opt TO savepoint_opt nm",
  113958. /* 25 */ "cmd ::= create_table create_table_args",
  113959. /* 26 */ "create_table ::= createkw temp TABLE ifnotexists nm dbnm",
  113960. /* 27 */ "createkw ::= CREATE",
  113961. /* 28 */ "ifnotexists ::=",
  113962. /* 29 */ "ifnotexists ::= IF NOT EXISTS",
  113963. /* 30 */ "temp ::= TEMP",
  113964. /* 31 */ "temp ::=",
  113965. /* 32 */ "create_table_args ::= LP columnlist conslist_opt RP table_options",
  113966. /* 33 */ "create_table_args ::= AS select",
  113967. /* 34 */ "table_options ::=",
  113968. /* 35 */ "table_options ::= WITHOUT nm",
  113969. /* 36 */ "columnlist ::= columnlist COMMA column",
  113970. /* 37 */ "columnlist ::= column",
  113971. /* 38 */ "column ::= columnid type carglist",
  113972. /* 39 */ "columnid ::= nm",
  113973. /* 40 */ "nm ::= ID|INDEXED",
  113974. /* 41 */ "nm ::= STRING",
  113975. /* 42 */ "nm ::= JOIN_KW",
  113976. /* 43 */ "type ::=",
  113977. /* 44 */ "type ::= typetoken",
  113978. /* 45 */ "typetoken ::= typename",
  113979. /* 46 */ "typetoken ::= typename LP signed RP",
  113980. /* 47 */ "typetoken ::= typename LP signed COMMA signed RP",
  113981. /* 48 */ "typename ::= ID|STRING",
  113982. /* 49 */ "typename ::= typename ID|STRING",
  113983. /* 50 */ "signed ::= plus_num",
  113984. /* 51 */ "signed ::= minus_num",
  113985. /* 52 */ "carglist ::= carglist ccons",
  113986. /* 53 */ "carglist ::=",
  113987. /* 54 */ "ccons ::= CONSTRAINT nm",
  113988. /* 55 */ "ccons ::= DEFAULT term",
  113989. /* 56 */ "ccons ::= DEFAULT LP expr RP",
  113990. /* 57 */ "ccons ::= DEFAULT PLUS term",
  113991. /* 58 */ "ccons ::= DEFAULT MINUS term",
  113992. /* 59 */ "ccons ::= DEFAULT ID|INDEXED",
  113993. /* 60 */ "ccons ::= NULL onconf",
  113994. /* 61 */ "ccons ::= NOT NULL onconf",
  113995. /* 62 */ "ccons ::= PRIMARY KEY sortorder onconf autoinc",
  113996. /* 63 */ "ccons ::= UNIQUE onconf",
  113997. /* 64 */ "ccons ::= CHECK LP expr RP",
  113998. /* 65 */ "ccons ::= REFERENCES nm idxlist_opt refargs",
  113999. /* 66 */ "ccons ::= defer_subclause",
  114000. /* 67 */ "ccons ::= COLLATE ID|STRING",
  114001. /* 68 */ "autoinc ::=",
  114002. /* 69 */ "autoinc ::= AUTOINCR",
  114003. /* 70 */ "refargs ::=",
  114004. /* 71 */ "refargs ::= refargs refarg",
  114005. /* 72 */ "refarg ::= MATCH nm",
  114006. /* 73 */ "refarg ::= ON INSERT refact",
  114007. /* 74 */ "refarg ::= ON DELETE refact",
  114008. /* 75 */ "refarg ::= ON UPDATE refact",
  114009. /* 76 */ "refact ::= SET NULL",
  114010. /* 77 */ "refact ::= SET DEFAULT",
  114011. /* 78 */ "refact ::= CASCADE",
  114012. /* 79 */ "refact ::= RESTRICT",
  114013. /* 80 */ "refact ::= NO ACTION",
  114014. /* 81 */ "defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt",
  114015. /* 82 */ "defer_subclause ::= DEFERRABLE init_deferred_pred_opt",
  114016. /* 83 */ "init_deferred_pred_opt ::=",
  114017. /* 84 */ "init_deferred_pred_opt ::= INITIALLY DEFERRED",
  114018. /* 85 */ "init_deferred_pred_opt ::= INITIALLY IMMEDIATE",
  114019. /* 86 */ "conslist_opt ::=",
  114020. /* 87 */ "conslist_opt ::= COMMA conslist",
  114021. /* 88 */ "conslist ::= conslist tconscomma tcons",
  114022. /* 89 */ "conslist ::= tcons",
  114023. /* 90 */ "tconscomma ::= COMMA",
  114024. /* 91 */ "tconscomma ::=",
  114025. /* 92 */ "tcons ::= CONSTRAINT nm",
  114026. /* 93 */ "tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf",
  114027. /* 94 */ "tcons ::= UNIQUE LP idxlist RP onconf",
  114028. /* 95 */ "tcons ::= CHECK LP expr RP onconf",
  114029. /* 96 */ "tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt",
  114030. /* 97 */ "defer_subclause_opt ::=",
  114031. /* 98 */ "defer_subclause_opt ::= defer_subclause",
  114032. /* 99 */ "onconf ::=",
  114033. /* 100 */ "onconf ::= ON CONFLICT resolvetype",
  114034. /* 101 */ "orconf ::=",
  114035. /* 102 */ "orconf ::= OR resolvetype",
  114036. /* 103 */ "resolvetype ::= raisetype",
  114037. /* 104 */ "resolvetype ::= IGNORE",
  114038. /* 105 */ "resolvetype ::= REPLACE",
  114039. /* 106 */ "cmd ::= DROP TABLE ifexists fullname",
  114040. /* 107 */ "ifexists ::= IF EXISTS",
  114041. /* 108 */ "ifexists ::=",
  114042. /* 109 */ "cmd ::= createkw temp VIEW ifnotexists nm dbnm AS select",
  114043. /* 110 */ "cmd ::= DROP VIEW ifexists fullname",
  114044. /* 111 */ "cmd ::= select",
  114045. /* 112 */ "select ::= with selectnowith",
  114046. /* 113 */ "selectnowith ::= oneselect",
  114047. /* 114 */ "selectnowith ::= selectnowith multiselect_op oneselect",
  114048. /* 115 */ "multiselect_op ::= UNION",
  114049. /* 116 */ "multiselect_op ::= UNION ALL",
  114050. /* 117 */ "multiselect_op ::= EXCEPT|INTERSECT",
  114051. /* 118 */ "oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt",
  114052. /* 119 */ "oneselect ::= values",
  114053. /* 120 */ "values ::= VALUES LP nexprlist RP",
  114054. /* 121 */ "values ::= values COMMA LP exprlist RP",
  114055. /* 122 */ "distinct ::= DISTINCT",
  114056. /* 123 */ "distinct ::= ALL",
  114057. /* 124 */ "distinct ::=",
  114058. /* 125 */ "sclp ::= selcollist COMMA",
  114059. /* 126 */ "sclp ::=",
  114060. /* 127 */ "selcollist ::= sclp expr as",
  114061. /* 128 */ "selcollist ::= sclp STAR",
  114062. /* 129 */ "selcollist ::= sclp nm DOT STAR",
  114063. /* 130 */ "as ::= AS nm",
  114064. /* 131 */ "as ::= ID|STRING",
  114065. /* 132 */ "as ::=",
  114066. /* 133 */ "from ::=",
  114067. /* 134 */ "from ::= FROM seltablist",
  114068. /* 135 */ "stl_prefix ::= seltablist joinop",
  114069. /* 136 */ "stl_prefix ::=",
  114070. /* 137 */ "seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt",
  114071. /* 138 */ "seltablist ::= stl_prefix LP select RP as on_opt using_opt",
  114072. /* 139 */ "seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt",
  114073. /* 140 */ "dbnm ::=",
  114074. /* 141 */ "dbnm ::= DOT nm",
  114075. /* 142 */ "fullname ::= nm dbnm",
  114076. /* 143 */ "joinop ::= COMMA|JOIN",
  114077. /* 144 */ "joinop ::= JOIN_KW JOIN",
  114078. /* 145 */ "joinop ::= JOIN_KW nm JOIN",
  114079. /* 146 */ "joinop ::= JOIN_KW nm nm JOIN",
  114080. /* 147 */ "on_opt ::= ON expr",
  114081. /* 148 */ "on_opt ::=",
  114082. /* 149 */ "indexed_opt ::=",
  114083. /* 150 */ "indexed_opt ::= INDEXED BY nm",
  114084. /* 151 */ "indexed_opt ::= NOT INDEXED",
  114085. /* 152 */ "using_opt ::= USING LP idlist RP",
  114086. /* 153 */ "using_opt ::=",
  114087. /* 154 */ "orderby_opt ::=",
  114088. /* 155 */ "orderby_opt ::= ORDER BY sortlist",
  114089. /* 156 */ "sortlist ::= sortlist COMMA expr sortorder",
  114090. /* 157 */ "sortlist ::= expr sortorder",
  114091. /* 158 */ "sortorder ::= ASC",
  114092. /* 159 */ "sortorder ::= DESC",
  114093. /* 160 */ "sortorder ::=",
  114094. /* 161 */ "groupby_opt ::=",
  114095. /* 162 */ "groupby_opt ::= GROUP BY nexprlist",
  114096. /* 163 */ "having_opt ::=",
  114097. /* 164 */ "having_opt ::= HAVING expr",
  114098. /* 165 */ "limit_opt ::=",
  114099. /* 166 */ "limit_opt ::= LIMIT expr",
  114100. /* 167 */ "limit_opt ::= LIMIT expr OFFSET expr",
  114101. /* 168 */ "limit_opt ::= LIMIT expr COMMA expr",
  114102. /* 169 */ "cmd ::= with DELETE FROM fullname indexed_opt where_opt",
  114103. /* 170 */ "where_opt ::=",
  114104. /* 171 */ "where_opt ::= WHERE expr",
  114105. /* 172 */ "cmd ::= with UPDATE orconf fullname indexed_opt SET setlist where_opt",
  114106. /* 173 */ "setlist ::= setlist COMMA nm EQ expr",
  114107. /* 174 */ "setlist ::= nm EQ expr",
  114108. /* 175 */ "cmd ::= with insert_cmd INTO fullname inscollist_opt select",
  114109. /* 176 */ "cmd ::= with insert_cmd INTO fullname inscollist_opt DEFAULT VALUES",
  114110. /* 177 */ "insert_cmd ::= INSERT orconf",
  114111. /* 178 */ "insert_cmd ::= REPLACE",
  114112. /* 179 */ "inscollist_opt ::=",
  114113. /* 180 */ "inscollist_opt ::= LP idlist RP",
  114114. /* 181 */ "idlist ::= idlist COMMA nm",
  114115. /* 182 */ "idlist ::= nm",
  114116. /* 183 */ "expr ::= term",
  114117. /* 184 */ "expr ::= LP expr RP",
  114118. /* 185 */ "term ::= NULL",
  114119. /* 186 */ "expr ::= ID|INDEXED",
  114120. /* 187 */ "expr ::= JOIN_KW",
  114121. /* 188 */ "expr ::= nm DOT nm",
  114122. /* 189 */ "expr ::= nm DOT nm DOT nm",
  114123. /* 190 */ "term ::= INTEGER|FLOAT|BLOB",
  114124. /* 191 */ "term ::= STRING",
  114125. /* 192 */ "expr ::= VARIABLE",
  114126. /* 193 */ "expr ::= expr COLLATE ID|STRING",
  114127. /* 194 */ "expr ::= CAST LP expr AS typetoken RP",
  114128. /* 195 */ "expr ::= ID|INDEXED LP distinct exprlist RP",
  114129. /* 196 */ "expr ::= ID|INDEXED LP STAR RP",
  114130. /* 197 */ "term ::= CTIME_KW",
  114131. /* 198 */ "expr ::= expr AND expr",
  114132. /* 199 */ "expr ::= expr OR expr",
  114133. /* 200 */ "expr ::= expr LT|GT|GE|LE expr",
  114134. /* 201 */ "expr ::= expr EQ|NE expr",
  114135. /* 202 */ "expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr",
  114136. /* 203 */ "expr ::= expr PLUS|MINUS expr",
  114137. /* 204 */ "expr ::= expr STAR|SLASH|REM expr",
  114138. /* 205 */ "expr ::= expr CONCAT expr",
  114139. /* 206 */ "likeop ::= LIKE_KW|MATCH",
  114140. /* 207 */ "likeop ::= NOT LIKE_KW|MATCH",
  114141. /* 208 */ "expr ::= expr likeop expr",
  114142. /* 209 */ "expr ::= expr likeop expr ESCAPE expr",
  114143. /* 210 */ "expr ::= expr ISNULL|NOTNULL",
  114144. /* 211 */ "expr ::= expr NOT NULL",
  114145. /* 212 */ "expr ::= expr IS expr",
  114146. /* 213 */ "expr ::= expr IS NOT expr",
  114147. /* 214 */ "expr ::= NOT expr",
  114148. /* 215 */ "expr ::= BITNOT expr",
  114149. /* 216 */ "expr ::= MINUS expr",
  114150. /* 217 */ "expr ::= PLUS expr",
  114151. /* 218 */ "between_op ::= BETWEEN",
  114152. /* 219 */ "between_op ::= NOT BETWEEN",
  114153. /* 220 */ "expr ::= expr between_op expr AND expr",
  114154. /* 221 */ "in_op ::= IN",
  114155. /* 222 */ "in_op ::= NOT IN",
  114156. /* 223 */ "expr ::= expr in_op LP exprlist RP",
  114157. /* 224 */ "expr ::= LP select RP",
  114158. /* 225 */ "expr ::= expr in_op LP select RP",
  114159. /* 226 */ "expr ::= expr in_op nm dbnm",
  114160. /* 227 */ "expr ::= EXISTS LP select RP",
  114161. /* 228 */ "expr ::= CASE case_operand case_exprlist case_else END",
  114162. /* 229 */ "case_exprlist ::= case_exprlist WHEN expr THEN expr",
  114163. /* 230 */ "case_exprlist ::= WHEN expr THEN expr",
  114164. /* 231 */ "case_else ::= ELSE expr",
  114165. /* 232 */ "case_else ::=",
  114166. /* 233 */ "case_operand ::= expr",
  114167. /* 234 */ "case_operand ::=",
  114168. /* 235 */ "exprlist ::= nexprlist",
  114169. /* 236 */ "exprlist ::=",
  114170. /* 237 */ "nexprlist ::= nexprlist COMMA expr",
  114171. /* 238 */ "nexprlist ::= expr",
  114172. /* 239 */ "cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP where_opt",
  114173. /* 240 */ "uniqueflag ::= UNIQUE",
  114174. /* 241 */ "uniqueflag ::=",
  114175. /* 242 */ "idxlist_opt ::=",
  114176. /* 243 */ "idxlist_opt ::= LP idxlist RP",
  114177. /* 244 */ "idxlist ::= idxlist COMMA nm collate sortorder",
  114178. /* 245 */ "idxlist ::= nm collate sortorder",
  114179. /* 246 */ "collate ::=",
  114180. /* 247 */ "collate ::= COLLATE ID|STRING",
  114181. /* 248 */ "cmd ::= DROP INDEX ifexists fullname",
  114182. /* 249 */ "cmd ::= VACUUM",
  114183. /* 250 */ "cmd ::= VACUUM nm",
  114184. /* 251 */ "cmd ::= PRAGMA nm dbnm",
  114185. /* 252 */ "cmd ::= PRAGMA nm dbnm EQ nmnum",
  114186. /* 253 */ "cmd ::= PRAGMA nm dbnm LP nmnum RP",
  114187. /* 254 */ "cmd ::= PRAGMA nm dbnm EQ minus_num",
  114188. /* 255 */ "cmd ::= PRAGMA nm dbnm LP minus_num RP",
  114189. /* 256 */ "nmnum ::= plus_num",
  114190. /* 257 */ "nmnum ::= nm",
  114191. /* 258 */ "nmnum ::= ON",
  114192. /* 259 */ "nmnum ::= DELETE",
  114193. /* 260 */ "nmnum ::= DEFAULT",
  114194. /* 261 */ "plus_num ::= PLUS INTEGER|FLOAT",
  114195. /* 262 */ "plus_num ::= INTEGER|FLOAT",
  114196. /* 263 */ "minus_num ::= MINUS INTEGER|FLOAT",
  114197. /* 264 */ "cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END",
  114198. /* 265 */ "trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause",
  114199. /* 266 */ "trigger_time ::= BEFORE",
  114200. /* 267 */ "trigger_time ::= AFTER",
  114201. /* 268 */ "trigger_time ::= INSTEAD OF",
  114202. /* 269 */ "trigger_time ::=",
  114203. /* 270 */ "trigger_event ::= DELETE|INSERT",
  114204. /* 271 */ "trigger_event ::= UPDATE",
  114205. /* 272 */ "trigger_event ::= UPDATE OF idlist",
  114206. /* 273 */ "foreach_clause ::=",
  114207. /* 274 */ "foreach_clause ::= FOR EACH ROW",
  114208. /* 275 */ "when_clause ::=",
  114209. /* 276 */ "when_clause ::= WHEN expr",
  114210. /* 277 */ "trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI",
  114211. /* 278 */ "trigger_cmd_list ::= trigger_cmd SEMI",
  114212. /* 279 */ "trnm ::= nm",
  114213. /* 280 */ "trnm ::= nm DOT nm",
  114214. /* 281 */ "tridxby ::=",
  114215. /* 282 */ "tridxby ::= INDEXED BY nm",
  114216. /* 283 */ "tridxby ::= NOT INDEXED",
  114217. /* 284 */ "trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt",
  114218. /* 285 */ "trigger_cmd ::= insert_cmd INTO trnm inscollist_opt select",
  114219. /* 286 */ "trigger_cmd ::= DELETE FROM trnm tridxby where_opt",
  114220. /* 287 */ "trigger_cmd ::= select",
  114221. /* 288 */ "expr ::= RAISE LP IGNORE RP",
  114222. /* 289 */ "expr ::= RAISE LP raisetype COMMA nm RP",
  114223. /* 290 */ "raisetype ::= ROLLBACK",
  114224. /* 291 */ "raisetype ::= ABORT",
  114225. /* 292 */ "raisetype ::= FAIL",
  114226. /* 293 */ "cmd ::= DROP TRIGGER ifexists fullname",
  114227. /* 294 */ "cmd ::= ATTACH database_kw_opt expr AS expr key_opt",
  114228. /* 295 */ "cmd ::= DETACH database_kw_opt expr",
  114229. /* 296 */ "key_opt ::=",
  114230. /* 297 */ "key_opt ::= KEY expr",
  114231. /* 298 */ "database_kw_opt ::= DATABASE",
  114232. /* 299 */ "database_kw_opt ::=",
  114233. /* 300 */ "cmd ::= REINDEX",
  114234. /* 301 */ "cmd ::= REINDEX nm dbnm",
  114235. /* 302 */ "cmd ::= ANALYZE",
  114236. /* 303 */ "cmd ::= ANALYZE nm dbnm",
  114237. /* 304 */ "cmd ::= ALTER TABLE fullname RENAME TO nm",
  114238. /* 305 */ "cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column",
  114239. /* 306 */ "add_column_fullname ::= fullname",
  114240. /* 307 */ "kwcolumn_opt ::=",
  114241. /* 308 */ "kwcolumn_opt ::= COLUMNKW",
  114242. /* 309 */ "cmd ::= create_vtab",
  114243. /* 310 */ "cmd ::= create_vtab LP vtabarglist RP",
  114244. /* 311 */ "create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm",
  114245. /* 312 */ "vtabarglist ::= vtabarg",
  114246. /* 313 */ "vtabarglist ::= vtabarglist COMMA vtabarg",
  114247. /* 314 */ "vtabarg ::=",
  114248. /* 315 */ "vtabarg ::= vtabarg vtabargtoken",
  114249. /* 316 */ "vtabargtoken ::= ANY",
  114250. /* 317 */ "vtabargtoken ::= lp anylist RP",
  114251. /* 318 */ "lp ::= LP",
  114252. /* 319 */ "anylist ::=",
  114253. /* 320 */ "anylist ::= anylist LP anylist RP",
  114254. /* 321 */ "anylist ::= anylist ANY",
  114255. /* 322 */ "with ::=",
  114256. /* 323 */ "with ::= WITH wqlist",
  114257. /* 324 */ "with ::= WITH RECURSIVE wqlist",
  114258. /* 325 */ "wqlist ::= nm idxlist_opt AS LP select RP",
  114259. /* 326 */ "wqlist ::= wqlist COMMA nm idxlist_opt AS LP select RP",
  114260. };
  114261. #endif /* NDEBUG */
  114262. #if YYSTACKDEPTH<=0
  114263. /*
  114264. ** Try to increase the size of the parser stack.
  114265. */
  114266. static void yyGrowStack(yyParser *p){
  114267. int newSize;
  114268. yyStackEntry *pNew;
  114269. newSize = p->yystksz*2 + 100;
  114270. pNew = realloc(p->yystack, newSize*sizeof(pNew[0]));
  114271. if( pNew ){
  114272. p->yystack = pNew;
  114273. p->yystksz = newSize;
  114274. #ifndef NDEBUG
  114275. if( yyTraceFILE ){
  114276. fprintf(yyTraceFILE,"%sStack grows to %d entries!\n",
  114277. yyTracePrompt, p->yystksz);
  114278. }
  114279. #endif
  114280. }
  114281. }
  114282. #endif
  114283. /*
  114284. ** This function allocates a new parser.
  114285. ** The only argument is a pointer to a function which works like
  114286. ** malloc.
  114287. **
  114288. ** Inputs:
  114289. ** A pointer to the function used to allocate memory.
  114290. **
  114291. ** Outputs:
  114292. ** A pointer to a parser. This pointer is used in subsequent calls
  114293. ** to sqlite3Parser and sqlite3ParserFree.
  114294. */
  114295. SQLITE_PRIVATE void *sqlite3ParserAlloc(void *(*mallocProc)(u64)){
  114296. yyParser *pParser;
  114297. pParser = (yyParser*)(*mallocProc)( (u64)sizeof(yyParser) );
  114298. if( pParser ){
  114299. pParser->yyidx = -1;
  114300. #ifdef YYTRACKMAXSTACKDEPTH
  114301. pParser->yyidxMax = 0;
  114302. #endif
  114303. #if YYSTACKDEPTH<=0
  114304. pParser->yystack = NULL;
  114305. pParser->yystksz = 0;
  114306. yyGrowStack(pParser);
  114307. #endif
  114308. }
  114309. return pParser;
  114310. }
  114311. /* The following function deletes the value associated with a
  114312. ** symbol. The symbol can be either a terminal or nonterminal.
  114313. ** "yymajor" is the symbol code, and "yypminor" is a pointer to
  114314. ** the value.
  114315. */
  114316. static void yy_destructor(
  114317. yyParser *yypParser, /* The parser */
  114318. YYCODETYPE yymajor, /* Type code for object to destroy */
  114319. YYMINORTYPE *yypminor /* The object to be destroyed */
  114320. ){
  114321. sqlite3ParserARG_FETCH;
  114322. switch( yymajor ){
  114323. /* Here is inserted the actions which take place when a
  114324. ** terminal or non-terminal is destroyed. This can happen
  114325. ** when the symbol is popped from the stack during a
  114326. ** reduce or during error processing or when a parser is
  114327. ** being destroyed before it is finished parsing.
  114328. **
  114329. ** Note: during a reduce, the only symbols destroyed are those
  114330. ** which appear on the RHS of the rule, but which are not used
  114331. ** inside the C code.
  114332. */
  114333. case 163: /* select */
  114334. case 195: /* selectnowith */
  114335. case 196: /* oneselect */
  114336. case 207: /* values */
  114337. {
  114338. sqlite3SelectDelete(pParse->db, (yypminor->yy3));
  114339. }
  114340. break;
  114341. case 174: /* term */
  114342. case 175: /* expr */
  114343. {
  114344. sqlite3ExprDelete(pParse->db, (yypminor->yy346).pExpr);
  114345. }
  114346. break;
  114347. case 179: /* idxlist_opt */
  114348. case 188: /* idxlist */
  114349. case 200: /* selcollist */
  114350. case 203: /* groupby_opt */
  114351. case 205: /* orderby_opt */
  114352. case 208: /* nexprlist */
  114353. case 209: /* exprlist */
  114354. case 210: /* sclp */
  114355. case 220: /* sortlist */
  114356. case 221: /* setlist */
  114357. case 228: /* case_exprlist */
  114358. {
  114359. sqlite3ExprListDelete(pParse->db, (yypminor->yy14));
  114360. }
  114361. break;
  114362. case 194: /* fullname */
  114363. case 201: /* from */
  114364. case 212: /* seltablist */
  114365. case 213: /* stl_prefix */
  114366. {
  114367. sqlite3SrcListDelete(pParse->db, (yypminor->yy65));
  114368. }
  114369. break;
  114370. case 197: /* with */
  114371. case 252: /* wqlist */
  114372. {
  114373. sqlite3WithDelete(pParse->db, (yypminor->yy59));
  114374. }
  114375. break;
  114376. case 202: /* where_opt */
  114377. case 204: /* having_opt */
  114378. case 216: /* on_opt */
  114379. case 227: /* case_operand */
  114380. case 229: /* case_else */
  114381. case 238: /* when_clause */
  114382. case 243: /* key_opt */
  114383. {
  114384. sqlite3ExprDelete(pParse->db, (yypminor->yy132));
  114385. }
  114386. break;
  114387. case 217: /* using_opt */
  114388. case 219: /* idlist */
  114389. case 223: /* inscollist_opt */
  114390. {
  114391. sqlite3IdListDelete(pParse->db, (yypminor->yy408));
  114392. }
  114393. break;
  114394. case 234: /* trigger_cmd_list */
  114395. case 239: /* trigger_cmd */
  114396. {
  114397. sqlite3DeleteTriggerStep(pParse->db, (yypminor->yy473));
  114398. }
  114399. break;
  114400. case 236: /* trigger_event */
  114401. {
  114402. sqlite3IdListDelete(pParse->db, (yypminor->yy378).b);
  114403. }
  114404. break;
  114405. default: break; /* If no destructor action specified: do nothing */
  114406. }
  114407. }
  114408. /*
  114409. ** Pop the parser's stack once.
  114410. **
  114411. ** If there is a destructor routine associated with the token which
  114412. ** is popped from the stack, then call it.
  114413. **
  114414. ** Return the major token number for the symbol popped.
  114415. */
  114416. static int yy_pop_parser_stack(yyParser *pParser){
  114417. YYCODETYPE yymajor;
  114418. yyStackEntry *yytos = &pParser->yystack[pParser->yyidx];
  114419. /* There is no mechanism by which the parser stack can be popped below
  114420. ** empty in SQLite. */
  114421. if( NEVER(pParser->yyidx<0) ) return 0;
  114422. #ifndef NDEBUG
  114423. if( yyTraceFILE && pParser->yyidx>=0 ){
  114424. fprintf(yyTraceFILE,"%sPopping %s\n",
  114425. yyTracePrompt,
  114426. yyTokenName[yytos->major]);
  114427. }
  114428. #endif
  114429. yymajor = yytos->major;
  114430. yy_destructor(pParser, yymajor, &yytos->minor);
  114431. pParser->yyidx--;
  114432. return yymajor;
  114433. }
  114434. /*
  114435. ** Deallocate and destroy a parser. Destructors are all called for
  114436. ** all stack elements before shutting the parser down.
  114437. **
  114438. ** Inputs:
  114439. ** <ul>
  114440. ** <li> A pointer to the parser. This should be a pointer
  114441. ** obtained from sqlite3ParserAlloc.
  114442. ** <li> A pointer to a function used to reclaim memory obtained
  114443. ** from malloc.
  114444. ** </ul>
  114445. */
  114446. SQLITE_PRIVATE void sqlite3ParserFree(
  114447. void *p, /* The parser to be deleted */
  114448. void (*freeProc)(void*) /* Function used to reclaim memory */
  114449. ){
  114450. yyParser *pParser = (yyParser*)p;
  114451. /* In SQLite, we never try to destroy a parser that was not successfully
  114452. ** created in the first place. */
  114453. if( NEVER(pParser==0) ) return;
  114454. while( pParser->yyidx>=0 ) yy_pop_parser_stack(pParser);
  114455. #if YYSTACKDEPTH<=0
  114456. free(pParser->yystack);
  114457. #endif
  114458. (*freeProc)((void*)pParser);
  114459. }
  114460. /*
  114461. ** Return the peak depth of the stack for a parser.
  114462. */
  114463. #ifdef YYTRACKMAXSTACKDEPTH
  114464. SQLITE_PRIVATE int sqlite3ParserStackPeak(void *p){
  114465. yyParser *pParser = (yyParser*)p;
  114466. return pParser->yyidxMax;
  114467. }
  114468. #endif
  114469. /*
  114470. ** Find the appropriate action for a parser given the terminal
  114471. ** look-ahead token iLookAhead.
  114472. **
  114473. ** If the look-ahead token is YYNOCODE, then check to see if the action is
  114474. ** independent of the look-ahead. If it is, return the action, otherwise
  114475. ** return YY_NO_ACTION.
  114476. */
  114477. static int yy_find_shift_action(
  114478. yyParser *pParser, /* The parser */
  114479. YYCODETYPE iLookAhead /* The look-ahead token */
  114480. ){
  114481. int i;
  114482. int stateno = pParser->yystack[pParser->yyidx].stateno;
  114483. if( stateno>YY_SHIFT_COUNT
  114484. || (i = yy_shift_ofst[stateno])==YY_SHIFT_USE_DFLT ){
  114485. return yy_default[stateno];
  114486. }
  114487. assert( iLookAhead!=YYNOCODE );
  114488. i += iLookAhead;
  114489. if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
  114490. if( iLookAhead>0 ){
  114491. #ifdef YYFALLBACK
  114492. YYCODETYPE iFallback; /* Fallback token */
  114493. if( iLookAhead<sizeof(yyFallback)/sizeof(yyFallback[0])
  114494. && (iFallback = yyFallback[iLookAhead])!=0 ){
  114495. #ifndef NDEBUG
  114496. if( yyTraceFILE ){
  114497. fprintf(yyTraceFILE, "%sFALLBACK %s => %s\n",
  114498. yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[iFallback]);
  114499. }
  114500. #endif
  114501. return yy_find_shift_action(pParser, iFallback);
  114502. }
  114503. #endif
  114504. #ifdef YYWILDCARD
  114505. {
  114506. int j = i - iLookAhead + YYWILDCARD;
  114507. if(
  114508. #if YY_SHIFT_MIN+YYWILDCARD<0
  114509. j>=0 &&
  114510. #endif
  114511. #if YY_SHIFT_MAX+YYWILDCARD>=YY_ACTTAB_COUNT
  114512. j<YY_ACTTAB_COUNT &&
  114513. #endif
  114514. yy_lookahead[j]==YYWILDCARD
  114515. ){
  114516. #ifndef NDEBUG
  114517. if( yyTraceFILE ){
  114518. fprintf(yyTraceFILE, "%sWILDCARD %s => %s\n",
  114519. yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[YYWILDCARD]);
  114520. }
  114521. #endif /* NDEBUG */
  114522. return yy_action[j];
  114523. }
  114524. }
  114525. #endif /* YYWILDCARD */
  114526. }
  114527. return yy_default[stateno];
  114528. }else{
  114529. return yy_action[i];
  114530. }
  114531. }
  114532. /*
  114533. ** Find the appropriate action for a parser given the non-terminal
  114534. ** look-ahead token iLookAhead.
  114535. **
  114536. ** If the look-ahead token is YYNOCODE, then check to see if the action is
  114537. ** independent of the look-ahead. If it is, return the action, otherwise
  114538. ** return YY_NO_ACTION.
  114539. */
  114540. static int yy_find_reduce_action(
  114541. int stateno, /* Current state number */
  114542. YYCODETYPE iLookAhead /* The look-ahead token */
  114543. ){
  114544. int i;
  114545. #ifdef YYERRORSYMBOL
  114546. if( stateno>YY_REDUCE_COUNT ){
  114547. return yy_default[stateno];
  114548. }
  114549. #else
  114550. assert( stateno<=YY_REDUCE_COUNT );
  114551. #endif
  114552. i = yy_reduce_ofst[stateno];
  114553. assert( i!=YY_REDUCE_USE_DFLT );
  114554. assert( iLookAhead!=YYNOCODE );
  114555. i += iLookAhead;
  114556. #ifdef YYERRORSYMBOL
  114557. if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
  114558. return yy_default[stateno];
  114559. }
  114560. #else
  114561. assert( i>=0 && i<YY_ACTTAB_COUNT );
  114562. assert( yy_lookahead[i]==iLookAhead );
  114563. #endif
  114564. return yy_action[i];
  114565. }
  114566. /*
  114567. ** The following routine is called if the stack overflows.
  114568. */
  114569. static void yyStackOverflow(yyParser *yypParser, YYMINORTYPE *yypMinor){
  114570. sqlite3ParserARG_FETCH;
  114571. yypParser->yyidx--;
  114572. #ifndef NDEBUG
  114573. if( yyTraceFILE ){
  114574. fprintf(yyTraceFILE,"%sStack Overflow!\n",yyTracePrompt);
  114575. }
  114576. #endif
  114577. while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
  114578. /* Here code is inserted which will execute if the parser
  114579. ** stack every overflows */
  114580. UNUSED_PARAMETER(yypMinor); /* Silence some compiler warnings */
  114581. sqlite3ErrorMsg(pParse, "parser stack overflow");
  114582. sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument var */
  114583. }
  114584. /*
  114585. ** Perform a shift action.
  114586. */
  114587. static void yy_shift(
  114588. yyParser *yypParser, /* The parser to be shifted */
  114589. int yyNewState, /* The new state to shift in */
  114590. int yyMajor, /* The major token to shift in */
  114591. YYMINORTYPE *yypMinor /* Pointer to the minor token to shift in */
  114592. ){
  114593. yyStackEntry *yytos;
  114594. yypParser->yyidx++;
  114595. #ifdef YYTRACKMAXSTACKDEPTH
  114596. if( yypParser->yyidx>yypParser->yyidxMax ){
  114597. yypParser->yyidxMax = yypParser->yyidx;
  114598. }
  114599. #endif
  114600. #if YYSTACKDEPTH>0
  114601. if( yypParser->yyidx>=YYSTACKDEPTH ){
  114602. yyStackOverflow(yypParser, yypMinor);
  114603. return;
  114604. }
  114605. #else
  114606. if( yypParser->yyidx>=yypParser->yystksz ){
  114607. yyGrowStack(yypParser);
  114608. if( yypParser->yyidx>=yypParser->yystksz ){
  114609. yyStackOverflow(yypParser, yypMinor);
  114610. return;
  114611. }
  114612. }
  114613. #endif
  114614. yytos = &yypParser->yystack[yypParser->yyidx];
  114615. yytos->stateno = (YYACTIONTYPE)yyNewState;
  114616. yytos->major = (YYCODETYPE)yyMajor;
  114617. yytos->minor = *yypMinor;
  114618. #ifndef NDEBUG
  114619. if( yyTraceFILE && yypParser->yyidx>0 ){
  114620. int i;
  114621. fprintf(yyTraceFILE,"%sShift %d\n",yyTracePrompt,yyNewState);
  114622. fprintf(yyTraceFILE,"%sStack:",yyTracePrompt);
  114623. for(i=1; i<=yypParser->yyidx; i++)
  114624. fprintf(yyTraceFILE," %s",yyTokenName[yypParser->yystack[i].major]);
  114625. fprintf(yyTraceFILE,"\n");
  114626. }
  114627. #endif
  114628. }
  114629. /* The following table contains information about every rule that
  114630. ** is used during the reduce.
  114631. */
  114632. static const struct {
  114633. YYCODETYPE lhs; /* Symbol on the left-hand side of the rule */
  114634. unsigned char nrhs; /* Number of right-hand side symbols in the rule */
  114635. } yyRuleInfo[] = {
  114636. { 144, 1 },
  114637. { 145, 2 },
  114638. { 145, 1 },
  114639. { 146, 1 },
  114640. { 146, 3 },
  114641. { 147, 0 },
  114642. { 147, 1 },
  114643. { 147, 3 },
  114644. { 148, 1 },
  114645. { 149, 3 },
  114646. { 151, 0 },
  114647. { 151, 1 },
  114648. { 151, 2 },
  114649. { 150, 0 },
  114650. { 150, 1 },
  114651. { 150, 1 },
  114652. { 150, 1 },
  114653. { 149, 2 },
  114654. { 149, 2 },
  114655. { 149, 2 },
  114656. { 153, 1 },
  114657. { 153, 0 },
  114658. { 149, 2 },
  114659. { 149, 3 },
  114660. { 149, 5 },
  114661. { 149, 2 },
  114662. { 154, 6 },
  114663. { 156, 1 },
  114664. { 158, 0 },
  114665. { 158, 3 },
  114666. { 157, 1 },
  114667. { 157, 0 },
  114668. { 155, 5 },
  114669. { 155, 2 },
  114670. { 162, 0 },
  114671. { 162, 2 },
  114672. { 160, 3 },
  114673. { 160, 1 },
  114674. { 164, 3 },
  114675. { 165, 1 },
  114676. { 152, 1 },
  114677. { 152, 1 },
  114678. { 152, 1 },
  114679. { 166, 0 },
  114680. { 166, 1 },
  114681. { 168, 1 },
  114682. { 168, 4 },
  114683. { 168, 6 },
  114684. { 169, 1 },
  114685. { 169, 2 },
  114686. { 170, 1 },
  114687. { 170, 1 },
  114688. { 167, 2 },
  114689. { 167, 0 },
  114690. { 173, 2 },
  114691. { 173, 2 },
  114692. { 173, 4 },
  114693. { 173, 3 },
  114694. { 173, 3 },
  114695. { 173, 2 },
  114696. { 173, 2 },
  114697. { 173, 3 },
  114698. { 173, 5 },
  114699. { 173, 2 },
  114700. { 173, 4 },
  114701. { 173, 4 },
  114702. { 173, 1 },
  114703. { 173, 2 },
  114704. { 178, 0 },
  114705. { 178, 1 },
  114706. { 180, 0 },
  114707. { 180, 2 },
  114708. { 182, 2 },
  114709. { 182, 3 },
  114710. { 182, 3 },
  114711. { 182, 3 },
  114712. { 183, 2 },
  114713. { 183, 2 },
  114714. { 183, 1 },
  114715. { 183, 1 },
  114716. { 183, 2 },
  114717. { 181, 3 },
  114718. { 181, 2 },
  114719. { 184, 0 },
  114720. { 184, 2 },
  114721. { 184, 2 },
  114722. { 161, 0 },
  114723. { 161, 2 },
  114724. { 185, 3 },
  114725. { 185, 1 },
  114726. { 186, 1 },
  114727. { 186, 0 },
  114728. { 187, 2 },
  114729. { 187, 7 },
  114730. { 187, 5 },
  114731. { 187, 5 },
  114732. { 187, 10 },
  114733. { 189, 0 },
  114734. { 189, 1 },
  114735. { 176, 0 },
  114736. { 176, 3 },
  114737. { 190, 0 },
  114738. { 190, 2 },
  114739. { 191, 1 },
  114740. { 191, 1 },
  114741. { 191, 1 },
  114742. { 149, 4 },
  114743. { 193, 2 },
  114744. { 193, 0 },
  114745. { 149, 8 },
  114746. { 149, 4 },
  114747. { 149, 1 },
  114748. { 163, 2 },
  114749. { 195, 1 },
  114750. { 195, 3 },
  114751. { 198, 1 },
  114752. { 198, 2 },
  114753. { 198, 1 },
  114754. { 196, 9 },
  114755. { 196, 1 },
  114756. { 207, 4 },
  114757. { 207, 5 },
  114758. { 199, 1 },
  114759. { 199, 1 },
  114760. { 199, 0 },
  114761. { 210, 2 },
  114762. { 210, 0 },
  114763. { 200, 3 },
  114764. { 200, 2 },
  114765. { 200, 4 },
  114766. { 211, 2 },
  114767. { 211, 1 },
  114768. { 211, 0 },
  114769. { 201, 0 },
  114770. { 201, 2 },
  114771. { 213, 2 },
  114772. { 213, 0 },
  114773. { 212, 7 },
  114774. { 212, 7 },
  114775. { 212, 7 },
  114776. { 159, 0 },
  114777. { 159, 2 },
  114778. { 194, 2 },
  114779. { 214, 1 },
  114780. { 214, 2 },
  114781. { 214, 3 },
  114782. { 214, 4 },
  114783. { 216, 2 },
  114784. { 216, 0 },
  114785. { 215, 0 },
  114786. { 215, 3 },
  114787. { 215, 2 },
  114788. { 217, 4 },
  114789. { 217, 0 },
  114790. { 205, 0 },
  114791. { 205, 3 },
  114792. { 220, 4 },
  114793. { 220, 2 },
  114794. { 177, 1 },
  114795. { 177, 1 },
  114796. { 177, 0 },
  114797. { 203, 0 },
  114798. { 203, 3 },
  114799. { 204, 0 },
  114800. { 204, 2 },
  114801. { 206, 0 },
  114802. { 206, 2 },
  114803. { 206, 4 },
  114804. { 206, 4 },
  114805. { 149, 6 },
  114806. { 202, 0 },
  114807. { 202, 2 },
  114808. { 149, 8 },
  114809. { 221, 5 },
  114810. { 221, 3 },
  114811. { 149, 6 },
  114812. { 149, 7 },
  114813. { 222, 2 },
  114814. { 222, 1 },
  114815. { 223, 0 },
  114816. { 223, 3 },
  114817. { 219, 3 },
  114818. { 219, 1 },
  114819. { 175, 1 },
  114820. { 175, 3 },
  114821. { 174, 1 },
  114822. { 175, 1 },
  114823. { 175, 1 },
  114824. { 175, 3 },
  114825. { 175, 5 },
  114826. { 174, 1 },
  114827. { 174, 1 },
  114828. { 175, 1 },
  114829. { 175, 3 },
  114830. { 175, 6 },
  114831. { 175, 5 },
  114832. { 175, 4 },
  114833. { 174, 1 },
  114834. { 175, 3 },
  114835. { 175, 3 },
  114836. { 175, 3 },
  114837. { 175, 3 },
  114838. { 175, 3 },
  114839. { 175, 3 },
  114840. { 175, 3 },
  114841. { 175, 3 },
  114842. { 224, 1 },
  114843. { 224, 2 },
  114844. { 175, 3 },
  114845. { 175, 5 },
  114846. { 175, 2 },
  114847. { 175, 3 },
  114848. { 175, 3 },
  114849. { 175, 4 },
  114850. { 175, 2 },
  114851. { 175, 2 },
  114852. { 175, 2 },
  114853. { 175, 2 },
  114854. { 225, 1 },
  114855. { 225, 2 },
  114856. { 175, 5 },
  114857. { 226, 1 },
  114858. { 226, 2 },
  114859. { 175, 5 },
  114860. { 175, 3 },
  114861. { 175, 5 },
  114862. { 175, 4 },
  114863. { 175, 4 },
  114864. { 175, 5 },
  114865. { 228, 5 },
  114866. { 228, 4 },
  114867. { 229, 2 },
  114868. { 229, 0 },
  114869. { 227, 1 },
  114870. { 227, 0 },
  114871. { 209, 1 },
  114872. { 209, 0 },
  114873. { 208, 3 },
  114874. { 208, 1 },
  114875. { 149, 12 },
  114876. { 230, 1 },
  114877. { 230, 0 },
  114878. { 179, 0 },
  114879. { 179, 3 },
  114880. { 188, 5 },
  114881. { 188, 3 },
  114882. { 231, 0 },
  114883. { 231, 2 },
  114884. { 149, 4 },
  114885. { 149, 1 },
  114886. { 149, 2 },
  114887. { 149, 3 },
  114888. { 149, 5 },
  114889. { 149, 6 },
  114890. { 149, 5 },
  114891. { 149, 6 },
  114892. { 232, 1 },
  114893. { 232, 1 },
  114894. { 232, 1 },
  114895. { 232, 1 },
  114896. { 232, 1 },
  114897. { 171, 2 },
  114898. { 171, 1 },
  114899. { 172, 2 },
  114900. { 149, 5 },
  114901. { 233, 11 },
  114902. { 235, 1 },
  114903. { 235, 1 },
  114904. { 235, 2 },
  114905. { 235, 0 },
  114906. { 236, 1 },
  114907. { 236, 1 },
  114908. { 236, 3 },
  114909. { 237, 0 },
  114910. { 237, 3 },
  114911. { 238, 0 },
  114912. { 238, 2 },
  114913. { 234, 3 },
  114914. { 234, 2 },
  114915. { 240, 1 },
  114916. { 240, 3 },
  114917. { 241, 0 },
  114918. { 241, 3 },
  114919. { 241, 2 },
  114920. { 239, 7 },
  114921. { 239, 5 },
  114922. { 239, 5 },
  114923. { 239, 1 },
  114924. { 175, 4 },
  114925. { 175, 6 },
  114926. { 192, 1 },
  114927. { 192, 1 },
  114928. { 192, 1 },
  114929. { 149, 4 },
  114930. { 149, 6 },
  114931. { 149, 3 },
  114932. { 243, 0 },
  114933. { 243, 2 },
  114934. { 242, 1 },
  114935. { 242, 0 },
  114936. { 149, 1 },
  114937. { 149, 3 },
  114938. { 149, 1 },
  114939. { 149, 3 },
  114940. { 149, 6 },
  114941. { 149, 6 },
  114942. { 244, 1 },
  114943. { 245, 0 },
  114944. { 245, 1 },
  114945. { 149, 1 },
  114946. { 149, 4 },
  114947. { 246, 8 },
  114948. { 247, 1 },
  114949. { 247, 3 },
  114950. { 248, 0 },
  114951. { 248, 2 },
  114952. { 249, 1 },
  114953. { 249, 3 },
  114954. { 250, 1 },
  114955. { 251, 0 },
  114956. { 251, 4 },
  114957. { 251, 2 },
  114958. { 197, 0 },
  114959. { 197, 2 },
  114960. { 197, 3 },
  114961. { 252, 6 },
  114962. { 252, 8 },
  114963. };
  114964. static void yy_accept(yyParser*); /* Forward Declaration */
  114965. /*
  114966. ** Perform a reduce action and the shift that must immediately
  114967. ** follow the reduce.
  114968. */
  114969. static void yy_reduce(
  114970. yyParser *yypParser, /* The parser */
  114971. int yyruleno /* Number of the rule by which to reduce */
  114972. ){
  114973. int yygoto; /* The next state */
  114974. int yyact; /* The next action */
  114975. YYMINORTYPE yygotominor; /* The LHS of the rule reduced */
  114976. yyStackEntry *yymsp; /* The top of the parser's stack */
  114977. int yysize; /* Amount to pop the stack */
  114978. sqlite3ParserARG_FETCH;
  114979. yymsp = &yypParser->yystack[yypParser->yyidx];
  114980. #ifndef NDEBUG
  114981. if( yyTraceFILE && yyruleno>=0
  114982. && yyruleno<(int)(sizeof(yyRuleName)/sizeof(yyRuleName[0])) ){
  114983. fprintf(yyTraceFILE, "%sReduce [%s].\n", yyTracePrompt,
  114984. yyRuleName[yyruleno]);
  114985. }
  114986. #endif /* NDEBUG */
  114987. /* Silence complaints from purify about yygotominor being uninitialized
  114988. ** in some cases when it is copied into the stack after the following
  114989. ** switch. yygotominor is uninitialized when a rule reduces that does
  114990. ** not set the value of its left-hand side nonterminal. Leaving the
  114991. ** value of the nonterminal uninitialized is utterly harmless as long
  114992. ** as the value is never used. So really the only thing this code
  114993. ** accomplishes is to quieten purify.
  114994. **
  114995. ** 2007-01-16: The wireshark project (www.wireshark.org) reports that
  114996. ** without this code, their parser segfaults. I'm not sure what there
  114997. ** parser is doing to make this happen. This is the second bug report
  114998. ** from wireshark this week. Clearly they are stressing Lemon in ways
  114999. ** that it has not been previously stressed... (SQLite ticket #2172)
  115000. */
  115001. /*memset(&yygotominor, 0, sizeof(yygotominor));*/
  115002. yygotominor = yyzerominor;
  115003. switch( yyruleno ){
  115004. /* Beginning here are the reduction cases. A typical example
  115005. ** follows:
  115006. ** case 0:
  115007. ** #line <lineno> <grammarfile>
  115008. ** { ... } // User supplied code
  115009. ** #line <lineno> <thisfile>
  115010. ** break;
  115011. */
  115012. case 5: /* explain ::= */
  115013. { sqlite3BeginParse(pParse, 0); }
  115014. break;
  115015. case 6: /* explain ::= EXPLAIN */
  115016. { sqlite3BeginParse(pParse, 1); }
  115017. break;
  115018. case 7: /* explain ::= EXPLAIN QUERY PLAN */
  115019. { sqlite3BeginParse(pParse, 2); }
  115020. break;
  115021. case 8: /* cmdx ::= cmd */
  115022. { sqlite3FinishCoding(pParse); }
  115023. break;
  115024. case 9: /* cmd ::= BEGIN transtype trans_opt */
  115025. {sqlite3BeginTransaction(pParse, yymsp[-1].minor.yy328);}
  115026. break;
  115027. case 13: /* transtype ::= */
  115028. {yygotominor.yy328 = TK_DEFERRED;}
  115029. break;
  115030. case 14: /* transtype ::= DEFERRED */
  115031. case 15: /* transtype ::= IMMEDIATE */ yytestcase(yyruleno==15);
  115032. case 16: /* transtype ::= EXCLUSIVE */ yytestcase(yyruleno==16);
  115033. case 115: /* multiselect_op ::= UNION */ yytestcase(yyruleno==115);
  115034. case 117: /* multiselect_op ::= EXCEPT|INTERSECT */ yytestcase(yyruleno==117);
  115035. {yygotominor.yy328 = yymsp[0].major;}
  115036. break;
  115037. case 17: /* cmd ::= COMMIT trans_opt */
  115038. case 18: /* cmd ::= END trans_opt */ yytestcase(yyruleno==18);
  115039. {sqlite3CommitTransaction(pParse);}
  115040. break;
  115041. case 19: /* cmd ::= ROLLBACK trans_opt */
  115042. {sqlite3RollbackTransaction(pParse);}
  115043. break;
  115044. case 22: /* cmd ::= SAVEPOINT nm */
  115045. {
  115046. sqlite3Savepoint(pParse, SAVEPOINT_BEGIN, &yymsp[0].minor.yy0);
  115047. }
  115048. break;
  115049. case 23: /* cmd ::= RELEASE savepoint_opt nm */
  115050. {
  115051. sqlite3Savepoint(pParse, SAVEPOINT_RELEASE, &yymsp[0].minor.yy0);
  115052. }
  115053. break;
  115054. case 24: /* cmd ::= ROLLBACK trans_opt TO savepoint_opt nm */
  115055. {
  115056. sqlite3Savepoint(pParse, SAVEPOINT_ROLLBACK, &yymsp[0].minor.yy0);
  115057. }
  115058. break;
  115059. case 26: /* create_table ::= createkw temp TABLE ifnotexists nm dbnm */
  115060. {
  115061. sqlite3StartTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,yymsp[-4].minor.yy328,0,0,yymsp[-2].minor.yy328);
  115062. }
  115063. break;
  115064. case 27: /* createkw ::= CREATE */
  115065. {
  115066. pParse->db->lookaside.bEnabled = 0;
  115067. yygotominor.yy0 = yymsp[0].minor.yy0;
  115068. }
  115069. break;
  115070. case 28: /* ifnotexists ::= */
  115071. case 31: /* temp ::= */ yytestcase(yyruleno==31);
  115072. case 68: /* autoinc ::= */ yytestcase(yyruleno==68);
  115073. case 81: /* defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt */ yytestcase(yyruleno==81);
  115074. case 83: /* init_deferred_pred_opt ::= */ yytestcase(yyruleno==83);
  115075. case 85: /* init_deferred_pred_opt ::= INITIALLY IMMEDIATE */ yytestcase(yyruleno==85);
  115076. case 97: /* defer_subclause_opt ::= */ yytestcase(yyruleno==97);
  115077. case 108: /* ifexists ::= */ yytestcase(yyruleno==108);
  115078. case 218: /* between_op ::= BETWEEN */ yytestcase(yyruleno==218);
  115079. case 221: /* in_op ::= IN */ yytestcase(yyruleno==221);
  115080. {yygotominor.yy328 = 0;}
  115081. break;
  115082. case 29: /* ifnotexists ::= IF NOT EXISTS */
  115083. case 30: /* temp ::= TEMP */ yytestcase(yyruleno==30);
  115084. case 69: /* autoinc ::= AUTOINCR */ yytestcase(yyruleno==69);
  115085. case 84: /* init_deferred_pred_opt ::= INITIALLY DEFERRED */ yytestcase(yyruleno==84);
  115086. case 107: /* ifexists ::= IF EXISTS */ yytestcase(yyruleno==107);
  115087. case 219: /* between_op ::= NOT BETWEEN */ yytestcase(yyruleno==219);
  115088. case 222: /* in_op ::= NOT IN */ yytestcase(yyruleno==222);
  115089. {yygotominor.yy328 = 1;}
  115090. break;
  115091. case 32: /* create_table_args ::= LP columnlist conslist_opt RP table_options */
  115092. {
  115093. sqlite3EndTable(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,yymsp[0].minor.yy186,0);
  115094. }
  115095. break;
  115096. case 33: /* create_table_args ::= AS select */
  115097. {
  115098. sqlite3EndTable(pParse,0,0,0,yymsp[0].minor.yy3);
  115099. sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy3);
  115100. }
  115101. break;
  115102. case 34: /* table_options ::= */
  115103. {yygotominor.yy186 = 0;}
  115104. break;
  115105. case 35: /* table_options ::= WITHOUT nm */
  115106. {
  115107. if( yymsp[0].minor.yy0.n==5 && sqlite3_strnicmp(yymsp[0].minor.yy0.z,"rowid",5)==0 ){
  115108. yygotominor.yy186 = TF_WithoutRowid;
  115109. }else{
  115110. yygotominor.yy186 = 0;
  115111. sqlite3ErrorMsg(pParse, "unknown table option: %.*s", yymsp[0].minor.yy0.n, yymsp[0].minor.yy0.z);
  115112. }
  115113. }
  115114. break;
  115115. case 38: /* column ::= columnid type carglist */
  115116. {
  115117. yygotominor.yy0.z = yymsp[-2].minor.yy0.z;
  115118. yygotominor.yy0.n = (int)(pParse->sLastToken.z-yymsp[-2].minor.yy0.z) + pParse->sLastToken.n;
  115119. }
  115120. break;
  115121. case 39: /* columnid ::= nm */
  115122. {
  115123. sqlite3AddColumn(pParse,&yymsp[0].minor.yy0);
  115124. yygotominor.yy0 = yymsp[0].minor.yy0;
  115125. pParse->constraintName.n = 0;
  115126. }
  115127. break;
  115128. case 40: /* nm ::= ID|INDEXED */
  115129. case 41: /* nm ::= STRING */ yytestcase(yyruleno==41);
  115130. case 42: /* nm ::= JOIN_KW */ yytestcase(yyruleno==42);
  115131. case 45: /* typetoken ::= typename */ yytestcase(yyruleno==45);
  115132. case 48: /* typename ::= ID|STRING */ yytestcase(yyruleno==48);
  115133. case 130: /* as ::= AS nm */ yytestcase(yyruleno==130);
  115134. case 131: /* as ::= ID|STRING */ yytestcase(yyruleno==131);
  115135. case 141: /* dbnm ::= DOT nm */ yytestcase(yyruleno==141);
  115136. case 150: /* indexed_opt ::= INDEXED BY nm */ yytestcase(yyruleno==150);
  115137. case 247: /* collate ::= COLLATE ID|STRING */ yytestcase(yyruleno==247);
  115138. case 256: /* nmnum ::= plus_num */ yytestcase(yyruleno==256);
  115139. case 257: /* nmnum ::= nm */ yytestcase(yyruleno==257);
  115140. case 258: /* nmnum ::= ON */ yytestcase(yyruleno==258);
  115141. case 259: /* nmnum ::= DELETE */ yytestcase(yyruleno==259);
  115142. case 260: /* nmnum ::= DEFAULT */ yytestcase(yyruleno==260);
  115143. case 261: /* plus_num ::= PLUS INTEGER|FLOAT */ yytestcase(yyruleno==261);
  115144. case 262: /* plus_num ::= INTEGER|FLOAT */ yytestcase(yyruleno==262);
  115145. case 263: /* minus_num ::= MINUS INTEGER|FLOAT */ yytestcase(yyruleno==263);
  115146. case 279: /* trnm ::= nm */ yytestcase(yyruleno==279);
  115147. {yygotominor.yy0 = yymsp[0].minor.yy0;}
  115148. break;
  115149. case 44: /* type ::= typetoken */
  115150. {sqlite3AddColumnType(pParse,&yymsp[0].minor.yy0);}
  115151. break;
  115152. case 46: /* typetoken ::= typename LP signed RP */
  115153. {
  115154. yygotominor.yy0.z = yymsp[-3].minor.yy0.z;
  115155. yygotominor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-3].minor.yy0.z);
  115156. }
  115157. break;
  115158. case 47: /* typetoken ::= typename LP signed COMMA signed RP */
  115159. {
  115160. yygotominor.yy0.z = yymsp[-5].minor.yy0.z;
  115161. yygotominor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-5].minor.yy0.z);
  115162. }
  115163. break;
  115164. case 49: /* typename ::= typename ID|STRING */
  115165. {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);}
  115166. break;
  115167. case 54: /* ccons ::= CONSTRAINT nm */
  115168. case 92: /* tcons ::= CONSTRAINT nm */ yytestcase(yyruleno==92);
  115169. {pParse->constraintName = yymsp[0].minor.yy0;}
  115170. break;
  115171. case 55: /* ccons ::= DEFAULT term */
  115172. case 57: /* ccons ::= DEFAULT PLUS term */ yytestcase(yyruleno==57);
  115173. {sqlite3AddDefaultValue(pParse,&yymsp[0].minor.yy346);}
  115174. break;
  115175. case 56: /* ccons ::= DEFAULT LP expr RP */
  115176. {sqlite3AddDefaultValue(pParse,&yymsp[-1].minor.yy346);}
  115177. break;
  115178. case 58: /* ccons ::= DEFAULT MINUS term */
  115179. {
  115180. ExprSpan v;
  115181. v.pExpr = sqlite3PExpr(pParse, TK_UMINUS, yymsp[0].minor.yy346.pExpr, 0, 0);
  115182. v.zStart = yymsp[-1].minor.yy0.z;
  115183. v.zEnd = yymsp[0].minor.yy346.zEnd;
  115184. sqlite3AddDefaultValue(pParse,&v);
  115185. }
  115186. break;
  115187. case 59: /* ccons ::= DEFAULT ID|INDEXED */
  115188. {
  115189. ExprSpan v;
  115190. spanExpr(&v, pParse, TK_STRING, &yymsp[0].minor.yy0);
  115191. sqlite3AddDefaultValue(pParse,&v);
  115192. }
  115193. break;
  115194. case 61: /* ccons ::= NOT NULL onconf */
  115195. {sqlite3AddNotNull(pParse, yymsp[0].minor.yy328);}
  115196. break;
  115197. case 62: /* ccons ::= PRIMARY KEY sortorder onconf autoinc */
  115198. {sqlite3AddPrimaryKey(pParse,0,yymsp[-1].minor.yy328,yymsp[0].minor.yy328,yymsp[-2].minor.yy328);}
  115199. break;
  115200. case 63: /* ccons ::= UNIQUE onconf */
  115201. {sqlite3CreateIndex(pParse,0,0,0,0,yymsp[0].minor.yy328,0,0,0,0);}
  115202. break;
  115203. case 64: /* ccons ::= CHECK LP expr RP */
  115204. {sqlite3AddCheckConstraint(pParse,yymsp[-1].minor.yy346.pExpr);}
  115205. break;
  115206. case 65: /* ccons ::= REFERENCES nm idxlist_opt refargs */
  115207. {sqlite3CreateForeignKey(pParse,0,&yymsp[-2].minor.yy0,yymsp[-1].minor.yy14,yymsp[0].minor.yy328);}
  115208. break;
  115209. case 66: /* ccons ::= defer_subclause */
  115210. {sqlite3DeferForeignKey(pParse,yymsp[0].minor.yy328);}
  115211. break;
  115212. case 67: /* ccons ::= COLLATE ID|STRING */
  115213. {sqlite3AddCollateType(pParse, &yymsp[0].minor.yy0);}
  115214. break;
  115215. case 70: /* refargs ::= */
  115216. { yygotominor.yy328 = OE_None*0x0101; /* EV: R-19803-45884 */}
  115217. break;
  115218. case 71: /* refargs ::= refargs refarg */
  115219. { yygotominor.yy328 = (yymsp[-1].minor.yy328 & ~yymsp[0].minor.yy429.mask) | yymsp[0].minor.yy429.value; }
  115220. break;
  115221. case 72: /* refarg ::= MATCH nm */
  115222. case 73: /* refarg ::= ON INSERT refact */ yytestcase(yyruleno==73);
  115223. { yygotominor.yy429.value = 0; yygotominor.yy429.mask = 0x000000; }
  115224. break;
  115225. case 74: /* refarg ::= ON DELETE refact */
  115226. { yygotominor.yy429.value = yymsp[0].minor.yy328; yygotominor.yy429.mask = 0x0000ff; }
  115227. break;
  115228. case 75: /* refarg ::= ON UPDATE refact */
  115229. { yygotominor.yy429.value = yymsp[0].minor.yy328<<8; yygotominor.yy429.mask = 0x00ff00; }
  115230. break;
  115231. case 76: /* refact ::= SET NULL */
  115232. { yygotominor.yy328 = OE_SetNull; /* EV: R-33326-45252 */}
  115233. break;
  115234. case 77: /* refact ::= SET DEFAULT */
  115235. { yygotominor.yy328 = OE_SetDflt; /* EV: R-33326-45252 */}
  115236. break;
  115237. case 78: /* refact ::= CASCADE */
  115238. { yygotominor.yy328 = OE_Cascade; /* EV: R-33326-45252 */}
  115239. break;
  115240. case 79: /* refact ::= RESTRICT */
  115241. { yygotominor.yy328 = OE_Restrict; /* EV: R-33326-45252 */}
  115242. break;
  115243. case 80: /* refact ::= NO ACTION */
  115244. { yygotominor.yy328 = OE_None; /* EV: R-33326-45252 */}
  115245. break;
  115246. case 82: /* defer_subclause ::= DEFERRABLE init_deferred_pred_opt */
  115247. case 98: /* defer_subclause_opt ::= defer_subclause */ yytestcase(yyruleno==98);
  115248. case 100: /* onconf ::= ON CONFLICT resolvetype */ yytestcase(yyruleno==100);
  115249. case 103: /* resolvetype ::= raisetype */ yytestcase(yyruleno==103);
  115250. {yygotominor.yy328 = yymsp[0].minor.yy328;}
  115251. break;
  115252. case 86: /* conslist_opt ::= */
  115253. {yygotominor.yy0.n = 0; yygotominor.yy0.z = 0;}
  115254. break;
  115255. case 87: /* conslist_opt ::= COMMA conslist */
  115256. {yygotominor.yy0 = yymsp[-1].minor.yy0;}
  115257. break;
  115258. case 90: /* tconscomma ::= COMMA */
  115259. {pParse->constraintName.n = 0;}
  115260. break;
  115261. case 93: /* tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf */
  115262. {sqlite3AddPrimaryKey(pParse,yymsp[-3].minor.yy14,yymsp[0].minor.yy328,yymsp[-2].minor.yy328,0);}
  115263. break;
  115264. case 94: /* tcons ::= UNIQUE LP idxlist RP onconf */
  115265. {sqlite3CreateIndex(pParse,0,0,0,yymsp[-2].minor.yy14,yymsp[0].minor.yy328,0,0,0,0);}
  115266. break;
  115267. case 95: /* tcons ::= CHECK LP expr RP onconf */
  115268. {sqlite3AddCheckConstraint(pParse,yymsp[-2].minor.yy346.pExpr);}
  115269. break;
  115270. case 96: /* tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt */
  115271. {
  115272. sqlite3CreateForeignKey(pParse, yymsp[-6].minor.yy14, &yymsp[-3].minor.yy0, yymsp[-2].minor.yy14, yymsp[-1].minor.yy328);
  115273. sqlite3DeferForeignKey(pParse, yymsp[0].minor.yy328);
  115274. }
  115275. break;
  115276. case 99: /* onconf ::= */
  115277. {yygotominor.yy328 = OE_Default;}
  115278. break;
  115279. case 101: /* orconf ::= */
  115280. {yygotominor.yy186 = OE_Default;}
  115281. break;
  115282. case 102: /* orconf ::= OR resolvetype */
  115283. {yygotominor.yy186 = (u8)yymsp[0].minor.yy328;}
  115284. break;
  115285. case 104: /* resolvetype ::= IGNORE */
  115286. {yygotominor.yy328 = OE_Ignore;}
  115287. break;
  115288. case 105: /* resolvetype ::= REPLACE */
  115289. {yygotominor.yy328 = OE_Replace;}
  115290. break;
  115291. case 106: /* cmd ::= DROP TABLE ifexists fullname */
  115292. {
  115293. sqlite3DropTable(pParse, yymsp[0].minor.yy65, 0, yymsp[-1].minor.yy328);
  115294. }
  115295. break;
  115296. case 109: /* cmd ::= createkw temp VIEW ifnotexists nm dbnm AS select */
  115297. {
  115298. 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);
  115299. }
  115300. break;
  115301. case 110: /* cmd ::= DROP VIEW ifexists fullname */
  115302. {
  115303. sqlite3DropTable(pParse, yymsp[0].minor.yy65, 1, yymsp[-1].minor.yy328);
  115304. }
  115305. break;
  115306. case 111: /* cmd ::= select */
  115307. {
  115308. SelectDest dest = {SRT_Output, 0, 0, 0, 0, 0};
  115309. sqlite3Select(pParse, yymsp[0].minor.yy3, &dest);
  115310. sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy3);
  115311. }
  115312. break;
  115313. case 112: /* select ::= with selectnowith */
  115314. {
  115315. Select *p = yymsp[0].minor.yy3, *pNext, *pLoop;
  115316. if( p ){
  115317. int cnt = 0, mxSelect;
  115318. p->pWith = yymsp[-1].minor.yy59;
  115319. if( p->pPrior ){
  115320. pNext = 0;
  115321. for(pLoop=p; pLoop; pNext=pLoop, pLoop=pLoop->pPrior, cnt++){
  115322. pLoop->pNext = pNext;
  115323. pLoop->selFlags |= SF_Compound;
  115324. }
  115325. mxSelect = pParse->db->aLimit[SQLITE_LIMIT_COMPOUND_SELECT];
  115326. if( mxSelect && cnt>mxSelect ){
  115327. sqlite3ErrorMsg(pParse, "too many terms in compound SELECT");
  115328. }
  115329. }
  115330. }else{
  115331. sqlite3WithDelete(pParse->db, yymsp[-1].minor.yy59);
  115332. }
  115333. yygotominor.yy3 = p;
  115334. }
  115335. break;
  115336. case 113: /* selectnowith ::= oneselect */
  115337. case 119: /* oneselect ::= values */ yytestcase(yyruleno==119);
  115338. {yygotominor.yy3 = yymsp[0].minor.yy3;}
  115339. break;
  115340. case 114: /* selectnowith ::= selectnowith multiselect_op oneselect */
  115341. {
  115342. Select *pRhs = yymsp[0].minor.yy3;
  115343. if( pRhs && pRhs->pPrior ){
  115344. SrcList *pFrom;
  115345. Token x;
  115346. x.n = 0;
  115347. pFrom = sqlite3SrcListAppendFromTerm(pParse,0,0,0,&x,pRhs,0,0);
  115348. pRhs = sqlite3SelectNew(pParse,0,pFrom,0,0,0,0,0,0,0);
  115349. }
  115350. if( pRhs ){
  115351. pRhs->op = (u8)yymsp[-1].minor.yy328;
  115352. pRhs->pPrior = yymsp[-2].minor.yy3;
  115353. if( yymsp[-1].minor.yy328!=TK_ALL ) pParse->hasCompound = 1;
  115354. }else{
  115355. sqlite3SelectDelete(pParse->db, yymsp[-2].minor.yy3);
  115356. }
  115357. yygotominor.yy3 = pRhs;
  115358. }
  115359. break;
  115360. case 116: /* multiselect_op ::= UNION ALL */
  115361. {yygotominor.yy328 = TK_ALL;}
  115362. break;
  115363. case 118: /* oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt */
  115364. {
  115365. 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);
  115366. #if SELECTTRACE_ENABLED
  115367. /* Populate the Select.zSelName[] string that is used to help with
  115368. ** query planner debugging, to differentiate between multiple Select
  115369. ** objects in a complex query.
  115370. **
  115371. ** If the SELECT keyword is immediately followed by a C-style comment
  115372. ** then extract the first few alphanumeric characters from within that
  115373. ** comment to be the zSelName value. Otherwise, the label is #N where
  115374. ** is an integer that is incremented with each SELECT statement seen.
  115375. */
  115376. if( yygotominor.yy3!=0 ){
  115377. const char *z = yymsp[-8].minor.yy0.z+6;
  115378. int i;
  115379. sqlite3_snprintf(sizeof(yygotominor.yy3->zSelName), yygotominor.yy3->zSelName, "#%d",
  115380. ++pParse->nSelect);
  115381. while( z[0]==' ' ) z++;
  115382. if( z[0]=='/' && z[1]=='*' ){
  115383. z += 2;
  115384. while( z[0]==' ' ) z++;
  115385. for(i=0; sqlite3Isalnum(z[i]); i++){}
  115386. sqlite3_snprintf(sizeof(yygotominor.yy3->zSelName), yygotominor.yy3->zSelName, "%.*s", i, z);
  115387. }
  115388. }
  115389. #endif /* SELECTRACE_ENABLED */
  115390. }
  115391. break;
  115392. case 120: /* values ::= VALUES LP nexprlist RP */
  115393. {
  115394. yygotominor.yy3 = sqlite3SelectNew(pParse,yymsp[-1].minor.yy14,0,0,0,0,0,SF_Values,0,0);
  115395. }
  115396. break;
  115397. case 121: /* values ::= values COMMA LP exprlist RP */
  115398. {
  115399. Select *pRight = sqlite3SelectNew(pParse,yymsp[-1].minor.yy14,0,0,0,0,0,SF_Values,0,0);
  115400. if( pRight ){
  115401. pRight->op = TK_ALL;
  115402. pRight->pPrior = yymsp[-4].minor.yy3;
  115403. yygotominor.yy3 = pRight;
  115404. }else{
  115405. yygotominor.yy3 = yymsp[-4].minor.yy3;
  115406. }
  115407. }
  115408. break;
  115409. case 122: /* distinct ::= DISTINCT */
  115410. {yygotominor.yy381 = SF_Distinct;}
  115411. break;
  115412. case 123: /* distinct ::= ALL */
  115413. case 124: /* distinct ::= */ yytestcase(yyruleno==124);
  115414. {yygotominor.yy381 = 0;}
  115415. break;
  115416. case 125: /* sclp ::= selcollist COMMA */
  115417. case 243: /* idxlist_opt ::= LP idxlist RP */ yytestcase(yyruleno==243);
  115418. {yygotominor.yy14 = yymsp[-1].minor.yy14;}
  115419. break;
  115420. case 126: /* sclp ::= */
  115421. case 154: /* orderby_opt ::= */ yytestcase(yyruleno==154);
  115422. case 161: /* groupby_opt ::= */ yytestcase(yyruleno==161);
  115423. case 236: /* exprlist ::= */ yytestcase(yyruleno==236);
  115424. case 242: /* idxlist_opt ::= */ yytestcase(yyruleno==242);
  115425. {yygotominor.yy14 = 0;}
  115426. break;
  115427. case 127: /* selcollist ::= sclp expr as */
  115428. {
  115429. yygotominor.yy14 = sqlite3ExprListAppend(pParse, yymsp[-2].minor.yy14, yymsp[-1].minor.yy346.pExpr);
  115430. if( yymsp[0].minor.yy0.n>0 ) sqlite3ExprListSetName(pParse, yygotominor.yy14, &yymsp[0].minor.yy0, 1);
  115431. sqlite3ExprListSetSpan(pParse,yygotominor.yy14,&yymsp[-1].minor.yy346);
  115432. }
  115433. break;
  115434. case 128: /* selcollist ::= sclp STAR */
  115435. {
  115436. Expr *p = sqlite3Expr(pParse->db, TK_ALL, 0);
  115437. yygotominor.yy14 = sqlite3ExprListAppend(pParse, yymsp[-1].minor.yy14, p);
  115438. }
  115439. break;
  115440. case 129: /* selcollist ::= sclp nm DOT STAR */
  115441. {
  115442. Expr *pRight = sqlite3PExpr(pParse, TK_ALL, 0, 0, &yymsp[0].minor.yy0);
  115443. Expr *pLeft = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
  115444. Expr *pDot = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
  115445. yygotominor.yy14 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy14, pDot);
  115446. }
  115447. break;
  115448. case 132: /* as ::= */
  115449. {yygotominor.yy0.n = 0;}
  115450. break;
  115451. case 133: /* from ::= */
  115452. {yygotominor.yy65 = sqlite3DbMallocZero(pParse->db, sizeof(*yygotominor.yy65));}
  115453. break;
  115454. case 134: /* from ::= FROM seltablist */
  115455. {
  115456. yygotominor.yy65 = yymsp[0].minor.yy65;
  115457. sqlite3SrcListShiftJoinType(yygotominor.yy65);
  115458. }
  115459. break;
  115460. case 135: /* stl_prefix ::= seltablist joinop */
  115461. {
  115462. yygotominor.yy65 = yymsp[-1].minor.yy65;
  115463. if( ALWAYS(yygotominor.yy65 && yygotominor.yy65->nSrc>0) ) yygotominor.yy65->a[yygotominor.yy65->nSrc-1].jointype = (u8)yymsp[0].minor.yy328;
  115464. }
  115465. break;
  115466. case 136: /* stl_prefix ::= */
  115467. {yygotominor.yy65 = 0;}
  115468. break;
  115469. case 137: /* seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt */
  115470. {
  115471. 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);
  115472. sqlite3SrcListIndexedBy(pParse, yygotominor.yy65, &yymsp[-2].minor.yy0);
  115473. }
  115474. break;
  115475. case 138: /* seltablist ::= stl_prefix LP select RP as on_opt using_opt */
  115476. {
  115477. 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);
  115478. }
  115479. break;
  115480. case 139: /* seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt */
  115481. {
  115482. if( yymsp[-6].minor.yy65==0 && yymsp[-2].minor.yy0.n==0 && yymsp[-1].minor.yy132==0 && yymsp[0].minor.yy408==0 ){
  115483. yygotominor.yy65 = yymsp[-4].minor.yy65;
  115484. }else if( yymsp[-4].minor.yy65->nSrc==1 ){
  115485. yygotominor.yy65 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy65,0,0,&yymsp[-2].minor.yy0,0,yymsp[-1].minor.yy132,yymsp[0].minor.yy408);
  115486. if( yygotominor.yy65 ){
  115487. struct SrcList_item *pNew = &yygotominor.yy65->a[yygotominor.yy65->nSrc-1];
  115488. struct SrcList_item *pOld = yymsp[-4].minor.yy65->a;
  115489. pNew->zName = pOld->zName;
  115490. pNew->zDatabase = pOld->zDatabase;
  115491. pNew->pSelect = pOld->pSelect;
  115492. pOld->zName = pOld->zDatabase = 0;
  115493. pOld->pSelect = 0;
  115494. }
  115495. sqlite3SrcListDelete(pParse->db, yymsp[-4].minor.yy65);
  115496. }else{
  115497. Select *pSubquery;
  115498. sqlite3SrcListShiftJoinType(yymsp[-4].minor.yy65);
  115499. pSubquery = sqlite3SelectNew(pParse,0,yymsp[-4].minor.yy65,0,0,0,0,SF_NestedFrom,0,0);
  115500. yygotominor.yy65 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy65,0,0,&yymsp[-2].minor.yy0,pSubquery,yymsp[-1].minor.yy132,yymsp[0].minor.yy408);
  115501. }
  115502. }
  115503. break;
  115504. case 140: /* dbnm ::= */
  115505. case 149: /* indexed_opt ::= */ yytestcase(yyruleno==149);
  115506. {yygotominor.yy0.z=0; yygotominor.yy0.n=0;}
  115507. break;
  115508. case 142: /* fullname ::= nm dbnm */
  115509. {yygotominor.yy65 = sqlite3SrcListAppend(pParse->db,0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);}
  115510. break;
  115511. case 143: /* joinop ::= COMMA|JOIN */
  115512. { yygotominor.yy328 = JT_INNER; }
  115513. break;
  115514. case 144: /* joinop ::= JOIN_KW JOIN */
  115515. { yygotominor.yy328 = sqlite3JoinType(pParse,&yymsp[-1].minor.yy0,0,0); }
  115516. break;
  115517. case 145: /* joinop ::= JOIN_KW nm JOIN */
  115518. { yygotominor.yy328 = sqlite3JoinType(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,0); }
  115519. break;
  115520. case 146: /* joinop ::= JOIN_KW nm nm JOIN */
  115521. { yygotominor.yy328 = sqlite3JoinType(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0); }
  115522. break;
  115523. case 147: /* on_opt ::= ON expr */
  115524. case 164: /* having_opt ::= HAVING expr */ yytestcase(yyruleno==164);
  115525. case 171: /* where_opt ::= WHERE expr */ yytestcase(yyruleno==171);
  115526. case 231: /* case_else ::= ELSE expr */ yytestcase(yyruleno==231);
  115527. case 233: /* case_operand ::= expr */ yytestcase(yyruleno==233);
  115528. {yygotominor.yy132 = yymsp[0].minor.yy346.pExpr;}
  115529. break;
  115530. case 148: /* on_opt ::= */
  115531. case 163: /* having_opt ::= */ yytestcase(yyruleno==163);
  115532. case 170: /* where_opt ::= */ yytestcase(yyruleno==170);
  115533. case 232: /* case_else ::= */ yytestcase(yyruleno==232);
  115534. case 234: /* case_operand ::= */ yytestcase(yyruleno==234);
  115535. {yygotominor.yy132 = 0;}
  115536. break;
  115537. case 151: /* indexed_opt ::= NOT INDEXED */
  115538. {yygotominor.yy0.z=0; yygotominor.yy0.n=1;}
  115539. break;
  115540. case 152: /* using_opt ::= USING LP idlist RP */
  115541. case 180: /* inscollist_opt ::= LP idlist RP */ yytestcase(yyruleno==180);
  115542. {yygotominor.yy408 = yymsp[-1].minor.yy408;}
  115543. break;
  115544. case 153: /* using_opt ::= */
  115545. case 179: /* inscollist_opt ::= */ yytestcase(yyruleno==179);
  115546. {yygotominor.yy408 = 0;}
  115547. break;
  115548. case 155: /* orderby_opt ::= ORDER BY sortlist */
  115549. case 162: /* groupby_opt ::= GROUP BY nexprlist */ yytestcase(yyruleno==162);
  115550. case 235: /* exprlist ::= nexprlist */ yytestcase(yyruleno==235);
  115551. {yygotominor.yy14 = yymsp[0].minor.yy14;}
  115552. break;
  115553. case 156: /* sortlist ::= sortlist COMMA expr sortorder */
  115554. {
  115555. yygotominor.yy14 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy14,yymsp[-1].minor.yy346.pExpr);
  115556. if( yygotominor.yy14 ) yygotominor.yy14->a[yygotominor.yy14->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy328;
  115557. }
  115558. break;
  115559. case 157: /* sortlist ::= expr sortorder */
  115560. {
  115561. yygotominor.yy14 = sqlite3ExprListAppend(pParse,0,yymsp[-1].minor.yy346.pExpr);
  115562. if( yygotominor.yy14 && ALWAYS(yygotominor.yy14->a) ) yygotominor.yy14->a[0].sortOrder = (u8)yymsp[0].minor.yy328;
  115563. }
  115564. break;
  115565. case 158: /* sortorder ::= ASC */
  115566. case 160: /* sortorder ::= */ yytestcase(yyruleno==160);
  115567. {yygotominor.yy328 = SQLITE_SO_ASC;}
  115568. break;
  115569. case 159: /* sortorder ::= DESC */
  115570. {yygotominor.yy328 = SQLITE_SO_DESC;}
  115571. break;
  115572. case 165: /* limit_opt ::= */
  115573. {yygotominor.yy476.pLimit = 0; yygotominor.yy476.pOffset = 0;}
  115574. break;
  115575. case 166: /* limit_opt ::= LIMIT expr */
  115576. {yygotominor.yy476.pLimit = yymsp[0].minor.yy346.pExpr; yygotominor.yy476.pOffset = 0;}
  115577. break;
  115578. case 167: /* limit_opt ::= LIMIT expr OFFSET expr */
  115579. {yygotominor.yy476.pLimit = yymsp[-2].minor.yy346.pExpr; yygotominor.yy476.pOffset = yymsp[0].minor.yy346.pExpr;}
  115580. break;
  115581. case 168: /* limit_opt ::= LIMIT expr COMMA expr */
  115582. {yygotominor.yy476.pOffset = yymsp[-2].minor.yy346.pExpr; yygotominor.yy476.pLimit = yymsp[0].minor.yy346.pExpr;}
  115583. break;
  115584. case 169: /* cmd ::= with DELETE FROM fullname indexed_opt where_opt */
  115585. {
  115586. sqlite3WithPush(pParse, yymsp[-5].minor.yy59, 1);
  115587. sqlite3SrcListIndexedBy(pParse, yymsp[-2].minor.yy65, &yymsp[-1].minor.yy0);
  115588. sqlite3DeleteFrom(pParse,yymsp[-2].minor.yy65,yymsp[0].minor.yy132);
  115589. }
  115590. break;
  115591. case 172: /* cmd ::= with UPDATE orconf fullname indexed_opt SET setlist where_opt */
  115592. {
  115593. sqlite3WithPush(pParse, yymsp[-7].minor.yy59, 1);
  115594. sqlite3SrcListIndexedBy(pParse, yymsp[-4].minor.yy65, &yymsp[-3].minor.yy0);
  115595. sqlite3ExprListCheckLength(pParse,yymsp[-1].minor.yy14,"set list");
  115596. sqlite3Update(pParse,yymsp[-4].minor.yy65,yymsp[-1].minor.yy14,yymsp[0].minor.yy132,yymsp[-5].minor.yy186);
  115597. }
  115598. break;
  115599. case 173: /* setlist ::= setlist COMMA nm EQ expr */
  115600. {
  115601. yygotominor.yy14 = sqlite3ExprListAppend(pParse, yymsp[-4].minor.yy14, yymsp[0].minor.yy346.pExpr);
  115602. sqlite3ExprListSetName(pParse, yygotominor.yy14, &yymsp[-2].minor.yy0, 1);
  115603. }
  115604. break;
  115605. case 174: /* setlist ::= nm EQ expr */
  115606. {
  115607. yygotominor.yy14 = sqlite3ExprListAppend(pParse, 0, yymsp[0].minor.yy346.pExpr);
  115608. sqlite3ExprListSetName(pParse, yygotominor.yy14, &yymsp[-2].minor.yy0, 1);
  115609. }
  115610. break;
  115611. case 175: /* cmd ::= with insert_cmd INTO fullname inscollist_opt select */
  115612. {
  115613. sqlite3WithPush(pParse, yymsp[-5].minor.yy59, 1);
  115614. sqlite3Insert(pParse, yymsp[-2].minor.yy65, yymsp[0].minor.yy3, yymsp[-1].minor.yy408, yymsp[-4].minor.yy186);
  115615. }
  115616. break;
  115617. case 176: /* cmd ::= with insert_cmd INTO fullname inscollist_opt DEFAULT VALUES */
  115618. {
  115619. sqlite3WithPush(pParse, yymsp[-6].minor.yy59, 1);
  115620. sqlite3Insert(pParse, yymsp[-3].minor.yy65, 0, yymsp[-2].minor.yy408, yymsp[-5].minor.yy186);
  115621. }
  115622. break;
  115623. case 177: /* insert_cmd ::= INSERT orconf */
  115624. {yygotominor.yy186 = yymsp[0].minor.yy186;}
  115625. break;
  115626. case 178: /* insert_cmd ::= REPLACE */
  115627. {yygotominor.yy186 = OE_Replace;}
  115628. break;
  115629. case 181: /* idlist ::= idlist COMMA nm */
  115630. {yygotominor.yy408 = sqlite3IdListAppend(pParse->db,yymsp[-2].minor.yy408,&yymsp[0].minor.yy0);}
  115631. break;
  115632. case 182: /* idlist ::= nm */
  115633. {yygotominor.yy408 = sqlite3IdListAppend(pParse->db,0,&yymsp[0].minor.yy0);}
  115634. break;
  115635. case 183: /* expr ::= term */
  115636. {yygotominor.yy346 = yymsp[0].minor.yy346;}
  115637. break;
  115638. case 184: /* expr ::= LP expr RP */
  115639. {yygotominor.yy346.pExpr = yymsp[-1].minor.yy346.pExpr; spanSet(&yygotominor.yy346,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);}
  115640. break;
  115641. case 185: /* term ::= NULL */
  115642. case 190: /* term ::= INTEGER|FLOAT|BLOB */ yytestcase(yyruleno==190);
  115643. case 191: /* term ::= STRING */ yytestcase(yyruleno==191);
  115644. {spanExpr(&yygotominor.yy346, pParse, yymsp[0].major, &yymsp[0].minor.yy0);}
  115645. break;
  115646. case 186: /* expr ::= ID|INDEXED */
  115647. case 187: /* expr ::= JOIN_KW */ yytestcase(yyruleno==187);
  115648. {spanExpr(&yygotominor.yy346, pParse, TK_ID, &yymsp[0].minor.yy0);}
  115649. break;
  115650. case 188: /* expr ::= nm DOT nm */
  115651. {
  115652. Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
  115653. Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
  115654. yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp2, 0);
  115655. spanSet(&yygotominor.yy346,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);
  115656. }
  115657. break;
  115658. case 189: /* expr ::= nm DOT nm DOT nm */
  115659. {
  115660. Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-4].minor.yy0);
  115661. Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
  115662. Expr *temp3 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
  115663. Expr *temp4 = sqlite3PExpr(pParse, TK_DOT, temp2, temp3, 0);
  115664. yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp4, 0);
  115665. spanSet(&yygotominor.yy346,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
  115666. }
  115667. break;
  115668. case 192: /* expr ::= VARIABLE */
  115669. {
  115670. if( yymsp[0].minor.yy0.n>=2 && yymsp[0].minor.yy0.z[0]=='#' && sqlite3Isdigit(yymsp[0].minor.yy0.z[1]) ){
  115671. /* When doing a nested parse, one can include terms in an expression
  115672. ** that look like this: #1 #2 ... These terms refer to registers
  115673. ** in the virtual machine. #N is the N-th register. */
  115674. if( pParse->nested==0 ){
  115675. sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &yymsp[0].minor.yy0);
  115676. yygotominor.yy346.pExpr = 0;
  115677. }else{
  115678. yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_REGISTER, 0, 0, &yymsp[0].minor.yy0);
  115679. if( yygotominor.yy346.pExpr ) sqlite3GetInt32(&yymsp[0].minor.yy0.z[1], &yygotominor.yy346.pExpr->iTable);
  115680. }
  115681. }else{
  115682. spanExpr(&yygotominor.yy346, pParse, TK_VARIABLE, &yymsp[0].minor.yy0);
  115683. sqlite3ExprAssignVarNumber(pParse, yygotominor.yy346.pExpr);
  115684. }
  115685. spanSet(&yygotominor.yy346, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
  115686. }
  115687. break;
  115688. case 193: /* expr ::= expr COLLATE ID|STRING */
  115689. {
  115690. yygotominor.yy346.pExpr = sqlite3ExprAddCollateToken(pParse, yymsp[-2].minor.yy346.pExpr, &yymsp[0].minor.yy0);
  115691. yygotominor.yy346.zStart = yymsp[-2].minor.yy346.zStart;
  115692. yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
  115693. }
  115694. break;
  115695. case 194: /* expr ::= CAST LP expr AS typetoken RP */
  115696. {
  115697. yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_CAST, yymsp[-3].minor.yy346.pExpr, 0, &yymsp[-1].minor.yy0);
  115698. spanSet(&yygotominor.yy346,&yymsp[-5].minor.yy0,&yymsp[0].minor.yy0);
  115699. }
  115700. break;
  115701. case 195: /* expr ::= ID|INDEXED LP distinct exprlist RP */
  115702. {
  115703. if( yymsp[-1].minor.yy14 && yymsp[-1].minor.yy14->nExpr>pParse->db->aLimit[SQLITE_LIMIT_FUNCTION_ARG] ){
  115704. sqlite3ErrorMsg(pParse, "too many arguments on function %T", &yymsp[-4].minor.yy0);
  115705. }
  115706. yygotominor.yy346.pExpr = sqlite3ExprFunction(pParse, yymsp[-1].minor.yy14, &yymsp[-4].minor.yy0);
  115707. spanSet(&yygotominor.yy346,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
  115708. if( yymsp[-2].minor.yy381 && yygotominor.yy346.pExpr ){
  115709. yygotominor.yy346.pExpr->flags |= EP_Distinct;
  115710. }
  115711. }
  115712. break;
  115713. case 196: /* expr ::= ID|INDEXED LP STAR RP */
  115714. {
  115715. yygotominor.yy346.pExpr = sqlite3ExprFunction(pParse, 0, &yymsp[-3].minor.yy0);
  115716. spanSet(&yygotominor.yy346,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0);
  115717. }
  115718. break;
  115719. case 197: /* term ::= CTIME_KW */
  115720. {
  115721. yygotominor.yy346.pExpr = sqlite3ExprFunction(pParse, 0, &yymsp[0].minor.yy0);
  115722. spanSet(&yygotominor.yy346, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
  115723. }
  115724. break;
  115725. case 198: /* expr ::= expr AND expr */
  115726. case 199: /* expr ::= expr OR expr */ yytestcase(yyruleno==199);
  115727. case 200: /* expr ::= expr LT|GT|GE|LE expr */ yytestcase(yyruleno==200);
  115728. case 201: /* expr ::= expr EQ|NE expr */ yytestcase(yyruleno==201);
  115729. case 202: /* expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */ yytestcase(yyruleno==202);
  115730. case 203: /* expr ::= expr PLUS|MINUS expr */ yytestcase(yyruleno==203);
  115731. case 204: /* expr ::= expr STAR|SLASH|REM expr */ yytestcase(yyruleno==204);
  115732. case 205: /* expr ::= expr CONCAT expr */ yytestcase(yyruleno==205);
  115733. {spanBinaryExpr(&yygotominor.yy346,pParse,yymsp[-1].major,&yymsp[-2].minor.yy346,&yymsp[0].minor.yy346);}
  115734. break;
  115735. case 206: /* likeop ::= LIKE_KW|MATCH */
  115736. {yygotominor.yy96.eOperator = yymsp[0].minor.yy0; yygotominor.yy96.bNot = 0;}
  115737. break;
  115738. case 207: /* likeop ::= NOT LIKE_KW|MATCH */
  115739. {yygotominor.yy96.eOperator = yymsp[0].minor.yy0; yygotominor.yy96.bNot = 1;}
  115740. break;
  115741. case 208: /* expr ::= expr likeop expr */
  115742. {
  115743. ExprList *pList;
  115744. pList = sqlite3ExprListAppend(pParse,0, yymsp[0].minor.yy346.pExpr);
  115745. pList = sqlite3ExprListAppend(pParse,pList, yymsp[-2].minor.yy346.pExpr);
  115746. yygotominor.yy346.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-1].minor.yy96.eOperator);
  115747. if( yymsp[-1].minor.yy96.bNot ) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0);
  115748. yygotominor.yy346.zStart = yymsp[-2].minor.yy346.zStart;
  115749. yygotominor.yy346.zEnd = yymsp[0].minor.yy346.zEnd;
  115750. if( yygotominor.yy346.pExpr ) yygotominor.yy346.pExpr->flags |= EP_InfixFunc;
  115751. }
  115752. break;
  115753. case 209: /* expr ::= expr likeop expr ESCAPE expr */
  115754. {
  115755. ExprList *pList;
  115756. pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy346.pExpr);
  115757. pList = sqlite3ExprListAppend(pParse,pList, yymsp[-4].minor.yy346.pExpr);
  115758. pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy346.pExpr);
  115759. yygotominor.yy346.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-3].minor.yy96.eOperator);
  115760. if( yymsp[-3].minor.yy96.bNot ) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0);
  115761. yygotominor.yy346.zStart = yymsp[-4].minor.yy346.zStart;
  115762. yygotominor.yy346.zEnd = yymsp[0].minor.yy346.zEnd;
  115763. if( yygotominor.yy346.pExpr ) yygotominor.yy346.pExpr->flags |= EP_InfixFunc;
  115764. }
  115765. break;
  115766. case 210: /* expr ::= expr ISNULL|NOTNULL */
  115767. {spanUnaryPostfix(&yygotominor.yy346,pParse,yymsp[0].major,&yymsp[-1].minor.yy346,&yymsp[0].minor.yy0);}
  115768. break;
  115769. case 211: /* expr ::= expr NOT NULL */
  115770. {spanUnaryPostfix(&yygotominor.yy346,pParse,TK_NOTNULL,&yymsp[-2].minor.yy346,&yymsp[0].minor.yy0);}
  115771. break;
  115772. case 212: /* expr ::= expr IS expr */
  115773. {
  115774. spanBinaryExpr(&yygotominor.yy346,pParse,TK_IS,&yymsp[-2].minor.yy346,&yymsp[0].minor.yy346);
  115775. binaryToUnaryIfNull(pParse, yymsp[0].minor.yy346.pExpr, yygotominor.yy346.pExpr, TK_ISNULL);
  115776. }
  115777. break;
  115778. case 213: /* expr ::= expr IS NOT expr */
  115779. {
  115780. spanBinaryExpr(&yygotominor.yy346,pParse,TK_ISNOT,&yymsp[-3].minor.yy346,&yymsp[0].minor.yy346);
  115781. binaryToUnaryIfNull(pParse, yymsp[0].minor.yy346.pExpr, yygotominor.yy346.pExpr, TK_NOTNULL);
  115782. }
  115783. break;
  115784. case 214: /* expr ::= NOT expr */
  115785. case 215: /* expr ::= BITNOT expr */ yytestcase(yyruleno==215);
  115786. {spanUnaryPrefix(&yygotominor.yy346,pParse,yymsp[-1].major,&yymsp[0].minor.yy346,&yymsp[-1].minor.yy0);}
  115787. break;
  115788. case 216: /* expr ::= MINUS expr */
  115789. {spanUnaryPrefix(&yygotominor.yy346,pParse,TK_UMINUS,&yymsp[0].minor.yy346,&yymsp[-1].minor.yy0);}
  115790. break;
  115791. case 217: /* expr ::= PLUS expr */
  115792. {spanUnaryPrefix(&yygotominor.yy346,pParse,TK_UPLUS,&yymsp[0].minor.yy346,&yymsp[-1].minor.yy0);}
  115793. break;
  115794. case 220: /* expr ::= expr between_op expr AND expr */
  115795. {
  115796. ExprList *pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy346.pExpr);
  115797. pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy346.pExpr);
  115798. yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_BETWEEN, yymsp[-4].minor.yy346.pExpr, 0, 0);
  115799. if( yygotominor.yy346.pExpr ){
  115800. yygotominor.yy346.pExpr->x.pList = pList;
  115801. }else{
  115802. sqlite3ExprListDelete(pParse->db, pList);
  115803. }
  115804. if( yymsp[-3].minor.yy328 ) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0);
  115805. yygotominor.yy346.zStart = yymsp[-4].minor.yy346.zStart;
  115806. yygotominor.yy346.zEnd = yymsp[0].minor.yy346.zEnd;
  115807. }
  115808. break;
  115809. case 223: /* expr ::= expr in_op LP exprlist RP */
  115810. {
  115811. if( yymsp[-1].minor.yy14==0 ){
  115812. /* Expressions of the form
  115813. **
  115814. ** expr1 IN ()
  115815. ** expr1 NOT IN ()
  115816. **
  115817. ** simplify to constants 0 (false) and 1 (true), respectively,
  115818. ** regardless of the value of expr1.
  115819. */
  115820. yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_INTEGER, 0, 0, &sqlite3IntTokens[yymsp[-3].minor.yy328]);
  115821. sqlite3ExprDelete(pParse->db, yymsp[-4].minor.yy346.pExpr);
  115822. }else if( yymsp[-1].minor.yy14->nExpr==1 ){
  115823. /* Expressions of the form:
  115824. **
  115825. ** expr1 IN (?1)
  115826. ** expr1 NOT IN (?2)
  115827. **
  115828. ** with exactly one value on the RHS can be simplified to something
  115829. ** like this:
  115830. **
  115831. ** expr1 == ?1
  115832. ** expr1 <> ?2
  115833. **
  115834. ** But, the RHS of the == or <> is marked with the EP_Generic flag
  115835. ** so that it may not contribute to the computation of comparison
  115836. ** affinity or the collating sequence to use for comparison. Otherwise,
  115837. ** the semantics would be subtly different from IN or NOT IN.
  115838. */
  115839. Expr *pRHS = yymsp[-1].minor.yy14->a[0].pExpr;
  115840. yymsp[-1].minor.yy14->a[0].pExpr = 0;
  115841. sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy14);
  115842. /* pRHS cannot be NULL because a malloc error would have been detected
  115843. ** before now and control would have never reached this point */
  115844. if( ALWAYS(pRHS) ){
  115845. pRHS->flags &= ~EP_Collate;
  115846. pRHS->flags |= EP_Generic;
  115847. }
  115848. yygotominor.yy346.pExpr = sqlite3PExpr(pParse, yymsp[-3].minor.yy328 ? TK_NE : TK_EQ, yymsp[-4].minor.yy346.pExpr, pRHS, 0);
  115849. }else{
  115850. yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy346.pExpr, 0, 0);
  115851. if( yygotominor.yy346.pExpr ){
  115852. yygotominor.yy346.pExpr->x.pList = yymsp[-1].minor.yy14;
  115853. sqlite3ExprSetHeight(pParse, yygotominor.yy346.pExpr);
  115854. }else{
  115855. sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy14);
  115856. }
  115857. if( yymsp[-3].minor.yy328 ) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0);
  115858. }
  115859. yygotominor.yy346.zStart = yymsp[-4].minor.yy346.zStart;
  115860. yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
  115861. }
  115862. break;
  115863. case 224: /* expr ::= LP select RP */
  115864. {
  115865. yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_SELECT, 0, 0, 0);
  115866. if( yygotominor.yy346.pExpr ){
  115867. yygotominor.yy346.pExpr->x.pSelect = yymsp[-1].minor.yy3;
  115868. ExprSetProperty(yygotominor.yy346.pExpr, EP_xIsSelect);
  115869. sqlite3ExprSetHeight(pParse, yygotominor.yy346.pExpr);
  115870. }else{
  115871. sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy3);
  115872. }
  115873. yygotominor.yy346.zStart = yymsp[-2].minor.yy0.z;
  115874. yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
  115875. }
  115876. break;
  115877. case 225: /* expr ::= expr in_op LP select RP */
  115878. {
  115879. yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy346.pExpr, 0, 0);
  115880. if( yygotominor.yy346.pExpr ){
  115881. yygotominor.yy346.pExpr->x.pSelect = yymsp[-1].minor.yy3;
  115882. ExprSetProperty(yygotominor.yy346.pExpr, EP_xIsSelect);
  115883. sqlite3ExprSetHeight(pParse, yygotominor.yy346.pExpr);
  115884. }else{
  115885. sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy3);
  115886. }
  115887. if( yymsp[-3].minor.yy328 ) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0);
  115888. yygotominor.yy346.zStart = yymsp[-4].minor.yy346.zStart;
  115889. yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
  115890. }
  115891. break;
  115892. case 226: /* expr ::= expr in_op nm dbnm */
  115893. {
  115894. SrcList *pSrc = sqlite3SrcListAppend(pParse->db, 0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);
  115895. yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-3].minor.yy346.pExpr, 0, 0);
  115896. if( yygotominor.yy346.pExpr ){
  115897. yygotominor.yy346.pExpr->x.pSelect = sqlite3SelectNew(pParse, 0,pSrc,0,0,0,0,0,0,0);
  115898. ExprSetProperty(yygotominor.yy346.pExpr, EP_xIsSelect);
  115899. sqlite3ExprSetHeight(pParse, yygotominor.yy346.pExpr);
  115900. }else{
  115901. sqlite3SrcListDelete(pParse->db, pSrc);
  115902. }
  115903. if( yymsp[-2].minor.yy328 ) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0);
  115904. yygotominor.yy346.zStart = yymsp[-3].minor.yy346.zStart;
  115905. 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];
  115906. }
  115907. break;
  115908. case 227: /* expr ::= EXISTS LP select RP */
  115909. {
  115910. Expr *p = yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_EXISTS, 0, 0, 0);
  115911. if( p ){
  115912. p->x.pSelect = yymsp[-1].minor.yy3;
  115913. ExprSetProperty(p, EP_xIsSelect);
  115914. sqlite3ExprSetHeight(pParse, p);
  115915. }else{
  115916. sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy3);
  115917. }
  115918. yygotominor.yy346.zStart = yymsp[-3].minor.yy0.z;
  115919. yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
  115920. }
  115921. break;
  115922. case 228: /* expr ::= CASE case_operand case_exprlist case_else END */
  115923. {
  115924. yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_CASE, yymsp[-3].minor.yy132, 0, 0);
  115925. if( yygotominor.yy346.pExpr ){
  115926. yygotominor.yy346.pExpr->x.pList = yymsp[-1].minor.yy132 ? sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy14,yymsp[-1].minor.yy132) : yymsp[-2].minor.yy14;
  115927. sqlite3ExprSetHeight(pParse, yygotominor.yy346.pExpr);
  115928. }else{
  115929. sqlite3ExprListDelete(pParse->db, yymsp[-2].minor.yy14);
  115930. sqlite3ExprDelete(pParse->db, yymsp[-1].minor.yy132);
  115931. }
  115932. yygotominor.yy346.zStart = yymsp[-4].minor.yy0.z;
  115933. yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
  115934. }
  115935. break;
  115936. case 229: /* case_exprlist ::= case_exprlist WHEN expr THEN expr */
  115937. {
  115938. yygotominor.yy14 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy14, yymsp[-2].minor.yy346.pExpr);
  115939. yygotominor.yy14 = sqlite3ExprListAppend(pParse,yygotominor.yy14, yymsp[0].minor.yy346.pExpr);
  115940. }
  115941. break;
  115942. case 230: /* case_exprlist ::= WHEN expr THEN expr */
  115943. {
  115944. yygotominor.yy14 = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy346.pExpr);
  115945. yygotominor.yy14 = sqlite3ExprListAppend(pParse,yygotominor.yy14, yymsp[0].minor.yy346.pExpr);
  115946. }
  115947. break;
  115948. case 237: /* nexprlist ::= nexprlist COMMA expr */
  115949. {yygotominor.yy14 = sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy14,yymsp[0].minor.yy346.pExpr);}
  115950. break;
  115951. case 238: /* nexprlist ::= expr */
  115952. {yygotominor.yy14 = sqlite3ExprListAppend(pParse,0,yymsp[0].minor.yy346.pExpr);}
  115953. break;
  115954. case 239: /* cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP where_opt */
  115955. {
  115956. sqlite3CreateIndex(pParse, &yymsp[-7].minor.yy0, &yymsp[-6].minor.yy0,
  115957. sqlite3SrcListAppend(pParse->db,0,&yymsp[-4].minor.yy0,0), yymsp[-2].minor.yy14, yymsp[-10].minor.yy328,
  115958. &yymsp[-11].minor.yy0, yymsp[0].minor.yy132, SQLITE_SO_ASC, yymsp[-8].minor.yy328);
  115959. }
  115960. break;
  115961. case 240: /* uniqueflag ::= UNIQUE */
  115962. case 291: /* raisetype ::= ABORT */ yytestcase(yyruleno==291);
  115963. {yygotominor.yy328 = OE_Abort;}
  115964. break;
  115965. case 241: /* uniqueflag ::= */
  115966. {yygotominor.yy328 = OE_None;}
  115967. break;
  115968. case 244: /* idxlist ::= idxlist COMMA nm collate sortorder */
  115969. {
  115970. Expr *p = sqlite3ExprAddCollateToken(pParse, 0, &yymsp[-1].minor.yy0);
  115971. yygotominor.yy14 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy14, p);
  115972. sqlite3ExprListSetName(pParse,yygotominor.yy14,&yymsp[-2].minor.yy0,1);
  115973. sqlite3ExprListCheckLength(pParse, yygotominor.yy14, "index");
  115974. if( yygotominor.yy14 ) yygotominor.yy14->a[yygotominor.yy14->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy328;
  115975. }
  115976. break;
  115977. case 245: /* idxlist ::= nm collate sortorder */
  115978. {
  115979. Expr *p = sqlite3ExprAddCollateToken(pParse, 0, &yymsp[-1].minor.yy0);
  115980. yygotominor.yy14 = sqlite3ExprListAppend(pParse,0, p);
  115981. sqlite3ExprListSetName(pParse, yygotominor.yy14, &yymsp[-2].minor.yy0, 1);
  115982. sqlite3ExprListCheckLength(pParse, yygotominor.yy14, "index");
  115983. if( yygotominor.yy14 ) yygotominor.yy14->a[yygotominor.yy14->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy328;
  115984. }
  115985. break;
  115986. case 246: /* collate ::= */
  115987. {yygotominor.yy0.z = 0; yygotominor.yy0.n = 0;}
  115988. break;
  115989. case 248: /* cmd ::= DROP INDEX ifexists fullname */
  115990. {sqlite3DropIndex(pParse, yymsp[0].minor.yy65, yymsp[-1].minor.yy328);}
  115991. break;
  115992. case 249: /* cmd ::= VACUUM */
  115993. case 250: /* cmd ::= VACUUM nm */ yytestcase(yyruleno==250);
  115994. {sqlite3Vacuum(pParse);}
  115995. break;
  115996. case 251: /* cmd ::= PRAGMA nm dbnm */
  115997. {sqlite3Pragma(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0,0);}
  115998. break;
  115999. case 252: /* cmd ::= PRAGMA nm dbnm EQ nmnum */
  116000. {sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,0);}
  116001. break;
  116002. case 253: /* cmd ::= PRAGMA nm dbnm LP nmnum RP */
  116003. {sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,0);}
  116004. break;
  116005. case 254: /* cmd ::= PRAGMA nm dbnm EQ minus_num */
  116006. {sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,1);}
  116007. break;
  116008. case 255: /* cmd ::= PRAGMA nm dbnm LP minus_num RP */
  116009. {sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,1);}
  116010. break;
  116011. case 264: /* cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END */
  116012. {
  116013. Token all;
  116014. all.z = yymsp[-3].minor.yy0.z;
  116015. all.n = (int)(yymsp[0].minor.yy0.z - yymsp[-3].minor.yy0.z) + yymsp[0].minor.yy0.n;
  116016. sqlite3FinishTrigger(pParse, yymsp[-1].minor.yy473, &all);
  116017. }
  116018. break;
  116019. case 265: /* trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */
  116020. {
  116021. 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);
  116022. yygotominor.yy0 = (yymsp[-6].minor.yy0.n==0?yymsp[-7].minor.yy0:yymsp[-6].minor.yy0);
  116023. }
  116024. break;
  116025. case 266: /* trigger_time ::= BEFORE */
  116026. case 269: /* trigger_time ::= */ yytestcase(yyruleno==269);
  116027. { yygotominor.yy328 = TK_BEFORE; }
  116028. break;
  116029. case 267: /* trigger_time ::= AFTER */
  116030. { yygotominor.yy328 = TK_AFTER; }
  116031. break;
  116032. case 268: /* trigger_time ::= INSTEAD OF */
  116033. { yygotominor.yy328 = TK_INSTEAD;}
  116034. break;
  116035. case 270: /* trigger_event ::= DELETE|INSERT */
  116036. case 271: /* trigger_event ::= UPDATE */ yytestcase(yyruleno==271);
  116037. {yygotominor.yy378.a = yymsp[0].major; yygotominor.yy378.b = 0;}
  116038. break;
  116039. case 272: /* trigger_event ::= UPDATE OF idlist */
  116040. {yygotominor.yy378.a = TK_UPDATE; yygotominor.yy378.b = yymsp[0].minor.yy408;}
  116041. break;
  116042. case 275: /* when_clause ::= */
  116043. case 296: /* key_opt ::= */ yytestcase(yyruleno==296);
  116044. { yygotominor.yy132 = 0; }
  116045. break;
  116046. case 276: /* when_clause ::= WHEN expr */
  116047. case 297: /* key_opt ::= KEY expr */ yytestcase(yyruleno==297);
  116048. { yygotominor.yy132 = yymsp[0].minor.yy346.pExpr; }
  116049. break;
  116050. case 277: /* trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */
  116051. {
  116052. assert( yymsp[-2].minor.yy473!=0 );
  116053. yymsp[-2].minor.yy473->pLast->pNext = yymsp[-1].minor.yy473;
  116054. yymsp[-2].minor.yy473->pLast = yymsp[-1].minor.yy473;
  116055. yygotominor.yy473 = yymsp[-2].minor.yy473;
  116056. }
  116057. break;
  116058. case 278: /* trigger_cmd_list ::= trigger_cmd SEMI */
  116059. {
  116060. assert( yymsp[-1].minor.yy473!=0 );
  116061. yymsp[-1].minor.yy473->pLast = yymsp[-1].minor.yy473;
  116062. yygotominor.yy473 = yymsp[-1].minor.yy473;
  116063. }
  116064. break;
  116065. case 280: /* trnm ::= nm DOT nm */
  116066. {
  116067. yygotominor.yy0 = yymsp[0].minor.yy0;
  116068. sqlite3ErrorMsg(pParse,
  116069. "qualified table names are not allowed on INSERT, UPDATE, and DELETE "
  116070. "statements within triggers");
  116071. }
  116072. break;
  116073. case 282: /* tridxby ::= INDEXED BY nm */
  116074. {
  116075. sqlite3ErrorMsg(pParse,
  116076. "the INDEXED BY clause is not allowed on UPDATE or DELETE statements "
  116077. "within triggers");
  116078. }
  116079. break;
  116080. case 283: /* tridxby ::= NOT INDEXED */
  116081. {
  116082. sqlite3ErrorMsg(pParse,
  116083. "the NOT INDEXED clause is not allowed on UPDATE or DELETE statements "
  116084. "within triggers");
  116085. }
  116086. break;
  116087. case 284: /* trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt */
  116088. { yygotominor.yy473 = sqlite3TriggerUpdateStep(pParse->db, &yymsp[-4].minor.yy0, yymsp[-1].minor.yy14, yymsp[0].minor.yy132, yymsp[-5].minor.yy186); }
  116089. break;
  116090. case 285: /* trigger_cmd ::= insert_cmd INTO trnm inscollist_opt select */
  116091. {yygotominor.yy473 = sqlite3TriggerInsertStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy408, yymsp[0].minor.yy3, yymsp[-4].minor.yy186);}
  116092. break;
  116093. case 286: /* trigger_cmd ::= DELETE FROM trnm tridxby where_opt */
  116094. {yygotominor.yy473 = sqlite3TriggerDeleteStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[0].minor.yy132);}
  116095. break;
  116096. case 287: /* trigger_cmd ::= select */
  116097. {yygotominor.yy473 = sqlite3TriggerSelectStep(pParse->db, yymsp[0].minor.yy3); }
  116098. break;
  116099. case 288: /* expr ::= RAISE LP IGNORE RP */
  116100. {
  116101. yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, 0);
  116102. if( yygotominor.yy346.pExpr ){
  116103. yygotominor.yy346.pExpr->affinity = OE_Ignore;
  116104. }
  116105. yygotominor.yy346.zStart = yymsp[-3].minor.yy0.z;
  116106. yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
  116107. }
  116108. break;
  116109. case 289: /* expr ::= RAISE LP raisetype COMMA nm RP */
  116110. {
  116111. yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, &yymsp[-1].minor.yy0);
  116112. if( yygotominor.yy346.pExpr ) {
  116113. yygotominor.yy346.pExpr->affinity = (char)yymsp[-3].minor.yy328;
  116114. }
  116115. yygotominor.yy346.zStart = yymsp[-5].minor.yy0.z;
  116116. yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
  116117. }
  116118. break;
  116119. case 290: /* raisetype ::= ROLLBACK */
  116120. {yygotominor.yy328 = OE_Rollback;}
  116121. break;
  116122. case 292: /* raisetype ::= FAIL */
  116123. {yygotominor.yy328 = OE_Fail;}
  116124. break;
  116125. case 293: /* cmd ::= DROP TRIGGER ifexists fullname */
  116126. {
  116127. sqlite3DropTrigger(pParse,yymsp[0].minor.yy65,yymsp[-1].minor.yy328);
  116128. }
  116129. break;
  116130. case 294: /* cmd ::= ATTACH database_kw_opt expr AS expr key_opt */
  116131. {
  116132. sqlite3Attach(pParse, yymsp[-3].minor.yy346.pExpr, yymsp[-1].minor.yy346.pExpr, yymsp[0].minor.yy132);
  116133. }
  116134. break;
  116135. case 295: /* cmd ::= DETACH database_kw_opt expr */
  116136. {
  116137. sqlite3Detach(pParse, yymsp[0].minor.yy346.pExpr);
  116138. }
  116139. break;
  116140. case 300: /* cmd ::= REINDEX */
  116141. {sqlite3Reindex(pParse, 0, 0);}
  116142. break;
  116143. case 301: /* cmd ::= REINDEX nm dbnm */
  116144. {sqlite3Reindex(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
  116145. break;
  116146. case 302: /* cmd ::= ANALYZE */
  116147. {sqlite3Analyze(pParse, 0, 0);}
  116148. break;
  116149. case 303: /* cmd ::= ANALYZE nm dbnm */
  116150. {sqlite3Analyze(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
  116151. break;
  116152. case 304: /* cmd ::= ALTER TABLE fullname RENAME TO nm */
  116153. {
  116154. sqlite3AlterRenameTable(pParse,yymsp[-3].minor.yy65,&yymsp[0].minor.yy0);
  116155. }
  116156. break;
  116157. case 305: /* cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column */
  116158. {
  116159. sqlite3AlterFinishAddColumn(pParse, &yymsp[0].minor.yy0);
  116160. }
  116161. break;
  116162. case 306: /* add_column_fullname ::= fullname */
  116163. {
  116164. pParse->db->lookaside.bEnabled = 0;
  116165. sqlite3AlterBeginAddColumn(pParse, yymsp[0].minor.yy65);
  116166. }
  116167. break;
  116168. case 309: /* cmd ::= create_vtab */
  116169. {sqlite3VtabFinishParse(pParse,0);}
  116170. break;
  116171. case 310: /* cmd ::= create_vtab LP vtabarglist RP */
  116172. {sqlite3VtabFinishParse(pParse,&yymsp[0].minor.yy0);}
  116173. break;
  116174. case 311: /* create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm */
  116175. {
  116176. sqlite3VtabBeginParse(pParse, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, &yymsp[0].minor.yy0, yymsp[-4].minor.yy328);
  116177. }
  116178. break;
  116179. case 314: /* vtabarg ::= */
  116180. {sqlite3VtabArgInit(pParse);}
  116181. break;
  116182. case 316: /* vtabargtoken ::= ANY */
  116183. case 317: /* vtabargtoken ::= lp anylist RP */ yytestcase(yyruleno==317);
  116184. case 318: /* lp ::= LP */ yytestcase(yyruleno==318);
  116185. {sqlite3VtabArgExtend(pParse,&yymsp[0].minor.yy0);}
  116186. break;
  116187. case 322: /* with ::= */
  116188. {yygotominor.yy59 = 0;}
  116189. break;
  116190. case 323: /* with ::= WITH wqlist */
  116191. case 324: /* with ::= WITH RECURSIVE wqlist */ yytestcase(yyruleno==324);
  116192. { yygotominor.yy59 = yymsp[0].minor.yy59; }
  116193. break;
  116194. case 325: /* wqlist ::= nm idxlist_opt AS LP select RP */
  116195. {
  116196. yygotominor.yy59 = sqlite3WithAdd(pParse, 0, &yymsp[-5].minor.yy0, yymsp[-4].minor.yy14, yymsp[-1].minor.yy3);
  116197. }
  116198. break;
  116199. case 326: /* wqlist ::= wqlist COMMA nm idxlist_opt AS LP select RP */
  116200. {
  116201. yygotominor.yy59 = sqlite3WithAdd(pParse, yymsp[-7].minor.yy59, &yymsp[-5].minor.yy0, yymsp[-4].minor.yy14, yymsp[-1].minor.yy3);
  116202. }
  116203. break;
  116204. default:
  116205. /* (0) input ::= cmdlist */ yytestcase(yyruleno==0);
  116206. /* (1) cmdlist ::= cmdlist ecmd */ yytestcase(yyruleno==1);
  116207. /* (2) cmdlist ::= ecmd */ yytestcase(yyruleno==2);
  116208. /* (3) ecmd ::= SEMI */ yytestcase(yyruleno==3);
  116209. /* (4) ecmd ::= explain cmdx SEMI */ yytestcase(yyruleno==4);
  116210. /* (10) trans_opt ::= */ yytestcase(yyruleno==10);
  116211. /* (11) trans_opt ::= TRANSACTION */ yytestcase(yyruleno==11);
  116212. /* (12) trans_opt ::= TRANSACTION nm */ yytestcase(yyruleno==12);
  116213. /* (20) savepoint_opt ::= SAVEPOINT */ yytestcase(yyruleno==20);
  116214. /* (21) savepoint_opt ::= */ yytestcase(yyruleno==21);
  116215. /* (25) cmd ::= create_table create_table_args */ yytestcase(yyruleno==25);
  116216. /* (36) columnlist ::= columnlist COMMA column */ yytestcase(yyruleno==36);
  116217. /* (37) columnlist ::= column */ yytestcase(yyruleno==37);
  116218. /* (43) type ::= */ yytestcase(yyruleno==43);
  116219. /* (50) signed ::= plus_num */ yytestcase(yyruleno==50);
  116220. /* (51) signed ::= minus_num */ yytestcase(yyruleno==51);
  116221. /* (52) carglist ::= carglist ccons */ yytestcase(yyruleno==52);
  116222. /* (53) carglist ::= */ yytestcase(yyruleno==53);
  116223. /* (60) ccons ::= NULL onconf */ yytestcase(yyruleno==60);
  116224. /* (88) conslist ::= conslist tconscomma tcons */ yytestcase(yyruleno==88);
  116225. /* (89) conslist ::= tcons */ yytestcase(yyruleno==89);
  116226. /* (91) tconscomma ::= */ yytestcase(yyruleno==91);
  116227. /* (273) foreach_clause ::= */ yytestcase(yyruleno==273);
  116228. /* (274) foreach_clause ::= FOR EACH ROW */ yytestcase(yyruleno==274);
  116229. /* (281) tridxby ::= */ yytestcase(yyruleno==281);
  116230. /* (298) database_kw_opt ::= DATABASE */ yytestcase(yyruleno==298);
  116231. /* (299) database_kw_opt ::= */ yytestcase(yyruleno==299);
  116232. /* (307) kwcolumn_opt ::= */ yytestcase(yyruleno==307);
  116233. /* (308) kwcolumn_opt ::= COLUMNKW */ yytestcase(yyruleno==308);
  116234. /* (312) vtabarglist ::= vtabarg */ yytestcase(yyruleno==312);
  116235. /* (313) vtabarglist ::= vtabarglist COMMA vtabarg */ yytestcase(yyruleno==313);
  116236. /* (315) vtabarg ::= vtabarg vtabargtoken */ yytestcase(yyruleno==315);
  116237. /* (319) anylist ::= */ yytestcase(yyruleno==319);
  116238. /* (320) anylist ::= anylist LP anylist RP */ yytestcase(yyruleno==320);
  116239. /* (321) anylist ::= anylist ANY */ yytestcase(yyruleno==321);
  116240. break;
  116241. };
  116242. assert( yyruleno>=0 && yyruleno<sizeof(yyRuleInfo)/sizeof(yyRuleInfo[0]) );
  116243. yygoto = yyRuleInfo[yyruleno].lhs;
  116244. yysize = yyRuleInfo[yyruleno].nrhs;
  116245. yypParser->yyidx -= yysize;
  116246. yyact = yy_find_reduce_action(yymsp[-yysize].stateno,(YYCODETYPE)yygoto);
  116247. if( yyact < YYNSTATE ){
  116248. #ifdef NDEBUG
  116249. /* If we are not debugging and the reduce action popped at least
  116250. ** one element off the stack, then we can push the new element back
  116251. ** onto the stack here, and skip the stack overflow test in yy_shift().
  116252. ** That gives a significant speed improvement. */
  116253. if( yysize ){
  116254. yypParser->yyidx++;
  116255. yymsp -= yysize-1;
  116256. yymsp->stateno = (YYACTIONTYPE)yyact;
  116257. yymsp->major = (YYCODETYPE)yygoto;
  116258. yymsp->minor = yygotominor;
  116259. }else
  116260. #endif
  116261. {
  116262. yy_shift(yypParser,yyact,yygoto,&yygotominor);
  116263. }
  116264. }else{
  116265. assert( yyact == YYNSTATE + YYNRULE + 1 );
  116266. yy_accept(yypParser);
  116267. }
  116268. }
  116269. /*
  116270. ** The following code executes when the parse fails
  116271. */
  116272. #ifndef YYNOERRORRECOVERY
  116273. static void yy_parse_failed(
  116274. yyParser *yypParser /* The parser */
  116275. ){
  116276. sqlite3ParserARG_FETCH;
  116277. #ifndef NDEBUG
  116278. if( yyTraceFILE ){
  116279. fprintf(yyTraceFILE,"%sFail!\n",yyTracePrompt);
  116280. }
  116281. #endif
  116282. while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
  116283. /* Here code is inserted which will be executed whenever the
  116284. ** parser fails */
  116285. sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
  116286. }
  116287. #endif /* YYNOERRORRECOVERY */
  116288. /*
  116289. ** The following code executes when a syntax error first occurs.
  116290. */
  116291. static void yy_syntax_error(
  116292. yyParser *yypParser, /* The parser */
  116293. int yymajor, /* The major type of the error token */
  116294. YYMINORTYPE yyminor /* The minor type of the error token */
  116295. ){
  116296. sqlite3ParserARG_FETCH;
  116297. #define TOKEN (yyminor.yy0)
  116298. UNUSED_PARAMETER(yymajor); /* Silence some compiler warnings */
  116299. assert( TOKEN.z[0] ); /* The tokenizer always gives us a token */
  116300. sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &TOKEN);
  116301. sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
  116302. }
  116303. /*
  116304. ** The following is executed when the parser accepts
  116305. */
  116306. static void yy_accept(
  116307. yyParser *yypParser /* The parser */
  116308. ){
  116309. sqlite3ParserARG_FETCH;
  116310. #ifndef NDEBUG
  116311. if( yyTraceFILE ){
  116312. fprintf(yyTraceFILE,"%sAccept!\n",yyTracePrompt);
  116313. }
  116314. #endif
  116315. while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
  116316. /* Here code is inserted which will be executed whenever the
  116317. ** parser accepts */
  116318. sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
  116319. }
  116320. /* The main parser program.
  116321. ** The first argument is a pointer to a structure obtained from
  116322. ** "sqlite3ParserAlloc" which describes the current state of the parser.
  116323. ** The second argument is the major token number. The third is
  116324. ** the minor token. The fourth optional argument is whatever the
  116325. ** user wants (and specified in the grammar) and is available for
  116326. ** use by the action routines.
  116327. **
  116328. ** Inputs:
  116329. ** <ul>
  116330. ** <li> A pointer to the parser (an opaque structure.)
  116331. ** <li> The major token number.
  116332. ** <li> The minor token number.
  116333. ** <li> An option argument of a grammar-specified type.
  116334. ** </ul>
  116335. **
  116336. ** Outputs:
  116337. ** None.
  116338. */
  116339. SQLITE_PRIVATE void sqlite3Parser(
  116340. void *yyp, /* The parser */
  116341. int yymajor, /* The major token code number */
  116342. sqlite3ParserTOKENTYPE yyminor /* The value for the token */
  116343. sqlite3ParserARG_PDECL /* Optional %extra_argument parameter */
  116344. ){
  116345. YYMINORTYPE yyminorunion;
  116346. int yyact; /* The parser action. */
  116347. #if !defined(YYERRORSYMBOL) && !defined(YYNOERRORRECOVERY)
  116348. int yyendofinput; /* True if we are at the end of input */
  116349. #endif
  116350. #ifdef YYERRORSYMBOL
  116351. int yyerrorhit = 0; /* True if yymajor has invoked an error */
  116352. #endif
  116353. yyParser *yypParser; /* The parser */
  116354. /* (re)initialize the parser, if necessary */
  116355. yypParser = (yyParser*)yyp;
  116356. if( yypParser->yyidx<0 ){
  116357. #if YYSTACKDEPTH<=0
  116358. if( yypParser->yystksz <=0 ){
  116359. /*memset(&yyminorunion, 0, sizeof(yyminorunion));*/
  116360. yyminorunion = yyzerominor;
  116361. yyStackOverflow(yypParser, &yyminorunion);
  116362. return;
  116363. }
  116364. #endif
  116365. yypParser->yyidx = 0;
  116366. yypParser->yyerrcnt = -1;
  116367. yypParser->yystack[0].stateno = 0;
  116368. yypParser->yystack[0].major = 0;
  116369. }
  116370. yyminorunion.yy0 = yyminor;
  116371. #if !defined(YYERRORSYMBOL) && !defined(YYNOERRORRECOVERY)
  116372. yyendofinput = (yymajor==0);
  116373. #endif
  116374. sqlite3ParserARG_STORE;
  116375. #ifndef NDEBUG
  116376. if( yyTraceFILE ){
  116377. fprintf(yyTraceFILE,"%sInput %s\n",yyTracePrompt,yyTokenName[yymajor]);
  116378. }
  116379. #endif
  116380. do{
  116381. yyact = yy_find_shift_action(yypParser,(YYCODETYPE)yymajor);
  116382. if( yyact<YYNSTATE ){
  116383. yy_shift(yypParser,yyact,yymajor,&yyminorunion);
  116384. yypParser->yyerrcnt--;
  116385. yymajor = YYNOCODE;
  116386. }else if( yyact < YYNSTATE + YYNRULE ){
  116387. yy_reduce(yypParser,yyact-YYNSTATE);
  116388. }else{
  116389. assert( yyact == YY_ERROR_ACTION );
  116390. #ifdef YYERRORSYMBOL
  116391. int yymx;
  116392. #endif
  116393. #ifndef NDEBUG
  116394. if( yyTraceFILE ){
  116395. fprintf(yyTraceFILE,"%sSyntax Error!\n",yyTracePrompt);
  116396. }
  116397. #endif
  116398. #ifdef YYERRORSYMBOL
  116399. /* A syntax error has occurred.
  116400. ** The response to an error depends upon whether or not the
  116401. ** grammar defines an error token "ERROR".
  116402. **
  116403. ** This is what we do if the grammar does define ERROR:
  116404. **
  116405. ** * Call the %syntax_error function.
  116406. **
  116407. ** * Begin popping the stack until we enter a state where
  116408. ** it is legal to shift the error symbol, then shift
  116409. ** the error symbol.
  116410. **
  116411. ** * Set the error count to three.
  116412. **
  116413. ** * Begin accepting and shifting new tokens. No new error
  116414. ** processing will occur until three tokens have been
  116415. ** shifted successfully.
  116416. **
  116417. */
  116418. if( yypParser->yyerrcnt<0 ){
  116419. yy_syntax_error(yypParser,yymajor,yyminorunion);
  116420. }
  116421. yymx = yypParser->yystack[yypParser->yyidx].major;
  116422. if( yymx==YYERRORSYMBOL || yyerrorhit ){
  116423. #ifndef NDEBUG
  116424. if( yyTraceFILE ){
  116425. fprintf(yyTraceFILE,"%sDiscard input token %s\n",
  116426. yyTracePrompt,yyTokenName[yymajor]);
  116427. }
  116428. #endif
  116429. yy_destructor(yypParser, (YYCODETYPE)yymajor,&yyminorunion);
  116430. yymajor = YYNOCODE;
  116431. }else{
  116432. while(
  116433. yypParser->yyidx >= 0 &&
  116434. yymx != YYERRORSYMBOL &&
  116435. (yyact = yy_find_reduce_action(
  116436. yypParser->yystack[yypParser->yyidx].stateno,
  116437. YYERRORSYMBOL)) >= YYNSTATE
  116438. ){
  116439. yy_pop_parser_stack(yypParser);
  116440. }
  116441. if( yypParser->yyidx < 0 || yymajor==0 ){
  116442. yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
  116443. yy_parse_failed(yypParser);
  116444. yymajor = YYNOCODE;
  116445. }else if( yymx!=YYERRORSYMBOL ){
  116446. YYMINORTYPE u2;
  116447. u2.YYERRSYMDT = 0;
  116448. yy_shift(yypParser,yyact,YYERRORSYMBOL,&u2);
  116449. }
  116450. }
  116451. yypParser->yyerrcnt = 3;
  116452. yyerrorhit = 1;
  116453. #elif defined(YYNOERRORRECOVERY)
  116454. /* If the YYNOERRORRECOVERY macro is defined, then do not attempt to
  116455. ** do any kind of error recovery. Instead, simply invoke the syntax
  116456. ** error routine and continue going as if nothing had happened.
  116457. **
  116458. ** Applications can set this macro (for example inside %include) if
  116459. ** they intend to abandon the parse upon the first syntax error seen.
  116460. */
  116461. yy_syntax_error(yypParser,yymajor,yyminorunion);
  116462. yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
  116463. yymajor = YYNOCODE;
  116464. #else /* YYERRORSYMBOL is not defined */
  116465. /* This is what we do if the grammar does not define ERROR:
  116466. **
  116467. ** * Report an error message, and throw away the input token.
  116468. **
  116469. ** * If the input token is $, then fail the parse.
  116470. **
  116471. ** As before, subsequent error messages are suppressed until
  116472. ** three input tokens have been successfully shifted.
  116473. */
  116474. if( yypParser->yyerrcnt<=0 ){
  116475. yy_syntax_error(yypParser,yymajor,yyminorunion);
  116476. }
  116477. yypParser->yyerrcnt = 3;
  116478. yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
  116479. if( yyendofinput ){
  116480. yy_parse_failed(yypParser);
  116481. }
  116482. yymajor = YYNOCODE;
  116483. #endif
  116484. }
  116485. }while( yymajor!=YYNOCODE && yypParser->yyidx>=0 );
  116486. return;
  116487. }
  116488. /************** End of parse.c ***********************************************/
  116489. /************** Begin file tokenize.c ****************************************/
  116490. /*
  116491. ** 2001 September 15
  116492. **
  116493. ** The author disclaims copyright to this source code. In place of
  116494. ** a legal notice, here is a blessing:
  116495. **
  116496. ** May you do good and not evil.
  116497. ** May you find forgiveness for yourself and forgive others.
  116498. ** May you share freely, never taking more than you give.
  116499. **
  116500. *************************************************************************
  116501. ** An tokenizer for SQL
  116502. **
  116503. ** This file contains C code that splits an SQL input string up into
  116504. ** individual tokens and sends those tokens one-by-one over to the
  116505. ** parser for analysis.
  116506. */
  116507. /* #include <stdlib.h> */
  116508. /*
  116509. ** The charMap() macro maps alphabetic characters into their
  116510. ** lower-case ASCII equivalent. On ASCII machines, this is just
  116511. ** an upper-to-lower case map. On EBCDIC machines we also need
  116512. ** to adjust the encoding. Only alphabetic characters and underscores
  116513. ** need to be translated.
  116514. */
  116515. #ifdef SQLITE_ASCII
  116516. # define charMap(X) sqlite3UpperToLower[(unsigned char)X]
  116517. #endif
  116518. #ifdef SQLITE_EBCDIC
  116519. # define charMap(X) ebcdicToAscii[(unsigned char)X]
  116520. const unsigned char ebcdicToAscii[] = {
  116521. /* 0 1 2 3 4 5 6 7 8 9 A B C D E F */
  116522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x */
  116523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 1x */
  116524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 2x */
  116525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 3x */
  116526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 4x */
  116527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 5x */
  116528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 95, 0, 0, /* 6x */
  116529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 7x */
  116530. 0, 97, 98, 99,100,101,102,103,104,105, 0, 0, 0, 0, 0, 0, /* 8x */
  116531. 0,106,107,108,109,110,111,112,113,114, 0, 0, 0, 0, 0, 0, /* 9x */
  116532. 0, 0,115,116,117,118,119,120,121,122, 0, 0, 0, 0, 0, 0, /* Ax */
  116533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Bx */
  116534. 0, 97, 98, 99,100,101,102,103,104,105, 0, 0, 0, 0, 0, 0, /* Cx */
  116535. 0,106,107,108,109,110,111,112,113,114, 0, 0, 0, 0, 0, 0, /* Dx */
  116536. 0, 0,115,116,117,118,119,120,121,122, 0, 0, 0, 0, 0, 0, /* Ex */
  116537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Fx */
  116538. };
  116539. #endif
  116540. /*
  116541. ** The sqlite3KeywordCode function looks up an identifier to determine if
  116542. ** it is a keyword. If it is a keyword, the token code of that keyword is
  116543. ** returned. If the input is not a keyword, TK_ID is returned.
  116544. **
  116545. ** The implementation of this routine was generated by a program,
  116546. ** mkkeywordhash.h, located in the tool subdirectory of the distribution.
  116547. ** The output of the mkkeywordhash.c program is written into a file
  116548. ** named keywordhash.h and then included into this source file by
  116549. ** the #include below.
  116550. */
  116551. /************** Include keywordhash.h in the middle of tokenize.c ************/
  116552. /************** Begin file keywordhash.h *************************************/
  116553. /***** This file contains automatically generated code ******
  116554. **
  116555. ** The code in this file has been automatically generated by
  116556. **
  116557. ** sqlite/tool/mkkeywordhash.c
  116558. **
  116559. ** The code in this file implements a function that determines whether
  116560. ** or not a given identifier is really an SQL keyword. The same thing
  116561. ** might be implemented more directly using a hand-written hash table.
  116562. ** But by using this automatically generated code, the size of the code
  116563. ** is substantially reduced. This is important for embedded applications
  116564. ** on platforms with limited memory.
  116565. */
  116566. /* Hash score: 182 */
  116567. static int keywordCode(const char *z, int n){
  116568. /* zText[] encodes 834 bytes of keywords in 554 bytes */
  116569. /* REINDEXEDESCAPEACHECKEYBEFOREIGNOREGEXPLAINSTEADDATABASELECT */
  116570. /* ABLEFTHENDEFERRABLELSEXCEPTRANSACTIONATURALTERAISEXCLUSIVE */
  116571. /* XISTSAVEPOINTERSECTRIGGEREFERENCESCONSTRAINTOFFSETEMPORARY */
  116572. /* UNIQUERYWITHOUTERELEASEATTACHAVINGROUPDATEBEGINNERECURSIVE */
  116573. /* BETWEENOTNULLIKECASCADELETECASECOLLATECREATECURRENT_DATEDETACH */
  116574. /* IMMEDIATEJOINSERTMATCHPLANALYZEPRAGMABORTVALUESVIRTUALIMITWHEN */
  116575. /* WHERENAMEAFTEREPLACEANDEFAULTAUTOINCREMENTCASTCOLUMNCOMMIT */
  116576. /* CONFLICTCROSSCURRENT_TIMESTAMPRIMARYDEFERREDISTINCTDROPFAIL */
  116577. /* FROMFULLGLOBYIFISNULLORDERESTRICTRIGHTROLLBACKROWUNIONUSING */
  116578. /* VACUUMVIEWINITIALLY */
  116579. static const char zText[553] = {
  116580. 'R','E','I','N','D','E','X','E','D','E','S','C','A','P','E','A','C','H',
  116581. 'E','C','K','E','Y','B','E','F','O','R','E','I','G','N','O','R','E','G',
  116582. 'E','X','P','L','A','I','N','S','T','E','A','D','D','A','T','A','B','A',
  116583. 'S','E','L','E','C','T','A','B','L','E','F','T','H','E','N','D','E','F',
  116584. 'E','R','R','A','B','L','E','L','S','E','X','C','E','P','T','R','A','N',
  116585. 'S','A','C','T','I','O','N','A','T','U','R','A','L','T','E','R','A','I',
  116586. 'S','E','X','C','L','U','S','I','V','E','X','I','S','T','S','A','V','E',
  116587. 'P','O','I','N','T','E','R','S','E','C','T','R','I','G','G','E','R','E',
  116588. 'F','E','R','E','N','C','E','S','C','O','N','S','T','R','A','I','N','T',
  116589. 'O','F','F','S','E','T','E','M','P','O','R','A','R','Y','U','N','I','Q',
  116590. 'U','E','R','Y','W','I','T','H','O','U','T','E','R','E','L','E','A','S',
  116591. 'E','A','T','T','A','C','H','A','V','I','N','G','R','O','U','P','D','A',
  116592. 'T','E','B','E','G','I','N','N','E','R','E','C','U','R','S','I','V','E',
  116593. 'B','E','T','W','E','E','N','O','T','N','U','L','L','I','K','E','C','A',
  116594. 'S','C','A','D','E','L','E','T','E','C','A','S','E','C','O','L','L','A',
  116595. 'T','E','C','R','E','A','T','E','C','U','R','R','E','N','T','_','D','A',
  116596. 'T','E','D','E','T','A','C','H','I','M','M','E','D','I','A','T','E','J',
  116597. 'O','I','N','S','E','R','T','M','A','T','C','H','P','L','A','N','A','L',
  116598. 'Y','Z','E','P','R','A','G','M','A','B','O','R','T','V','A','L','U','E',
  116599. 'S','V','I','R','T','U','A','L','I','M','I','T','W','H','E','N','W','H',
  116600. 'E','R','E','N','A','M','E','A','F','T','E','R','E','P','L','A','C','E',
  116601. 'A','N','D','E','F','A','U','L','T','A','U','T','O','I','N','C','R','E',
  116602. 'M','E','N','T','C','A','S','T','C','O','L','U','M','N','C','O','M','M',
  116603. 'I','T','C','O','N','F','L','I','C','T','C','R','O','S','S','C','U','R',
  116604. 'R','E','N','T','_','T','I','M','E','S','T','A','M','P','R','I','M','A',
  116605. 'R','Y','D','E','F','E','R','R','E','D','I','S','T','I','N','C','T','D',
  116606. 'R','O','P','F','A','I','L','F','R','O','M','F','U','L','L','G','L','O',
  116607. 'B','Y','I','F','I','S','N','U','L','L','O','R','D','E','R','E','S','T',
  116608. 'R','I','C','T','R','I','G','H','T','R','O','L','L','B','A','C','K','R',
  116609. 'O','W','U','N','I','O','N','U','S','I','N','G','V','A','C','U','U','M',
  116610. 'V','I','E','W','I','N','I','T','I','A','L','L','Y',
  116611. };
  116612. static const unsigned char aHash[127] = {
  116613. 76, 105, 117, 74, 0, 45, 0, 0, 82, 0, 77, 0, 0,
  116614. 42, 12, 78, 15, 0, 116, 85, 54, 112, 0, 19, 0, 0,
  116615. 121, 0, 119, 115, 0, 22, 93, 0, 9, 0, 0, 70, 71,
  116616. 0, 69, 6, 0, 48, 90, 102, 0, 118, 101, 0, 0, 44,
  116617. 0, 103, 24, 0, 17, 0, 122, 53, 23, 0, 5, 110, 25,
  116618. 96, 0, 0, 124, 106, 60, 123, 57, 28, 55, 0, 91, 0,
  116619. 100, 26, 0, 99, 0, 0, 0, 95, 92, 97, 88, 109, 14,
  116620. 39, 108, 0, 81, 0, 18, 89, 111, 32, 0, 120, 80, 113,
  116621. 62, 46, 84, 0, 0, 94, 40, 59, 114, 0, 36, 0, 0,
  116622. 29, 0, 86, 63, 64, 0, 20, 61, 0, 56,
  116623. };
  116624. static const unsigned char aNext[124] = {
  116625. 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0,
  116626. 0, 2, 0, 0, 0, 0, 0, 0, 13, 0, 0, 0, 0,
  116627. 0, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116628. 0, 0, 0, 0, 33, 0, 21, 0, 0, 0, 0, 0, 50,
  116629. 0, 43, 3, 47, 0, 0, 0, 0, 30, 0, 58, 0, 38,
  116630. 0, 0, 0, 1, 66, 0, 0, 67, 0, 41, 0, 0, 0,
  116631. 0, 0, 0, 49, 65, 0, 0, 0, 0, 31, 52, 16, 34,
  116632. 10, 0, 0, 0, 0, 0, 0, 0, 11, 72, 79, 0, 8,
  116633. 0, 104, 98, 0, 107, 0, 87, 0, 75, 51, 0, 27, 37,
  116634. 73, 83, 0, 35, 68, 0, 0,
  116635. };
  116636. static const unsigned char aLen[124] = {
  116637. 7, 7, 5, 4, 6, 4, 5, 3, 6, 7, 3, 6, 6,
  116638. 7, 7, 3, 8, 2, 6, 5, 4, 4, 3, 10, 4, 6,
  116639. 11, 6, 2, 7, 5, 5, 9, 6, 9, 9, 7, 10, 10,
  116640. 4, 6, 2, 3, 9, 4, 2, 6, 5, 7, 4, 5, 7,
  116641. 6, 6, 5, 6, 5, 5, 9, 7, 7, 3, 2, 4, 4,
  116642. 7, 3, 6, 4, 7, 6, 12, 6, 9, 4, 6, 5, 4,
  116643. 7, 6, 5, 6, 7, 5, 4, 5, 6, 5, 7, 3, 7,
  116644. 13, 2, 2, 4, 6, 6, 8, 5, 17, 12, 7, 8, 8,
  116645. 2, 4, 4, 4, 4, 4, 2, 2, 6, 5, 8, 5, 8,
  116646. 3, 5, 5, 6, 4, 9, 3,
  116647. };
  116648. static const unsigned short int aOffset[124] = {
  116649. 0, 2, 2, 8, 9, 14, 16, 20, 23, 25, 25, 29, 33,
  116650. 36, 41, 46, 48, 53, 54, 59, 62, 65, 67, 69, 78, 81,
  116651. 86, 91, 95, 96, 101, 105, 109, 117, 122, 128, 136, 142, 152,
  116652. 159, 162, 162, 165, 167, 167, 171, 176, 179, 184, 184, 188, 192,
  116653. 199, 204, 209, 212, 218, 221, 225, 234, 240, 240, 240, 243, 246,
  116654. 250, 251, 255, 261, 265, 272, 278, 290, 296, 305, 307, 313, 318,
  116655. 320, 327, 332, 337, 343, 349, 354, 358, 361, 367, 371, 378, 380,
  116656. 387, 389, 391, 400, 404, 410, 416, 424, 429, 429, 445, 452, 459,
  116657. 460, 467, 471, 475, 479, 483, 486, 488, 490, 496, 500, 508, 513,
  116658. 521, 524, 529, 534, 540, 544, 549,
  116659. };
  116660. static const unsigned char aCode[124] = {
  116661. TK_REINDEX, TK_INDEXED, TK_INDEX, TK_DESC, TK_ESCAPE,
  116662. TK_EACH, TK_CHECK, TK_KEY, TK_BEFORE, TK_FOREIGN,
  116663. TK_FOR, TK_IGNORE, TK_LIKE_KW, TK_EXPLAIN, TK_INSTEAD,
  116664. TK_ADD, TK_DATABASE, TK_AS, TK_SELECT, TK_TABLE,
  116665. TK_JOIN_KW, TK_THEN, TK_END, TK_DEFERRABLE, TK_ELSE,
  116666. TK_EXCEPT, TK_TRANSACTION,TK_ACTION, TK_ON, TK_JOIN_KW,
  116667. TK_ALTER, TK_RAISE, TK_EXCLUSIVE, TK_EXISTS, TK_SAVEPOINT,
  116668. TK_INTERSECT, TK_TRIGGER, TK_REFERENCES, TK_CONSTRAINT, TK_INTO,
  116669. TK_OFFSET, TK_OF, TK_SET, TK_TEMP, TK_TEMP,
  116670. TK_OR, TK_UNIQUE, TK_QUERY, TK_WITHOUT, TK_WITH,
  116671. TK_JOIN_KW, TK_RELEASE, TK_ATTACH, TK_HAVING, TK_GROUP,
  116672. TK_UPDATE, TK_BEGIN, TK_JOIN_KW, TK_RECURSIVE, TK_BETWEEN,
  116673. TK_NOTNULL, TK_NOT, TK_NO, TK_NULL, TK_LIKE_KW,
  116674. TK_CASCADE, TK_ASC, TK_DELETE, TK_CASE, TK_COLLATE,
  116675. TK_CREATE, TK_CTIME_KW, TK_DETACH, TK_IMMEDIATE, TK_JOIN,
  116676. TK_INSERT, TK_MATCH, TK_PLAN, TK_ANALYZE, TK_PRAGMA,
  116677. TK_ABORT, TK_VALUES, TK_VIRTUAL, TK_LIMIT, TK_WHEN,
  116678. TK_WHERE, TK_RENAME, TK_AFTER, TK_REPLACE, TK_AND,
  116679. TK_DEFAULT, TK_AUTOINCR, TK_TO, TK_IN, TK_CAST,
  116680. TK_COLUMNKW, TK_COMMIT, TK_CONFLICT, TK_JOIN_KW, TK_CTIME_KW,
  116681. TK_CTIME_KW, TK_PRIMARY, TK_DEFERRED, TK_DISTINCT, TK_IS,
  116682. TK_DROP, TK_FAIL, TK_FROM, TK_JOIN_KW, TK_LIKE_KW,
  116683. TK_BY, TK_IF, TK_ISNULL, TK_ORDER, TK_RESTRICT,
  116684. TK_JOIN_KW, TK_ROLLBACK, TK_ROW, TK_UNION, TK_USING,
  116685. TK_VACUUM, TK_VIEW, TK_INITIALLY, TK_ALL,
  116686. };
  116687. int h, i;
  116688. if( n<2 ) return TK_ID;
  116689. h = ((charMap(z[0])*4) ^
  116690. (charMap(z[n-1])*3) ^
  116691. n) % 127;
  116692. for(i=((int)aHash[h])-1; i>=0; i=((int)aNext[i])-1){
  116693. if( aLen[i]==n && sqlite3StrNICmp(&zText[aOffset[i]],z,n)==0 ){
  116694. testcase( i==0 ); /* REINDEX */
  116695. testcase( i==1 ); /* INDEXED */
  116696. testcase( i==2 ); /* INDEX */
  116697. testcase( i==3 ); /* DESC */
  116698. testcase( i==4 ); /* ESCAPE */
  116699. testcase( i==5 ); /* EACH */
  116700. testcase( i==6 ); /* CHECK */
  116701. testcase( i==7 ); /* KEY */
  116702. testcase( i==8 ); /* BEFORE */
  116703. testcase( i==9 ); /* FOREIGN */
  116704. testcase( i==10 ); /* FOR */
  116705. testcase( i==11 ); /* IGNORE */
  116706. testcase( i==12 ); /* REGEXP */
  116707. testcase( i==13 ); /* EXPLAIN */
  116708. testcase( i==14 ); /* INSTEAD */
  116709. testcase( i==15 ); /* ADD */
  116710. testcase( i==16 ); /* DATABASE */
  116711. testcase( i==17 ); /* AS */
  116712. testcase( i==18 ); /* SELECT */
  116713. testcase( i==19 ); /* TABLE */
  116714. testcase( i==20 ); /* LEFT */
  116715. testcase( i==21 ); /* THEN */
  116716. testcase( i==22 ); /* END */
  116717. testcase( i==23 ); /* DEFERRABLE */
  116718. testcase( i==24 ); /* ELSE */
  116719. testcase( i==25 ); /* EXCEPT */
  116720. testcase( i==26 ); /* TRANSACTION */
  116721. testcase( i==27 ); /* ACTION */
  116722. testcase( i==28 ); /* ON */
  116723. testcase( i==29 ); /* NATURAL */
  116724. testcase( i==30 ); /* ALTER */
  116725. testcase( i==31 ); /* RAISE */
  116726. testcase( i==32 ); /* EXCLUSIVE */
  116727. testcase( i==33 ); /* EXISTS */
  116728. testcase( i==34 ); /* SAVEPOINT */
  116729. testcase( i==35 ); /* INTERSECT */
  116730. testcase( i==36 ); /* TRIGGER */
  116731. testcase( i==37 ); /* REFERENCES */
  116732. testcase( i==38 ); /* CONSTRAINT */
  116733. testcase( i==39 ); /* INTO */
  116734. testcase( i==40 ); /* OFFSET */
  116735. testcase( i==41 ); /* OF */
  116736. testcase( i==42 ); /* SET */
  116737. testcase( i==43 ); /* TEMPORARY */
  116738. testcase( i==44 ); /* TEMP */
  116739. testcase( i==45 ); /* OR */
  116740. testcase( i==46 ); /* UNIQUE */
  116741. testcase( i==47 ); /* QUERY */
  116742. testcase( i==48 ); /* WITHOUT */
  116743. testcase( i==49 ); /* WITH */
  116744. testcase( i==50 ); /* OUTER */
  116745. testcase( i==51 ); /* RELEASE */
  116746. testcase( i==52 ); /* ATTACH */
  116747. testcase( i==53 ); /* HAVING */
  116748. testcase( i==54 ); /* GROUP */
  116749. testcase( i==55 ); /* UPDATE */
  116750. testcase( i==56 ); /* BEGIN */
  116751. testcase( i==57 ); /* INNER */
  116752. testcase( i==58 ); /* RECURSIVE */
  116753. testcase( i==59 ); /* BETWEEN */
  116754. testcase( i==60 ); /* NOTNULL */
  116755. testcase( i==61 ); /* NOT */
  116756. testcase( i==62 ); /* NO */
  116757. testcase( i==63 ); /* NULL */
  116758. testcase( i==64 ); /* LIKE */
  116759. testcase( i==65 ); /* CASCADE */
  116760. testcase( i==66 ); /* ASC */
  116761. testcase( i==67 ); /* DELETE */
  116762. testcase( i==68 ); /* CASE */
  116763. testcase( i==69 ); /* COLLATE */
  116764. testcase( i==70 ); /* CREATE */
  116765. testcase( i==71 ); /* CURRENT_DATE */
  116766. testcase( i==72 ); /* DETACH */
  116767. testcase( i==73 ); /* IMMEDIATE */
  116768. testcase( i==74 ); /* JOIN */
  116769. testcase( i==75 ); /* INSERT */
  116770. testcase( i==76 ); /* MATCH */
  116771. testcase( i==77 ); /* PLAN */
  116772. testcase( i==78 ); /* ANALYZE */
  116773. testcase( i==79 ); /* PRAGMA */
  116774. testcase( i==80 ); /* ABORT */
  116775. testcase( i==81 ); /* VALUES */
  116776. testcase( i==82 ); /* VIRTUAL */
  116777. testcase( i==83 ); /* LIMIT */
  116778. testcase( i==84 ); /* WHEN */
  116779. testcase( i==85 ); /* WHERE */
  116780. testcase( i==86 ); /* RENAME */
  116781. testcase( i==87 ); /* AFTER */
  116782. testcase( i==88 ); /* REPLACE */
  116783. testcase( i==89 ); /* AND */
  116784. testcase( i==90 ); /* DEFAULT */
  116785. testcase( i==91 ); /* AUTOINCREMENT */
  116786. testcase( i==92 ); /* TO */
  116787. testcase( i==93 ); /* IN */
  116788. testcase( i==94 ); /* CAST */
  116789. testcase( i==95 ); /* COLUMN */
  116790. testcase( i==96 ); /* COMMIT */
  116791. testcase( i==97 ); /* CONFLICT */
  116792. testcase( i==98 ); /* CROSS */
  116793. testcase( i==99 ); /* CURRENT_TIMESTAMP */
  116794. testcase( i==100 ); /* CURRENT_TIME */
  116795. testcase( i==101 ); /* PRIMARY */
  116796. testcase( i==102 ); /* DEFERRED */
  116797. testcase( i==103 ); /* DISTINCT */
  116798. testcase( i==104 ); /* IS */
  116799. testcase( i==105 ); /* DROP */
  116800. testcase( i==106 ); /* FAIL */
  116801. testcase( i==107 ); /* FROM */
  116802. testcase( i==108 ); /* FULL */
  116803. testcase( i==109 ); /* GLOB */
  116804. testcase( i==110 ); /* BY */
  116805. testcase( i==111 ); /* IF */
  116806. testcase( i==112 ); /* ISNULL */
  116807. testcase( i==113 ); /* ORDER */
  116808. testcase( i==114 ); /* RESTRICT */
  116809. testcase( i==115 ); /* RIGHT */
  116810. testcase( i==116 ); /* ROLLBACK */
  116811. testcase( i==117 ); /* ROW */
  116812. testcase( i==118 ); /* UNION */
  116813. testcase( i==119 ); /* USING */
  116814. testcase( i==120 ); /* VACUUM */
  116815. testcase( i==121 ); /* VIEW */
  116816. testcase( i==122 ); /* INITIALLY */
  116817. testcase( i==123 ); /* ALL */
  116818. return aCode[i];
  116819. }
  116820. }
  116821. return TK_ID;
  116822. }
  116823. SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char *z, int n){
  116824. return keywordCode((char*)z, n);
  116825. }
  116826. #define SQLITE_N_KEYWORD 124
  116827. /************** End of keywordhash.h *****************************************/
  116828. /************** Continuing where we left off in tokenize.c *******************/
  116829. /*
  116830. ** If X is a character that can be used in an identifier then
  116831. ** IdChar(X) will be true. Otherwise it is false.
  116832. **
  116833. ** For ASCII, any character with the high-order bit set is
  116834. ** allowed in an identifier. For 7-bit characters,
  116835. ** sqlite3IsIdChar[X] must be 1.
  116836. **
  116837. ** For EBCDIC, the rules are more complex but have the same
  116838. ** end result.
  116839. **
  116840. ** Ticket #1066. the SQL standard does not allow '$' in the
  116841. ** middle of identifiers. But many SQL implementations do.
  116842. ** SQLite will allow '$' in identifiers for compatibility.
  116843. ** But the feature is undocumented.
  116844. */
  116845. #ifdef SQLITE_ASCII
  116846. #define IdChar(C) ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
  116847. #endif
  116848. #ifdef SQLITE_EBCDIC
  116849. SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[] = {
  116850. /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
  116851. 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 4x */
  116852. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, /* 5x */
  116853. 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, /* 6x */
  116854. 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, /* 7x */
  116855. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0, /* 8x */
  116856. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0, /* 9x */
  116857. 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, /* Ax */
  116858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Bx */
  116859. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, /* Cx */
  116860. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, /* Dx */
  116861. 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, /* Ex */
  116862. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, /* Fx */
  116863. };
  116864. #define IdChar(C) (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
  116865. #endif
  116866. SQLITE_PRIVATE int sqlite3IsIdChar(u8 c){ return IdChar(c); }
  116867. /*
  116868. ** Return the length of the token that begins at z[0].
  116869. ** Store the token type in *tokenType before returning.
  116870. */
  116871. SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *z, int *tokenType){
  116872. int i, c;
  116873. switch( *z ){
  116874. case ' ': case '\t': case '\n': case '\f': case '\r': {
  116875. testcase( z[0]==' ' );
  116876. testcase( z[0]=='\t' );
  116877. testcase( z[0]=='\n' );
  116878. testcase( z[0]=='\f' );
  116879. testcase( z[0]=='\r' );
  116880. for(i=1; sqlite3Isspace(z[i]); i++){}
  116881. *tokenType = TK_SPACE;
  116882. return i;
  116883. }
  116884. case '-': {
  116885. if( z[1]=='-' ){
  116886. for(i=2; (c=z[i])!=0 && c!='\n'; i++){}
  116887. *tokenType = TK_SPACE; /* IMP: R-22934-25134 */
  116888. return i;
  116889. }
  116890. *tokenType = TK_MINUS;
  116891. return 1;
  116892. }
  116893. case '(': {
  116894. *tokenType = TK_LP;
  116895. return 1;
  116896. }
  116897. case ')': {
  116898. *tokenType = TK_RP;
  116899. return 1;
  116900. }
  116901. case ';': {
  116902. *tokenType = TK_SEMI;
  116903. return 1;
  116904. }
  116905. case '+': {
  116906. *tokenType = TK_PLUS;
  116907. return 1;
  116908. }
  116909. case '*': {
  116910. *tokenType = TK_STAR;
  116911. return 1;
  116912. }
  116913. case '/': {
  116914. if( z[1]!='*' || z[2]==0 ){
  116915. *tokenType = TK_SLASH;
  116916. return 1;
  116917. }
  116918. for(i=3, c=z[2]; (c!='*' || z[i]!='/') && (c=z[i])!=0; i++){}
  116919. if( c ) i++;
  116920. *tokenType = TK_SPACE; /* IMP: R-22934-25134 */
  116921. return i;
  116922. }
  116923. case '%': {
  116924. *tokenType = TK_REM;
  116925. return 1;
  116926. }
  116927. case '=': {
  116928. *tokenType = TK_EQ;
  116929. return 1 + (z[1]=='=');
  116930. }
  116931. case '<': {
  116932. if( (c=z[1])=='=' ){
  116933. *tokenType = TK_LE;
  116934. return 2;
  116935. }else if( c=='>' ){
  116936. *tokenType = TK_NE;
  116937. return 2;
  116938. }else if( c=='<' ){
  116939. *tokenType = TK_LSHIFT;
  116940. return 2;
  116941. }else{
  116942. *tokenType = TK_LT;
  116943. return 1;
  116944. }
  116945. }
  116946. case '>': {
  116947. if( (c=z[1])=='=' ){
  116948. *tokenType = TK_GE;
  116949. return 2;
  116950. }else if( c=='>' ){
  116951. *tokenType = TK_RSHIFT;
  116952. return 2;
  116953. }else{
  116954. *tokenType = TK_GT;
  116955. return 1;
  116956. }
  116957. }
  116958. case '!': {
  116959. if( z[1]!='=' ){
  116960. *tokenType = TK_ILLEGAL;
  116961. return 2;
  116962. }else{
  116963. *tokenType = TK_NE;
  116964. return 2;
  116965. }
  116966. }
  116967. case '|': {
  116968. if( z[1]!='|' ){
  116969. *tokenType = TK_BITOR;
  116970. return 1;
  116971. }else{
  116972. *tokenType = TK_CONCAT;
  116973. return 2;
  116974. }
  116975. }
  116976. case ',': {
  116977. *tokenType = TK_COMMA;
  116978. return 1;
  116979. }
  116980. case '&': {
  116981. *tokenType = TK_BITAND;
  116982. return 1;
  116983. }
  116984. case '~': {
  116985. *tokenType = TK_BITNOT;
  116986. return 1;
  116987. }
  116988. case '`':
  116989. case '\'':
  116990. case '"': {
  116991. int delim = z[0];
  116992. testcase( delim=='`' );
  116993. testcase( delim=='\'' );
  116994. testcase( delim=='"' );
  116995. for(i=1; (c=z[i])!=0; i++){
  116996. if( c==delim ){
  116997. if( z[i+1]==delim ){
  116998. i++;
  116999. }else{
  117000. break;
  117001. }
  117002. }
  117003. }
  117004. if( c=='\'' ){
  117005. *tokenType = TK_STRING;
  117006. return i+1;
  117007. }else if( c!=0 ){
  117008. *tokenType = TK_ID;
  117009. return i+1;
  117010. }else{
  117011. *tokenType = TK_ILLEGAL;
  117012. return i;
  117013. }
  117014. }
  117015. case '.': {
  117016. #ifndef SQLITE_OMIT_FLOATING_POINT
  117017. if( !sqlite3Isdigit(z[1]) )
  117018. #endif
  117019. {
  117020. *tokenType = TK_DOT;
  117021. return 1;
  117022. }
  117023. /* If the next character is a digit, this is a floating point
  117024. ** number that begins with ".". Fall thru into the next case */
  117025. }
  117026. case '0': case '1': case '2': case '3': case '4':
  117027. case '5': case '6': case '7': case '8': case '9': {
  117028. testcase( z[0]=='0' ); testcase( z[0]=='1' ); testcase( z[0]=='2' );
  117029. testcase( z[0]=='3' ); testcase( z[0]=='4' ); testcase( z[0]=='5' );
  117030. testcase( z[0]=='6' ); testcase( z[0]=='7' ); testcase( z[0]=='8' );
  117031. testcase( z[0]=='9' );
  117032. *tokenType = TK_INTEGER;
  117033. #ifndef SQLITE_OMIT_HEX_INTEGER
  117034. if( z[0]=='0' && (z[1]=='x' || z[1]=='X') && sqlite3Isxdigit(z[2]) ){
  117035. for(i=3; sqlite3Isxdigit(z[i]); i++){}
  117036. return i;
  117037. }
  117038. #endif
  117039. for(i=0; sqlite3Isdigit(z[i]); i++){}
  117040. #ifndef SQLITE_OMIT_FLOATING_POINT
  117041. if( z[i]=='.' ){
  117042. i++;
  117043. while( sqlite3Isdigit(z[i]) ){ i++; }
  117044. *tokenType = TK_FLOAT;
  117045. }
  117046. if( (z[i]=='e' || z[i]=='E') &&
  117047. ( sqlite3Isdigit(z[i+1])
  117048. || ((z[i+1]=='+' || z[i+1]=='-') && sqlite3Isdigit(z[i+2]))
  117049. )
  117050. ){
  117051. i += 2;
  117052. while( sqlite3Isdigit(z[i]) ){ i++; }
  117053. *tokenType = TK_FLOAT;
  117054. }
  117055. #endif
  117056. while( IdChar(z[i]) ){
  117057. *tokenType = TK_ILLEGAL;
  117058. i++;
  117059. }
  117060. return i;
  117061. }
  117062. case '[': {
  117063. for(i=1, c=z[0]; c!=']' && (c=z[i])!=0; i++){}
  117064. *tokenType = c==']' ? TK_ID : TK_ILLEGAL;
  117065. return i;
  117066. }
  117067. case '?': {
  117068. *tokenType = TK_VARIABLE;
  117069. for(i=1; sqlite3Isdigit(z[i]); i++){}
  117070. return i;
  117071. }
  117072. #ifndef SQLITE_OMIT_TCL_VARIABLE
  117073. case '$':
  117074. #endif
  117075. case '@': /* For compatibility with MS SQL Server */
  117076. case '#':
  117077. case ':': {
  117078. int n = 0;
  117079. testcase( z[0]=='$' ); testcase( z[0]=='@' );
  117080. testcase( z[0]==':' ); testcase( z[0]=='#' );
  117081. *tokenType = TK_VARIABLE;
  117082. for(i=1; (c=z[i])!=0; i++){
  117083. if( IdChar(c) ){
  117084. n++;
  117085. #ifndef SQLITE_OMIT_TCL_VARIABLE
  117086. }else if( c=='(' && n>0 ){
  117087. do{
  117088. i++;
  117089. }while( (c=z[i])!=0 && !sqlite3Isspace(c) && c!=')' );
  117090. if( c==')' ){
  117091. i++;
  117092. }else{
  117093. *tokenType = TK_ILLEGAL;
  117094. }
  117095. break;
  117096. }else if( c==':' && z[i+1]==':' ){
  117097. i++;
  117098. #endif
  117099. }else{
  117100. break;
  117101. }
  117102. }
  117103. if( n==0 ) *tokenType = TK_ILLEGAL;
  117104. return i;
  117105. }
  117106. #ifndef SQLITE_OMIT_BLOB_LITERAL
  117107. case 'x': case 'X': {
  117108. testcase( z[0]=='x' ); testcase( z[0]=='X' );
  117109. if( z[1]=='\'' ){
  117110. *tokenType = TK_BLOB;
  117111. for(i=2; sqlite3Isxdigit(z[i]); i++){}
  117112. if( z[i]!='\'' || i%2 ){
  117113. *tokenType = TK_ILLEGAL;
  117114. while( z[i] && z[i]!='\'' ){ i++; }
  117115. }
  117116. if( z[i] ) i++;
  117117. return i;
  117118. }
  117119. /* Otherwise fall through to the next case */
  117120. }
  117121. #endif
  117122. default: {
  117123. if( !IdChar(*z) ){
  117124. break;
  117125. }
  117126. for(i=1; IdChar(z[i]); i++){}
  117127. *tokenType = keywordCode((char*)z, i);
  117128. return i;
  117129. }
  117130. }
  117131. *tokenType = TK_ILLEGAL;
  117132. return 1;
  117133. }
  117134. /*
  117135. ** Run the parser on the given SQL string. The parser structure is
  117136. ** passed in. An SQLITE_ status code is returned. If an error occurs
  117137. ** then an and attempt is made to write an error message into
  117138. ** memory obtained from sqlite3_malloc() and to make *pzErrMsg point to that
  117139. ** error message.
  117140. */
  117141. SQLITE_PRIVATE int sqlite3RunParser(Parse *pParse, const char *zSql, char **pzErrMsg){
  117142. int nErr = 0; /* Number of errors encountered */
  117143. int i; /* Loop counter */
  117144. void *pEngine; /* The LEMON-generated LALR(1) parser */
  117145. int tokenType; /* type of the next token */
  117146. int lastTokenParsed = -1; /* type of the previous token */
  117147. u8 enableLookaside; /* Saved value of db->lookaside.bEnabled */
  117148. sqlite3 *db = pParse->db; /* The database connection */
  117149. int mxSqlLen; /* Max length of an SQL string */
  117150. mxSqlLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
  117151. if( db->nVdbeActive==0 ){
  117152. db->u1.isInterrupted = 0;
  117153. }
  117154. pParse->rc = SQLITE_OK;
  117155. pParse->zTail = zSql;
  117156. i = 0;
  117157. assert( pzErrMsg!=0 );
  117158. pEngine = sqlite3ParserAlloc(sqlite3Malloc);
  117159. if( pEngine==0 ){
  117160. db->mallocFailed = 1;
  117161. return SQLITE_NOMEM;
  117162. }
  117163. assert( pParse->pNewTable==0 );
  117164. assert( pParse->pNewTrigger==0 );
  117165. assert( pParse->nVar==0 );
  117166. assert( pParse->nzVar==0 );
  117167. assert( pParse->azVar==0 );
  117168. enableLookaside = db->lookaside.bEnabled;
  117169. if( db->lookaside.pStart ) db->lookaside.bEnabled = 1;
  117170. while( !db->mallocFailed && zSql[i]!=0 ){
  117171. assert( i>=0 );
  117172. pParse->sLastToken.z = &zSql[i];
  117173. pParse->sLastToken.n = sqlite3GetToken((unsigned char*)&zSql[i],&tokenType);
  117174. i += pParse->sLastToken.n;
  117175. if( i>mxSqlLen ){
  117176. pParse->rc = SQLITE_TOOBIG;
  117177. break;
  117178. }
  117179. switch( tokenType ){
  117180. case TK_SPACE: {
  117181. if( db->u1.isInterrupted ){
  117182. sqlite3ErrorMsg(pParse, "interrupt");
  117183. pParse->rc = SQLITE_INTERRUPT;
  117184. goto abort_parse;
  117185. }
  117186. break;
  117187. }
  117188. case TK_ILLEGAL: {
  117189. sqlite3DbFree(db, *pzErrMsg);
  117190. *pzErrMsg = sqlite3MPrintf(db, "unrecognized token: \"%T\"",
  117191. &pParse->sLastToken);
  117192. nErr++;
  117193. goto abort_parse;
  117194. }
  117195. case TK_SEMI: {
  117196. pParse->zTail = &zSql[i];
  117197. /* Fall thru into the default case */
  117198. }
  117199. default: {
  117200. sqlite3Parser(pEngine, tokenType, pParse->sLastToken, pParse);
  117201. lastTokenParsed = tokenType;
  117202. if( pParse->rc!=SQLITE_OK ){
  117203. goto abort_parse;
  117204. }
  117205. break;
  117206. }
  117207. }
  117208. }
  117209. abort_parse:
  117210. if( zSql[i]==0 && nErr==0 && pParse->rc==SQLITE_OK ){
  117211. if( lastTokenParsed!=TK_SEMI ){
  117212. sqlite3Parser(pEngine, TK_SEMI, pParse->sLastToken, pParse);
  117213. pParse->zTail = &zSql[i];
  117214. }
  117215. sqlite3Parser(pEngine, 0, pParse->sLastToken, pParse);
  117216. }
  117217. #ifdef YYTRACKMAXSTACKDEPTH
  117218. sqlite3StatusSet(SQLITE_STATUS_PARSER_STACK,
  117219. sqlite3ParserStackPeak(pEngine)
  117220. );
  117221. #endif /* YYDEBUG */
  117222. sqlite3ParserFree(pEngine, sqlite3_free);
  117223. db->lookaside.bEnabled = enableLookaside;
  117224. if( db->mallocFailed ){
  117225. pParse->rc = SQLITE_NOMEM;
  117226. }
  117227. if( pParse->rc!=SQLITE_OK && pParse->rc!=SQLITE_DONE && pParse->zErrMsg==0 ){
  117228. sqlite3SetString(&pParse->zErrMsg, db, "%s", sqlite3ErrStr(pParse->rc));
  117229. }
  117230. assert( pzErrMsg!=0 );
  117231. if( pParse->zErrMsg ){
  117232. *pzErrMsg = pParse->zErrMsg;
  117233. sqlite3_log(pParse->rc, "%s", *pzErrMsg);
  117234. pParse->zErrMsg = 0;
  117235. nErr++;
  117236. }
  117237. if( pParse->pVdbe && pParse->nErr>0 && pParse->nested==0 ){
  117238. sqlite3VdbeDelete(pParse->pVdbe);
  117239. pParse->pVdbe = 0;
  117240. }
  117241. #ifndef SQLITE_OMIT_SHARED_CACHE
  117242. if( pParse->nested==0 ){
  117243. sqlite3DbFree(db, pParse->aTableLock);
  117244. pParse->aTableLock = 0;
  117245. pParse->nTableLock = 0;
  117246. }
  117247. #endif
  117248. #ifndef SQLITE_OMIT_VIRTUALTABLE
  117249. sqlite3_free(pParse->apVtabLock);
  117250. #endif
  117251. if( !IN_DECLARE_VTAB ){
  117252. /* If the pParse->declareVtab flag is set, do not delete any table
  117253. ** structure built up in pParse->pNewTable. The calling code (see vtab.c)
  117254. ** will take responsibility for freeing the Table structure.
  117255. */
  117256. sqlite3DeleteTable(db, pParse->pNewTable);
  117257. }
  117258. if( pParse->bFreeWith ) sqlite3WithDelete(db, pParse->pWith);
  117259. sqlite3DeleteTrigger(db, pParse->pNewTrigger);
  117260. for(i=pParse->nzVar-1; i>=0; i--) sqlite3DbFree(db, pParse->azVar[i]);
  117261. sqlite3DbFree(db, pParse->azVar);
  117262. while( pParse->pAinc ){
  117263. AutoincInfo *p = pParse->pAinc;
  117264. pParse->pAinc = p->pNext;
  117265. sqlite3DbFree(db, p);
  117266. }
  117267. while( pParse->pZombieTab ){
  117268. Table *p = pParse->pZombieTab;
  117269. pParse->pZombieTab = p->pNextZombie;
  117270. sqlite3DeleteTable(db, p);
  117271. }
  117272. if( nErr>0 && pParse->rc==SQLITE_OK ){
  117273. pParse->rc = SQLITE_ERROR;
  117274. }
  117275. return nErr;
  117276. }
  117277. /************** End of tokenize.c ********************************************/
  117278. /************** Begin file complete.c ****************************************/
  117279. /*
  117280. ** 2001 September 15
  117281. **
  117282. ** The author disclaims copyright to this source code. In place of
  117283. ** a legal notice, here is a blessing:
  117284. **
  117285. ** May you do good and not evil.
  117286. ** May you find forgiveness for yourself and forgive others.
  117287. ** May you share freely, never taking more than you give.
  117288. **
  117289. *************************************************************************
  117290. ** An tokenizer for SQL
  117291. **
  117292. ** This file contains C code that implements the sqlite3_complete() API.
  117293. ** This code used to be part of the tokenizer.c source file. But by
  117294. ** separating it out, the code will be automatically omitted from
  117295. ** static links that do not use it.
  117296. */
  117297. #ifndef SQLITE_OMIT_COMPLETE
  117298. /*
  117299. ** This is defined in tokenize.c. We just have to import the definition.
  117300. */
  117301. #ifndef SQLITE_AMALGAMATION
  117302. #ifdef SQLITE_ASCII
  117303. #define IdChar(C) ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
  117304. #endif
  117305. #ifdef SQLITE_EBCDIC
  117306. SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[];
  117307. #define IdChar(C) (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
  117308. #endif
  117309. #endif /* SQLITE_AMALGAMATION */
  117310. /*
  117311. ** Token types used by the sqlite3_complete() routine. See the header
  117312. ** comments on that procedure for additional information.
  117313. */
  117314. #define tkSEMI 0
  117315. #define tkWS 1
  117316. #define tkOTHER 2
  117317. #ifndef SQLITE_OMIT_TRIGGER
  117318. #define tkEXPLAIN 3
  117319. #define tkCREATE 4
  117320. #define tkTEMP 5
  117321. #define tkTRIGGER 6
  117322. #define tkEND 7
  117323. #endif
  117324. /*
  117325. ** Return TRUE if the given SQL string ends in a semicolon.
  117326. **
  117327. ** Special handling is require for CREATE TRIGGER statements.
  117328. ** Whenever the CREATE TRIGGER keywords are seen, the statement
  117329. ** must end with ";END;".
  117330. **
  117331. ** This implementation uses a state machine with 8 states:
  117332. **
  117333. ** (0) INVALID We have not yet seen a non-whitespace character.
  117334. **
  117335. ** (1) START At the beginning or end of an SQL statement. This routine
  117336. ** returns 1 if it ends in the START state and 0 if it ends
  117337. ** in any other state.
  117338. **
  117339. ** (2) NORMAL We are in the middle of statement which ends with a single
  117340. ** semicolon.
  117341. **
  117342. ** (3) EXPLAIN The keyword EXPLAIN has been seen at the beginning of
  117343. ** a statement.
  117344. **
  117345. ** (4) CREATE The keyword CREATE has been seen at the beginning of a
  117346. ** statement, possibly preceded by EXPLAIN and/or followed by
  117347. ** TEMP or TEMPORARY
  117348. **
  117349. ** (5) TRIGGER We are in the middle of a trigger definition that must be
  117350. ** ended by a semicolon, the keyword END, and another semicolon.
  117351. **
  117352. ** (6) SEMI We've seen the first semicolon in the ";END;" that occurs at
  117353. ** the end of a trigger definition.
  117354. **
  117355. ** (7) END We've seen the ";END" of the ";END;" that occurs at the end
  117356. ** of a trigger definition.
  117357. **
  117358. ** Transitions between states above are determined by tokens extracted
  117359. ** from the input. The following tokens are significant:
  117360. **
  117361. ** (0) tkSEMI A semicolon.
  117362. ** (1) tkWS Whitespace.
  117363. ** (2) tkOTHER Any other SQL token.
  117364. ** (3) tkEXPLAIN The "explain" keyword.
  117365. ** (4) tkCREATE The "create" keyword.
  117366. ** (5) tkTEMP The "temp" or "temporary" keyword.
  117367. ** (6) tkTRIGGER The "trigger" keyword.
  117368. ** (7) tkEND The "end" keyword.
  117369. **
  117370. ** Whitespace never causes a state transition and is always ignored.
  117371. ** This means that a SQL string of all whitespace is invalid.
  117372. **
  117373. ** If we compile with SQLITE_OMIT_TRIGGER, all of the computation needed
  117374. ** to recognize the end of a trigger can be omitted. All we have to do
  117375. ** is look for a semicolon that is not part of an string or comment.
  117376. */
  117377. SQLITE_API int sqlite3_complete(const char *zSql){
  117378. u8 state = 0; /* Current state, using numbers defined in header comment */
  117379. u8 token; /* Value of the next token */
  117380. #ifdef SQLITE_ENABLE_API_ARMOR
  117381. if( zSql==0 ){
  117382. (void)SQLITE_MISUSE_BKPT;
  117383. return 0;
  117384. }
  117385. #endif
  117386. #ifndef SQLITE_OMIT_TRIGGER
  117387. /* A complex statement machine used to detect the end of a CREATE TRIGGER
  117388. ** statement. This is the normal case.
  117389. */
  117390. static const u8 trans[8][8] = {
  117391. /* Token: */
  117392. /* State: ** SEMI WS OTHER EXPLAIN CREATE TEMP TRIGGER END */
  117393. /* 0 INVALID: */ { 1, 0, 2, 3, 4, 2, 2, 2, },
  117394. /* 1 START: */ { 1, 1, 2, 3, 4, 2, 2, 2, },
  117395. /* 2 NORMAL: */ { 1, 2, 2, 2, 2, 2, 2, 2, },
  117396. /* 3 EXPLAIN: */ { 1, 3, 3, 2, 4, 2, 2, 2, },
  117397. /* 4 CREATE: */ { 1, 4, 2, 2, 2, 4, 5, 2, },
  117398. /* 5 TRIGGER: */ { 6, 5, 5, 5, 5, 5, 5, 5, },
  117399. /* 6 SEMI: */ { 6, 6, 5, 5, 5, 5, 5, 7, },
  117400. /* 7 END: */ { 1, 7, 5, 5, 5, 5, 5, 5, },
  117401. };
  117402. #else
  117403. /* If triggers are not supported by this compile then the statement machine
  117404. ** used to detect the end of a statement is much simpler
  117405. */
  117406. static const u8 trans[3][3] = {
  117407. /* Token: */
  117408. /* State: ** SEMI WS OTHER */
  117409. /* 0 INVALID: */ { 1, 0, 2, },
  117410. /* 1 START: */ { 1, 1, 2, },
  117411. /* 2 NORMAL: */ { 1, 2, 2, },
  117412. };
  117413. #endif /* SQLITE_OMIT_TRIGGER */
  117414. while( *zSql ){
  117415. switch( *zSql ){
  117416. case ';': { /* A semicolon */
  117417. token = tkSEMI;
  117418. break;
  117419. }
  117420. case ' ':
  117421. case '\r':
  117422. case '\t':
  117423. case '\n':
  117424. case '\f': { /* White space is ignored */
  117425. token = tkWS;
  117426. break;
  117427. }
  117428. case '/': { /* C-style comments */
  117429. if( zSql[1]!='*' ){
  117430. token = tkOTHER;
  117431. break;
  117432. }
  117433. zSql += 2;
  117434. while( zSql[0] && (zSql[0]!='*' || zSql[1]!='/') ){ zSql++; }
  117435. if( zSql[0]==0 ) return 0;
  117436. zSql++;
  117437. token = tkWS;
  117438. break;
  117439. }
  117440. case '-': { /* SQL-style comments from "--" to end of line */
  117441. if( zSql[1]!='-' ){
  117442. token = tkOTHER;
  117443. break;
  117444. }
  117445. while( *zSql && *zSql!='\n' ){ zSql++; }
  117446. if( *zSql==0 ) return state==1;
  117447. token = tkWS;
  117448. break;
  117449. }
  117450. case '[': { /* Microsoft-style identifiers in [...] */
  117451. zSql++;
  117452. while( *zSql && *zSql!=']' ){ zSql++; }
  117453. if( *zSql==0 ) return 0;
  117454. token = tkOTHER;
  117455. break;
  117456. }
  117457. case '`': /* Grave-accent quoted symbols used by MySQL */
  117458. case '"': /* single- and double-quoted strings */
  117459. case '\'': {
  117460. int c = *zSql;
  117461. zSql++;
  117462. while( *zSql && *zSql!=c ){ zSql++; }
  117463. if( *zSql==0 ) return 0;
  117464. token = tkOTHER;
  117465. break;
  117466. }
  117467. default: {
  117468. #ifdef SQLITE_EBCDIC
  117469. unsigned char c;
  117470. #endif
  117471. if( IdChar((u8)*zSql) ){
  117472. /* Keywords and unquoted identifiers */
  117473. int nId;
  117474. for(nId=1; IdChar(zSql[nId]); nId++){}
  117475. #ifdef SQLITE_OMIT_TRIGGER
  117476. token = tkOTHER;
  117477. #else
  117478. switch( *zSql ){
  117479. case 'c': case 'C': {
  117480. if( nId==6 && sqlite3StrNICmp(zSql, "create", 6)==0 ){
  117481. token = tkCREATE;
  117482. }else{
  117483. token = tkOTHER;
  117484. }
  117485. break;
  117486. }
  117487. case 't': case 'T': {
  117488. if( nId==7 && sqlite3StrNICmp(zSql, "trigger", 7)==0 ){
  117489. token = tkTRIGGER;
  117490. }else if( nId==4 && sqlite3StrNICmp(zSql, "temp", 4)==0 ){
  117491. token = tkTEMP;
  117492. }else if( nId==9 && sqlite3StrNICmp(zSql, "temporary", 9)==0 ){
  117493. token = tkTEMP;
  117494. }else{
  117495. token = tkOTHER;
  117496. }
  117497. break;
  117498. }
  117499. case 'e': case 'E': {
  117500. if( nId==3 && sqlite3StrNICmp(zSql, "end", 3)==0 ){
  117501. token = tkEND;
  117502. }else
  117503. #ifndef SQLITE_OMIT_EXPLAIN
  117504. if( nId==7 && sqlite3StrNICmp(zSql, "explain", 7)==0 ){
  117505. token = tkEXPLAIN;
  117506. }else
  117507. #endif
  117508. {
  117509. token = tkOTHER;
  117510. }
  117511. break;
  117512. }
  117513. default: {
  117514. token = tkOTHER;
  117515. break;
  117516. }
  117517. }
  117518. #endif /* SQLITE_OMIT_TRIGGER */
  117519. zSql += nId-1;
  117520. }else{
  117521. /* Operators and special symbols */
  117522. token = tkOTHER;
  117523. }
  117524. break;
  117525. }
  117526. }
  117527. state = trans[state][token];
  117528. zSql++;
  117529. }
  117530. return state==1;
  117531. }
  117532. #ifndef SQLITE_OMIT_UTF16
  117533. /*
  117534. ** This routine is the same as the sqlite3_complete() routine described
  117535. ** above, except that the parameter is required to be UTF-16 encoded, not
  117536. ** UTF-8.
  117537. */
  117538. SQLITE_API int sqlite3_complete16(const void *zSql){
  117539. sqlite3_value *pVal;
  117540. char const *zSql8;
  117541. int rc = SQLITE_NOMEM;
  117542. #ifndef SQLITE_OMIT_AUTOINIT
  117543. rc = sqlite3_initialize();
  117544. if( rc ) return rc;
  117545. #endif
  117546. pVal = sqlite3ValueNew(0);
  117547. sqlite3ValueSetStr(pVal, -1, zSql, SQLITE_UTF16NATIVE, SQLITE_STATIC);
  117548. zSql8 = sqlite3ValueText(pVal, SQLITE_UTF8);
  117549. if( zSql8 ){
  117550. rc = sqlite3_complete(zSql8);
  117551. }else{
  117552. rc = SQLITE_NOMEM;
  117553. }
  117554. sqlite3ValueFree(pVal);
  117555. return sqlite3ApiExit(0, rc);
  117556. }
  117557. #endif /* SQLITE_OMIT_UTF16 */
  117558. #endif /* SQLITE_OMIT_COMPLETE */
  117559. /************** End of complete.c ********************************************/
  117560. /************** Begin file main.c ********************************************/
  117561. /*
  117562. ** 2001 September 15
  117563. **
  117564. ** The author disclaims copyright to this source code. In place of
  117565. ** a legal notice, here is a blessing:
  117566. **
  117567. ** May you do good and not evil.
  117568. ** May you find forgiveness for yourself and forgive others.
  117569. ** May you share freely, never taking more than you give.
  117570. **
  117571. *************************************************************************
  117572. ** Main file for the SQLite library. The routines in this file
  117573. ** implement the programmer interface to the library. Routines in
  117574. ** other files are for internal use by SQLite and should not be
  117575. ** accessed by users of the library.
  117576. */
  117577. #ifdef SQLITE_ENABLE_FTS3
  117578. /************** Include fts3.h in the middle of main.c ***********************/
  117579. /************** Begin file fts3.h ********************************************/
  117580. /*
  117581. ** 2006 Oct 10
  117582. **
  117583. ** The author disclaims copyright to this source code. In place of
  117584. ** a legal notice, here is a blessing:
  117585. **
  117586. ** May you do good and not evil.
  117587. ** May you find forgiveness for yourself and forgive others.
  117588. ** May you share freely, never taking more than you give.
  117589. **
  117590. ******************************************************************************
  117591. **
  117592. ** This header file is used by programs that want to link against the
  117593. ** FTS3 library. All it does is declare the sqlite3Fts3Init() interface.
  117594. */
  117595. #if 0
  117596. extern "C" {
  117597. #endif /* __cplusplus */
  117598. SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db);
  117599. #if 0
  117600. } /* extern "C" */
  117601. #endif /* __cplusplus */
  117602. /************** End of fts3.h ************************************************/
  117603. /************** Continuing where we left off in main.c ***********************/
  117604. #endif
  117605. #ifdef SQLITE_ENABLE_RTREE
  117606. /************** Include rtree.h in the middle of main.c **********************/
  117607. /************** Begin file rtree.h *******************************************/
  117608. /*
  117609. ** 2008 May 26
  117610. **
  117611. ** The author disclaims copyright to this source code. In place of
  117612. ** a legal notice, here is a blessing:
  117613. **
  117614. ** May you do good and not evil.
  117615. ** May you find forgiveness for yourself and forgive others.
  117616. ** May you share freely, never taking more than you give.
  117617. **
  117618. ******************************************************************************
  117619. **
  117620. ** This header file is used by programs that want to link against the
  117621. ** RTREE library. All it does is declare the sqlite3RtreeInit() interface.
  117622. */
  117623. #if 0
  117624. extern "C" {
  117625. #endif /* __cplusplus */
  117626. SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db);
  117627. #if 0
  117628. } /* extern "C" */
  117629. #endif /* __cplusplus */
  117630. /************** End of rtree.h ***********************************************/
  117631. /************** Continuing where we left off in main.c ***********************/
  117632. #endif
  117633. #ifdef SQLITE_ENABLE_ICU
  117634. /************** Include sqliteicu.h in the middle of main.c ******************/
  117635. /************** Begin file sqliteicu.h ***************************************/
  117636. /*
  117637. ** 2008 May 26
  117638. **
  117639. ** The author disclaims copyright to this source code. In place of
  117640. ** a legal notice, here is a blessing:
  117641. **
  117642. ** May you do good and not evil.
  117643. ** May you find forgiveness for yourself and forgive others.
  117644. ** May you share freely, never taking more than you give.
  117645. **
  117646. ******************************************************************************
  117647. **
  117648. ** This header file is used by programs that want to link against the
  117649. ** ICU extension. All it does is declare the sqlite3IcuInit() interface.
  117650. */
  117651. #if 0
  117652. extern "C" {
  117653. #endif /* __cplusplus */
  117654. SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db);
  117655. #if 0
  117656. } /* extern "C" */
  117657. #endif /* __cplusplus */
  117658. /************** End of sqliteicu.h *******************************************/
  117659. /************** Continuing where we left off in main.c ***********************/
  117660. #endif
  117661. #ifndef SQLITE_AMALGAMATION
  117662. /* IMPLEMENTATION-OF: R-46656-45156 The sqlite3_version[] string constant
  117663. ** contains the text of SQLITE_VERSION macro.
  117664. */
  117665. SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
  117666. #endif
  117667. /* IMPLEMENTATION-OF: R-53536-42575 The sqlite3_libversion() function returns
  117668. ** a pointer to the to the sqlite3_version[] string constant.
  117669. */
  117670. SQLITE_API const char *sqlite3_libversion(void){ return sqlite3_version; }
  117671. /* IMPLEMENTATION-OF: R-63124-39300 The sqlite3_sourceid() function returns a
  117672. ** pointer to a string constant whose value is the same as the
  117673. ** SQLITE_SOURCE_ID C preprocessor macro.
  117674. */
  117675. SQLITE_API const char *sqlite3_sourceid(void){ return SQLITE_SOURCE_ID; }
  117676. /* IMPLEMENTATION-OF: R-35210-63508 The sqlite3_libversion_number() function
  117677. ** returns an integer equal to SQLITE_VERSION_NUMBER.
  117678. */
  117679. SQLITE_API int sqlite3_libversion_number(void){ return SQLITE_VERSION_NUMBER; }
  117680. /* IMPLEMENTATION-OF: R-20790-14025 The sqlite3_threadsafe() function returns
  117681. ** zero if and only if SQLite was compiled with mutexing code omitted due to
  117682. ** the SQLITE_THREADSAFE compile-time option being set to 0.
  117683. */
  117684. SQLITE_API int sqlite3_threadsafe(void){ return SQLITE_THREADSAFE; }
  117685. #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
  117686. /*
  117687. ** If the following function pointer is not NULL and if
  117688. ** SQLITE_ENABLE_IOTRACE is enabled, then messages describing
  117689. ** I/O active are written using this function. These messages
  117690. ** are intended for debugging activity only.
  117691. */
  117692. SQLITE_PRIVATE void (*sqlite3IoTrace)(const char*, ...) = 0;
  117693. #endif
  117694. /*
  117695. ** If the following global variable points to a string which is the
  117696. ** name of a directory, then that directory will be used to store
  117697. ** temporary files.
  117698. **
  117699. ** See also the "PRAGMA temp_store_directory" SQL command.
  117700. */
  117701. SQLITE_API char *sqlite3_temp_directory = 0;
  117702. /*
  117703. ** If the following global variable points to a string which is the
  117704. ** name of a directory, then that directory will be used to store
  117705. ** all database files specified with a relative pathname.
  117706. **
  117707. ** See also the "PRAGMA data_store_directory" SQL command.
  117708. */
  117709. SQLITE_API char *sqlite3_data_directory = 0;
  117710. /*
  117711. ** Initialize SQLite.
  117712. **
  117713. ** This routine must be called to initialize the memory allocation,
  117714. ** VFS, and mutex subsystems prior to doing any serious work with
  117715. ** SQLite. But as long as you do not compile with SQLITE_OMIT_AUTOINIT
  117716. ** this routine will be called automatically by key routines such as
  117717. ** sqlite3_open().
  117718. **
  117719. ** This routine is a no-op except on its very first call for the process,
  117720. ** or for the first call after a call to sqlite3_shutdown.
  117721. **
  117722. ** The first thread to call this routine runs the initialization to
  117723. ** completion. If subsequent threads call this routine before the first
  117724. ** thread has finished the initialization process, then the subsequent
  117725. ** threads must block until the first thread finishes with the initialization.
  117726. **
  117727. ** The first thread might call this routine recursively. Recursive
  117728. ** calls to this routine should not block, of course. Otherwise the
  117729. ** initialization process would never complete.
  117730. **
  117731. ** Let X be the first thread to enter this routine. Let Y be some other
  117732. ** thread. Then while the initial invocation of this routine by X is
  117733. ** incomplete, it is required that:
  117734. **
  117735. ** * Calls to this routine from Y must block until the outer-most
  117736. ** call by X completes.
  117737. **
  117738. ** * Recursive calls to this routine from thread X return immediately
  117739. ** without blocking.
  117740. */
  117741. SQLITE_API int sqlite3_initialize(void){
  117742. MUTEX_LOGIC( sqlite3_mutex *pMaster; ) /* The main static mutex */
  117743. int rc; /* Result code */
  117744. #ifdef SQLITE_EXTRA_INIT
  117745. int bRunExtraInit = 0; /* Extra initialization needed */
  117746. #endif
  117747. #ifdef SQLITE_OMIT_WSD
  117748. rc = sqlite3_wsd_init(4096, 24);
  117749. if( rc!=SQLITE_OK ){
  117750. return rc;
  117751. }
  117752. #endif
  117753. /* If SQLite is already completely initialized, then this call
  117754. ** to sqlite3_initialize() should be a no-op. But the initialization
  117755. ** must be complete. So isInit must not be set until the very end
  117756. ** of this routine.
  117757. */
  117758. if( sqlite3GlobalConfig.isInit ) return SQLITE_OK;
  117759. /* Make sure the mutex subsystem is initialized. If unable to
  117760. ** initialize the mutex subsystem, return early with the error.
  117761. ** If the system is so sick that we are unable to allocate a mutex,
  117762. ** there is not much SQLite is going to be able to do.
  117763. **
  117764. ** The mutex subsystem must take care of serializing its own
  117765. ** initialization.
  117766. */
  117767. rc = sqlite3MutexInit();
  117768. if( rc ) return rc;
  117769. /* Initialize the malloc() system and the recursive pInitMutex mutex.
  117770. ** This operation is protected by the STATIC_MASTER mutex. Note that
  117771. ** MutexAlloc() is called for a static mutex prior to initializing the
  117772. ** malloc subsystem - this implies that the allocation of a static
  117773. ** mutex must not require support from the malloc subsystem.
  117774. */
  117775. MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
  117776. sqlite3_mutex_enter(pMaster);
  117777. sqlite3GlobalConfig.isMutexInit = 1;
  117778. if( !sqlite3GlobalConfig.isMallocInit ){
  117779. rc = sqlite3MallocInit();
  117780. }
  117781. if( rc==SQLITE_OK ){
  117782. sqlite3GlobalConfig.isMallocInit = 1;
  117783. if( !sqlite3GlobalConfig.pInitMutex ){
  117784. sqlite3GlobalConfig.pInitMutex =
  117785. sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
  117786. if( sqlite3GlobalConfig.bCoreMutex && !sqlite3GlobalConfig.pInitMutex ){
  117787. rc = SQLITE_NOMEM;
  117788. }
  117789. }
  117790. }
  117791. if( rc==SQLITE_OK ){
  117792. sqlite3GlobalConfig.nRefInitMutex++;
  117793. }
  117794. sqlite3_mutex_leave(pMaster);
  117795. /* If rc is not SQLITE_OK at this point, then either the malloc
  117796. ** subsystem could not be initialized or the system failed to allocate
  117797. ** the pInitMutex mutex. Return an error in either case. */
  117798. if( rc!=SQLITE_OK ){
  117799. return rc;
  117800. }
  117801. /* Do the rest of the initialization under the recursive mutex so
  117802. ** that we will be able to handle recursive calls into
  117803. ** sqlite3_initialize(). The recursive calls normally come through
  117804. ** sqlite3_os_init() when it invokes sqlite3_vfs_register(), but other
  117805. ** recursive calls might also be possible.
  117806. **
  117807. ** IMPLEMENTATION-OF: R-00140-37445 SQLite automatically serializes calls
  117808. ** to the xInit method, so the xInit method need not be threadsafe.
  117809. **
  117810. ** The following mutex is what serializes access to the appdef pcache xInit
  117811. ** methods. The sqlite3_pcache_methods.xInit() all is embedded in the
  117812. ** call to sqlite3PcacheInitialize().
  117813. */
  117814. sqlite3_mutex_enter(sqlite3GlobalConfig.pInitMutex);
  117815. if( sqlite3GlobalConfig.isInit==0 && sqlite3GlobalConfig.inProgress==0 ){
  117816. FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
  117817. sqlite3GlobalConfig.inProgress = 1;
  117818. memset(pHash, 0, sizeof(sqlite3GlobalFunctions));
  117819. sqlite3RegisterGlobalFunctions();
  117820. if( sqlite3GlobalConfig.isPCacheInit==0 ){
  117821. rc = sqlite3PcacheInitialize();
  117822. }
  117823. if( rc==SQLITE_OK ){
  117824. sqlite3GlobalConfig.isPCacheInit = 1;
  117825. rc = sqlite3OsInit();
  117826. }
  117827. if( rc==SQLITE_OK ){
  117828. sqlite3PCacheBufferSetup( sqlite3GlobalConfig.pPage,
  117829. sqlite3GlobalConfig.szPage, sqlite3GlobalConfig.nPage);
  117830. sqlite3GlobalConfig.isInit = 1;
  117831. #ifdef SQLITE_EXTRA_INIT
  117832. bRunExtraInit = 1;
  117833. #endif
  117834. }
  117835. sqlite3GlobalConfig.inProgress = 0;
  117836. }
  117837. sqlite3_mutex_leave(sqlite3GlobalConfig.pInitMutex);
  117838. /* Go back under the static mutex and clean up the recursive
  117839. ** mutex to prevent a resource leak.
  117840. */
  117841. sqlite3_mutex_enter(pMaster);
  117842. sqlite3GlobalConfig.nRefInitMutex--;
  117843. if( sqlite3GlobalConfig.nRefInitMutex<=0 ){
  117844. assert( sqlite3GlobalConfig.nRefInitMutex==0 );
  117845. sqlite3_mutex_free(sqlite3GlobalConfig.pInitMutex);
  117846. sqlite3GlobalConfig.pInitMutex = 0;
  117847. }
  117848. sqlite3_mutex_leave(pMaster);
  117849. /* The following is just a sanity check to make sure SQLite has
  117850. ** been compiled correctly. It is important to run this code, but
  117851. ** we don't want to run it too often and soak up CPU cycles for no
  117852. ** reason. So we run it once during initialization.
  117853. */
  117854. #ifndef NDEBUG
  117855. #ifndef SQLITE_OMIT_FLOATING_POINT
  117856. /* This section of code's only "output" is via assert() statements. */
  117857. if ( rc==SQLITE_OK ){
  117858. u64 x = (((u64)1)<<63)-1;
  117859. double y;
  117860. assert(sizeof(x)==8);
  117861. assert(sizeof(x)==sizeof(y));
  117862. memcpy(&y, &x, 8);
  117863. assert( sqlite3IsNaN(y) );
  117864. }
  117865. #endif
  117866. #endif
  117867. /* Do extra initialization steps requested by the SQLITE_EXTRA_INIT
  117868. ** compile-time option.
  117869. */
  117870. #ifdef SQLITE_EXTRA_INIT
  117871. if( bRunExtraInit ){
  117872. int SQLITE_EXTRA_INIT(const char*);
  117873. rc = SQLITE_EXTRA_INIT(0);
  117874. }
  117875. #endif
  117876. return rc;
  117877. }
  117878. /*
  117879. ** Undo the effects of sqlite3_initialize(). Must not be called while
  117880. ** there are outstanding database connections or memory allocations or
  117881. ** while any part of SQLite is otherwise in use in any thread. This
  117882. ** routine is not threadsafe. But it is safe to invoke this routine
  117883. ** on when SQLite is already shut down. If SQLite is already shut down
  117884. ** when this routine is invoked, then this routine is a harmless no-op.
  117885. */
  117886. SQLITE_API int sqlite3_shutdown(void){
  117887. if( sqlite3GlobalConfig.isInit ){
  117888. #ifdef SQLITE_EXTRA_SHUTDOWN
  117889. void SQLITE_EXTRA_SHUTDOWN(void);
  117890. SQLITE_EXTRA_SHUTDOWN();
  117891. #endif
  117892. sqlite3_os_end();
  117893. sqlite3_reset_auto_extension();
  117894. sqlite3GlobalConfig.isInit = 0;
  117895. }
  117896. if( sqlite3GlobalConfig.isPCacheInit ){
  117897. sqlite3PcacheShutdown();
  117898. sqlite3GlobalConfig.isPCacheInit = 0;
  117899. }
  117900. if( sqlite3GlobalConfig.isMallocInit ){
  117901. sqlite3MallocEnd();
  117902. sqlite3GlobalConfig.isMallocInit = 0;
  117903. #ifndef SQLITE_OMIT_SHUTDOWN_DIRECTORIES
  117904. /* The heap subsystem has now been shutdown and these values are supposed
  117905. ** to be NULL or point to memory that was obtained from sqlite3_malloc(),
  117906. ** which would rely on that heap subsystem; therefore, make sure these
  117907. ** values cannot refer to heap memory that was just invalidated when the
  117908. ** heap subsystem was shutdown. This is only done if the current call to
  117909. ** this function resulted in the heap subsystem actually being shutdown.
  117910. */
  117911. sqlite3_data_directory = 0;
  117912. sqlite3_temp_directory = 0;
  117913. #endif
  117914. }
  117915. if( sqlite3GlobalConfig.isMutexInit ){
  117916. sqlite3MutexEnd();
  117917. sqlite3GlobalConfig.isMutexInit = 0;
  117918. }
  117919. return SQLITE_OK;
  117920. }
  117921. /*
  117922. ** This API allows applications to modify the global configuration of
  117923. ** the SQLite library at run-time.
  117924. **
  117925. ** This routine should only be called when there are no outstanding
  117926. ** database connections or memory allocations. This routine is not
  117927. ** threadsafe. Failure to heed these warnings can lead to unpredictable
  117928. ** behavior.
  117929. */
  117930. SQLITE_API int sqlite3_config(int op, ...){
  117931. va_list ap;
  117932. int rc = SQLITE_OK;
  117933. /* sqlite3_config() shall return SQLITE_MISUSE if it is invoked while
  117934. ** the SQLite library is in use. */
  117935. if( sqlite3GlobalConfig.isInit ) return SQLITE_MISUSE_BKPT;
  117936. va_start(ap, op);
  117937. switch( op ){
  117938. /* Mutex configuration options are only available in a threadsafe
  117939. ** compile.
  117940. */
  117941. #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0
  117942. case SQLITE_CONFIG_SINGLETHREAD: {
  117943. /* Disable all mutexing */
  117944. sqlite3GlobalConfig.bCoreMutex = 0;
  117945. sqlite3GlobalConfig.bFullMutex = 0;
  117946. break;
  117947. }
  117948. case SQLITE_CONFIG_MULTITHREAD: {
  117949. /* Disable mutexing of database connections */
  117950. /* Enable mutexing of core data structures */
  117951. sqlite3GlobalConfig.bCoreMutex = 1;
  117952. sqlite3GlobalConfig.bFullMutex = 0;
  117953. break;
  117954. }
  117955. case SQLITE_CONFIG_SERIALIZED: {
  117956. /* Enable all mutexing */
  117957. sqlite3GlobalConfig.bCoreMutex = 1;
  117958. sqlite3GlobalConfig.bFullMutex = 1;
  117959. break;
  117960. }
  117961. case SQLITE_CONFIG_MUTEX: {
  117962. /* Specify an alternative mutex implementation */
  117963. sqlite3GlobalConfig.mutex = *va_arg(ap, sqlite3_mutex_methods*);
  117964. break;
  117965. }
  117966. case SQLITE_CONFIG_GETMUTEX: {
  117967. /* Retrieve the current mutex implementation */
  117968. *va_arg(ap, sqlite3_mutex_methods*) = sqlite3GlobalConfig.mutex;
  117969. break;
  117970. }
  117971. #endif
  117972. case SQLITE_CONFIG_MALLOC: {
  117973. /* Specify an alternative malloc implementation */
  117974. sqlite3GlobalConfig.m = *va_arg(ap, sqlite3_mem_methods*);
  117975. break;
  117976. }
  117977. case SQLITE_CONFIG_GETMALLOC: {
  117978. /* Retrieve the current malloc() implementation */
  117979. if( sqlite3GlobalConfig.m.xMalloc==0 ) sqlite3MemSetDefault();
  117980. *va_arg(ap, sqlite3_mem_methods*) = sqlite3GlobalConfig.m;
  117981. break;
  117982. }
  117983. case SQLITE_CONFIG_MEMSTATUS: {
  117984. /* Enable or disable the malloc status collection */
  117985. sqlite3GlobalConfig.bMemstat = va_arg(ap, int);
  117986. break;
  117987. }
  117988. case SQLITE_CONFIG_SCRATCH: {
  117989. /* Designate a buffer for scratch memory space */
  117990. sqlite3GlobalConfig.pScratch = va_arg(ap, void*);
  117991. sqlite3GlobalConfig.szScratch = va_arg(ap, int);
  117992. sqlite3GlobalConfig.nScratch = va_arg(ap, int);
  117993. break;
  117994. }
  117995. case SQLITE_CONFIG_PAGECACHE: {
  117996. /* Designate a buffer for page cache memory space */
  117997. sqlite3GlobalConfig.pPage = va_arg(ap, void*);
  117998. sqlite3GlobalConfig.szPage = va_arg(ap, int);
  117999. sqlite3GlobalConfig.nPage = va_arg(ap, int);
  118000. break;
  118001. }
  118002. case SQLITE_CONFIG_PCACHE: {
  118003. /* no-op */
  118004. break;
  118005. }
  118006. case SQLITE_CONFIG_GETPCACHE: {
  118007. /* now an error */
  118008. rc = SQLITE_ERROR;
  118009. break;
  118010. }
  118011. case SQLITE_CONFIG_PCACHE2: {
  118012. /* Specify an alternative page cache implementation */
  118013. sqlite3GlobalConfig.pcache2 = *va_arg(ap, sqlite3_pcache_methods2*);
  118014. break;
  118015. }
  118016. case SQLITE_CONFIG_GETPCACHE2: {
  118017. if( sqlite3GlobalConfig.pcache2.xInit==0 ){
  118018. sqlite3PCacheSetDefault();
  118019. }
  118020. *va_arg(ap, sqlite3_pcache_methods2*) = sqlite3GlobalConfig.pcache2;
  118021. break;
  118022. }
  118023. #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
  118024. case SQLITE_CONFIG_HEAP: {
  118025. /* Designate a buffer for heap memory space */
  118026. sqlite3GlobalConfig.pHeap = va_arg(ap, void*);
  118027. sqlite3GlobalConfig.nHeap = va_arg(ap, int);
  118028. sqlite3GlobalConfig.mnReq = va_arg(ap, int);
  118029. if( sqlite3GlobalConfig.mnReq<1 ){
  118030. sqlite3GlobalConfig.mnReq = 1;
  118031. }else if( sqlite3GlobalConfig.mnReq>(1<<12) ){
  118032. /* cap min request size at 2^12 */
  118033. sqlite3GlobalConfig.mnReq = (1<<12);
  118034. }
  118035. if( sqlite3GlobalConfig.pHeap==0 ){
  118036. /* If the heap pointer is NULL, then restore the malloc implementation
  118037. ** back to NULL pointers too. This will cause the malloc to go
  118038. ** back to its default implementation when sqlite3_initialize() is
  118039. ** run.
  118040. */
  118041. memset(&sqlite3GlobalConfig.m, 0, sizeof(sqlite3GlobalConfig.m));
  118042. }else{
  118043. /* The heap pointer is not NULL, then install one of the
  118044. ** mem5.c/mem3.c methods. The enclosing #if guarantees at
  118045. ** least one of these methods is currently enabled.
  118046. */
  118047. #ifdef SQLITE_ENABLE_MEMSYS3
  118048. sqlite3GlobalConfig.m = *sqlite3MemGetMemsys3();
  118049. #endif
  118050. #ifdef SQLITE_ENABLE_MEMSYS5
  118051. sqlite3GlobalConfig.m = *sqlite3MemGetMemsys5();
  118052. #endif
  118053. }
  118054. break;
  118055. }
  118056. #endif
  118057. case SQLITE_CONFIG_LOOKASIDE: {
  118058. sqlite3GlobalConfig.szLookaside = va_arg(ap, int);
  118059. sqlite3GlobalConfig.nLookaside = va_arg(ap, int);
  118060. break;
  118061. }
  118062. /* Record a pointer to the logger function and its first argument.
  118063. ** The default is NULL. Logging is disabled if the function pointer is
  118064. ** NULL.
  118065. */
  118066. case SQLITE_CONFIG_LOG: {
  118067. /* MSVC is picky about pulling func ptrs from va lists.
  118068. ** http://support.microsoft.com/kb/47961
  118069. ** sqlite3GlobalConfig.xLog = va_arg(ap, void(*)(void*,int,const char*));
  118070. */
  118071. typedef void(*LOGFUNC_t)(void*,int,const char*);
  118072. sqlite3GlobalConfig.xLog = va_arg(ap, LOGFUNC_t);
  118073. sqlite3GlobalConfig.pLogArg = va_arg(ap, void*);
  118074. break;
  118075. }
  118076. /* EVIDENCE-OF: R-55548-33817 The compile-time setting for URI filenames
  118077. ** can be changed at start-time using the
  118078. ** sqlite3_config(SQLITE_CONFIG_URI,1) or
  118079. ** sqlite3_config(SQLITE_CONFIG_URI,0) configuration calls.
  118080. */
  118081. case SQLITE_CONFIG_URI: {
  118082. sqlite3GlobalConfig.bOpenUri = va_arg(ap, int);
  118083. break;
  118084. }
  118085. case SQLITE_CONFIG_COVERING_INDEX_SCAN: {
  118086. sqlite3GlobalConfig.bUseCis = va_arg(ap, int);
  118087. break;
  118088. }
  118089. #ifdef SQLITE_ENABLE_SQLLOG
  118090. case SQLITE_CONFIG_SQLLOG: {
  118091. typedef void(*SQLLOGFUNC_t)(void*, sqlite3*, const char*, int);
  118092. sqlite3GlobalConfig.xSqllog = va_arg(ap, SQLLOGFUNC_t);
  118093. sqlite3GlobalConfig.pSqllogArg = va_arg(ap, void *);
  118094. break;
  118095. }
  118096. #endif
  118097. case SQLITE_CONFIG_MMAP_SIZE: {
  118098. sqlite3_int64 szMmap = va_arg(ap, sqlite3_int64);
  118099. sqlite3_int64 mxMmap = va_arg(ap, sqlite3_int64);
  118100. if( mxMmap<0 || mxMmap>SQLITE_MAX_MMAP_SIZE ){
  118101. mxMmap = SQLITE_MAX_MMAP_SIZE;
  118102. }
  118103. sqlite3GlobalConfig.mxMmap = mxMmap;
  118104. if( szMmap<0 ) szMmap = SQLITE_DEFAULT_MMAP_SIZE;
  118105. if( szMmap>mxMmap) szMmap = mxMmap;
  118106. sqlite3GlobalConfig.szMmap = szMmap;
  118107. break;
  118108. }
  118109. #if SQLITE_OS_WIN && defined(SQLITE_WIN32_MALLOC)
  118110. case SQLITE_CONFIG_WIN32_HEAPSIZE: {
  118111. sqlite3GlobalConfig.nHeap = va_arg(ap, int);
  118112. break;
  118113. }
  118114. #endif
  118115. default: {
  118116. rc = SQLITE_ERROR;
  118117. break;
  118118. }
  118119. }
  118120. va_end(ap);
  118121. return rc;
  118122. }
  118123. /*
  118124. ** Set up the lookaside buffers for a database connection.
  118125. ** Return SQLITE_OK on success.
  118126. ** If lookaside is already active, return SQLITE_BUSY.
  118127. **
  118128. ** The sz parameter is the number of bytes in each lookaside slot.
  118129. ** The cnt parameter is the number of slots. If pStart is NULL the
  118130. ** space for the lookaside memory is obtained from sqlite3_malloc().
  118131. ** If pStart is not NULL then it is sz*cnt bytes of memory to use for
  118132. ** the lookaside memory.
  118133. */
  118134. static int setupLookaside(sqlite3 *db, void *pBuf, int sz, int cnt){
  118135. void *pStart;
  118136. if( db->lookaside.nOut ){
  118137. return SQLITE_BUSY;
  118138. }
  118139. /* Free any existing lookaside buffer for this handle before
  118140. ** allocating a new one so we don't have to have space for
  118141. ** both at the same time.
  118142. */
  118143. if( db->lookaside.bMalloced ){
  118144. sqlite3_free(db->lookaside.pStart);
  118145. }
  118146. /* The size of a lookaside slot after ROUNDDOWN8 needs to be larger
  118147. ** than a pointer to be useful.
  118148. */
  118149. sz = ROUNDDOWN8(sz); /* IMP: R-33038-09382 */
  118150. if( sz<=(int)sizeof(LookasideSlot*) ) sz = 0;
  118151. if( cnt<0 ) cnt = 0;
  118152. if( sz==0 || cnt==0 ){
  118153. sz = 0;
  118154. pStart = 0;
  118155. }else if( pBuf==0 ){
  118156. sqlite3BeginBenignMalloc();
  118157. pStart = sqlite3Malloc( sz*cnt ); /* IMP: R-61949-35727 */
  118158. sqlite3EndBenignMalloc();
  118159. if( pStart ) cnt = sqlite3MallocSize(pStart)/sz;
  118160. }else{
  118161. pStart = pBuf;
  118162. }
  118163. db->lookaside.pStart = pStart;
  118164. db->lookaside.pFree = 0;
  118165. db->lookaside.sz = (u16)sz;
  118166. if( pStart ){
  118167. int i;
  118168. LookasideSlot *p;
  118169. assert( sz > (int)sizeof(LookasideSlot*) );
  118170. p = (LookasideSlot*)pStart;
  118171. for(i=cnt-1; i>=0; i--){
  118172. p->pNext = db->lookaside.pFree;
  118173. db->lookaside.pFree = p;
  118174. p = (LookasideSlot*)&((u8*)p)[sz];
  118175. }
  118176. db->lookaside.pEnd = p;
  118177. db->lookaside.bEnabled = 1;
  118178. db->lookaside.bMalloced = pBuf==0 ?1:0;
  118179. }else{
  118180. db->lookaside.pStart = db;
  118181. db->lookaside.pEnd = db;
  118182. db->lookaside.bEnabled = 0;
  118183. db->lookaside.bMalloced = 0;
  118184. }
  118185. return SQLITE_OK;
  118186. }
  118187. /*
  118188. ** Return the mutex associated with a database connection.
  118189. */
  118190. SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3 *db){
  118191. #ifdef SQLITE_ENABLE_API_ARMOR
  118192. if( !sqlite3SafetyCheckOk(db) ){
  118193. (void)SQLITE_MISUSE_BKPT;
  118194. return 0;
  118195. }
  118196. #endif
  118197. return db->mutex;
  118198. }
  118199. /*
  118200. ** Free up as much memory as we can from the given database
  118201. ** connection.
  118202. */
  118203. SQLITE_API int sqlite3_db_release_memory(sqlite3 *db){
  118204. int i;
  118205. #ifdef SQLITE_ENABLE_API_ARMOR
  118206. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  118207. #endif
  118208. sqlite3_mutex_enter(db->mutex);
  118209. sqlite3BtreeEnterAll(db);
  118210. for(i=0; i<db->nDb; i++){
  118211. Btree *pBt = db->aDb[i].pBt;
  118212. if( pBt ){
  118213. Pager *pPager = sqlite3BtreePager(pBt);
  118214. sqlite3PagerShrink(pPager);
  118215. }
  118216. }
  118217. sqlite3BtreeLeaveAll(db);
  118218. sqlite3_mutex_leave(db->mutex);
  118219. return SQLITE_OK;
  118220. }
  118221. /*
  118222. ** Configuration settings for an individual database connection
  118223. */
  118224. SQLITE_API int sqlite3_db_config(sqlite3 *db, int op, ...){
  118225. va_list ap;
  118226. int rc;
  118227. va_start(ap, op);
  118228. switch( op ){
  118229. case SQLITE_DBCONFIG_LOOKASIDE: {
  118230. void *pBuf = va_arg(ap, void*); /* IMP: R-26835-10964 */
  118231. int sz = va_arg(ap, int); /* IMP: R-47871-25994 */
  118232. int cnt = va_arg(ap, int); /* IMP: R-04460-53386 */
  118233. rc = setupLookaside(db, pBuf, sz, cnt);
  118234. break;
  118235. }
  118236. default: {
  118237. static const struct {
  118238. int op; /* The opcode */
  118239. u32 mask; /* Mask of the bit in sqlite3.flags to set/clear */
  118240. } aFlagOp[] = {
  118241. { SQLITE_DBCONFIG_ENABLE_FKEY, SQLITE_ForeignKeys },
  118242. { SQLITE_DBCONFIG_ENABLE_TRIGGER, SQLITE_EnableTrigger },
  118243. };
  118244. unsigned int i;
  118245. rc = SQLITE_ERROR; /* IMP: R-42790-23372 */
  118246. for(i=0; i<ArraySize(aFlagOp); i++){
  118247. if( aFlagOp[i].op==op ){
  118248. int onoff = va_arg(ap, int);
  118249. int *pRes = va_arg(ap, int*);
  118250. int oldFlags = db->flags;
  118251. if( onoff>0 ){
  118252. db->flags |= aFlagOp[i].mask;
  118253. }else if( onoff==0 ){
  118254. db->flags &= ~aFlagOp[i].mask;
  118255. }
  118256. if( oldFlags!=db->flags ){
  118257. sqlite3ExpirePreparedStatements(db);
  118258. }
  118259. if( pRes ){
  118260. *pRes = (db->flags & aFlagOp[i].mask)!=0;
  118261. }
  118262. rc = SQLITE_OK;
  118263. break;
  118264. }
  118265. }
  118266. break;
  118267. }
  118268. }
  118269. va_end(ap);
  118270. return rc;
  118271. }
  118272. /*
  118273. ** Return true if the buffer z[0..n-1] contains all spaces.
  118274. */
  118275. static int allSpaces(const char *z, int n){
  118276. while( n>0 && z[n-1]==' ' ){ n--; }
  118277. return n==0;
  118278. }
  118279. /*
  118280. ** This is the default collating function named "BINARY" which is always
  118281. ** available.
  118282. **
  118283. ** If the padFlag argument is not NULL then space padding at the end
  118284. ** of strings is ignored. This implements the RTRIM collation.
  118285. */
  118286. static int binCollFunc(
  118287. void *padFlag,
  118288. int nKey1, const void *pKey1,
  118289. int nKey2, const void *pKey2
  118290. ){
  118291. int rc, n;
  118292. n = nKey1<nKey2 ? nKey1 : nKey2;
  118293. rc = memcmp(pKey1, pKey2, n);
  118294. if( rc==0 ){
  118295. if( padFlag
  118296. && allSpaces(((char*)pKey1)+n, nKey1-n)
  118297. && allSpaces(((char*)pKey2)+n, nKey2-n)
  118298. ){
  118299. /* Leave rc unchanged at 0 */
  118300. }else{
  118301. rc = nKey1 - nKey2;
  118302. }
  118303. }
  118304. return rc;
  118305. }
  118306. /*
  118307. ** Another built-in collating sequence: NOCASE.
  118308. **
  118309. ** This collating sequence is intended to be used for "case independent
  118310. ** comparison". SQLite's knowledge of upper and lower case equivalents
  118311. ** extends only to the 26 characters used in the English language.
  118312. **
  118313. ** At the moment there is only a UTF-8 implementation.
  118314. */
  118315. static int nocaseCollatingFunc(
  118316. void *NotUsed,
  118317. int nKey1, const void *pKey1,
  118318. int nKey2, const void *pKey2
  118319. ){
  118320. int r = sqlite3StrNICmp(
  118321. (const char *)pKey1, (const char *)pKey2, (nKey1<nKey2)?nKey1:nKey2);
  118322. UNUSED_PARAMETER(NotUsed);
  118323. if( 0==r ){
  118324. r = nKey1-nKey2;
  118325. }
  118326. return r;
  118327. }
  118328. /*
  118329. ** Return the ROWID of the most recent insert
  118330. */
  118331. SQLITE_API sqlite_int64 sqlite3_last_insert_rowid(sqlite3 *db){
  118332. #ifdef SQLITE_ENABLE_API_ARMOR
  118333. if( !sqlite3SafetyCheckOk(db) ){
  118334. (void)SQLITE_MISUSE_BKPT;
  118335. return 0;
  118336. }
  118337. #endif
  118338. return db->lastRowid;
  118339. }
  118340. /*
  118341. ** Return the number of changes in the most recent call to sqlite3_exec().
  118342. */
  118343. SQLITE_API int sqlite3_changes(sqlite3 *db){
  118344. #ifdef SQLITE_ENABLE_API_ARMOR
  118345. if( !sqlite3SafetyCheckOk(db) ){
  118346. (void)SQLITE_MISUSE_BKPT;
  118347. return 0;
  118348. }
  118349. #endif
  118350. return db->nChange;
  118351. }
  118352. /*
  118353. ** Return the number of changes since the database handle was opened.
  118354. */
  118355. SQLITE_API int sqlite3_total_changes(sqlite3 *db){
  118356. #ifdef SQLITE_ENABLE_API_ARMOR
  118357. if( !sqlite3SafetyCheckOk(db) ){
  118358. (void)SQLITE_MISUSE_BKPT;
  118359. return 0;
  118360. }
  118361. #endif
  118362. return db->nTotalChange;
  118363. }
  118364. /*
  118365. ** Close all open savepoints. This function only manipulates fields of the
  118366. ** database handle object, it does not close any savepoints that may be open
  118367. ** at the b-tree/pager level.
  118368. */
  118369. SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *db){
  118370. while( db->pSavepoint ){
  118371. Savepoint *pTmp = db->pSavepoint;
  118372. db->pSavepoint = pTmp->pNext;
  118373. sqlite3DbFree(db, pTmp);
  118374. }
  118375. db->nSavepoint = 0;
  118376. db->nStatement = 0;
  118377. db->isTransactionSavepoint = 0;
  118378. }
  118379. /*
  118380. ** Invoke the destructor function associated with FuncDef p, if any. Except,
  118381. ** if this is not the last copy of the function, do not invoke it. Multiple
  118382. ** copies of a single function are created when create_function() is called
  118383. ** with SQLITE_ANY as the encoding.
  118384. */
  118385. static void functionDestroy(sqlite3 *db, FuncDef *p){
  118386. FuncDestructor *pDestructor = p->pDestructor;
  118387. if( pDestructor ){
  118388. pDestructor->nRef--;
  118389. if( pDestructor->nRef==0 ){
  118390. pDestructor->xDestroy(pDestructor->pUserData);
  118391. sqlite3DbFree(db, pDestructor);
  118392. }
  118393. }
  118394. }
  118395. /*
  118396. ** Disconnect all sqlite3_vtab objects that belong to database connection
  118397. ** db. This is called when db is being closed.
  118398. */
  118399. static void disconnectAllVtab(sqlite3 *db){
  118400. #ifndef SQLITE_OMIT_VIRTUALTABLE
  118401. int i;
  118402. sqlite3BtreeEnterAll(db);
  118403. for(i=0; i<db->nDb; i++){
  118404. Schema *pSchema = db->aDb[i].pSchema;
  118405. if( db->aDb[i].pSchema ){
  118406. HashElem *p;
  118407. for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){
  118408. Table *pTab = (Table *)sqliteHashData(p);
  118409. if( IsVirtual(pTab) ) sqlite3VtabDisconnect(db, pTab);
  118410. }
  118411. }
  118412. }
  118413. sqlite3VtabUnlockList(db);
  118414. sqlite3BtreeLeaveAll(db);
  118415. #else
  118416. UNUSED_PARAMETER(db);
  118417. #endif
  118418. }
  118419. /*
  118420. ** Return TRUE if database connection db has unfinalized prepared
  118421. ** statements or unfinished sqlite3_backup objects.
  118422. */
  118423. static int connectionIsBusy(sqlite3 *db){
  118424. int j;
  118425. assert( sqlite3_mutex_held(db->mutex) );
  118426. if( db->pVdbe ) return 1;
  118427. for(j=0; j<db->nDb; j++){
  118428. Btree *pBt = db->aDb[j].pBt;
  118429. if( pBt && sqlite3BtreeIsInBackup(pBt) ) return 1;
  118430. }
  118431. return 0;
  118432. }
  118433. /*
  118434. ** Close an existing SQLite database
  118435. */
  118436. static int sqlite3Close(sqlite3 *db, int forceZombie){
  118437. if( !db ){
  118438. /* EVIDENCE-OF: R-63257-11740 Calling sqlite3_close() or
  118439. ** sqlite3_close_v2() with a NULL pointer argument is a harmless no-op. */
  118440. return SQLITE_OK;
  118441. }
  118442. if( !sqlite3SafetyCheckSickOrOk(db) ){
  118443. return SQLITE_MISUSE_BKPT;
  118444. }
  118445. sqlite3_mutex_enter(db->mutex);
  118446. /* Force xDisconnect calls on all virtual tables */
  118447. disconnectAllVtab(db);
  118448. /* If a transaction is open, the disconnectAllVtab() call above
  118449. ** will not have called the xDisconnect() method on any virtual
  118450. ** tables in the db->aVTrans[] array. The following sqlite3VtabRollback()
  118451. ** call will do so. We need to do this before the check for active
  118452. ** SQL statements below, as the v-table implementation may be storing
  118453. ** some prepared statements internally.
  118454. */
  118455. sqlite3VtabRollback(db);
  118456. /* Legacy behavior (sqlite3_close() behavior) is to return
  118457. ** SQLITE_BUSY if the connection can not be closed immediately.
  118458. */
  118459. if( !forceZombie && connectionIsBusy(db) ){
  118460. sqlite3ErrorWithMsg(db, SQLITE_BUSY, "unable to close due to unfinalized "
  118461. "statements or unfinished backups");
  118462. sqlite3_mutex_leave(db->mutex);
  118463. return SQLITE_BUSY;
  118464. }
  118465. #ifdef SQLITE_ENABLE_SQLLOG
  118466. if( sqlite3GlobalConfig.xSqllog ){
  118467. /* Closing the handle. Fourth parameter is passed the value 2. */
  118468. sqlite3GlobalConfig.xSqllog(sqlite3GlobalConfig.pSqllogArg, db, 0, 2);
  118469. }
  118470. #endif
  118471. /* Convert the connection into a zombie and then close it.
  118472. */
  118473. db->magic = SQLITE_MAGIC_ZOMBIE;
  118474. sqlite3LeaveMutexAndCloseZombie(db);
  118475. return SQLITE_OK;
  118476. }
  118477. /*
  118478. ** Two variations on the public interface for closing a database
  118479. ** connection. The sqlite3_close() version returns SQLITE_BUSY and
  118480. ** leaves the connection option if there are unfinalized prepared
  118481. ** statements or unfinished sqlite3_backups. The sqlite3_close_v2()
  118482. ** version forces the connection to become a zombie if there are
  118483. ** unclosed resources, and arranges for deallocation when the last
  118484. ** prepare statement or sqlite3_backup closes.
  118485. */
  118486. SQLITE_API int sqlite3_close(sqlite3 *db){ return sqlite3Close(db,0); }
  118487. SQLITE_API int sqlite3_close_v2(sqlite3 *db){ return sqlite3Close(db,1); }
  118488. /*
  118489. ** Close the mutex on database connection db.
  118490. **
  118491. ** Furthermore, if database connection db is a zombie (meaning that there
  118492. ** has been a prior call to sqlite3_close(db) or sqlite3_close_v2(db)) and
  118493. ** every sqlite3_stmt has now been finalized and every sqlite3_backup has
  118494. ** finished, then free all resources.
  118495. */
  118496. SQLITE_PRIVATE void sqlite3LeaveMutexAndCloseZombie(sqlite3 *db){
  118497. HashElem *i; /* Hash table iterator */
  118498. int j;
  118499. /* If there are outstanding sqlite3_stmt or sqlite3_backup objects
  118500. ** or if the connection has not yet been closed by sqlite3_close_v2(),
  118501. ** then just leave the mutex and return.
  118502. */
  118503. if( db->magic!=SQLITE_MAGIC_ZOMBIE || connectionIsBusy(db) ){
  118504. sqlite3_mutex_leave(db->mutex);
  118505. return;
  118506. }
  118507. /* If we reach this point, it means that the database connection has
  118508. ** closed all sqlite3_stmt and sqlite3_backup objects and has been
  118509. ** passed to sqlite3_close (meaning that it is a zombie). Therefore,
  118510. ** go ahead and free all resources.
  118511. */
  118512. /* If a transaction is open, roll it back. This also ensures that if
  118513. ** any database schemas have been modified by an uncommitted transaction
  118514. ** they are reset. And that the required b-tree mutex is held to make
  118515. ** the pager rollback and schema reset an atomic operation. */
  118516. sqlite3RollbackAll(db, SQLITE_OK);
  118517. /* Free any outstanding Savepoint structures. */
  118518. sqlite3CloseSavepoints(db);
  118519. /* Close all database connections */
  118520. for(j=0; j<db->nDb; j++){
  118521. struct Db *pDb = &db->aDb[j];
  118522. if( pDb->pBt ){
  118523. sqlite3BtreeClose(pDb->pBt);
  118524. pDb->pBt = 0;
  118525. if( j!=1 ){
  118526. pDb->pSchema = 0;
  118527. }
  118528. }
  118529. }
  118530. /* Clear the TEMP schema separately and last */
  118531. if( db->aDb[1].pSchema ){
  118532. sqlite3SchemaClear(db->aDb[1].pSchema);
  118533. }
  118534. sqlite3VtabUnlockList(db);
  118535. /* Free up the array of auxiliary databases */
  118536. sqlite3CollapseDatabaseArray(db);
  118537. assert( db->nDb<=2 );
  118538. assert( db->aDb==db->aDbStatic );
  118539. /* Tell the code in notify.c that the connection no longer holds any
  118540. ** locks and does not require any further unlock-notify callbacks.
  118541. */
  118542. sqlite3ConnectionClosed(db);
  118543. for(j=0; j<ArraySize(db->aFunc.a); j++){
  118544. FuncDef *pNext, *pHash, *p;
  118545. for(p=db->aFunc.a[j]; p; p=pHash){
  118546. pHash = p->pHash;
  118547. while( p ){
  118548. functionDestroy(db, p);
  118549. pNext = p->pNext;
  118550. sqlite3DbFree(db, p);
  118551. p = pNext;
  118552. }
  118553. }
  118554. }
  118555. for(i=sqliteHashFirst(&db->aCollSeq); i; i=sqliteHashNext(i)){
  118556. CollSeq *pColl = (CollSeq *)sqliteHashData(i);
  118557. /* Invoke any destructors registered for collation sequence user data. */
  118558. for(j=0; j<3; j++){
  118559. if( pColl[j].xDel ){
  118560. pColl[j].xDel(pColl[j].pUser);
  118561. }
  118562. }
  118563. sqlite3DbFree(db, pColl);
  118564. }
  118565. sqlite3HashClear(&db->aCollSeq);
  118566. #ifndef SQLITE_OMIT_VIRTUALTABLE
  118567. for(i=sqliteHashFirst(&db->aModule); i; i=sqliteHashNext(i)){
  118568. Module *pMod = (Module *)sqliteHashData(i);
  118569. if( pMod->xDestroy ){
  118570. pMod->xDestroy(pMod->pAux);
  118571. }
  118572. sqlite3DbFree(db, pMod);
  118573. }
  118574. sqlite3HashClear(&db->aModule);
  118575. #endif
  118576. sqlite3Error(db, SQLITE_OK); /* Deallocates any cached error strings. */
  118577. sqlite3ValueFree(db->pErr);
  118578. sqlite3CloseExtensions(db);
  118579. #if SQLITE_USER_AUTHENTICATION
  118580. sqlite3_free(db->auth.zAuthUser);
  118581. sqlite3_free(db->auth.zAuthPW);
  118582. #endif
  118583. db->magic = SQLITE_MAGIC_ERROR;
  118584. /* The temp-database schema is allocated differently from the other schema
  118585. ** objects (using sqliteMalloc() directly, instead of sqlite3BtreeSchema()).
  118586. ** So it needs to be freed here. Todo: Why not roll the temp schema into
  118587. ** the same sqliteMalloc() as the one that allocates the database
  118588. ** structure?
  118589. */
  118590. sqlite3DbFree(db, db->aDb[1].pSchema);
  118591. sqlite3_mutex_leave(db->mutex);
  118592. db->magic = SQLITE_MAGIC_CLOSED;
  118593. sqlite3_mutex_free(db->mutex);
  118594. assert( db->lookaside.nOut==0 ); /* Fails on a lookaside memory leak */
  118595. if( db->lookaside.bMalloced ){
  118596. sqlite3_free(db->lookaside.pStart);
  118597. }
  118598. sqlite3_free(db);
  118599. }
  118600. /*
  118601. ** Rollback all database files. If tripCode is not SQLITE_OK, then
  118602. ** any open cursors are invalidated ("tripped" - as in "tripping a circuit
  118603. ** breaker") and made to return tripCode if there are any further
  118604. ** attempts to use that cursor.
  118605. */
  118606. SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3 *db, int tripCode){
  118607. int i;
  118608. int inTrans = 0;
  118609. assert( sqlite3_mutex_held(db->mutex) );
  118610. sqlite3BeginBenignMalloc();
  118611. /* Obtain all b-tree mutexes before making any calls to BtreeRollback().
  118612. ** This is important in case the transaction being rolled back has
  118613. ** modified the database schema. If the b-tree mutexes are not taken
  118614. ** here, then another shared-cache connection might sneak in between
  118615. ** the database rollback and schema reset, which can cause false
  118616. ** corruption reports in some cases. */
  118617. sqlite3BtreeEnterAll(db);
  118618. for(i=0; i<db->nDb; i++){
  118619. Btree *p = db->aDb[i].pBt;
  118620. if( p ){
  118621. if( sqlite3BtreeIsInTrans(p) ){
  118622. inTrans = 1;
  118623. }
  118624. sqlite3BtreeRollback(p, tripCode);
  118625. }
  118626. }
  118627. sqlite3VtabRollback(db);
  118628. sqlite3EndBenignMalloc();
  118629. if( (db->flags&SQLITE_InternChanges)!=0 && db->init.busy==0 ){
  118630. sqlite3ExpirePreparedStatements(db);
  118631. sqlite3ResetAllSchemasOfConnection(db);
  118632. }
  118633. sqlite3BtreeLeaveAll(db);
  118634. /* Any deferred constraint violations have now been resolved. */
  118635. db->nDeferredCons = 0;
  118636. db->nDeferredImmCons = 0;
  118637. db->flags &= ~SQLITE_DeferFKs;
  118638. /* If one has been configured, invoke the rollback-hook callback */
  118639. if( db->xRollbackCallback && (inTrans || !db->autoCommit) ){
  118640. db->xRollbackCallback(db->pRollbackArg);
  118641. }
  118642. }
  118643. /*
  118644. ** Return a static string containing the name corresponding to the error code
  118645. ** specified in the argument.
  118646. */
  118647. #if (defined(SQLITE_DEBUG) && SQLITE_OS_WIN) || defined(SQLITE_TEST)
  118648. SQLITE_PRIVATE const char *sqlite3ErrName(int rc){
  118649. const char *zName = 0;
  118650. int i, origRc = rc;
  118651. for(i=0; i<2 && zName==0; i++, rc &= 0xff){
  118652. switch( rc ){
  118653. case SQLITE_OK: zName = "SQLITE_OK"; break;
  118654. case SQLITE_ERROR: zName = "SQLITE_ERROR"; break;
  118655. case SQLITE_INTERNAL: zName = "SQLITE_INTERNAL"; break;
  118656. case SQLITE_PERM: zName = "SQLITE_PERM"; break;
  118657. case SQLITE_ABORT: zName = "SQLITE_ABORT"; break;
  118658. case SQLITE_ABORT_ROLLBACK: zName = "SQLITE_ABORT_ROLLBACK"; break;
  118659. case SQLITE_BUSY: zName = "SQLITE_BUSY"; break;
  118660. case SQLITE_BUSY_RECOVERY: zName = "SQLITE_BUSY_RECOVERY"; break;
  118661. case SQLITE_BUSY_SNAPSHOT: zName = "SQLITE_BUSY_SNAPSHOT"; break;
  118662. case SQLITE_LOCKED: zName = "SQLITE_LOCKED"; break;
  118663. case SQLITE_LOCKED_SHAREDCACHE: zName = "SQLITE_LOCKED_SHAREDCACHE";break;
  118664. case SQLITE_NOMEM: zName = "SQLITE_NOMEM"; break;
  118665. case SQLITE_READONLY: zName = "SQLITE_READONLY"; break;
  118666. case SQLITE_READONLY_RECOVERY: zName = "SQLITE_READONLY_RECOVERY"; break;
  118667. case SQLITE_READONLY_CANTLOCK: zName = "SQLITE_READONLY_CANTLOCK"; break;
  118668. case SQLITE_READONLY_ROLLBACK: zName = "SQLITE_READONLY_ROLLBACK"; break;
  118669. case SQLITE_READONLY_DBMOVED: zName = "SQLITE_READONLY_DBMOVED"; break;
  118670. case SQLITE_INTERRUPT: zName = "SQLITE_INTERRUPT"; break;
  118671. case SQLITE_IOERR: zName = "SQLITE_IOERR"; break;
  118672. case SQLITE_IOERR_READ: zName = "SQLITE_IOERR_READ"; break;
  118673. case SQLITE_IOERR_SHORT_READ: zName = "SQLITE_IOERR_SHORT_READ"; break;
  118674. case SQLITE_IOERR_WRITE: zName = "SQLITE_IOERR_WRITE"; break;
  118675. case SQLITE_IOERR_FSYNC: zName = "SQLITE_IOERR_FSYNC"; break;
  118676. case SQLITE_IOERR_DIR_FSYNC: zName = "SQLITE_IOERR_DIR_FSYNC"; break;
  118677. case SQLITE_IOERR_TRUNCATE: zName = "SQLITE_IOERR_TRUNCATE"; break;
  118678. case SQLITE_IOERR_FSTAT: zName = "SQLITE_IOERR_FSTAT"; break;
  118679. case SQLITE_IOERR_UNLOCK: zName = "SQLITE_IOERR_UNLOCK"; break;
  118680. case SQLITE_IOERR_RDLOCK: zName = "SQLITE_IOERR_RDLOCK"; break;
  118681. case SQLITE_IOERR_DELETE: zName = "SQLITE_IOERR_DELETE"; break;
  118682. case SQLITE_IOERR_NOMEM: zName = "SQLITE_IOERR_NOMEM"; break;
  118683. case SQLITE_IOERR_ACCESS: zName = "SQLITE_IOERR_ACCESS"; break;
  118684. case SQLITE_IOERR_CHECKRESERVEDLOCK:
  118685. zName = "SQLITE_IOERR_CHECKRESERVEDLOCK"; break;
  118686. case SQLITE_IOERR_LOCK: zName = "SQLITE_IOERR_LOCK"; break;
  118687. case SQLITE_IOERR_CLOSE: zName = "SQLITE_IOERR_CLOSE"; break;
  118688. case SQLITE_IOERR_DIR_CLOSE: zName = "SQLITE_IOERR_DIR_CLOSE"; break;
  118689. case SQLITE_IOERR_SHMOPEN: zName = "SQLITE_IOERR_SHMOPEN"; break;
  118690. case SQLITE_IOERR_SHMSIZE: zName = "SQLITE_IOERR_SHMSIZE"; break;
  118691. case SQLITE_IOERR_SHMLOCK: zName = "SQLITE_IOERR_SHMLOCK"; break;
  118692. case SQLITE_IOERR_SHMMAP: zName = "SQLITE_IOERR_SHMMAP"; break;
  118693. case SQLITE_IOERR_SEEK: zName = "SQLITE_IOERR_SEEK"; break;
  118694. case SQLITE_IOERR_DELETE_NOENT: zName = "SQLITE_IOERR_DELETE_NOENT";break;
  118695. case SQLITE_IOERR_MMAP: zName = "SQLITE_IOERR_MMAP"; break;
  118696. case SQLITE_IOERR_GETTEMPPATH: zName = "SQLITE_IOERR_GETTEMPPATH"; break;
  118697. case SQLITE_IOERR_CONVPATH: zName = "SQLITE_IOERR_CONVPATH"; break;
  118698. case SQLITE_CORRUPT: zName = "SQLITE_CORRUPT"; break;
  118699. case SQLITE_CORRUPT_VTAB: zName = "SQLITE_CORRUPT_VTAB"; break;
  118700. case SQLITE_NOTFOUND: zName = "SQLITE_NOTFOUND"; break;
  118701. case SQLITE_FULL: zName = "SQLITE_FULL"; break;
  118702. case SQLITE_CANTOPEN: zName = "SQLITE_CANTOPEN"; break;
  118703. case SQLITE_CANTOPEN_NOTEMPDIR: zName = "SQLITE_CANTOPEN_NOTEMPDIR";break;
  118704. case SQLITE_CANTOPEN_ISDIR: zName = "SQLITE_CANTOPEN_ISDIR"; break;
  118705. case SQLITE_CANTOPEN_FULLPATH: zName = "SQLITE_CANTOPEN_FULLPATH"; break;
  118706. case SQLITE_CANTOPEN_CONVPATH: zName = "SQLITE_CANTOPEN_CONVPATH"; break;
  118707. case SQLITE_PROTOCOL: zName = "SQLITE_PROTOCOL"; break;
  118708. case SQLITE_EMPTY: zName = "SQLITE_EMPTY"; break;
  118709. case SQLITE_SCHEMA: zName = "SQLITE_SCHEMA"; break;
  118710. case SQLITE_TOOBIG: zName = "SQLITE_TOOBIG"; break;
  118711. case SQLITE_CONSTRAINT: zName = "SQLITE_CONSTRAINT"; break;
  118712. case SQLITE_CONSTRAINT_UNIQUE: zName = "SQLITE_CONSTRAINT_UNIQUE"; break;
  118713. case SQLITE_CONSTRAINT_TRIGGER: zName = "SQLITE_CONSTRAINT_TRIGGER";break;
  118714. case SQLITE_CONSTRAINT_FOREIGNKEY:
  118715. zName = "SQLITE_CONSTRAINT_FOREIGNKEY"; break;
  118716. case SQLITE_CONSTRAINT_CHECK: zName = "SQLITE_CONSTRAINT_CHECK"; break;
  118717. case SQLITE_CONSTRAINT_PRIMARYKEY:
  118718. zName = "SQLITE_CONSTRAINT_PRIMARYKEY"; break;
  118719. case SQLITE_CONSTRAINT_NOTNULL: zName = "SQLITE_CONSTRAINT_NOTNULL";break;
  118720. case SQLITE_CONSTRAINT_COMMITHOOK:
  118721. zName = "SQLITE_CONSTRAINT_COMMITHOOK"; break;
  118722. case SQLITE_CONSTRAINT_VTAB: zName = "SQLITE_CONSTRAINT_VTAB"; break;
  118723. case SQLITE_CONSTRAINT_FUNCTION:
  118724. zName = "SQLITE_CONSTRAINT_FUNCTION"; break;
  118725. case SQLITE_CONSTRAINT_ROWID: zName = "SQLITE_CONSTRAINT_ROWID"; break;
  118726. case SQLITE_MISMATCH: zName = "SQLITE_MISMATCH"; break;
  118727. case SQLITE_MISUSE: zName = "SQLITE_MISUSE"; break;
  118728. case SQLITE_NOLFS: zName = "SQLITE_NOLFS"; break;
  118729. case SQLITE_AUTH: zName = "SQLITE_AUTH"; break;
  118730. case SQLITE_FORMAT: zName = "SQLITE_FORMAT"; break;
  118731. case SQLITE_RANGE: zName = "SQLITE_RANGE"; break;
  118732. case SQLITE_NOTADB: zName = "SQLITE_NOTADB"; break;
  118733. case SQLITE_ROW: zName = "SQLITE_ROW"; break;
  118734. case SQLITE_NOTICE: zName = "SQLITE_NOTICE"; break;
  118735. case SQLITE_NOTICE_RECOVER_WAL: zName = "SQLITE_NOTICE_RECOVER_WAL";break;
  118736. case SQLITE_NOTICE_RECOVER_ROLLBACK:
  118737. zName = "SQLITE_NOTICE_RECOVER_ROLLBACK"; break;
  118738. case SQLITE_WARNING: zName = "SQLITE_WARNING"; break;
  118739. case SQLITE_WARNING_AUTOINDEX: zName = "SQLITE_WARNING_AUTOINDEX"; break;
  118740. case SQLITE_DONE: zName = "SQLITE_DONE"; break;
  118741. }
  118742. }
  118743. if( zName==0 ){
  118744. static char zBuf[50];
  118745. sqlite3_snprintf(sizeof(zBuf), zBuf, "SQLITE_UNKNOWN(%d)", origRc);
  118746. zName = zBuf;
  118747. }
  118748. return zName;
  118749. }
  118750. #endif
  118751. /*
  118752. ** Return a static string that describes the kind of error specified in the
  118753. ** argument.
  118754. */
  118755. SQLITE_PRIVATE const char *sqlite3ErrStr(int rc){
  118756. static const char* const aMsg[] = {
  118757. /* SQLITE_OK */ "not an error",
  118758. /* SQLITE_ERROR */ "SQL logic error or missing database",
  118759. /* SQLITE_INTERNAL */ 0,
  118760. /* SQLITE_PERM */ "access permission denied",
  118761. /* SQLITE_ABORT */ "callback requested query abort",
  118762. /* SQLITE_BUSY */ "database is locked",
  118763. /* SQLITE_LOCKED */ "database table is locked",
  118764. /* SQLITE_NOMEM */ "out of memory",
  118765. /* SQLITE_READONLY */ "attempt to write a readonly database",
  118766. /* SQLITE_INTERRUPT */ "interrupted",
  118767. /* SQLITE_IOERR */ "disk I/O error",
  118768. /* SQLITE_CORRUPT */ "database disk image is malformed",
  118769. /* SQLITE_NOTFOUND */ "unknown operation",
  118770. /* SQLITE_FULL */ "database or disk is full",
  118771. /* SQLITE_CANTOPEN */ "unable to open database file",
  118772. /* SQLITE_PROTOCOL */ "locking protocol",
  118773. /* SQLITE_EMPTY */ "table contains no data",
  118774. /* SQLITE_SCHEMA */ "database schema has changed",
  118775. /* SQLITE_TOOBIG */ "string or blob too big",
  118776. /* SQLITE_CONSTRAINT */ "constraint failed",
  118777. /* SQLITE_MISMATCH */ "datatype mismatch",
  118778. /* SQLITE_MISUSE */ "library routine called out of sequence",
  118779. /* SQLITE_NOLFS */ "large file support is disabled",
  118780. /* SQLITE_AUTH */ "authorization denied",
  118781. /* SQLITE_FORMAT */ "auxiliary database format error",
  118782. /* SQLITE_RANGE */ "bind or column index out of range",
  118783. /* SQLITE_NOTADB */ "file is encrypted or is not a database",
  118784. };
  118785. const char *zErr = "unknown error";
  118786. switch( rc ){
  118787. case SQLITE_ABORT_ROLLBACK: {
  118788. zErr = "abort due to ROLLBACK";
  118789. break;
  118790. }
  118791. default: {
  118792. rc &= 0xff;
  118793. if( ALWAYS(rc>=0) && rc<ArraySize(aMsg) && aMsg[rc]!=0 ){
  118794. zErr = aMsg[rc];
  118795. }
  118796. break;
  118797. }
  118798. }
  118799. return zErr;
  118800. }
  118801. /*
  118802. ** This routine implements a busy callback that sleeps and tries
  118803. ** again until a timeout value is reached. The timeout value is
  118804. ** an integer number of milliseconds passed in as the first
  118805. ** argument.
  118806. */
  118807. static int sqliteDefaultBusyCallback(
  118808. void *ptr, /* Database connection */
  118809. int count /* Number of times table has been busy */
  118810. ){
  118811. #if SQLITE_OS_WIN || (defined(HAVE_USLEEP) && HAVE_USLEEP)
  118812. static const u8 delays[] =
  118813. { 1, 2, 5, 10, 15, 20, 25, 25, 25, 50, 50, 100 };
  118814. static const u8 totals[] =
  118815. { 0, 1, 3, 8, 18, 33, 53, 78, 103, 128, 178, 228 };
  118816. # define NDELAY ArraySize(delays)
  118817. sqlite3 *db = (sqlite3 *)ptr;
  118818. int timeout = db->busyTimeout;
  118819. int delay, prior;
  118820. assert( count>=0 );
  118821. if( count < NDELAY ){
  118822. delay = delays[count];
  118823. prior = totals[count];
  118824. }else{
  118825. delay = delays[NDELAY-1];
  118826. prior = totals[NDELAY-1] + delay*(count-(NDELAY-1));
  118827. }
  118828. if( prior + delay > timeout ){
  118829. delay = timeout - prior;
  118830. if( delay<=0 ) return 0;
  118831. }
  118832. sqlite3OsSleep(db->pVfs, delay*1000);
  118833. return 1;
  118834. #else
  118835. sqlite3 *db = (sqlite3 *)ptr;
  118836. int timeout = ((sqlite3 *)ptr)->busyTimeout;
  118837. if( (count+1)*1000 > timeout ){
  118838. return 0;
  118839. }
  118840. sqlite3OsSleep(db->pVfs, 1000000);
  118841. return 1;
  118842. #endif
  118843. }
  118844. /*
  118845. ** Invoke the given busy handler.
  118846. **
  118847. ** This routine is called when an operation failed with a lock.
  118848. ** If this routine returns non-zero, the lock is retried. If it
  118849. ** returns 0, the operation aborts with an SQLITE_BUSY error.
  118850. */
  118851. SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler *p){
  118852. int rc;
  118853. if( NEVER(p==0) || p->xFunc==0 || p->nBusy<0 ) return 0;
  118854. rc = p->xFunc(p->pArg, p->nBusy);
  118855. if( rc==0 ){
  118856. p->nBusy = -1;
  118857. }else{
  118858. p->nBusy++;
  118859. }
  118860. return rc;
  118861. }
  118862. /*
  118863. ** This routine sets the busy callback for an Sqlite database to the
  118864. ** given callback function with the given argument.
  118865. */
  118866. SQLITE_API int sqlite3_busy_handler(
  118867. sqlite3 *db,
  118868. int (*xBusy)(void*,int),
  118869. void *pArg
  118870. ){
  118871. #ifdef SQLITE_ENABLE_API_ARMOR
  118872. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE;
  118873. #endif
  118874. sqlite3_mutex_enter(db->mutex);
  118875. db->busyHandler.xFunc = xBusy;
  118876. db->busyHandler.pArg = pArg;
  118877. db->busyHandler.nBusy = 0;
  118878. db->busyTimeout = 0;
  118879. sqlite3_mutex_leave(db->mutex);
  118880. return SQLITE_OK;
  118881. }
  118882. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  118883. /*
  118884. ** This routine sets the progress callback for an Sqlite database to the
  118885. ** given callback function with the given argument. The progress callback will
  118886. ** be invoked every nOps opcodes.
  118887. */
  118888. SQLITE_API void sqlite3_progress_handler(
  118889. sqlite3 *db,
  118890. int nOps,
  118891. int (*xProgress)(void*),
  118892. void *pArg
  118893. ){
  118894. #ifdef SQLITE_ENABLE_API_ARMOR
  118895. if( !sqlite3SafetyCheckOk(db) ){
  118896. (void)SQLITE_MISUSE_BKPT;
  118897. return;
  118898. }
  118899. #endif
  118900. sqlite3_mutex_enter(db->mutex);
  118901. if( nOps>0 ){
  118902. db->xProgress = xProgress;
  118903. db->nProgressOps = (unsigned)nOps;
  118904. db->pProgressArg = pArg;
  118905. }else{
  118906. db->xProgress = 0;
  118907. db->nProgressOps = 0;
  118908. db->pProgressArg = 0;
  118909. }
  118910. sqlite3_mutex_leave(db->mutex);
  118911. }
  118912. #endif
  118913. /*
  118914. ** This routine installs a default busy handler that waits for the
  118915. ** specified number of milliseconds before returning 0.
  118916. */
  118917. SQLITE_API int sqlite3_busy_timeout(sqlite3 *db, int ms){
  118918. #ifdef SQLITE_ENABLE_API_ARMOR
  118919. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  118920. #endif
  118921. if( ms>0 ){
  118922. sqlite3_busy_handler(db, sqliteDefaultBusyCallback, (void*)db);
  118923. db->busyTimeout = ms;
  118924. }else{
  118925. sqlite3_busy_handler(db, 0, 0);
  118926. }
  118927. return SQLITE_OK;
  118928. }
  118929. /*
  118930. ** Cause any pending operation to stop at its earliest opportunity.
  118931. */
  118932. SQLITE_API void sqlite3_interrupt(sqlite3 *db){
  118933. #ifdef SQLITE_ENABLE_API_ARMOR
  118934. if( !sqlite3SafetyCheckOk(db) ){
  118935. (void)SQLITE_MISUSE_BKPT;
  118936. return;
  118937. }
  118938. #endif
  118939. db->u1.isInterrupted = 1;
  118940. }
  118941. /*
  118942. ** This function is exactly the same as sqlite3_create_function(), except
  118943. ** that it is designed to be called by internal code. The difference is
  118944. ** that if a malloc() fails in sqlite3_create_function(), an error code
  118945. ** is returned and the mallocFailed flag cleared.
  118946. */
  118947. SQLITE_PRIVATE int sqlite3CreateFunc(
  118948. sqlite3 *db,
  118949. const char *zFunctionName,
  118950. int nArg,
  118951. int enc,
  118952. void *pUserData,
  118953. void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
  118954. void (*xStep)(sqlite3_context*,int,sqlite3_value **),
  118955. void (*xFinal)(sqlite3_context*),
  118956. FuncDestructor *pDestructor
  118957. ){
  118958. FuncDef *p;
  118959. int nName;
  118960. int extraFlags;
  118961. assert( sqlite3_mutex_held(db->mutex) );
  118962. if( zFunctionName==0 ||
  118963. (xFunc && (xFinal || xStep)) ||
  118964. (!xFunc && (xFinal && !xStep)) ||
  118965. (!xFunc && (!xFinal && xStep)) ||
  118966. (nArg<-1 || nArg>SQLITE_MAX_FUNCTION_ARG) ||
  118967. (255<(nName = sqlite3Strlen30( zFunctionName))) ){
  118968. return SQLITE_MISUSE_BKPT;
  118969. }
  118970. assert( SQLITE_FUNC_CONSTANT==SQLITE_DETERMINISTIC );
  118971. extraFlags = enc & SQLITE_DETERMINISTIC;
  118972. enc &= (SQLITE_FUNC_ENCMASK|SQLITE_ANY);
  118973. #ifndef SQLITE_OMIT_UTF16
  118974. /* If SQLITE_UTF16 is specified as the encoding type, transform this
  118975. ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
  118976. ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
  118977. **
  118978. ** If SQLITE_ANY is specified, add three versions of the function
  118979. ** to the hash table.
  118980. */
  118981. if( enc==SQLITE_UTF16 ){
  118982. enc = SQLITE_UTF16NATIVE;
  118983. }else if( enc==SQLITE_ANY ){
  118984. int rc;
  118985. rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF8|extraFlags,
  118986. pUserData, xFunc, xStep, xFinal, pDestructor);
  118987. if( rc==SQLITE_OK ){
  118988. rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF16LE|extraFlags,
  118989. pUserData, xFunc, xStep, xFinal, pDestructor);
  118990. }
  118991. if( rc!=SQLITE_OK ){
  118992. return rc;
  118993. }
  118994. enc = SQLITE_UTF16BE;
  118995. }
  118996. #else
  118997. enc = SQLITE_UTF8;
  118998. #endif
  118999. /* Check if an existing function is being overridden or deleted. If so,
  119000. ** and there are active VMs, then return SQLITE_BUSY. If a function
  119001. ** is being overridden/deleted but there are no active VMs, allow the
  119002. ** operation to continue but invalidate all precompiled statements.
  119003. */
  119004. p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 0);
  119005. if( p && (p->funcFlags & SQLITE_FUNC_ENCMASK)==enc && p->nArg==nArg ){
  119006. if( db->nVdbeActive ){
  119007. sqlite3ErrorWithMsg(db, SQLITE_BUSY,
  119008. "unable to delete/modify user-function due to active statements");
  119009. assert( !db->mallocFailed );
  119010. return SQLITE_BUSY;
  119011. }else{
  119012. sqlite3ExpirePreparedStatements(db);
  119013. }
  119014. }
  119015. p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 1);
  119016. assert(p || db->mallocFailed);
  119017. if( !p ){
  119018. return SQLITE_NOMEM;
  119019. }
  119020. /* If an older version of the function with a configured destructor is
  119021. ** being replaced invoke the destructor function here. */
  119022. functionDestroy(db, p);
  119023. if( pDestructor ){
  119024. pDestructor->nRef++;
  119025. }
  119026. p->pDestructor = pDestructor;
  119027. p->funcFlags = (p->funcFlags & SQLITE_FUNC_ENCMASK) | extraFlags;
  119028. testcase( p->funcFlags & SQLITE_DETERMINISTIC );
  119029. p->xFunc = xFunc;
  119030. p->xStep = xStep;
  119031. p->xFinalize = xFinal;
  119032. p->pUserData = pUserData;
  119033. p->nArg = (u16)nArg;
  119034. return SQLITE_OK;
  119035. }
  119036. /*
  119037. ** Create new user functions.
  119038. */
  119039. SQLITE_API int sqlite3_create_function(
  119040. sqlite3 *db,
  119041. const char *zFunc,
  119042. int nArg,
  119043. int enc,
  119044. void *p,
  119045. void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
  119046. void (*xStep)(sqlite3_context*,int,sqlite3_value **),
  119047. void (*xFinal)(sqlite3_context*)
  119048. ){
  119049. return sqlite3_create_function_v2(db, zFunc, nArg, enc, p, xFunc, xStep,
  119050. xFinal, 0);
  119051. }
  119052. SQLITE_API int sqlite3_create_function_v2(
  119053. sqlite3 *db,
  119054. const char *zFunc,
  119055. int nArg,
  119056. int enc,
  119057. void *p,
  119058. void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
  119059. void (*xStep)(sqlite3_context*,int,sqlite3_value **),
  119060. void (*xFinal)(sqlite3_context*),
  119061. void (*xDestroy)(void *)
  119062. ){
  119063. int rc = SQLITE_ERROR;
  119064. FuncDestructor *pArg = 0;
  119065. #ifdef SQLITE_ENABLE_API_ARMOR
  119066. if( !sqlite3SafetyCheckOk(db) ){
  119067. return SQLITE_MISUSE_BKPT;
  119068. }
  119069. #endif
  119070. sqlite3_mutex_enter(db->mutex);
  119071. if( xDestroy ){
  119072. pArg = (FuncDestructor *)sqlite3DbMallocZero(db, sizeof(FuncDestructor));
  119073. if( !pArg ){
  119074. xDestroy(p);
  119075. goto out;
  119076. }
  119077. pArg->xDestroy = xDestroy;
  119078. pArg->pUserData = p;
  119079. }
  119080. rc = sqlite3CreateFunc(db, zFunc, nArg, enc, p, xFunc, xStep, xFinal, pArg);
  119081. if( pArg && pArg->nRef==0 ){
  119082. assert( rc!=SQLITE_OK );
  119083. xDestroy(p);
  119084. sqlite3DbFree(db, pArg);
  119085. }
  119086. out:
  119087. rc = sqlite3ApiExit(db, rc);
  119088. sqlite3_mutex_leave(db->mutex);
  119089. return rc;
  119090. }
  119091. #ifndef SQLITE_OMIT_UTF16
  119092. SQLITE_API int sqlite3_create_function16(
  119093. sqlite3 *db,
  119094. const void *zFunctionName,
  119095. int nArg,
  119096. int eTextRep,
  119097. void *p,
  119098. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  119099. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  119100. void (*xFinal)(sqlite3_context*)
  119101. ){
  119102. int rc;
  119103. char *zFunc8;
  119104. #ifdef SQLITE_ENABLE_API_ARMOR
  119105. if( !sqlite3SafetyCheckOk(db) || zFunctionName==0 ) return SQLITE_MISUSE_BKPT;
  119106. #endif
  119107. sqlite3_mutex_enter(db->mutex);
  119108. assert( !db->mallocFailed );
  119109. zFunc8 = sqlite3Utf16to8(db, zFunctionName, -1, SQLITE_UTF16NATIVE);
  119110. rc = sqlite3CreateFunc(db, zFunc8, nArg, eTextRep, p, xFunc, xStep, xFinal,0);
  119111. sqlite3DbFree(db, zFunc8);
  119112. rc = sqlite3ApiExit(db, rc);
  119113. sqlite3_mutex_leave(db->mutex);
  119114. return rc;
  119115. }
  119116. #endif
  119117. /*
  119118. ** Declare that a function has been overloaded by a virtual table.
  119119. **
  119120. ** If the function already exists as a regular global function, then
  119121. ** this routine is a no-op. If the function does not exist, then create
  119122. ** a new one that always throws a run-time error.
  119123. **
  119124. ** When virtual tables intend to provide an overloaded function, they
  119125. ** should call this routine to make sure the global function exists.
  119126. ** A global function must exist in order for name resolution to work
  119127. ** properly.
  119128. */
  119129. SQLITE_API int sqlite3_overload_function(
  119130. sqlite3 *db,
  119131. const char *zName,
  119132. int nArg
  119133. ){
  119134. int nName = sqlite3Strlen30(zName);
  119135. int rc = SQLITE_OK;
  119136. #ifdef SQLITE_ENABLE_API_ARMOR
  119137. if( !sqlite3SafetyCheckOk(db) || zName==0 || nArg<-2 ){
  119138. return SQLITE_MISUSE_BKPT;
  119139. }
  119140. #endif
  119141. sqlite3_mutex_enter(db->mutex);
  119142. if( sqlite3FindFunction(db, zName, nName, nArg, SQLITE_UTF8, 0)==0 ){
  119143. rc = sqlite3CreateFunc(db, zName, nArg, SQLITE_UTF8,
  119144. 0, sqlite3InvalidFunction, 0, 0, 0);
  119145. }
  119146. rc = sqlite3ApiExit(db, rc);
  119147. sqlite3_mutex_leave(db->mutex);
  119148. return rc;
  119149. }
  119150. #ifndef SQLITE_OMIT_TRACE
  119151. /*
  119152. ** Register a trace function. The pArg from the previously registered trace
  119153. ** is returned.
  119154. **
  119155. ** A NULL trace function means that no tracing is executes. A non-NULL
  119156. ** trace is a pointer to a function that is invoked at the start of each
  119157. ** SQL statement.
  119158. */
  119159. SQLITE_API void *sqlite3_trace(sqlite3 *db, void (*xTrace)(void*,const char*), void *pArg){
  119160. void *pOld;
  119161. #ifdef SQLITE_ENABLE_API_ARMOR
  119162. if( !sqlite3SafetyCheckOk(db) ){
  119163. (void)SQLITE_MISUSE_BKPT;
  119164. return 0;
  119165. }
  119166. #endif
  119167. sqlite3_mutex_enter(db->mutex);
  119168. pOld = db->pTraceArg;
  119169. db->xTrace = xTrace;
  119170. db->pTraceArg = pArg;
  119171. sqlite3_mutex_leave(db->mutex);
  119172. return pOld;
  119173. }
  119174. /*
  119175. ** Register a profile function. The pArg from the previously registered
  119176. ** profile function is returned.
  119177. **
  119178. ** A NULL profile function means that no profiling is executes. A non-NULL
  119179. ** profile is a pointer to a function that is invoked at the conclusion of
  119180. ** each SQL statement that is run.
  119181. */
  119182. SQLITE_API void *sqlite3_profile(
  119183. sqlite3 *db,
  119184. void (*xProfile)(void*,const char*,sqlite_uint64),
  119185. void *pArg
  119186. ){
  119187. void *pOld;
  119188. #ifdef SQLITE_ENABLE_API_ARMOR
  119189. if( !sqlite3SafetyCheckOk(db) ){
  119190. (void)SQLITE_MISUSE_BKPT;
  119191. return 0;
  119192. }
  119193. #endif
  119194. sqlite3_mutex_enter(db->mutex);
  119195. pOld = db->pProfileArg;
  119196. db->xProfile = xProfile;
  119197. db->pProfileArg = pArg;
  119198. sqlite3_mutex_leave(db->mutex);
  119199. return pOld;
  119200. }
  119201. #endif /* SQLITE_OMIT_TRACE */
  119202. /*
  119203. ** Register a function to be invoked when a transaction commits.
  119204. ** If the invoked function returns non-zero, then the commit becomes a
  119205. ** rollback.
  119206. */
  119207. SQLITE_API void *sqlite3_commit_hook(
  119208. sqlite3 *db, /* Attach the hook to this database */
  119209. int (*xCallback)(void*), /* Function to invoke on each commit */
  119210. void *pArg /* Argument to the function */
  119211. ){
  119212. void *pOld;
  119213. #ifdef SQLITE_ENABLE_API_ARMOR
  119214. if( !sqlite3SafetyCheckOk(db) ){
  119215. (void)SQLITE_MISUSE_BKPT;
  119216. return 0;
  119217. }
  119218. #endif
  119219. sqlite3_mutex_enter(db->mutex);
  119220. pOld = db->pCommitArg;
  119221. db->xCommitCallback = xCallback;
  119222. db->pCommitArg = pArg;
  119223. sqlite3_mutex_leave(db->mutex);
  119224. return pOld;
  119225. }
  119226. /*
  119227. ** Register a callback to be invoked each time a row is updated,
  119228. ** inserted or deleted using this database connection.
  119229. */
  119230. SQLITE_API void *sqlite3_update_hook(
  119231. sqlite3 *db, /* Attach the hook to this database */
  119232. void (*xCallback)(void*,int,char const *,char const *,sqlite_int64),
  119233. void *pArg /* Argument to the function */
  119234. ){
  119235. void *pRet;
  119236. #ifdef SQLITE_ENABLE_API_ARMOR
  119237. if( !sqlite3SafetyCheckOk(db) ){
  119238. (void)SQLITE_MISUSE_BKPT;
  119239. return 0;
  119240. }
  119241. #endif
  119242. sqlite3_mutex_enter(db->mutex);
  119243. pRet = db->pUpdateArg;
  119244. db->xUpdateCallback = xCallback;
  119245. db->pUpdateArg = pArg;
  119246. sqlite3_mutex_leave(db->mutex);
  119247. return pRet;
  119248. }
  119249. /*
  119250. ** Register a callback to be invoked each time a transaction is rolled
  119251. ** back by this database connection.
  119252. */
  119253. SQLITE_API void *sqlite3_rollback_hook(
  119254. sqlite3 *db, /* Attach the hook to this database */
  119255. void (*xCallback)(void*), /* Callback function */
  119256. void *pArg /* Argument to the function */
  119257. ){
  119258. void *pRet;
  119259. #ifdef SQLITE_ENABLE_API_ARMOR
  119260. if( !sqlite3SafetyCheckOk(db) ){
  119261. (void)SQLITE_MISUSE_BKPT;
  119262. return 0;
  119263. }
  119264. #endif
  119265. sqlite3_mutex_enter(db->mutex);
  119266. pRet = db->pRollbackArg;
  119267. db->xRollbackCallback = xCallback;
  119268. db->pRollbackArg = pArg;
  119269. sqlite3_mutex_leave(db->mutex);
  119270. return pRet;
  119271. }
  119272. #ifndef SQLITE_OMIT_WAL
  119273. /*
  119274. ** The sqlite3_wal_hook() callback registered by sqlite3_wal_autocheckpoint().
  119275. ** Invoke sqlite3_wal_checkpoint if the number of frames in the log file
  119276. ** is greater than sqlite3.pWalArg cast to an integer (the value configured by
  119277. ** wal_autocheckpoint()).
  119278. */
  119279. SQLITE_PRIVATE int sqlite3WalDefaultHook(
  119280. void *pClientData, /* Argument */
  119281. sqlite3 *db, /* Connection */
  119282. const char *zDb, /* Database */
  119283. int nFrame /* Size of WAL */
  119284. ){
  119285. if( nFrame>=SQLITE_PTR_TO_INT(pClientData) ){
  119286. sqlite3BeginBenignMalloc();
  119287. sqlite3_wal_checkpoint(db, zDb);
  119288. sqlite3EndBenignMalloc();
  119289. }
  119290. return SQLITE_OK;
  119291. }
  119292. #endif /* SQLITE_OMIT_WAL */
  119293. /*
  119294. ** Configure an sqlite3_wal_hook() callback to automatically checkpoint
  119295. ** a database after committing a transaction if there are nFrame or
  119296. ** more frames in the log file. Passing zero or a negative value as the
  119297. ** nFrame parameter disables automatic checkpoints entirely.
  119298. **
  119299. ** The callback registered by this function replaces any existing callback
  119300. ** registered using sqlite3_wal_hook(). Likewise, registering a callback
  119301. ** using sqlite3_wal_hook() disables the automatic checkpoint mechanism
  119302. ** configured by this function.
  119303. */
  119304. SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int nFrame){
  119305. #ifdef SQLITE_OMIT_WAL
  119306. UNUSED_PARAMETER(db);
  119307. UNUSED_PARAMETER(nFrame);
  119308. #else
  119309. #ifdef SQLITE_ENABLE_API_ARMOR
  119310. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  119311. #endif
  119312. if( nFrame>0 ){
  119313. sqlite3_wal_hook(db, sqlite3WalDefaultHook, SQLITE_INT_TO_PTR(nFrame));
  119314. }else{
  119315. sqlite3_wal_hook(db, 0, 0);
  119316. }
  119317. #endif
  119318. return SQLITE_OK;
  119319. }
  119320. /*
  119321. ** Register a callback to be invoked each time a transaction is written
  119322. ** into the write-ahead-log by this database connection.
  119323. */
  119324. SQLITE_API void *sqlite3_wal_hook(
  119325. sqlite3 *db, /* Attach the hook to this db handle */
  119326. int(*xCallback)(void *, sqlite3*, const char*, int),
  119327. void *pArg /* First argument passed to xCallback() */
  119328. ){
  119329. #ifndef SQLITE_OMIT_WAL
  119330. void *pRet;
  119331. #ifdef SQLITE_ENABLE_API_ARMOR
  119332. if( !sqlite3SafetyCheckOk(db) ){
  119333. (void)SQLITE_MISUSE_BKPT;
  119334. return 0;
  119335. }
  119336. #endif
  119337. sqlite3_mutex_enter(db->mutex);
  119338. pRet = db->pWalArg;
  119339. db->xWalCallback = xCallback;
  119340. db->pWalArg = pArg;
  119341. sqlite3_mutex_leave(db->mutex);
  119342. return pRet;
  119343. #else
  119344. return 0;
  119345. #endif
  119346. }
  119347. /*
  119348. ** Checkpoint database zDb.
  119349. */
  119350. SQLITE_API int sqlite3_wal_checkpoint_v2(
  119351. sqlite3 *db, /* Database handle */
  119352. const char *zDb, /* Name of attached database (or NULL) */
  119353. int eMode, /* SQLITE_CHECKPOINT_* value */
  119354. int *pnLog, /* OUT: Size of WAL log in frames */
  119355. int *pnCkpt /* OUT: Total number of frames checkpointed */
  119356. ){
  119357. #ifdef SQLITE_OMIT_WAL
  119358. return SQLITE_OK;
  119359. #else
  119360. int rc; /* Return code */
  119361. int iDb = SQLITE_MAX_ATTACHED; /* sqlite3.aDb[] index of db to checkpoint */
  119362. #ifdef SQLITE_ENABLE_API_ARMOR
  119363. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  119364. #endif
  119365. /* Initialize the output variables to -1 in case an error occurs. */
  119366. if( pnLog ) *pnLog = -1;
  119367. if( pnCkpt ) *pnCkpt = -1;
  119368. assert( SQLITE_CHECKPOINT_FULL>SQLITE_CHECKPOINT_PASSIVE );
  119369. assert( SQLITE_CHECKPOINT_FULL<SQLITE_CHECKPOINT_RESTART );
  119370. assert( SQLITE_CHECKPOINT_PASSIVE+2==SQLITE_CHECKPOINT_RESTART );
  119371. if( eMode<SQLITE_CHECKPOINT_PASSIVE || eMode>SQLITE_CHECKPOINT_RESTART ){
  119372. return SQLITE_MISUSE;
  119373. }
  119374. sqlite3_mutex_enter(db->mutex);
  119375. if( zDb && zDb[0] ){
  119376. iDb = sqlite3FindDbName(db, zDb);
  119377. }
  119378. if( iDb<0 ){
  119379. rc = SQLITE_ERROR;
  119380. sqlite3ErrorWithMsg(db, SQLITE_ERROR, "unknown database: %s", zDb);
  119381. }else{
  119382. rc = sqlite3Checkpoint(db, iDb, eMode, pnLog, pnCkpt);
  119383. sqlite3Error(db, rc);
  119384. }
  119385. rc = sqlite3ApiExit(db, rc);
  119386. sqlite3_mutex_leave(db->mutex);
  119387. return rc;
  119388. #endif
  119389. }
  119390. /*
  119391. ** Checkpoint database zDb. If zDb is NULL, or if the buffer zDb points
  119392. ** to contains a zero-length string, all attached databases are
  119393. ** checkpointed.
  119394. */
  119395. SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb){
  119396. return sqlite3_wal_checkpoint_v2(db, zDb, SQLITE_CHECKPOINT_PASSIVE, 0, 0);
  119397. }
  119398. #ifndef SQLITE_OMIT_WAL
  119399. /*
  119400. ** Run a checkpoint on database iDb. This is a no-op if database iDb is
  119401. ** not currently open in WAL mode.
  119402. **
  119403. ** If a transaction is open on the database being checkpointed, this
  119404. ** function returns SQLITE_LOCKED and a checkpoint is not attempted. If
  119405. ** an error occurs while running the checkpoint, an SQLite error code is
  119406. ** returned (i.e. SQLITE_IOERR). Otherwise, SQLITE_OK.
  119407. **
  119408. ** The mutex on database handle db should be held by the caller. The mutex
  119409. ** associated with the specific b-tree being checkpointed is taken by
  119410. ** this function while the checkpoint is running.
  119411. **
  119412. ** If iDb is passed SQLITE_MAX_ATTACHED, then all attached databases are
  119413. ** checkpointed. If an error is encountered it is returned immediately -
  119414. ** no attempt is made to checkpoint any remaining databases.
  119415. **
  119416. ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
  119417. */
  119418. SQLITE_PRIVATE int sqlite3Checkpoint(sqlite3 *db, int iDb, int eMode, int *pnLog, int *pnCkpt){
  119419. int rc = SQLITE_OK; /* Return code */
  119420. int i; /* Used to iterate through attached dbs */
  119421. int bBusy = 0; /* True if SQLITE_BUSY has been encountered */
  119422. assert( sqlite3_mutex_held(db->mutex) );
  119423. assert( !pnLog || *pnLog==-1 );
  119424. assert( !pnCkpt || *pnCkpt==-1 );
  119425. for(i=0; i<db->nDb && rc==SQLITE_OK; i++){
  119426. if( i==iDb || iDb==SQLITE_MAX_ATTACHED ){
  119427. rc = sqlite3BtreeCheckpoint(db->aDb[i].pBt, eMode, pnLog, pnCkpt);
  119428. pnLog = 0;
  119429. pnCkpt = 0;
  119430. if( rc==SQLITE_BUSY ){
  119431. bBusy = 1;
  119432. rc = SQLITE_OK;
  119433. }
  119434. }
  119435. }
  119436. return (rc==SQLITE_OK && bBusy) ? SQLITE_BUSY : rc;
  119437. }
  119438. #endif /* SQLITE_OMIT_WAL */
  119439. /*
  119440. ** This function returns true if main-memory should be used instead of
  119441. ** a temporary file for transient pager files and statement journals.
  119442. ** The value returned depends on the value of db->temp_store (runtime
  119443. ** parameter) and the compile time value of SQLITE_TEMP_STORE. The
  119444. ** following table describes the relationship between these two values
  119445. ** and this functions return value.
  119446. **
  119447. ** SQLITE_TEMP_STORE db->temp_store Location of temporary database
  119448. ** ----------------- -------------- ------------------------------
  119449. ** 0 any file (return 0)
  119450. ** 1 1 file (return 0)
  119451. ** 1 2 memory (return 1)
  119452. ** 1 0 file (return 0)
  119453. ** 2 1 file (return 0)
  119454. ** 2 2 memory (return 1)
  119455. ** 2 0 memory (return 1)
  119456. ** 3 any memory (return 1)
  119457. */
  119458. SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3 *db){
  119459. #if SQLITE_TEMP_STORE==1
  119460. return ( db->temp_store==2 );
  119461. #endif
  119462. #if SQLITE_TEMP_STORE==2
  119463. return ( db->temp_store!=1 );
  119464. #endif
  119465. #if SQLITE_TEMP_STORE==3
  119466. return 1;
  119467. #endif
  119468. #if SQLITE_TEMP_STORE<1 || SQLITE_TEMP_STORE>3
  119469. return 0;
  119470. #endif
  119471. }
  119472. /*
  119473. ** Return UTF-8 encoded English language explanation of the most recent
  119474. ** error.
  119475. */
  119476. SQLITE_API const char *sqlite3_errmsg(sqlite3 *db){
  119477. const char *z;
  119478. if( !db ){
  119479. return sqlite3ErrStr(SQLITE_NOMEM);
  119480. }
  119481. if( !sqlite3SafetyCheckSickOrOk(db) ){
  119482. return sqlite3ErrStr(SQLITE_MISUSE_BKPT);
  119483. }
  119484. sqlite3_mutex_enter(db->mutex);
  119485. if( db->mallocFailed ){
  119486. z = sqlite3ErrStr(SQLITE_NOMEM);
  119487. }else{
  119488. testcase( db->pErr==0 );
  119489. z = (char*)sqlite3_value_text(db->pErr);
  119490. assert( !db->mallocFailed );
  119491. if( z==0 ){
  119492. z = sqlite3ErrStr(db->errCode);
  119493. }
  119494. }
  119495. sqlite3_mutex_leave(db->mutex);
  119496. return z;
  119497. }
  119498. #ifndef SQLITE_OMIT_UTF16
  119499. /*
  119500. ** Return UTF-16 encoded English language explanation of the most recent
  119501. ** error.
  119502. */
  119503. SQLITE_API const void *sqlite3_errmsg16(sqlite3 *db){
  119504. static const u16 outOfMem[] = {
  119505. 'o', 'u', 't', ' ', 'o', 'f', ' ', 'm', 'e', 'm', 'o', 'r', 'y', 0
  119506. };
  119507. static const u16 misuse[] = {
  119508. 'l', 'i', 'b', 'r', 'a', 'r', 'y', ' ',
  119509. 'r', 'o', 'u', 't', 'i', 'n', 'e', ' ',
  119510. 'c', 'a', 'l', 'l', 'e', 'd', ' ',
  119511. 'o', 'u', 't', ' ',
  119512. 'o', 'f', ' ',
  119513. 's', 'e', 'q', 'u', 'e', 'n', 'c', 'e', 0
  119514. };
  119515. const void *z;
  119516. if( !db ){
  119517. return (void *)outOfMem;
  119518. }
  119519. if( !sqlite3SafetyCheckSickOrOk(db) ){
  119520. return (void *)misuse;
  119521. }
  119522. sqlite3_mutex_enter(db->mutex);
  119523. if( db->mallocFailed ){
  119524. z = (void *)outOfMem;
  119525. }else{
  119526. z = sqlite3_value_text16(db->pErr);
  119527. if( z==0 ){
  119528. sqlite3ErrorWithMsg(db, db->errCode, sqlite3ErrStr(db->errCode));
  119529. z = sqlite3_value_text16(db->pErr);
  119530. }
  119531. /* A malloc() may have failed within the call to sqlite3_value_text16()
  119532. ** above. If this is the case, then the db->mallocFailed flag needs to
  119533. ** be cleared before returning. Do this directly, instead of via
  119534. ** sqlite3ApiExit(), to avoid setting the database handle error message.
  119535. */
  119536. db->mallocFailed = 0;
  119537. }
  119538. sqlite3_mutex_leave(db->mutex);
  119539. return z;
  119540. }
  119541. #endif /* SQLITE_OMIT_UTF16 */
  119542. /*
  119543. ** Return the most recent error code generated by an SQLite routine. If NULL is
  119544. ** passed to this function, we assume a malloc() failed during sqlite3_open().
  119545. */
  119546. SQLITE_API int sqlite3_errcode(sqlite3 *db){
  119547. if( db && !sqlite3SafetyCheckSickOrOk(db) ){
  119548. return SQLITE_MISUSE_BKPT;
  119549. }
  119550. if( !db || db->mallocFailed ){
  119551. return SQLITE_NOMEM;
  119552. }
  119553. return db->errCode & db->errMask;
  119554. }
  119555. SQLITE_API int sqlite3_extended_errcode(sqlite3 *db){
  119556. if( db && !sqlite3SafetyCheckSickOrOk(db) ){
  119557. return SQLITE_MISUSE_BKPT;
  119558. }
  119559. if( !db || db->mallocFailed ){
  119560. return SQLITE_NOMEM;
  119561. }
  119562. return db->errCode;
  119563. }
  119564. /*
  119565. ** Return a string that describes the kind of error specified in the
  119566. ** argument. For now, this simply calls the internal sqlite3ErrStr()
  119567. ** function.
  119568. */
  119569. SQLITE_API const char *sqlite3_errstr(int rc){
  119570. return sqlite3ErrStr(rc);
  119571. }
  119572. /*
  119573. ** Invalidate all cached KeyInfo objects for database connection "db"
  119574. */
  119575. static void invalidateCachedKeyInfo(sqlite3 *db){
  119576. Db *pDb; /* A single database */
  119577. int iDb; /* The database index number */
  119578. HashElem *k; /* For looping over tables in pDb */
  119579. Table *pTab; /* A table in the database */
  119580. Index *pIdx; /* Each index */
  119581. for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
  119582. if( pDb->pBt==0 ) continue;
  119583. sqlite3BtreeEnter(pDb->pBt);
  119584. for(k=sqliteHashFirst(&pDb->pSchema->tblHash); k; k=sqliteHashNext(k)){
  119585. pTab = (Table*)sqliteHashData(k);
  119586. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  119587. if( pIdx->pKeyInfo && pIdx->pKeyInfo->db==db ){
  119588. sqlite3KeyInfoUnref(pIdx->pKeyInfo);
  119589. pIdx->pKeyInfo = 0;
  119590. }
  119591. }
  119592. }
  119593. sqlite3BtreeLeave(pDb->pBt);
  119594. }
  119595. }
  119596. /*
  119597. ** Create a new collating function for database "db". The name is zName
  119598. ** and the encoding is enc.
  119599. */
  119600. static int createCollation(
  119601. sqlite3* db,
  119602. const char *zName,
  119603. u8 enc,
  119604. void* pCtx,
  119605. int(*xCompare)(void*,int,const void*,int,const void*),
  119606. void(*xDel)(void*)
  119607. ){
  119608. CollSeq *pColl;
  119609. int enc2;
  119610. assert( sqlite3_mutex_held(db->mutex) );
  119611. /* If SQLITE_UTF16 is specified as the encoding type, transform this
  119612. ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
  119613. ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
  119614. */
  119615. enc2 = enc;
  119616. testcase( enc2==SQLITE_UTF16 );
  119617. testcase( enc2==SQLITE_UTF16_ALIGNED );
  119618. if( enc2==SQLITE_UTF16 || enc2==SQLITE_UTF16_ALIGNED ){
  119619. enc2 = SQLITE_UTF16NATIVE;
  119620. }
  119621. if( enc2<SQLITE_UTF8 || enc2>SQLITE_UTF16BE ){
  119622. return SQLITE_MISUSE_BKPT;
  119623. }
  119624. /* Check if this call is removing or replacing an existing collation
  119625. ** sequence. If so, and there are active VMs, return busy. If there
  119626. ** are no active VMs, invalidate any pre-compiled statements.
  119627. */
  119628. pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 0);
  119629. if( pColl && pColl->xCmp ){
  119630. if( db->nVdbeActive ){
  119631. sqlite3ErrorWithMsg(db, SQLITE_BUSY,
  119632. "unable to delete/modify collation sequence due to active statements");
  119633. return SQLITE_BUSY;
  119634. }
  119635. sqlite3ExpirePreparedStatements(db);
  119636. invalidateCachedKeyInfo(db);
  119637. /* If collation sequence pColl was created directly by a call to
  119638. ** sqlite3_create_collation, and not generated by synthCollSeq(),
  119639. ** then any copies made by synthCollSeq() need to be invalidated.
  119640. ** Also, collation destructor - CollSeq.xDel() - function may need
  119641. ** to be called.
  119642. */
  119643. if( (pColl->enc & ~SQLITE_UTF16_ALIGNED)==enc2 ){
  119644. CollSeq *aColl = sqlite3HashFind(&db->aCollSeq, zName);
  119645. int j;
  119646. for(j=0; j<3; j++){
  119647. CollSeq *p = &aColl[j];
  119648. if( p->enc==pColl->enc ){
  119649. if( p->xDel ){
  119650. p->xDel(p->pUser);
  119651. }
  119652. p->xCmp = 0;
  119653. }
  119654. }
  119655. }
  119656. }
  119657. pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 1);
  119658. if( pColl==0 ) return SQLITE_NOMEM;
  119659. pColl->xCmp = xCompare;
  119660. pColl->pUser = pCtx;
  119661. pColl->xDel = xDel;
  119662. pColl->enc = (u8)(enc2 | (enc & SQLITE_UTF16_ALIGNED));
  119663. sqlite3Error(db, SQLITE_OK);
  119664. return SQLITE_OK;
  119665. }
  119666. /*
  119667. ** This array defines hard upper bounds on limit values. The
  119668. ** initializer must be kept in sync with the SQLITE_LIMIT_*
  119669. ** #defines in sqlite3.h.
  119670. */
  119671. static const int aHardLimit[] = {
  119672. SQLITE_MAX_LENGTH,
  119673. SQLITE_MAX_SQL_LENGTH,
  119674. SQLITE_MAX_COLUMN,
  119675. SQLITE_MAX_EXPR_DEPTH,
  119676. SQLITE_MAX_COMPOUND_SELECT,
  119677. SQLITE_MAX_VDBE_OP,
  119678. SQLITE_MAX_FUNCTION_ARG,
  119679. SQLITE_MAX_ATTACHED,
  119680. SQLITE_MAX_LIKE_PATTERN_LENGTH,
  119681. SQLITE_MAX_VARIABLE_NUMBER, /* IMP: R-38091-32352 */
  119682. SQLITE_MAX_TRIGGER_DEPTH,
  119683. SQLITE_MAX_WORKER_THREADS,
  119684. };
  119685. /*
  119686. ** Make sure the hard limits are set to reasonable values
  119687. */
  119688. #if SQLITE_MAX_LENGTH<100
  119689. # error SQLITE_MAX_LENGTH must be at least 100
  119690. #endif
  119691. #if SQLITE_MAX_SQL_LENGTH<100
  119692. # error SQLITE_MAX_SQL_LENGTH must be at least 100
  119693. #endif
  119694. #if SQLITE_MAX_SQL_LENGTH>SQLITE_MAX_LENGTH
  119695. # error SQLITE_MAX_SQL_LENGTH must not be greater than SQLITE_MAX_LENGTH
  119696. #endif
  119697. #if SQLITE_MAX_COMPOUND_SELECT<2
  119698. # error SQLITE_MAX_COMPOUND_SELECT must be at least 2
  119699. #endif
  119700. #if SQLITE_MAX_VDBE_OP<40
  119701. # error SQLITE_MAX_VDBE_OP must be at least 40
  119702. #endif
  119703. #if SQLITE_MAX_FUNCTION_ARG<0 || SQLITE_MAX_FUNCTION_ARG>1000
  119704. # error SQLITE_MAX_FUNCTION_ARG must be between 0 and 1000
  119705. #endif
  119706. #if SQLITE_MAX_ATTACHED<0 || SQLITE_MAX_ATTACHED>125
  119707. # error SQLITE_MAX_ATTACHED must be between 0 and 125
  119708. #endif
  119709. #if SQLITE_MAX_LIKE_PATTERN_LENGTH<1
  119710. # error SQLITE_MAX_LIKE_PATTERN_LENGTH must be at least 1
  119711. #endif
  119712. #if SQLITE_MAX_COLUMN>32767
  119713. # error SQLITE_MAX_COLUMN must not exceed 32767
  119714. #endif
  119715. #if SQLITE_MAX_TRIGGER_DEPTH<1
  119716. # error SQLITE_MAX_TRIGGER_DEPTH must be at least 1
  119717. #endif
  119718. #if SQLITE_MAX_WORKER_THREADS<0 || SQLITE_MAX_WORKER_THREADS>50
  119719. # error SQLITE_MAX_WORKER_THREADS must be between 0 and 50
  119720. #endif
  119721. /*
  119722. ** Change the value of a limit. Report the old value.
  119723. ** If an invalid limit index is supplied, report -1.
  119724. ** Make no changes but still report the old value if the
  119725. ** new limit is negative.
  119726. **
  119727. ** A new lower limit does not shrink existing constructs.
  119728. ** It merely prevents new constructs that exceed the limit
  119729. ** from forming.
  119730. */
  119731. SQLITE_API int sqlite3_limit(sqlite3 *db, int limitId, int newLimit){
  119732. int oldLimit;
  119733. #ifdef SQLITE_ENABLE_API_ARMOR
  119734. if( !sqlite3SafetyCheckOk(db) ){
  119735. (void)SQLITE_MISUSE_BKPT;
  119736. return -1;
  119737. }
  119738. #endif
  119739. /* EVIDENCE-OF: R-30189-54097 For each limit category SQLITE_LIMIT_NAME
  119740. ** there is a hard upper bound set at compile-time by a C preprocessor
  119741. ** macro called SQLITE_MAX_NAME. (The "_LIMIT_" in the name is changed to
  119742. ** "_MAX_".)
  119743. */
  119744. assert( aHardLimit[SQLITE_LIMIT_LENGTH]==SQLITE_MAX_LENGTH );
  119745. assert( aHardLimit[SQLITE_LIMIT_SQL_LENGTH]==SQLITE_MAX_SQL_LENGTH );
  119746. assert( aHardLimit[SQLITE_LIMIT_COLUMN]==SQLITE_MAX_COLUMN );
  119747. assert( aHardLimit[SQLITE_LIMIT_EXPR_DEPTH]==SQLITE_MAX_EXPR_DEPTH );
  119748. assert( aHardLimit[SQLITE_LIMIT_COMPOUND_SELECT]==SQLITE_MAX_COMPOUND_SELECT);
  119749. assert( aHardLimit[SQLITE_LIMIT_VDBE_OP]==SQLITE_MAX_VDBE_OP );
  119750. assert( aHardLimit[SQLITE_LIMIT_FUNCTION_ARG]==SQLITE_MAX_FUNCTION_ARG );
  119751. assert( aHardLimit[SQLITE_LIMIT_ATTACHED]==SQLITE_MAX_ATTACHED );
  119752. assert( aHardLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]==
  119753. SQLITE_MAX_LIKE_PATTERN_LENGTH );
  119754. assert( aHardLimit[SQLITE_LIMIT_VARIABLE_NUMBER]==SQLITE_MAX_VARIABLE_NUMBER);
  119755. assert( aHardLimit[SQLITE_LIMIT_TRIGGER_DEPTH]==SQLITE_MAX_TRIGGER_DEPTH );
  119756. assert( aHardLimit[SQLITE_LIMIT_WORKER_THREADS]==SQLITE_MAX_WORKER_THREADS );
  119757. assert( SQLITE_LIMIT_WORKER_THREADS==(SQLITE_N_LIMIT-1) );
  119758. if( limitId<0 || limitId>=SQLITE_N_LIMIT ){
  119759. return -1;
  119760. }
  119761. oldLimit = db->aLimit[limitId];
  119762. if( newLimit>=0 ){ /* IMP: R-52476-28732 */
  119763. if( newLimit>aHardLimit[limitId] ){
  119764. newLimit = aHardLimit[limitId]; /* IMP: R-51463-25634 */
  119765. }
  119766. db->aLimit[limitId] = newLimit;
  119767. }
  119768. return oldLimit; /* IMP: R-53341-35419 */
  119769. }
  119770. /*
  119771. ** This function is used to parse both URIs and non-URI filenames passed by the
  119772. ** user to API functions sqlite3_open() or sqlite3_open_v2(), and for database
  119773. ** URIs specified as part of ATTACH statements.
  119774. **
  119775. ** The first argument to this function is the name of the VFS to use (or
  119776. ** a NULL to signify the default VFS) if the URI does not contain a "vfs=xxx"
  119777. ** query parameter. The second argument contains the URI (or non-URI filename)
  119778. ** itself. When this function is called the *pFlags variable should contain
  119779. ** the default flags to open the database handle with. The value stored in
  119780. ** *pFlags may be updated before returning if the URI filename contains
  119781. ** "cache=xxx" or "mode=xxx" query parameters.
  119782. **
  119783. ** If successful, SQLITE_OK is returned. In this case *ppVfs is set to point to
  119784. ** the VFS that should be used to open the database file. *pzFile is set to
  119785. ** point to a buffer containing the name of the file to open. It is the
  119786. ** responsibility of the caller to eventually call sqlite3_free() to release
  119787. ** this buffer.
  119788. **
  119789. ** If an error occurs, then an SQLite error code is returned and *pzErrMsg
  119790. ** may be set to point to a buffer containing an English language error
  119791. ** message. It is the responsibility of the caller to eventually release
  119792. ** this buffer by calling sqlite3_free().
  119793. */
  119794. SQLITE_PRIVATE int sqlite3ParseUri(
  119795. const char *zDefaultVfs, /* VFS to use if no "vfs=xxx" query option */
  119796. const char *zUri, /* Nul-terminated URI to parse */
  119797. unsigned int *pFlags, /* IN/OUT: SQLITE_OPEN_XXX flags */
  119798. sqlite3_vfs **ppVfs, /* OUT: VFS to use */
  119799. char **pzFile, /* OUT: Filename component of URI */
  119800. char **pzErrMsg /* OUT: Error message (if rc!=SQLITE_OK) */
  119801. ){
  119802. int rc = SQLITE_OK;
  119803. unsigned int flags = *pFlags;
  119804. const char *zVfs = zDefaultVfs;
  119805. char *zFile;
  119806. char c;
  119807. int nUri = sqlite3Strlen30(zUri);
  119808. assert( *pzErrMsg==0 );
  119809. if( ((flags & SQLITE_OPEN_URI) || sqlite3GlobalConfig.bOpenUri)
  119810. && nUri>=5 && memcmp(zUri, "file:", 5)==0 /* IMP: R-57884-37496 */
  119811. ){
  119812. char *zOpt;
  119813. int eState; /* Parser state when parsing URI */
  119814. int iIn; /* Input character index */
  119815. int iOut = 0; /* Output character index */
  119816. int nByte = nUri+2; /* Bytes of space to allocate */
  119817. /* Make sure the SQLITE_OPEN_URI flag is set to indicate to the VFS xOpen
  119818. ** method that there may be extra parameters following the file-name. */
  119819. flags |= SQLITE_OPEN_URI;
  119820. for(iIn=0; iIn<nUri; iIn++) nByte += (zUri[iIn]=='&');
  119821. zFile = sqlite3_malloc(nByte);
  119822. if( !zFile ) return SQLITE_NOMEM;
  119823. iIn = 5;
  119824. #ifndef SQLITE_ALLOW_URI_AUTHORITY
  119825. /* Discard the scheme and authority segments of the URI. */
  119826. if( zUri[5]=='/' && zUri[6]=='/' ){
  119827. iIn = 7;
  119828. while( zUri[iIn] && zUri[iIn]!='/' ) iIn++;
  119829. if( iIn!=7 && (iIn!=16 || memcmp("localhost", &zUri[7], 9)) ){
  119830. *pzErrMsg = sqlite3_mprintf("invalid uri authority: %.*s",
  119831. iIn-7, &zUri[7]);
  119832. rc = SQLITE_ERROR;
  119833. goto parse_uri_out;
  119834. }
  119835. }
  119836. #endif
  119837. /* Copy the filename and any query parameters into the zFile buffer.
  119838. ** Decode %HH escape codes along the way.
  119839. **
  119840. ** Within this loop, variable eState may be set to 0, 1 or 2, depending
  119841. ** on the parsing context. As follows:
  119842. **
  119843. ** 0: Parsing file-name.
  119844. ** 1: Parsing name section of a name=value query parameter.
  119845. ** 2: Parsing value section of a name=value query parameter.
  119846. */
  119847. eState = 0;
  119848. while( (c = zUri[iIn])!=0 && c!='#' ){
  119849. iIn++;
  119850. if( c=='%'
  119851. && sqlite3Isxdigit(zUri[iIn])
  119852. && sqlite3Isxdigit(zUri[iIn+1])
  119853. ){
  119854. int octet = (sqlite3HexToInt(zUri[iIn++]) << 4);
  119855. octet += sqlite3HexToInt(zUri[iIn++]);
  119856. assert( octet>=0 && octet<256 );
  119857. if( octet==0 ){
  119858. /* This branch is taken when "%00" appears within the URI. In this
  119859. ** case we ignore all text in the remainder of the path, name or
  119860. ** value currently being parsed. So ignore the current character
  119861. ** and skip to the next "?", "=" or "&", as appropriate. */
  119862. while( (c = zUri[iIn])!=0 && c!='#'
  119863. && (eState!=0 || c!='?')
  119864. && (eState!=1 || (c!='=' && c!='&'))
  119865. && (eState!=2 || c!='&')
  119866. ){
  119867. iIn++;
  119868. }
  119869. continue;
  119870. }
  119871. c = octet;
  119872. }else if( eState==1 && (c=='&' || c=='=') ){
  119873. if( zFile[iOut-1]==0 ){
  119874. /* An empty option name. Ignore this option altogether. */
  119875. while( zUri[iIn] && zUri[iIn]!='#' && zUri[iIn-1]!='&' ) iIn++;
  119876. continue;
  119877. }
  119878. if( c=='&' ){
  119879. zFile[iOut++] = '\0';
  119880. }else{
  119881. eState = 2;
  119882. }
  119883. c = 0;
  119884. }else if( (eState==0 && c=='?') || (eState==2 && c=='&') ){
  119885. c = 0;
  119886. eState = 1;
  119887. }
  119888. zFile[iOut++] = c;
  119889. }
  119890. if( eState==1 ) zFile[iOut++] = '\0';
  119891. zFile[iOut++] = '\0';
  119892. zFile[iOut++] = '\0';
  119893. /* Check if there were any options specified that should be interpreted
  119894. ** here. Options that are interpreted here include "vfs" and those that
  119895. ** correspond to flags that may be passed to the sqlite3_open_v2()
  119896. ** method. */
  119897. zOpt = &zFile[sqlite3Strlen30(zFile)+1];
  119898. while( zOpt[0] ){
  119899. int nOpt = sqlite3Strlen30(zOpt);
  119900. char *zVal = &zOpt[nOpt+1];
  119901. int nVal = sqlite3Strlen30(zVal);
  119902. if( nOpt==3 && memcmp("vfs", zOpt, 3)==0 ){
  119903. zVfs = zVal;
  119904. }else{
  119905. struct OpenMode {
  119906. const char *z;
  119907. int mode;
  119908. } *aMode = 0;
  119909. char *zModeType = 0;
  119910. int mask = 0;
  119911. int limit = 0;
  119912. if( nOpt==5 && memcmp("cache", zOpt, 5)==0 ){
  119913. static struct OpenMode aCacheMode[] = {
  119914. { "shared", SQLITE_OPEN_SHAREDCACHE },
  119915. { "private", SQLITE_OPEN_PRIVATECACHE },
  119916. { 0, 0 }
  119917. };
  119918. mask = SQLITE_OPEN_SHAREDCACHE|SQLITE_OPEN_PRIVATECACHE;
  119919. aMode = aCacheMode;
  119920. limit = mask;
  119921. zModeType = "cache";
  119922. }
  119923. if( nOpt==4 && memcmp("mode", zOpt, 4)==0 ){
  119924. static struct OpenMode aOpenMode[] = {
  119925. { "ro", SQLITE_OPEN_READONLY },
  119926. { "rw", SQLITE_OPEN_READWRITE },
  119927. { "rwc", SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE },
  119928. { "memory", SQLITE_OPEN_MEMORY },
  119929. { 0, 0 }
  119930. };
  119931. mask = SQLITE_OPEN_READONLY | SQLITE_OPEN_READWRITE
  119932. | SQLITE_OPEN_CREATE | SQLITE_OPEN_MEMORY;
  119933. aMode = aOpenMode;
  119934. limit = mask & flags;
  119935. zModeType = "access";
  119936. }
  119937. if( aMode ){
  119938. int i;
  119939. int mode = 0;
  119940. for(i=0; aMode[i].z; i++){
  119941. const char *z = aMode[i].z;
  119942. if( nVal==sqlite3Strlen30(z) && 0==memcmp(zVal, z, nVal) ){
  119943. mode = aMode[i].mode;
  119944. break;
  119945. }
  119946. }
  119947. if( mode==0 ){
  119948. *pzErrMsg = sqlite3_mprintf("no such %s mode: %s", zModeType, zVal);
  119949. rc = SQLITE_ERROR;
  119950. goto parse_uri_out;
  119951. }
  119952. if( (mode & ~SQLITE_OPEN_MEMORY)>limit ){
  119953. *pzErrMsg = sqlite3_mprintf("%s mode not allowed: %s",
  119954. zModeType, zVal);
  119955. rc = SQLITE_PERM;
  119956. goto parse_uri_out;
  119957. }
  119958. flags = (flags & ~mask) | mode;
  119959. }
  119960. }
  119961. zOpt = &zVal[nVal+1];
  119962. }
  119963. }else{
  119964. zFile = sqlite3_malloc(nUri+2);
  119965. if( !zFile ) return SQLITE_NOMEM;
  119966. memcpy(zFile, zUri, nUri);
  119967. zFile[nUri] = '\0';
  119968. zFile[nUri+1] = '\0';
  119969. flags &= ~SQLITE_OPEN_URI;
  119970. }
  119971. *ppVfs = sqlite3_vfs_find(zVfs);
  119972. if( *ppVfs==0 ){
  119973. *pzErrMsg = sqlite3_mprintf("no such vfs: %s", zVfs);
  119974. rc = SQLITE_ERROR;
  119975. }
  119976. parse_uri_out:
  119977. if( rc!=SQLITE_OK ){
  119978. sqlite3_free(zFile);
  119979. zFile = 0;
  119980. }
  119981. *pFlags = flags;
  119982. *pzFile = zFile;
  119983. return rc;
  119984. }
  119985. /*
  119986. ** This routine does the work of opening a database on behalf of
  119987. ** sqlite3_open() and sqlite3_open16(). The database filename "zFilename"
  119988. ** is UTF-8 encoded.
  119989. */
  119990. static int openDatabase(
  119991. const char *zFilename, /* Database filename UTF-8 encoded */
  119992. sqlite3 **ppDb, /* OUT: Returned database handle */
  119993. unsigned int flags, /* Operational flags */
  119994. const char *zVfs /* Name of the VFS to use */
  119995. ){
  119996. sqlite3 *db; /* Store allocated handle here */
  119997. int rc; /* Return code */
  119998. int isThreadsafe; /* True for threadsafe connections */
  119999. char *zOpen = 0; /* Filename argument to pass to BtreeOpen() */
  120000. char *zErrMsg = 0; /* Error message from sqlite3ParseUri() */
  120001. #ifdef SQLITE_ENABLE_API_ARMOR
  120002. if( ppDb==0 ) return SQLITE_MISUSE_BKPT;
  120003. #endif
  120004. *ppDb = 0;
  120005. #ifndef SQLITE_OMIT_AUTOINIT
  120006. rc = sqlite3_initialize();
  120007. if( rc ) return rc;
  120008. #endif
  120009. /* Only allow sensible combinations of bits in the flags argument.
  120010. ** Throw an error if any non-sense combination is used. If we
  120011. ** do not block illegal combinations here, it could trigger
  120012. ** assert() statements in deeper layers. Sensible combinations
  120013. ** are:
  120014. **
  120015. ** 1: SQLITE_OPEN_READONLY
  120016. ** 2: SQLITE_OPEN_READWRITE
  120017. ** 6: SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE
  120018. */
  120019. assert( SQLITE_OPEN_READONLY == 0x01 );
  120020. assert( SQLITE_OPEN_READWRITE == 0x02 );
  120021. assert( SQLITE_OPEN_CREATE == 0x04 );
  120022. testcase( (1<<(flags&7))==0x02 ); /* READONLY */
  120023. testcase( (1<<(flags&7))==0x04 ); /* READWRITE */
  120024. testcase( (1<<(flags&7))==0x40 ); /* READWRITE | CREATE */
  120025. if( ((1<<(flags&7)) & 0x46)==0 ){
  120026. return SQLITE_MISUSE_BKPT; /* IMP: R-65497-44594 */
  120027. }
  120028. if( sqlite3GlobalConfig.bCoreMutex==0 ){
  120029. isThreadsafe = 0;
  120030. }else if( flags & SQLITE_OPEN_NOMUTEX ){
  120031. isThreadsafe = 0;
  120032. }else if( flags & SQLITE_OPEN_FULLMUTEX ){
  120033. isThreadsafe = 1;
  120034. }else{
  120035. isThreadsafe = sqlite3GlobalConfig.bFullMutex;
  120036. }
  120037. if( flags & SQLITE_OPEN_PRIVATECACHE ){
  120038. flags &= ~SQLITE_OPEN_SHAREDCACHE;
  120039. }else if( sqlite3GlobalConfig.sharedCacheEnabled ){
  120040. flags |= SQLITE_OPEN_SHAREDCACHE;
  120041. }
  120042. /* Remove harmful bits from the flags parameter
  120043. **
  120044. ** The SQLITE_OPEN_NOMUTEX and SQLITE_OPEN_FULLMUTEX flags were
  120045. ** dealt with in the previous code block. Besides these, the only
  120046. ** valid input flags for sqlite3_open_v2() are SQLITE_OPEN_READONLY,
  120047. ** SQLITE_OPEN_READWRITE, SQLITE_OPEN_CREATE, SQLITE_OPEN_SHAREDCACHE,
  120048. ** SQLITE_OPEN_PRIVATECACHE, and some reserved bits. Silently mask
  120049. ** off all other flags.
  120050. */
  120051. flags &= ~( SQLITE_OPEN_DELETEONCLOSE |
  120052. SQLITE_OPEN_EXCLUSIVE |
  120053. SQLITE_OPEN_MAIN_DB |
  120054. SQLITE_OPEN_TEMP_DB |
  120055. SQLITE_OPEN_TRANSIENT_DB |
  120056. SQLITE_OPEN_MAIN_JOURNAL |
  120057. SQLITE_OPEN_TEMP_JOURNAL |
  120058. SQLITE_OPEN_SUBJOURNAL |
  120059. SQLITE_OPEN_MASTER_JOURNAL |
  120060. SQLITE_OPEN_NOMUTEX |
  120061. SQLITE_OPEN_FULLMUTEX |
  120062. SQLITE_OPEN_WAL
  120063. );
  120064. /* Allocate the sqlite data structure */
  120065. db = sqlite3MallocZero( sizeof(sqlite3) );
  120066. if( db==0 ) goto opendb_out;
  120067. if( isThreadsafe ){
  120068. db->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
  120069. if( db->mutex==0 ){
  120070. sqlite3_free(db);
  120071. db = 0;
  120072. goto opendb_out;
  120073. }
  120074. }
  120075. sqlite3_mutex_enter(db->mutex);
  120076. db->errMask = 0xff;
  120077. db->nDb = 2;
  120078. db->magic = SQLITE_MAGIC_BUSY;
  120079. db->aDb = db->aDbStatic;
  120080. assert( sizeof(db->aLimit)==sizeof(aHardLimit) );
  120081. memcpy(db->aLimit, aHardLimit, sizeof(db->aLimit));
  120082. db->aLimit[SQLITE_LIMIT_WORKER_THREADS] = SQLITE_DEFAULT_WORKER_THREADS;
  120083. db->autoCommit = 1;
  120084. db->nextAutovac = -1;
  120085. db->szMmap = sqlite3GlobalConfig.szMmap;
  120086. db->nextPagesize = 0;
  120087. db->nMaxSorterMmap = 0x7FFFFFFF;
  120088. db->flags |= SQLITE_ShortColNames | SQLITE_EnableTrigger | SQLITE_CacheSpill
  120089. #if !defined(SQLITE_DEFAULT_AUTOMATIC_INDEX) || SQLITE_DEFAULT_AUTOMATIC_INDEX
  120090. | SQLITE_AutoIndex
  120091. #endif
  120092. #if SQLITE_DEFAULT_FILE_FORMAT<4
  120093. | SQLITE_LegacyFileFmt
  120094. #endif
  120095. #ifdef SQLITE_ENABLE_LOAD_EXTENSION
  120096. | SQLITE_LoadExtension
  120097. #endif
  120098. #if SQLITE_DEFAULT_RECURSIVE_TRIGGERS
  120099. | SQLITE_RecTriggers
  120100. #endif
  120101. #if defined(SQLITE_DEFAULT_FOREIGN_KEYS) && SQLITE_DEFAULT_FOREIGN_KEYS
  120102. | SQLITE_ForeignKeys
  120103. #endif
  120104. ;
  120105. sqlite3HashInit(&db->aCollSeq);
  120106. #ifndef SQLITE_OMIT_VIRTUALTABLE
  120107. sqlite3HashInit(&db->aModule);
  120108. #endif
  120109. /* Add the default collation sequence BINARY. BINARY works for both UTF-8
  120110. ** and UTF-16, so add a version for each to avoid any unnecessary
  120111. ** conversions. The only error that can occur here is a malloc() failure.
  120112. */
  120113. createCollation(db, "BINARY", SQLITE_UTF8, 0, binCollFunc, 0);
  120114. createCollation(db, "BINARY", SQLITE_UTF16BE, 0, binCollFunc, 0);
  120115. createCollation(db, "BINARY", SQLITE_UTF16LE, 0, binCollFunc, 0);
  120116. createCollation(db, "RTRIM", SQLITE_UTF8, (void*)1, binCollFunc, 0);
  120117. if( db->mallocFailed ){
  120118. goto opendb_out;
  120119. }
  120120. db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "BINARY", 0);
  120121. assert( db->pDfltColl!=0 );
  120122. /* Also add a UTF-8 case-insensitive collation sequence. */
  120123. createCollation(db, "NOCASE", SQLITE_UTF8, 0, nocaseCollatingFunc, 0);
  120124. /* Parse the filename/URI argument. */
  120125. db->openFlags = flags;
  120126. rc = sqlite3ParseUri(zVfs, zFilename, &flags, &db->pVfs, &zOpen, &zErrMsg);
  120127. if( rc!=SQLITE_OK ){
  120128. if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
  120129. sqlite3ErrorWithMsg(db, rc, zErrMsg ? "%s" : 0, zErrMsg);
  120130. sqlite3_free(zErrMsg);
  120131. goto opendb_out;
  120132. }
  120133. /* Open the backend database driver */
  120134. rc = sqlite3BtreeOpen(db->pVfs, zOpen, db, &db->aDb[0].pBt, 0,
  120135. flags | SQLITE_OPEN_MAIN_DB);
  120136. if( rc!=SQLITE_OK ){
  120137. if( rc==SQLITE_IOERR_NOMEM ){
  120138. rc = SQLITE_NOMEM;
  120139. }
  120140. sqlite3Error(db, rc);
  120141. goto opendb_out;
  120142. }
  120143. db->aDb[0].pSchema = sqlite3SchemaGet(db, db->aDb[0].pBt);
  120144. db->aDb[1].pSchema = sqlite3SchemaGet(db, 0);
  120145. /* The default safety_level for the main database is 'full'; for the temp
  120146. ** database it is 'NONE'. This matches the pager layer defaults.
  120147. */
  120148. db->aDb[0].zName = "main";
  120149. db->aDb[0].safety_level = 3;
  120150. db->aDb[1].zName = "temp";
  120151. db->aDb[1].safety_level = 1;
  120152. db->magic = SQLITE_MAGIC_OPEN;
  120153. if( db->mallocFailed ){
  120154. goto opendb_out;
  120155. }
  120156. /* Register all built-in functions, but do not attempt to read the
  120157. ** database schema yet. This is delayed until the first time the database
  120158. ** is accessed.
  120159. */
  120160. sqlite3Error(db, SQLITE_OK);
  120161. sqlite3RegisterBuiltinFunctions(db);
  120162. /* Load automatic extensions - extensions that have been registered
  120163. ** using the sqlite3_automatic_extension() API.
  120164. */
  120165. rc = sqlite3_errcode(db);
  120166. if( rc==SQLITE_OK ){
  120167. sqlite3AutoLoadExtensions(db);
  120168. rc = sqlite3_errcode(db);
  120169. if( rc!=SQLITE_OK ){
  120170. goto opendb_out;
  120171. }
  120172. }
  120173. #ifdef SQLITE_ENABLE_FTS1
  120174. if( !db->mallocFailed ){
  120175. extern int sqlite3Fts1Init(sqlite3*);
  120176. rc = sqlite3Fts1Init(db);
  120177. }
  120178. #endif
  120179. #ifdef SQLITE_ENABLE_FTS2
  120180. if( !db->mallocFailed && rc==SQLITE_OK ){
  120181. extern int sqlite3Fts2Init(sqlite3*);
  120182. rc = sqlite3Fts2Init(db);
  120183. }
  120184. #endif
  120185. #ifdef SQLITE_ENABLE_FTS3
  120186. if( !db->mallocFailed && rc==SQLITE_OK ){
  120187. rc = sqlite3Fts3Init(db);
  120188. }
  120189. #endif
  120190. #ifdef SQLITE_ENABLE_ICU
  120191. if( !db->mallocFailed && rc==SQLITE_OK ){
  120192. rc = sqlite3IcuInit(db);
  120193. }
  120194. #endif
  120195. #ifdef SQLITE_ENABLE_RTREE
  120196. if( !db->mallocFailed && rc==SQLITE_OK){
  120197. rc = sqlite3RtreeInit(db);
  120198. }
  120199. #endif
  120200. /* -DSQLITE_DEFAULT_LOCKING_MODE=1 makes EXCLUSIVE the default locking
  120201. ** mode. -DSQLITE_DEFAULT_LOCKING_MODE=0 make NORMAL the default locking
  120202. ** mode. Doing nothing at all also makes NORMAL the default.
  120203. */
  120204. #ifdef SQLITE_DEFAULT_LOCKING_MODE
  120205. db->dfltLockMode = SQLITE_DEFAULT_LOCKING_MODE;
  120206. sqlite3PagerLockingMode(sqlite3BtreePager(db->aDb[0].pBt),
  120207. SQLITE_DEFAULT_LOCKING_MODE);
  120208. #endif
  120209. if( rc ) sqlite3Error(db, rc);
  120210. /* Enable the lookaside-malloc subsystem */
  120211. setupLookaside(db, 0, sqlite3GlobalConfig.szLookaside,
  120212. sqlite3GlobalConfig.nLookaside);
  120213. sqlite3_wal_autocheckpoint(db, SQLITE_DEFAULT_WAL_AUTOCHECKPOINT);
  120214. opendb_out:
  120215. sqlite3_free(zOpen);
  120216. if( db ){
  120217. assert( db->mutex!=0 || isThreadsafe==0 || sqlite3GlobalConfig.bFullMutex==0 );
  120218. sqlite3_mutex_leave(db->mutex);
  120219. }
  120220. rc = sqlite3_errcode(db);
  120221. assert( db!=0 || rc==SQLITE_NOMEM );
  120222. if( rc==SQLITE_NOMEM ){
  120223. sqlite3_close(db);
  120224. db = 0;
  120225. }else if( rc!=SQLITE_OK ){
  120226. db->magic = SQLITE_MAGIC_SICK;
  120227. }
  120228. *ppDb = db;
  120229. #ifdef SQLITE_ENABLE_SQLLOG
  120230. if( sqlite3GlobalConfig.xSqllog ){
  120231. /* Opening a db handle. Fourth parameter is passed 0. */
  120232. void *pArg = sqlite3GlobalConfig.pSqllogArg;
  120233. sqlite3GlobalConfig.xSqllog(pArg, db, zFilename, 0);
  120234. }
  120235. #endif
  120236. return sqlite3ApiExit(0, rc);
  120237. }
  120238. /*
  120239. ** Open a new database handle.
  120240. */
  120241. SQLITE_API int sqlite3_open(
  120242. const char *zFilename,
  120243. sqlite3 **ppDb
  120244. ){
  120245. return openDatabase(zFilename, ppDb,
  120246. SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
  120247. }
  120248. SQLITE_API int sqlite3_open_v2(
  120249. const char *filename, /* Database filename (UTF-8) */
  120250. sqlite3 **ppDb, /* OUT: SQLite db handle */
  120251. int flags, /* Flags */
  120252. const char *zVfs /* Name of VFS module to use */
  120253. ){
  120254. return openDatabase(filename, ppDb, (unsigned int)flags, zVfs);
  120255. }
  120256. #ifndef SQLITE_OMIT_UTF16
  120257. /*
  120258. ** Open a new database handle.
  120259. */
  120260. SQLITE_API int sqlite3_open16(
  120261. const void *zFilename,
  120262. sqlite3 **ppDb
  120263. ){
  120264. char const *zFilename8; /* zFilename encoded in UTF-8 instead of UTF-16 */
  120265. sqlite3_value *pVal;
  120266. int rc;
  120267. #ifdef SQLITE_ENABLE_API_ARMOR
  120268. if( ppDb==0 ) return SQLITE_MISUSE_BKPT;
  120269. #endif
  120270. *ppDb = 0;
  120271. #ifndef SQLITE_OMIT_AUTOINIT
  120272. rc = sqlite3_initialize();
  120273. if( rc ) return rc;
  120274. #endif
  120275. if( zFilename==0 ) zFilename = "\000\000";
  120276. pVal = sqlite3ValueNew(0);
  120277. sqlite3ValueSetStr(pVal, -1, zFilename, SQLITE_UTF16NATIVE, SQLITE_STATIC);
  120278. zFilename8 = sqlite3ValueText(pVal, SQLITE_UTF8);
  120279. if( zFilename8 ){
  120280. rc = openDatabase(zFilename8, ppDb,
  120281. SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
  120282. assert( *ppDb || rc==SQLITE_NOMEM );
  120283. if( rc==SQLITE_OK && !DbHasProperty(*ppDb, 0, DB_SchemaLoaded) ){
  120284. ENC(*ppDb) = SQLITE_UTF16NATIVE;
  120285. }
  120286. }else{
  120287. rc = SQLITE_NOMEM;
  120288. }
  120289. sqlite3ValueFree(pVal);
  120290. return sqlite3ApiExit(0, rc);
  120291. }
  120292. #endif /* SQLITE_OMIT_UTF16 */
  120293. /*
  120294. ** Register a new collation sequence with the database handle db.
  120295. */
  120296. SQLITE_API int sqlite3_create_collation(
  120297. sqlite3* db,
  120298. const char *zName,
  120299. int enc,
  120300. void* pCtx,
  120301. int(*xCompare)(void*,int,const void*,int,const void*)
  120302. ){
  120303. return sqlite3_create_collation_v2(db, zName, enc, pCtx, xCompare, 0);
  120304. }
  120305. /*
  120306. ** Register a new collation sequence with the database handle db.
  120307. */
  120308. SQLITE_API int sqlite3_create_collation_v2(
  120309. sqlite3* db,
  120310. const char *zName,
  120311. int enc,
  120312. void* pCtx,
  120313. int(*xCompare)(void*,int,const void*,int,const void*),
  120314. void(*xDel)(void*)
  120315. ){
  120316. int rc;
  120317. #ifdef SQLITE_ENABLE_API_ARMOR
  120318. if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
  120319. #endif
  120320. sqlite3_mutex_enter(db->mutex);
  120321. assert( !db->mallocFailed );
  120322. rc = createCollation(db, zName, (u8)enc, pCtx, xCompare, xDel);
  120323. rc = sqlite3ApiExit(db, rc);
  120324. sqlite3_mutex_leave(db->mutex);
  120325. return rc;
  120326. }
  120327. #ifndef SQLITE_OMIT_UTF16
  120328. /*
  120329. ** Register a new collation sequence with the database handle db.
  120330. */
  120331. SQLITE_API int sqlite3_create_collation16(
  120332. sqlite3* db,
  120333. const void *zName,
  120334. int enc,
  120335. void* pCtx,
  120336. int(*xCompare)(void*,int,const void*,int,const void*)
  120337. ){
  120338. int rc = SQLITE_OK;
  120339. char *zName8;
  120340. #ifdef SQLITE_ENABLE_API_ARMOR
  120341. if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
  120342. #endif
  120343. sqlite3_mutex_enter(db->mutex);
  120344. assert( !db->mallocFailed );
  120345. zName8 = sqlite3Utf16to8(db, zName, -1, SQLITE_UTF16NATIVE);
  120346. if( zName8 ){
  120347. rc = createCollation(db, zName8, (u8)enc, pCtx, xCompare, 0);
  120348. sqlite3DbFree(db, zName8);
  120349. }
  120350. rc = sqlite3ApiExit(db, rc);
  120351. sqlite3_mutex_leave(db->mutex);
  120352. return rc;
  120353. }
  120354. #endif /* SQLITE_OMIT_UTF16 */
  120355. /*
  120356. ** Register a collation sequence factory callback with the database handle
  120357. ** db. Replace any previously installed collation sequence factory.
  120358. */
  120359. SQLITE_API int sqlite3_collation_needed(
  120360. sqlite3 *db,
  120361. void *pCollNeededArg,
  120362. void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*)
  120363. ){
  120364. #ifdef SQLITE_ENABLE_API_ARMOR
  120365. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  120366. #endif
  120367. sqlite3_mutex_enter(db->mutex);
  120368. db->xCollNeeded = xCollNeeded;
  120369. db->xCollNeeded16 = 0;
  120370. db->pCollNeededArg = pCollNeededArg;
  120371. sqlite3_mutex_leave(db->mutex);
  120372. return SQLITE_OK;
  120373. }
  120374. #ifndef SQLITE_OMIT_UTF16
  120375. /*
  120376. ** Register a collation sequence factory callback with the database handle
  120377. ** db. Replace any previously installed collation sequence factory.
  120378. */
  120379. SQLITE_API int sqlite3_collation_needed16(
  120380. sqlite3 *db,
  120381. void *pCollNeededArg,
  120382. void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*)
  120383. ){
  120384. #ifdef SQLITE_ENABLE_API_ARMOR
  120385. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  120386. #endif
  120387. sqlite3_mutex_enter(db->mutex);
  120388. db->xCollNeeded = 0;
  120389. db->xCollNeeded16 = xCollNeeded16;
  120390. db->pCollNeededArg = pCollNeededArg;
  120391. sqlite3_mutex_leave(db->mutex);
  120392. return SQLITE_OK;
  120393. }
  120394. #endif /* SQLITE_OMIT_UTF16 */
  120395. #ifndef SQLITE_OMIT_DEPRECATED
  120396. /*
  120397. ** This function is now an anachronism. It used to be used to recover from a
  120398. ** malloc() failure, but SQLite now does this automatically.
  120399. */
  120400. SQLITE_API int sqlite3_global_recover(void){
  120401. return SQLITE_OK;
  120402. }
  120403. #endif
  120404. /*
  120405. ** Test to see whether or not the database connection is in autocommit
  120406. ** mode. Return TRUE if it is and FALSE if not. Autocommit mode is on
  120407. ** by default. Autocommit is disabled by a BEGIN statement and reenabled
  120408. ** by the next COMMIT or ROLLBACK.
  120409. */
  120410. SQLITE_API int sqlite3_get_autocommit(sqlite3 *db){
  120411. #ifdef SQLITE_ENABLE_API_ARMOR
  120412. if( !sqlite3SafetyCheckOk(db) ){
  120413. (void)SQLITE_MISUSE_BKPT;
  120414. return 0;
  120415. }
  120416. #endif
  120417. return db->autoCommit;
  120418. }
  120419. /*
  120420. ** The following routines are substitutes for constants SQLITE_CORRUPT,
  120421. ** SQLITE_MISUSE, SQLITE_CANTOPEN, SQLITE_IOERR and possibly other error
  120422. ** constants. They serve two purposes:
  120423. **
  120424. ** 1. Serve as a convenient place to set a breakpoint in a debugger
  120425. ** to detect when version error conditions occurs.
  120426. **
  120427. ** 2. Invoke sqlite3_log() to provide the source code location where
  120428. ** a low-level error is first detected.
  120429. */
  120430. SQLITE_PRIVATE int sqlite3CorruptError(int lineno){
  120431. testcase( sqlite3GlobalConfig.xLog!=0 );
  120432. sqlite3_log(SQLITE_CORRUPT,
  120433. "database corruption at line %d of [%.10s]",
  120434. lineno, 20+sqlite3_sourceid());
  120435. return SQLITE_CORRUPT;
  120436. }
  120437. SQLITE_PRIVATE int sqlite3MisuseError(int lineno){
  120438. testcase( sqlite3GlobalConfig.xLog!=0 );
  120439. sqlite3_log(SQLITE_MISUSE,
  120440. "misuse at line %d of [%.10s]",
  120441. lineno, 20+sqlite3_sourceid());
  120442. return SQLITE_MISUSE;
  120443. }
  120444. SQLITE_PRIVATE int sqlite3CantopenError(int lineno){
  120445. testcase( sqlite3GlobalConfig.xLog!=0 );
  120446. sqlite3_log(SQLITE_CANTOPEN,
  120447. "cannot open file at line %d of [%.10s]",
  120448. lineno, 20+sqlite3_sourceid());
  120449. return SQLITE_CANTOPEN;
  120450. }
  120451. #ifndef SQLITE_OMIT_DEPRECATED
  120452. /*
  120453. ** This is a convenience routine that makes sure that all thread-specific
  120454. ** data for this thread has been deallocated.
  120455. **
  120456. ** SQLite no longer uses thread-specific data so this routine is now a
  120457. ** no-op. It is retained for historical compatibility.
  120458. */
  120459. SQLITE_API void sqlite3_thread_cleanup(void){
  120460. }
  120461. #endif
  120462. /*
  120463. ** Return meta information about a specific column of a database table.
  120464. ** See comment in sqlite3.h (sqlite.h.in) for details.
  120465. */
  120466. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  120467. SQLITE_API int sqlite3_table_column_metadata(
  120468. sqlite3 *db, /* Connection handle */
  120469. const char *zDbName, /* Database name or NULL */
  120470. const char *zTableName, /* Table name */
  120471. const char *zColumnName, /* Column name */
  120472. char const **pzDataType, /* OUTPUT: Declared data type */
  120473. char const **pzCollSeq, /* OUTPUT: Collation sequence name */
  120474. int *pNotNull, /* OUTPUT: True if NOT NULL constraint exists */
  120475. int *pPrimaryKey, /* OUTPUT: True if column part of PK */
  120476. int *pAutoinc /* OUTPUT: True if column is auto-increment */
  120477. ){
  120478. int rc;
  120479. char *zErrMsg = 0;
  120480. Table *pTab = 0;
  120481. Column *pCol = 0;
  120482. int iCol;
  120483. char const *zDataType = 0;
  120484. char const *zCollSeq = 0;
  120485. int notnull = 0;
  120486. int primarykey = 0;
  120487. int autoinc = 0;
  120488. /* Ensure the database schema has been loaded */
  120489. sqlite3_mutex_enter(db->mutex);
  120490. sqlite3BtreeEnterAll(db);
  120491. rc = sqlite3Init(db, &zErrMsg);
  120492. if( SQLITE_OK!=rc ){
  120493. goto error_out;
  120494. }
  120495. /* Locate the table in question */
  120496. pTab = sqlite3FindTable(db, zTableName, zDbName);
  120497. if( !pTab || pTab->pSelect ){
  120498. pTab = 0;
  120499. goto error_out;
  120500. }
  120501. /* Find the column for which info is requested */
  120502. if( sqlite3IsRowid(zColumnName) ){
  120503. iCol = pTab->iPKey;
  120504. if( iCol>=0 ){
  120505. pCol = &pTab->aCol[iCol];
  120506. }
  120507. }else{
  120508. for(iCol=0; iCol<pTab->nCol; iCol++){
  120509. pCol = &pTab->aCol[iCol];
  120510. if( 0==sqlite3StrICmp(pCol->zName, zColumnName) ){
  120511. break;
  120512. }
  120513. }
  120514. if( iCol==pTab->nCol ){
  120515. pTab = 0;
  120516. goto error_out;
  120517. }
  120518. }
  120519. /* The following block stores the meta information that will be returned
  120520. ** to the caller in local variables zDataType, zCollSeq, notnull, primarykey
  120521. ** and autoinc. At this point there are two possibilities:
  120522. **
  120523. ** 1. The specified column name was rowid", "oid" or "_rowid_"
  120524. ** and there is no explicitly declared IPK column.
  120525. **
  120526. ** 2. The table is not a view and the column name identified an
  120527. ** explicitly declared column. Copy meta information from *pCol.
  120528. */
  120529. if( pCol ){
  120530. zDataType = pCol->zType;
  120531. zCollSeq = pCol->zColl;
  120532. notnull = pCol->notNull!=0;
  120533. primarykey = (pCol->colFlags & COLFLAG_PRIMKEY)!=0;
  120534. autoinc = pTab->iPKey==iCol && (pTab->tabFlags & TF_Autoincrement)!=0;
  120535. }else{
  120536. zDataType = "INTEGER";
  120537. primarykey = 1;
  120538. }
  120539. if( !zCollSeq ){
  120540. zCollSeq = "BINARY";
  120541. }
  120542. error_out:
  120543. sqlite3BtreeLeaveAll(db);
  120544. /* Whether the function call succeeded or failed, set the output parameters
  120545. ** to whatever their local counterparts contain. If an error did occur,
  120546. ** this has the effect of zeroing all output parameters.
  120547. */
  120548. if( pzDataType ) *pzDataType = zDataType;
  120549. if( pzCollSeq ) *pzCollSeq = zCollSeq;
  120550. if( pNotNull ) *pNotNull = notnull;
  120551. if( pPrimaryKey ) *pPrimaryKey = primarykey;
  120552. if( pAutoinc ) *pAutoinc = autoinc;
  120553. if( SQLITE_OK==rc && !pTab ){
  120554. sqlite3DbFree(db, zErrMsg);
  120555. zErrMsg = sqlite3MPrintf(db, "no such table column: %s.%s", zTableName,
  120556. zColumnName);
  120557. rc = SQLITE_ERROR;
  120558. }
  120559. sqlite3ErrorWithMsg(db, rc, (zErrMsg?"%s":0), zErrMsg);
  120560. sqlite3DbFree(db, zErrMsg);
  120561. rc = sqlite3ApiExit(db, rc);
  120562. sqlite3_mutex_leave(db->mutex);
  120563. return rc;
  120564. }
  120565. #endif
  120566. /*
  120567. ** Sleep for a little while. Return the amount of time slept.
  120568. */
  120569. SQLITE_API int sqlite3_sleep(int ms){
  120570. sqlite3_vfs *pVfs;
  120571. int rc;
  120572. pVfs = sqlite3_vfs_find(0);
  120573. if( pVfs==0 ) return 0;
  120574. /* This function works in milliseconds, but the underlying OsSleep()
  120575. ** API uses microseconds. Hence the 1000's.
  120576. */
  120577. rc = (sqlite3OsSleep(pVfs, 1000*ms)/1000);
  120578. return rc;
  120579. }
  120580. /*
  120581. ** Enable or disable the extended result codes.
  120582. */
  120583. SQLITE_API int sqlite3_extended_result_codes(sqlite3 *db, int onoff){
  120584. #ifdef SQLITE_ENABLE_API_ARMOR
  120585. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  120586. #endif
  120587. sqlite3_mutex_enter(db->mutex);
  120588. db->errMask = onoff ? 0xffffffff : 0xff;
  120589. sqlite3_mutex_leave(db->mutex);
  120590. return SQLITE_OK;
  120591. }
  120592. /*
  120593. ** Invoke the xFileControl method on a particular database.
  120594. */
  120595. SQLITE_API int sqlite3_file_control(sqlite3 *db, const char *zDbName, int op, void *pArg){
  120596. int rc = SQLITE_ERROR;
  120597. Btree *pBtree;
  120598. #ifdef SQLITE_ENABLE_API_ARMOR
  120599. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  120600. #endif
  120601. sqlite3_mutex_enter(db->mutex);
  120602. pBtree = sqlite3DbNameToBtree(db, zDbName);
  120603. if( pBtree ){
  120604. Pager *pPager;
  120605. sqlite3_file *fd;
  120606. sqlite3BtreeEnter(pBtree);
  120607. pPager = sqlite3BtreePager(pBtree);
  120608. assert( pPager!=0 );
  120609. fd = sqlite3PagerFile(pPager);
  120610. assert( fd!=0 );
  120611. if( op==SQLITE_FCNTL_FILE_POINTER ){
  120612. *(sqlite3_file**)pArg = fd;
  120613. rc = SQLITE_OK;
  120614. }else if( fd->pMethods ){
  120615. rc = sqlite3OsFileControl(fd, op, pArg);
  120616. }else{
  120617. rc = SQLITE_NOTFOUND;
  120618. }
  120619. sqlite3BtreeLeave(pBtree);
  120620. }
  120621. sqlite3_mutex_leave(db->mutex);
  120622. return rc;
  120623. }
  120624. /*
  120625. ** Interface to the testing logic.
  120626. */
  120627. SQLITE_API int sqlite3_test_control(int op, ...){
  120628. int rc = 0;
  120629. #ifndef SQLITE_OMIT_BUILTIN_TEST
  120630. va_list ap;
  120631. va_start(ap, op);
  120632. switch( op ){
  120633. /*
  120634. ** Save the current state of the PRNG.
  120635. */
  120636. case SQLITE_TESTCTRL_PRNG_SAVE: {
  120637. sqlite3PrngSaveState();
  120638. break;
  120639. }
  120640. /*
  120641. ** Restore the state of the PRNG to the last state saved using
  120642. ** PRNG_SAVE. If PRNG_SAVE has never before been called, then
  120643. ** this verb acts like PRNG_RESET.
  120644. */
  120645. case SQLITE_TESTCTRL_PRNG_RESTORE: {
  120646. sqlite3PrngRestoreState();
  120647. break;
  120648. }
  120649. /*
  120650. ** Reset the PRNG back to its uninitialized state. The next call
  120651. ** to sqlite3_randomness() will reseed the PRNG using a single call
  120652. ** to the xRandomness method of the default VFS.
  120653. */
  120654. case SQLITE_TESTCTRL_PRNG_RESET: {
  120655. sqlite3_randomness(0,0);
  120656. break;
  120657. }
  120658. /*
  120659. ** sqlite3_test_control(BITVEC_TEST, size, program)
  120660. **
  120661. ** Run a test against a Bitvec object of size. The program argument
  120662. ** is an array of integers that defines the test. Return -1 on a
  120663. ** memory allocation error, 0 on success, or non-zero for an error.
  120664. ** See the sqlite3BitvecBuiltinTest() for additional information.
  120665. */
  120666. case SQLITE_TESTCTRL_BITVEC_TEST: {
  120667. int sz = va_arg(ap, int);
  120668. int *aProg = va_arg(ap, int*);
  120669. rc = sqlite3BitvecBuiltinTest(sz, aProg);
  120670. break;
  120671. }
  120672. /*
  120673. ** sqlite3_test_control(FAULT_INSTALL, xCallback)
  120674. **
  120675. ** Arrange to invoke xCallback() whenever sqlite3FaultSim() is called,
  120676. ** if xCallback is not NULL.
  120677. **
  120678. ** As a test of the fault simulator mechanism itself, sqlite3FaultSim(0)
  120679. ** is called immediately after installing the new callback and the return
  120680. ** value from sqlite3FaultSim(0) becomes the return from
  120681. ** sqlite3_test_control().
  120682. */
  120683. case SQLITE_TESTCTRL_FAULT_INSTALL: {
  120684. /* MSVC is picky about pulling func ptrs from va lists.
  120685. ** http://support.microsoft.com/kb/47961
  120686. ** sqlite3GlobalConfig.xTestCallback = va_arg(ap, int(*)(int));
  120687. */
  120688. typedef int(*TESTCALLBACKFUNC_t)(int);
  120689. sqlite3GlobalConfig.xTestCallback = va_arg(ap, TESTCALLBACKFUNC_t);
  120690. rc = sqlite3FaultSim(0);
  120691. break;
  120692. }
  120693. /*
  120694. ** sqlite3_test_control(BENIGN_MALLOC_HOOKS, xBegin, xEnd)
  120695. **
  120696. ** Register hooks to call to indicate which malloc() failures
  120697. ** are benign.
  120698. */
  120699. case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS: {
  120700. typedef void (*void_function)(void);
  120701. void_function xBenignBegin;
  120702. void_function xBenignEnd;
  120703. xBenignBegin = va_arg(ap, void_function);
  120704. xBenignEnd = va_arg(ap, void_function);
  120705. sqlite3BenignMallocHooks(xBenignBegin, xBenignEnd);
  120706. break;
  120707. }
  120708. /*
  120709. ** sqlite3_test_control(SQLITE_TESTCTRL_PENDING_BYTE, unsigned int X)
  120710. **
  120711. ** Set the PENDING byte to the value in the argument, if X>0.
  120712. ** Make no changes if X==0. Return the value of the pending byte
  120713. ** as it existing before this routine was called.
  120714. **
  120715. ** IMPORTANT: Changing the PENDING byte from 0x40000000 results in
  120716. ** an incompatible database file format. Changing the PENDING byte
  120717. ** while any database connection is open results in undefined and
  120718. ** deleterious behavior.
  120719. */
  120720. case SQLITE_TESTCTRL_PENDING_BYTE: {
  120721. rc = PENDING_BYTE;
  120722. #ifndef SQLITE_OMIT_WSD
  120723. {
  120724. unsigned int newVal = va_arg(ap, unsigned int);
  120725. if( newVal ) sqlite3PendingByte = newVal;
  120726. }
  120727. #endif
  120728. break;
  120729. }
  120730. /*
  120731. ** sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, int X)
  120732. **
  120733. ** This action provides a run-time test to see whether or not
  120734. ** assert() was enabled at compile-time. If X is true and assert()
  120735. ** is enabled, then the return value is true. If X is true and
  120736. ** assert() is disabled, then the return value is zero. If X is
  120737. ** false and assert() is enabled, then the assertion fires and the
  120738. ** process aborts. If X is false and assert() is disabled, then the
  120739. ** return value is zero.
  120740. */
  120741. case SQLITE_TESTCTRL_ASSERT: {
  120742. volatile int x = 0;
  120743. assert( (x = va_arg(ap,int))!=0 );
  120744. rc = x;
  120745. break;
  120746. }
  120747. /*
  120748. ** sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, int X)
  120749. **
  120750. ** This action provides a run-time test to see how the ALWAYS and
  120751. ** NEVER macros were defined at compile-time.
  120752. **
  120753. ** The return value is ALWAYS(X).
  120754. **
  120755. ** The recommended test is X==2. If the return value is 2, that means
  120756. ** ALWAYS() and NEVER() are both no-op pass-through macros, which is the
  120757. ** default setting. If the return value is 1, then ALWAYS() is either
  120758. ** hard-coded to true or else it asserts if its argument is false.
  120759. ** The first behavior (hard-coded to true) is the case if
  120760. ** SQLITE_TESTCTRL_ASSERT shows that assert() is disabled and the second
  120761. ** behavior (assert if the argument to ALWAYS() is false) is the case if
  120762. ** SQLITE_TESTCTRL_ASSERT shows that assert() is enabled.
  120763. **
  120764. ** The run-time test procedure might look something like this:
  120765. **
  120766. ** if( sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, 2)==2 ){
  120767. ** // ALWAYS() and NEVER() are no-op pass-through macros
  120768. ** }else if( sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, 1) ){
  120769. ** // ALWAYS(x) asserts that x is true. NEVER(x) asserts x is false.
  120770. ** }else{
  120771. ** // ALWAYS(x) is a constant 1. NEVER(x) is a constant 0.
  120772. ** }
  120773. */
  120774. case SQLITE_TESTCTRL_ALWAYS: {
  120775. int x = va_arg(ap,int);
  120776. rc = ALWAYS(x);
  120777. break;
  120778. }
  120779. /*
  120780. ** sqlite3_test_control(SQLITE_TESTCTRL_BYTEORDER);
  120781. **
  120782. ** The integer returned reveals the byte-order of the computer on which
  120783. ** SQLite is running:
  120784. **
  120785. ** 1 big-endian, determined at run-time
  120786. ** 10 little-endian, determined at run-time
  120787. ** 432101 big-endian, determined at compile-time
  120788. ** 123410 little-endian, determined at compile-time
  120789. */
  120790. case SQLITE_TESTCTRL_BYTEORDER: {
  120791. rc = SQLITE_BYTEORDER*100 + SQLITE_LITTLEENDIAN*10 + SQLITE_BIGENDIAN;
  120792. break;
  120793. }
  120794. /* sqlite3_test_control(SQLITE_TESTCTRL_RESERVE, sqlite3 *db, int N)
  120795. **
  120796. ** Set the nReserve size to N for the main database on the database
  120797. ** connection db.
  120798. */
  120799. case SQLITE_TESTCTRL_RESERVE: {
  120800. sqlite3 *db = va_arg(ap, sqlite3*);
  120801. int x = va_arg(ap,int);
  120802. sqlite3_mutex_enter(db->mutex);
  120803. sqlite3BtreeSetPageSize(db->aDb[0].pBt, 0, x, 0);
  120804. sqlite3_mutex_leave(db->mutex);
  120805. break;
  120806. }
  120807. /* sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS, sqlite3 *db, int N)
  120808. **
  120809. ** Enable or disable various optimizations for testing purposes. The
  120810. ** argument N is a bitmask of optimizations to be disabled. For normal
  120811. ** operation N should be 0. The idea is that a test program (like the
  120812. ** SQL Logic Test or SLT test module) can run the same SQL multiple times
  120813. ** with various optimizations disabled to verify that the same answer
  120814. ** is obtained in every case.
  120815. */
  120816. case SQLITE_TESTCTRL_OPTIMIZATIONS: {
  120817. sqlite3 *db = va_arg(ap, sqlite3*);
  120818. db->dbOptFlags = (u16)(va_arg(ap, int) & 0xffff);
  120819. break;
  120820. }
  120821. #ifdef SQLITE_N_KEYWORD
  120822. /* sqlite3_test_control(SQLITE_TESTCTRL_ISKEYWORD, const char *zWord)
  120823. **
  120824. ** If zWord is a keyword recognized by the parser, then return the
  120825. ** number of keywords. Or if zWord is not a keyword, return 0.
  120826. **
  120827. ** This test feature is only available in the amalgamation since
  120828. ** the SQLITE_N_KEYWORD macro is not defined in this file if SQLite
  120829. ** is built using separate source files.
  120830. */
  120831. case SQLITE_TESTCTRL_ISKEYWORD: {
  120832. const char *zWord = va_arg(ap, const char*);
  120833. int n = sqlite3Strlen30(zWord);
  120834. rc = (sqlite3KeywordCode((u8*)zWord, n)!=TK_ID) ? SQLITE_N_KEYWORD : 0;
  120835. break;
  120836. }
  120837. #endif
  120838. /* sqlite3_test_control(SQLITE_TESTCTRL_SCRATCHMALLOC, sz, &pNew, pFree);
  120839. **
  120840. ** Pass pFree into sqlite3ScratchFree().
  120841. ** If sz>0 then allocate a scratch buffer into pNew.
  120842. */
  120843. case SQLITE_TESTCTRL_SCRATCHMALLOC: {
  120844. void *pFree, **ppNew;
  120845. int sz;
  120846. sz = va_arg(ap, int);
  120847. ppNew = va_arg(ap, void**);
  120848. pFree = va_arg(ap, void*);
  120849. if( sz ) *ppNew = sqlite3ScratchMalloc(sz);
  120850. sqlite3ScratchFree(pFree);
  120851. break;
  120852. }
  120853. /* sqlite3_test_control(SQLITE_TESTCTRL_LOCALTIME_FAULT, int onoff);
  120854. **
  120855. ** If parameter onoff is non-zero, configure the wrappers so that all
  120856. ** subsequent calls to localtime() and variants fail. If onoff is zero,
  120857. ** undo this setting.
  120858. */
  120859. case SQLITE_TESTCTRL_LOCALTIME_FAULT: {
  120860. sqlite3GlobalConfig.bLocaltimeFault = va_arg(ap, int);
  120861. break;
  120862. }
  120863. /* sqlite3_test_control(SQLITE_TESTCTRL_NEVER_CORRUPT, int);
  120864. **
  120865. ** Set or clear a flag that indicates that the database file is always well-
  120866. ** formed and never corrupt. This flag is clear by default, indicating that
  120867. ** database files might have arbitrary corruption. Setting the flag during
  120868. ** testing causes certain assert() statements in the code to be activated
  120869. ** that demonstrat invariants on well-formed database files.
  120870. */
  120871. case SQLITE_TESTCTRL_NEVER_CORRUPT: {
  120872. sqlite3GlobalConfig.neverCorrupt = va_arg(ap, int);
  120873. break;
  120874. }
  120875. /* sqlite3_test_control(SQLITE_TESTCTRL_VDBE_COVERAGE, xCallback, ptr);
  120876. **
  120877. ** Set the VDBE coverage callback function to xCallback with context
  120878. ** pointer ptr.
  120879. */
  120880. case SQLITE_TESTCTRL_VDBE_COVERAGE: {
  120881. #ifdef SQLITE_VDBE_COVERAGE
  120882. typedef void (*branch_callback)(void*,int,u8,u8);
  120883. sqlite3GlobalConfig.xVdbeBranch = va_arg(ap,branch_callback);
  120884. sqlite3GlobalConfig.pVdbeBranchArg = va_arg(ap,void*);
  120885. #endif
  120886. break;
  120887. }
  120888. /* sqlite3_test_control(SQLITE_TESTCTRL_SORTER_MMAP, db, nMax); */
  120889. case SQLITE_TESTCTRL_SORTER_MMAP: {
  120890. sqlite3 *db = va_arg(ap, sqlite3*);
  120891. db->nMaxSorterMmap = va_arg(ap, int);
  120892. break;
  120893. }
  120894. /* sqlite3_test_control(SQLITE_TESTCTRL_ISINIT);
  120895. **
  120896. ** Return SQLITE_OK if SQLite has been initialized and SQLITE_ERROR if
  120897. ** not.
  120898. */
  120899. case SQLITE_TESTCTRL_ISINIT: {
  120900. if( sqlite3GlobalConfig.isInit==0 ) rc = SQLITE_ERROR;
  120901. break;
  120902. }
  120903. }
  120904. va_end(ap);
  120905. #endif /* SQLITE_OMIT_BUILTIN_TEST */
  120906. return rc;
  120907. }
  120908. /*
  120909. ** This is a utility routine, useful to VFS implementations, that checks
  120910. ** to see if a database file was a URI that contained a specific query
  120911. ** parameter, and if so obtains the value of the query parameter.
  120912. **
  120913. ** The zFilename argument is the filename pointer passed into the xOpen()
  120914. ** method of a VFS implementation. The zParam argument is the name of the
  120915. ** query parameter we seek. This routine returns the value of the zParam
  120916. ** parameter if it exists. If the parameter does not exist, this routine
  120917. ** returns a NULL pointer.
  120918. */
  120919. SQLITE_API const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam){
  120920. if( zFilename==0 || zParam==0 ) return 0;
  120921. zFilename += sqlite3Strlen30(zFilename) + 1;
  120922. while( zFilename[0] ){
  120923. int x = strcmp(zFilename, zParam);
  120924. zFilename += sqlite3Strlen30(zFilename) + 1;
  120925. if( x==0 ) return zFilename;
  120926. zFilename += sqlite3Strlen30(zFilename) + 1;
  120927. }
  120928. return 0;
  120929. }
  120930. /*
  120931. ** Return a boolean value for a query parameter.
  120932. */
  120933. SQLITE_API int sqlite3_uri_boolean(const char *zFilename, const char *zParam, int bDflt){
  120934. const char *z = sqlite3_uri_parameter(zFilename, zParam);
  120935. bDflt = bDflt!=0;
  120936. return z ? sqlite3GetBoolean(z, bDflt) : bDflt;
  120937. }
  120938. /*
  120939. ** Return a 64-bit integer value for a query parameter.
  120940. */
  120941. SQLITE_API sqlite3_int64 sqlite3_uri_int64(
  120942. const char *zFilename, /* Filename as passed to xOpen */
  120943. const char *zParam, /* URI parameter sought */
  120944. sqlite3_int64 bDflt /* return if parameter is missing */
  120945. ){
  120946. const char *z = sqlite3_uri_parameter(zFilename, zParam);
  120947. sqlite3_int64 v;
  120948. if( z && sqlite3DecOrHexToI64(z, &v)==SQLITE_OK ){
  120949. bDflt = v;
  120950. }
  120951. return bDflt;
  120952. }
  120953. /*
  120954. ** Return the Btree pointer identified by zDbName. Return NULL if not found.
  120955. */
  120956. SQLITE_PRIVATE Btree *sqlite3DbNameToBtree(sqlite3 *db, const char *zDbName){
  120957. int i;
  120958. for(i=0; i<db->nDb; i++){
  120959. if( db->aDb[i].pBt
  120960. && (zDbName==0 || sqlite3StrICmp(zDbName, db->aDb[i].zName)==0)
  120961. ){
  120962. return db->aDb[i].pBt;
  120963. }
  120964. }
  120965. return 0;
  120966. }
  120967. /*
  120968. ** Return the filename of the database associated with a database
  120969. ** connection.
  120970. */
  120971. SQLITE_API const char *sqlite3_db_filename(sqlite3 *db, const char *zDbName){
  120972. #ifdef SQLITE_ENABLE_API_ARMOR
  120973. if( !sqlite3SafetyCheckOk(db) ){
  120974. (void)SQLITE_MISUSE_BKPT;
  120975. return 0;
  120976. }
  120977. #endif
  120978. Btree *pBt = sqlite3DbNameToBtree(db, zDbName);
  120979. return pBt ? sqlite3BtreeGetFilename(pBt) : 0;
  120980. }
  120981. /*
  120982. ** Return 1 if database is read-only or 0 if read/write. Return -1 if
  120983. ** no such database exists.
  120984. */
  120985. SQLITE_API int sqlite3_db_readonly(sqlite3 *db, const char *zDbName){
  120986. #ifdef SQLITE_ENABLE_API_ARMOR
  120987. if( !sqlite3SafetyCheckOk(db) ){
  120988. (void)SQLITE_MISUSE_BKPT;
  120989. return -1;
  120990. }
  120991. #endif
  120992. Btree *pBt = sqlite3DbNameToBtree(db, zDbName);
  120993. return pBt ? sqlite3BtreeIsReadonly(pBt) : -1;
  120994. }
  120995. /************** End of main.c ************************************************/
  120996. /************** Begin file notify.c ******************************************/
  120997. /*
  120998. ** 2009 March 3
  120999. **
  121000. ** The author disclaims copyright to this source code. In place of
  121001. ** a legal notice, here is a blessing:
  121002. **
  121003. ** May you do good and not evil.
  121004. ** May you find forgiveness for yourself and forgive others.
  121005. ** May you share freely, never taking more than you give.
  121006. **
  121007. *************************************************************************
  121008. **
  121009. ** This file contains the implementation of the sqlite3_unlock_notify()
  121010. ** API method and its associated functionality.
  121011. */
  121012. /* Omit this entire file if SQLITE_ENABLE_UNLOCK_NOTIFY is not defined. */
  121013. #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
  121014. /*
  121015. ** Public interfaces:
  121016. **
  121017. ** sqlite3ConnectionBlocked()
  121018. ** sqlite3ConnectionUnlocked()
  121019. ** sqlite3ConnectionClosed()
  121020. ** sqlite3_unlock_notify()
  121021. */
  121022. #define assertMutexHeld() \
  121023. assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) )
  121024. /*
  121025. ** Head of a linked list of all sqlite3 objects created by this process
  121026. ** for which either sqlite3.pBlockingConnection or sqlite3.pUnlockConnection
  121027. ** is not NULL. This variable may only accessed while the STATIC_MASTER
  121028. ** mutex is held.
  121029. */
  121030. static sqlite3 *SQLITE_WSD sqlite3BlockedList = 0;
  121031. #ifndef NDEBUG
  121032. /*
  121033. ** This function is a complex assert() that verifies the following
  121034. ** properties of the blocked connections list:
  121035. **
  121036. ** 1) Each entry in the list has a non-NULL value for either
  121037. ** pUnlockConnection or pBlockingConnection, or both.
  121038. **
  121039. ** 2) All entries in the list that share a common value for
  121040. ** xUnlockNotify are grouped together.
  121041. **
  121042. ** 3) If the argument db is not NULL, then none of the entries in the
  121043. ** blocked connections list have pUnlockConnection or pBlockingConnection
  121044. ** set to db. This is used when closing connection db.
  121045. */
  121046. static void checkListProperties(sqlite3 *db){
  121047. sqlite3 *p;
  121048. for(p=sqlite3BlockedList; p; p=p->pNextBlocked){
  121049. int seen = 0;
  121050. sqlite3 *p2;
  121051. /* Verify property (1) */
  121052. assert( p->pUnlockConnection || p->pBlockingConnection );
  121053. /* Verify property (2) */
  121054. for(p2=sqlite3BlockedList; p2!=p; p2=p2->pNextBlocked){
  121055. if( p2->xUnlockNotify==p->xUnlockNotify ) seen = 1;
  121056. assert( p2->xUnlockNotify==p->xUnlockNotify || !seen );
  121057. assert( db==0 || p->pUnlockConnection!=db );
  121058. assert( db==0 || p->pBlockingConnection!=db );
  121059. }
  121060. }
  121061. }
  121062. #else
  121063. # define checkListProperties(x)
  121064. #endif
  121065. /*
  121066. ** Remove connection db from the blocked connections list. If connection
  121067. ** db is not currently a part of the list, this function is a no-op.
  121068. */
  121069. static void removeFromBlockedList(sqlite3 *db){
  121070. sqlite3 **pp;
  121071. assertMutexHeld();
  121072. for(pp=&sqlite3BlockedList; *pp; pp = &(*pp)->pNextBlocked){
  121073. if( *pp==db ){
  121074. *pp = (*pp)->pNextBlocked;
  121075. break;
  121076. }
  121077. }
  121078. }
  121079. /*
  121080. ** Add connection db to the blocked connections list. It is assumed
  121081. ** that it is not already a part of the list.
  121082. */
  121083. static void addToBlockedList(sqlite3 *db){
  121084. sqlite3 **pp;
  121085. assertMutexHeld();
  121086. for(
  121087. pp=&sqlite3BlockedList;
  121088. *pp && (*pp)->xUnlockNotify!=db->xUnlockNotify;
  121089. pp=&(*pp)->pNextBlocked
  121090. );
  121091. db->pNextBlocked = *pp;
  121092. *pp = db;
  121093. }
  121094. /*
  121095. ** Obtain the STATIC_MASTER mutex.
  121096. */
  121097. static void enterMutex(void){
  121098. sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  121099. checkListProperties(0);
  121100. }
  121101. /*
  121102. ** Release the STATIC_MASTER mutex.
  121103. */
  121104. static void leaveMutex(void){
  121105. assertMutexHeld();
  121106. checkListProperties(0);
  121107. sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  121108. }
  121109. /*
  121110. ** Register an unlock-notify callback.
  121111. **
  121112. ** This is called after connection "db" has attempted some operation
  121113. ** but has received an SQLITE_LOCKED error because another connection
  121114. ** (call it pOther) in the same process was busy using the same shared
  121115. ** cache. pOther is found by looking at db->pBlockingConnection.
  121116. **
  121117. ** If there is no blocking connection, the callback is invoked immediately,
  121118. ** before this routine returns.
  121119. **
  121120. ** If pOther is already blocked on db, then report SQLITE_LOCKED, to indicate
  121121. ** a deadlock.
  121122. **
  121123. ** Otherwise, make arrangements to invoke xNotify when pOther drops
  121124. ** its locks.
  121125. **
  121126. ** Each call to this routine overrides any prior callbacks registered
  121127. ** on the same "db". If xNotify==0 then any prior callbacks are immediately
  121128. ** cancelled.
  121129. */
  121130. SQLITE_API int sqlite3_unlock_notify(
  121131. sqlite3 *db,
  121132. void (*xNotify)(void **, int),
  121133. void *pArg
  121134. ){
  121135. int rc = SQLITE_OK;
  121136. sqlite3_mutex_enter(db->mutex);
  121137. enterMutex();
  121138. if( xNotify==0 ){
  121139. removeFromBlockedList(db);
  121140. db->pBlockingConnection = 0;
  121141. db->pUnlockConnection = 0;
  121142. db->xUnlockNotify = 0;
  121143. db->pUnlockArg = 0;
  121144. }else if( 0==db->pBlockingConnection ){
  121145. /* The blocking transaction has been concluded. Or there never was a
  121146. ** blocking transaction. In either case, invoke the notify callback
  121147. ** immediately.
  121148. */
  121149. xNotify(&pArg, 1);
  121150. }else{
  121151. sqlite3 *p;
  121152. for(p=db->pBlockingConnection; p && p!=db; p=p->pUnlockConnection){}
  121153. if( p ){
  121154. rc = SQLITE_LOCKED; /* Deadlock detected. */
  121155. }else{
  121156. db->pUnlockConnection = db->pBlockingConnection;
  121157. db->xUnlockNotify = xNotify;
  121158. db->pUnlockArg = pArg;
  121159. removeFromBlockedList(db);
  121160. addToBlockedList(db);
  121161. }
  121162. }
  121163. leaveMutex();
  121164. assert( !db->mallocFailed );
  121165. sqlite3ErrorWithMsg(db, rc, (rc?"database is deadlocked":0));
  121166. sqlite3_mutex_leave(db->mutex);
  121167. return rc;
  121168. }
  121169. /*
  121170. ** This function is called while stepping or preparing a statement
  121171. ** associated with connection db. The operation will return SQLITE_LOCKED
  121172. ** to the user because it requires a lock that will not be available
  121173. ** until connection pBlocker concludes its current transaction.
  121174. */
  121175. SQLITE_PRIVATE void sqlite3ConnectionBlocked(sqlite3 *db, sqlite3 *pBlocker){
  121176. enterMutex();
  121177. if( db->pBlockingConnection==0 && db->pUnlockConnection==0 ){
  121178. addToBlockedList(db);
  121179. }
  121180. db->pBlockingConnection = pBlocker;
  121181. leaveMutex();
  121182. }
  121183. /*
  121184. ** This function is called when
  121185. ** the transaction opened by database db has just finished. Locks held
  121186. ** by database connection db have been released.
  121187. **
  121188. ** This function loops through each entry in the blocked connections
  121189. ** list and does the following:
  121190. **
  121191. ** 1) If the sqlite3.pBlockingConnection member of a list entry is
  121192. ** set to db, then set pBlockingConnection=0.
  121193. **
  121194. ** 2) If the sqlite3.pUnlockConnection member of a list entry is
  121195. ** set to db, then invoke the configured unlock-notify callback and
  121196. ** set pUnlockConnection=0.
  121197. **
  121198. ** 3) If the two steps above mean that pBlockingConnection==0 and
  121199. ** pUnlockConnection==0, remove the entry from the blocked connections
  121200. ** list.
  121201. */
  121202. SQLITE_PRIVATE void sqlite3ConnectionUnlocked(sqlite3 *db){
  121203. void (*xUnlockNotify)(void **, int) = 0; /* Unlock-notify cb to invoke */
  121204. int nArg = 0; /* Number of entries in aArg[] */
  121205. sqlite3 **pp; /* Iterator variable */
  121206. void **aArg; /* Arguments to the unlock callback */
  121207. void **aDyn = 0; /* Dynamically allocated space for aArg[] */
  121208. void *aStatic[16]; /* Starter space for aArg[]. No malloc required */
  121209. aArg = aStatic;
  121210. enterMutex(); /* Enter STATIC_MASTER mutex */
  121211. /* This loop runs once for each entry in the blocked-connections list. */
  121212. for(pp=&sqlite3BlockedList; *pp; /* no-op */ ){
  121213. sqlite3 *p = *pp;
  121214. /* Step 1. */
  121215. if( p->pBlockingConnection==db ){
  121216. p->pBlockingConnection = 0;
  121217. }
  121218. /* Step 2. */
  121219. if( p->pUnlockConnection==db ){
  121220. assert( p->xUnlockNotify );
  121221. if( p->xUnlockNotify!=xUnlockNotify && nArg!=0 ){
  121222. xUnlockNotify(aArg, nArg);
  121223. nArg = 0;
  121224. }
  121225. sqlite3BeginBenignMalloc();
  121226. assert( aArg==aDyn || (aDyn==0 && aArg==aStatic) );
  121227. assert( nArg<=(int)ArraySize(aStatic) || aArg==aDyn );
  121228. if( (!aDyn && nArg==(int)ArraySize(aStatic))
  121229. || (aDyn && nArg==(int)(sqlite3MallocSize(aDyn)/sizeof(void*)))
  121230. ){
  121231. /* The aArg[] array needs to grow. */
  121232. void **pNew = (void **)sqlite3Malloc(nArg*sizeof(void *)*2);
  121233. if( pNew ){
  121234. memcpy(pNew, aArg, nArg*sizeof(void *));
  121235. sqlite3_free(aDyn);
  121236. aDyn = aArg = pNew;
  121237. }else{
  121238. /* This occurs when the array of context pointers that need to
  121239. ** be passed to the unlock-notify callback is larger than the
  121240. ** aStatic[] array allocated on the stack and the attempt to
  121241. ** allocate a larger array from the heap has failed.
  121242. **
  121243. ** This is a difficult situation to handle. Returning an error
  121244. ** code to the caller is insufficient, as even if an error code
  121245. ** is returned the transaction on connection db will still be
  121246. ** closed and the unlock-notify callbacks on blocked connections
  121247. ** will go unissued. This might cause the application to wait
  121248. ** indefinitely for an unlock-notify callback that will never
  121249. ** arrive.
  121250. **
  121251. ** Instead, invoke the unlock-notify callback with the context
  121252. ** array already accumulated. We can then clear the array and
  121253. ** begin accumulating any further context pointers without
  121254. ** requiring any dynamic allocation. This is sub-optimal because
  121255. ** it means that instead of one callback with a large array of
  121256. ** context pointers the application will receive two or more
  121257. ** callbacks with smaller arrays of context pointers, which will
  121258. ** reduce the applications ability to prioritize multiple
  121259. ** connections. But it is the best that can be done under the
  121260. ** circumstances.
  121261. */
  121262. xUnlockNotify(aArg, nArg);
  121263. nArg = 0;
  121264. }
  121265. }
  121266. sqlite3EndBenignMalloc();
  121267. aArg[nArg++] = p->pUnlockArg;
  121268. xUnlockNotify = p->xUnlockNotify;
  121269. p->pUnlockConnection = 0;
  121270. p->xUnlockNotify = 0;
  121271. p->pUnlockArg = 0;
  121272. }
  121273. /* Step 3. */
  121274. if( p->pBlockingConnection==0 && p->pUnlockConnection==0 ){
  121275. /* Remove connection p from the blocked connections list. */
  121276. *pp = p->pNextBlocked;
  121277. p->pNextBlocked = 0;
  121278. }else{
  121279. pp = &p->pNextBlocked;
  121280. }
  121281. }
  121282. if( nArg!=0 ){
  121283. xUnlockNotify(aArg, nArg);
  121284. }
  121285. sqlite3_free(aDyn);
  121286. leaveMutex(); /* Leave STATIC_MASTER mutex */
  121287. }
  121288. /*
  121289. ** This is called when the database connection passed as an argument is
  121290. ** being closed. The connection is removed from the blocked list.
  121291. */
  121292. SQLITE_PRIVATE void sqlite3ConnectionClosed(sqlite3 *db){
  121293. sqlite3ConnectionUnlocked(db);
  121294. enterMutex();
  121295. removeFromBlockedList(db);
  121296. checkListProperties(db);
  121297. leaveMutex();
  121298. }
  121299. #endif
  121300. /************** End of notify.c **********************************************/
  121301. /************** Begin file fts3.c ********************************************/
  121302. /*
  121303. ** 2006 Oct 10
  121304. **
  121305. ** The author disclaims copyright to this source code. In place of
  121306. ** a legal notice, here is a blessing:
  121307. **
  121308. ** May you do good and not evil.
  121309. ** May you find forgiveness for yourself and forgive others.
  121310. ** May you share freely, never taking more than you give.
  121311. **
  121312. ******************************************************************************
  121313. **
  121314. ** This is an SQLite module implementing full-text search.
  121315. */
  121316. /*
  121317. ** The code in this file is only compiled if:
  121318. **
  121319. ** * The FTS3 module is being built as an extension
  121320. ** (in which case SQLITE_CORE is not defined), or
  121321. **
  121322. ** * The FTS3 module is being built into the core of
  121323. ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
  121324. */
  121325. /* The full-text index is stored in a series of b+tree (-like)
  121326. ** structures called segments which map terms to doclists. The
  121327. ** structures are like b+trees in layout, but are constructed from the
  121328. ** bottom up in optimal fashion and are not updatable. Since trees
  121329. ** are built from the bottom up, things will be described from the
  121330. ** bottom up.
  121331. **
  121332. **
  121333. **** Varints ****
  121334. ** The basic unit of encoding is a variable-length integer called a
  121335. ** varint. We encode variable-length integers in little-endian order
  121336. ** using seven bits * per byte as follows:
  121337. **
  121338. ** KEY:
  121339. ** A = 0xxxxxxx 7 bits of data and one flag bit
  121340. ** B = 1xxxxxxx 7 bits of data and one flag bit
  121341. **
  121342. ** 7 bits - A
  121343. ** 14 bits - BA
  121344. ** 21 bits - BBA
  121345. ** and so on.
  121346. **
  121347. ** This is similar in concept to how sqlite encodes "varints" but
  121348. ** the encoding is not the same. SQLite varints are big-endian
  121349. ** are are limited to 9 bytes in length whereas FTS3 varints are
  121350. ** little-endian and can be up to 10 bytes in length (in theory).
  121351. **
  121352. ** Example encodings:
  121353. **
  121354. ** 1: 0x01
  121355. ** 127: 0x7f
  121356. ** 128: 0x81 0x00
  121357. **
  121358. **
  121359. **** Document lists ****
  121360. ** A doclist (document list) holds a docid-sorted list of hits for a
  121361. ** given term. Doclists hold docids and associated token positions.
  121362. ** A docid is the unique integer identifier for a single document.
  121363. ** A position is the index of a word within the document. The first
  121364. ** word of the document has a position of 0.
  121365. **
  121366. ** FTS3 used to optionally store character offsets using a compile-time
  121367. ** option. But that functionality is no longer supported.
  121368. **
  121369. ** A doclist is stored like this:
  121370. **
  121371. ** array {
  121372. ** varint docid; (delta from previous doclist)
  121373. ** array { (position list for column 0)
  121374. ** varint position; (2 more than the delta from previous position)
  121375. ** }
  121376. ** array {
  121377. ** varint POS_COLUMN; (marks start of position list for new column)
  121378. ** varint column; (index of new column)
  121379. ** array {
  121380. ** varint position; (2 more than the delta from previous position)
  121381. ** }
  121382. ** }
  121383. ** varint POS_END; (marks end of positions for this document.
  121384. ** }
  121385. **
  121386. ** Here, array { X } means zero or more occurrences of X, adjacent in
  121387. ** memory. A "position" is an index of a token in the token stream
  121388. ** generated by the tokenizer. Note that POS_END and POS_COLUMN occur
  121389. ** in the same logical place as the position element, and act as sentinals
  121390. ** ending a position list array. POS_END is 0. POS_COLUMN is 1.
  121391. ** The positions numbers are not stored literally but rather as two more
  121392. ** than the difference from the prior position, or the just the position plus
  121393. ** 2 for the first position. Example:
  121394. **
  121395. ** label: A B C D E F G H I J K
  121396. ** value: 123 5 9 1 1 14 35 0 234 72 0
  121397. **
  121398. ** The 123 value is the first docid. For column zero in this document
  121399. ** there are two matches at positions 3 and 10 (5-2 and 9-2+3). The 1
  121400. ** at D signals the start of a new column; the 1 at E indicates that the
  121401. ** new column is column number 1. There are two positions at 12 and 45
  121402. ** (14-2 and 35-2+12). The 0 at H indicate the end-of-document. The
  121403. ** 234 at I is the delta to next docid (357). It has one position 70
  121404. ** (72-2) and then terminates with the 0 at K.
  121405. **
  121406. ** A "position-list" is the list of positions for multiple columns for
  121407. ** a single docid. A "column-list" is the set of positions for a single
  121408. ** column. Hence, a position-list consists of one or more column-lists,
  121409. ** a document record consists of a docid followed by a position-list and
  121410. ** a doclist consists of one or more document records.
  121411. **
  121412. ** A bare doclist omits the position information, becoming an
  121413. ** array of varint-encoded docids.
  121414. **
  121415. **** Segment leaf nodes ****
  121416. ** Segment leaf nodes store terms and doclists, ordered by term. Leaf
  121417. ** nodes are written using LeafWriter, and read using LeafReader (to
  121418. ** iterate through a single leaf node's data) and LeavesReader (to
  121419. ** iterate through a segment's entire leaf layer). Leaf nodes have
  121420. ** the format:
  121421. **
  121422. ** varint iHeight; (height from leaf level, always 0)
  121423. ** varint nTerm; (length of first term)
  121424. ** char pTerm[nTerm]; (content of first term)
  121425. ** varint nDoclist; (length of term's associated doclist)
  121426. ** char pDoclist[nDoclist]; (content of doclist)
  121427. ** array {
  121428. ** (further terms are delta-encoded)
  121429. ** varint nPrefix; (length of prefix shared with previous term)
  121430. ** varint nSuffix; (length of unshared suffix)
  121431. ** char pTermSuffix[nSuffix];(unshared suffix of next term)
  121432. ** varint nDoclist; (length of term's associated doclist)
  121433. ** char pDoclist[nDoclist]; (content of doclist)
  121434. ** }
  121435. **
  121436. ** Here, array { X } means zero or more occurrences of X, adjacent in
  121437. ** memory.
  121438. **
  121439. ** Leaf nodes are broken into blocks which are stored contiguously in
  121440. ** the %_segments table in sorted order. This means that when the end
  121441. ** of a node is reached, the next term is in the node with the next
  121442. ** greater node id.
  121443. **
  121444. ** New data is spilled to a new leaf node when the current node
  121445. ** exceeds LEAF_MAX bytes (default 2048). New data which itself is
  121446. ** larger than STANDALONE_MIN (default 1024) is placed in a standalone
  121447. ** node (a leaf node with a single term and doclist). The goal of
  121448. ** these settings is to pack together groups of small doclists while
  121449. ** making it efficient to directly access large doclists. The
  121450. ** assumption is that large doclists represent terms which are more
  121451. ** likely to be query targets.
  121452. **
  121453. ** TODO(shess) It may be useful for blocking decisions to be more
  121454. ** dynamic. For instance, it may make more sense to have a 2.5k leaf
  121455. ** node rather than splitting into 2k and .5k nodes. My intuition is
  121456. ** that this might extend through 2x or 4x the pagesize.
  121457. **
  121458. **
  121459. **** Segment interior nodes ****
  121460. ** Segment interior nodes store blockids for subtree nodes and terms
  121461. ** to describe what data is stored by the each subtree. Interior
  121462. ** nodes are written using InteriorWriter, and read using
  121463. ** InteriorReader. InteriorWriters are created as needed when
  121464. ** SegmentWriter creates new leaf nodes, or when an interior node
  121465. ** itself grows too big and must be split. The format of interior
  121466. ** nodes:
  121467. **
  121468. ** varint iHeight; (height from leaf level, always >0)
  121469. ** varint iBlockid; (block id of node's leftmost subtree)
  121470. ** optional {
  121471. ** varint nTerm; (length of first term)
  121472. ** char pTerm[nTerm]; (content of first term)
  121473. ** array {
  121474. ** (further terms are delta-encoded)
  121475. ** varint nPrefix; (length of shared prefix with previous term)
  121476. ** varint nSuffix; (length of unshared suffix)
  121477. ** char pTermSuffix[nSuffix]; (unshared suffix of next term)
  121478. ** }
  121479. ** }
  121480. **
  121481. ** Here, optional { X } means an optional element, while array { X }
  121482. ** means zero or more occurrences of X, adjacent in memory.
  121483. **
  121484. ** An interior node encodes n terms separating n+1 subtrees. The
  121485. ** subtree blocks are contiguous, so only the first subtree's blockid
  121486. ** is encoded. The subtree at iBlockid will contain all terms less
  121487. ** than the first term encoded (or all terms if no term is encoded).
  121488. ** Otherwise, for terms greater than or equal to pTerm[i] but less
  121489. ** than pTerm[i+1], the subtree for that term will be rooted at
  121490. ** iBlockid+i. Interior nodes only store enough term data to
  121491. ** distinguish adjacent children (if the rightmost term of the left
  121492. ** child is "something", and the leftmost term of the right child is
  121493. ** "wicked", only "w" is stored).
  121494. **
  121495. ** New data is spilled to a new interior node at the same height when
  121496. ** the current node exceeds INTERIOR_MAX bytes (default 2048).
  121497. ** INTERIOR_MIN_TERMS (default 7) keeps large terms from monopolizing
  121498. ** interior nodes and making the tree too skinny. The interior nodes
  121499. ** at a given height are naturally tracked by interior nodes at
  121500. ** height+1, and so on.
  121501. **
  121502. **
  121503. **** Segment directory ****
  121504. ** The segment directory in table %_segdir stores meta-information for
  121505. ** merging and deleting segments, and also the root node of the
  121506. ** segment's tree.
  121507. **
  121508. ** The root node is the top node of the segment's tree after encoding
  121509. ** the entire segment, restricted to ROOT_MAX bytes (default 1024).
  121510. ** This could be either a leaf node or an interior node. If the top
  121511. ** node requires more than ROOT_MAX bytes, it is flushed to %_segments
  121512. ** and a new root interior node is generated (which should always fit
  121513. ** within ROOT_MAX because it only needs space for 2 varints, the
  121514. ** height and the blockid of the previous root).
  121515. **
  121516. ** The meta-information in the segment directory is:
  121517. ** level - segment level (see below)
  121518. ** idx - index within level
  121519. ** - (level,idx uniquely identify a segment)
  121520. ** start_block - first leaf node
  121521. ** leaves_end_block - last leaf node
  121522. ** end_block - last block (including interior nodes)
  121523. ** root - contents of root node
  121524. **
  121525. ** If the root node is a leaf node, then start_block,
  121526. ** leaves_end_block, and end_block are all 0.
  121527. **
  121528. **
  121529. **** Segment merging ****
  121530. ** To amortize update costs, segments are grouped into levels and
  121531. ** merged in batches. Each increase in level represents exponentially
  121532. ** more documents.
  121533. **
  121534. ** New documents (actually, document updates) are tokenized and
  121535. ** written individually (using LeafWriter) to a level 0 segment, with
  121536. ** incrementing idx. When idx reaches MERGE_COUNT (default 16), all
  121537. ** level 0 segments are merged into a single level 1 segment. Level 1
  121538. ** is populated like level 0, and eventually MERGE_COUNT level 1
  121539. ** segments are merged to a single level 2 segment (representing
  121540. ** MERGE_COUNT^2 updates), and so on.
  121541. **
  121542. ** A segment merge traverses all segments at a given level in
  121543. ** parallel, performing a straightforward sorted merge. Since segment
  121544. ** leaf nodes are written in to the %_segments table in order, this
  121545. ** merge traverses the underlying sqlite disk structures efficiently.
  121546. ** After the merge, all segment blocks from the merged level are
  121547. ** deleted.
  121548. **
  121549. ** MERGE_COUNT controls how often we merge segments. 16 seems to be
  121550. ** somewhat of a sweet spot for insertion performance. 32 and 64 show
  121551. ** very similar performance numbers to 16 on insertion, though they're
  121552. ** a tiny bit slower (perhaps due to more overhead in merge-time
  121553. ** sorting). 8 is about 20% slower than 16, 4 about 50% slower than
  121554. ** 16, 2 about 66% slower than 16.
  121555. **
  121556. ** At query time, high MERGE_COUNT increases the number of segments
  121557. ** which need to be scanned and merged. For instance, with 100k docs
  121558. ** inserted:
  121559. **
  121560. ** MERGE_COUNT segments
  121561. ** 16 25
  121562. ** 8 12
  121563. ** 4 10
  121564. ** 2 6
  121565. **
  121566. ** This appears to have only a moderate impact on queries for very
  121567. ** frequent terms (which are somewhat dominated by segment merge
  121568. ** costs), and infrequent and non-existent terms still seem to be fast
  121569. ** even with many segments.
  121570. **
  121571. ** TODO(shess) That said, it would be nice to have a better query-side
  121572. ** argument for MERGE_COUNT of 16. Also, it is possible/likely that
  121573. ** optimizations to things like doclist merging will swing the sweet
  121574. ** spot around.
  121575. **
  121576. **
  121577. **
  121578. **** Handling of deletions and updates ****
  121579. ** Since we're using a segmented structure, with no docid-oriented
  121580. ** index into the term index, we clearly cannot simply update the term
  121581. ** index when a document is deleted or updated. For deletions, we
  121582. ** write an empty doclist (varint(docid) varint(POS_END)), for updates
  121583. ** we simply write the new doclist. Segment merges overwrite older
  121584. ** data for a particular docid with newer data, so deletes or updates
  121585. ** will eventually overtake the earlier data and knock it out. The
  121586. ** query logic likewise merges doclists so that newer data knocks out
  121587. ** older data.
  121588. */
  121589. /************** Include fts3Int.h in the middle of fts3.c ********************/
  121590. /************** Begin file fts3Int.h *****************************************/
  121591. /*
  121592. ** 2009 Nov 12
  121593. **
  121594. ** The author disclaims copyright to this source code. In place of
  121595. ** a legal notice, here is a blessing:
  121596. **
  121597. ** May you do good and not evil.
  121598. ** May you find forgiveness for yourself and forgive others.
  121599. ** May you share freely, never taking more than you give.
  121600. **
  121601. ******************************************************************************
  121602. **
  121603. */
  121604. #ifndef _FTSINT_H
  121605. #define _FTSINT_H
  121606. #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
  121607. # define NDEBUG 1
  121608. #endif
  121609. /*
  121610. ** FTS4 is really an extension for FTS3. It is enabled using the
  121611. ** SQLITE_ENABLE_FTS3 macro. But to avoid confusion we also all
  121612. ** the SQLITE_ENABLE_FTS4 macro to serve as an alisse for SQLITE_ENABLE_FTS3.
  121613. */
  121614. #if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3)
  121615. # define SQLITE_ENABLE_FTS3
  121616. #endif
  121617. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  121618. /* If not building as part of the core, include sqlite3ext.h. */
  121619. #ifndef SQLITE_CORE
  121620. SQLITE_EXTENSION_INIT3
  121621. #endif
  121622. /************** Include fts3_tokenizer.h in the middle of fts3Int.h **********/
  121623. /************** Begin file fts3_tokenizer.h **********************************/
  121624. /*
  121625. ** 2006 July 10
  121626. **
  121627. ** The author disclaims copyright to this source code.
  121628. **
  121629. *************************************************************************
  121630. ** Defines the interface to tokenizers used by fulltext-search. There
  121631. ** are three basic components:
  121632. **
  121633. ** sqlite3_tokenizer_module is a singleton defining the tokenizer
  121634. ** interface functions. This is essentially the class structure for
  121635. ** tokenizers.
  121636. **
  121637. ** sqlite3_tokenizer is used to define a particular tokenizer, perhaps
  121638. ** including customization information defined at creation time.
  121639. **
  121640. ** sqlite3_tokenizer_cursor is generated by a tokenizer to generate
  121641. ** tokens from a particular input.
  121642. */
  121643. #ifndef _FTS3_TOKENIZER_H_
  121644. #define _FTS3_TOKENIZER_H_
  121645. /* TODO(shess) Only used for SQLITE_OK and SQLITE_DONE at this time.
  121646. ** If tokenizers are to be allowed to call sqlite3_*() functions, then
  121647. ** we will need a way to register the API consistently.
  121648. */
  121649. /*
  121650. ** Structures used by the tokenizer interface. When a new tokenizer
  121651. ** implementation is registered, the caller provides a pointer to
  121652. ** an sqlite3_tokenizer_module containing pointers to the callback
  121653. ** functions that make up an implementation.
  121654. **
  121655. ** When an fts3 table is created, it passes any arguments passed to
  121656. ** the tokenizer clause of the CREATE VIRTUAL TABLE statement to the
  121657. ** sqlite3_tokenizer_module.xCreate() function of the requested tokenizer
  121658. ** implementation. The xCreate() function in turn returns an
  121659. ** sqlite3_tokenizer structure representing the specific tokenizer to
  121660. ** be used for the fts3 table (customized by the tokenizer clause arguments).
  121661. **
  121662. ** To tokenize an input buffer, the sqlite3_tokenizer_module.xOpen()
  121663. ** method is called. It returns an sqlite3_tokenizer_cursor object
  121664. ** that may be used to tokenize a specific input buffer based on
  121665. ** the tokenization rules supplied by a specific sqlite3_tokenizer
  121666. ** object.
  121667. */
  121668. typedef struct sqlite3_tokenizer_module sqlite3_tokenizer_module;
  121669. typedef struct sqlite3_tokenizer sqlite3_tokenizer;
  121670. typedef struct sqlite3_tokenizer_cursor sqlite3_tokenizer_cursor;
  121671. struct sqlite3_tokenizer_module {
  121672. /*
  121673. ** Structure version. Should always be set to 0 or 1.
  121674. */
  121675. int iVersion;
  121676. /*
  121677. ** Create a new tokenizer. The values in the argv[] array are the
  121678. ** arguments passed to the "tokenizer" clause of the CREATE VIRTUAL
  121679. ** TABLE statement that created the fts3 table. For example, if
  121680. ** the following SQL is executed:
  121681. **
  121682. ** CREATE .. USING fts3( ... , tokenizer <tokenizer-name> arg1 arg2)
  121683. **
  121684. ** then argc is set to 2, and the argv[] array contains pointers
  121685. ** to the strings "arg1" and "arg2".
  121686. **
  121687. ** This method should return either SQLITE_OK (0), or an SQLite error
  121688. ** code. If SQLITE_OK is returned, then *ppTokenizer should be set
  121689. ** to point at the newly created tokenizer structure. The generic
  121690. ** sqlite3_tokenizer.pModule variable should not be initialized by
  121691. ** this callback. The caller will do so.
  121692. */
  121693. int (*xCreate)(
  121694. int argc, /* Size of argv array */
  121695. const char *const*argv, /* Tokenizer argument strings */
  121696. sqlite3_tokenizer **ppTokenizer /* OUT: Created tokenizer */
  121697. );
  121698. /*
  121699. ** Destroy an existing tokenizer. The fts3 module calls this method
  121700. ** exactly once for each successful call to xCreate().
  121701. */
  121702. int (*xDestroy)(sqlite3_tokenizer *pTokenizer);
  121703. /*
  121704. ** Create a tokenizer cursor to tokenize an input buffer. The caller
  121705. ** is responsible for ensuring that the input buffer remains valid
  121706. ** until the cursor is closed (using the xClose() method).
  121707. */
  121708. int (*xOpen)(
  121709. sqlite3_tokenizer *pTokenizer, /* Tokenizer object */
  121710. const char *pInput, int nBytes, /* Input buffer */
  121711. sqlite3_tokenizer_cursor **ppCursor /* OUT: Created tokenizer cursor */
  121712. );
  121713. /*
  121714. ** Destroy an existing tokenizer cursor. The fts3 module calls this
  121715. ** method exactly once for each successful call to xOpen().
  121716. */
  121717. int (*xClose)(sqlite3_tokenizer_cursor *pCursor);
  121718. /*
  121719. ** Retrieve the next token from the tokenizer cursor pCursor. This
  121720. ** method should either return SQLITE_OK and set the values of the
  121721. ** "OUT" variables identified below, or SQLITE_DONE to indicate that
  121722. ** the end of the buffer has been reached, or an SQLite error code.
  121723. **
  121724. ** *ppToken should be set to point at a buffer containing the
  121725. ** normalized version of the token (i.e. after any case-folding and/or
  121726. ** stemming has been performed). *pnBytes should be set to the length
  121727. ** of this buffer in bytes. The input text that generated the token is
  121728. ** identified by the byte offsets returned in *piStartOffset and
  121729. ** *piEndOffset. *piStartOffset should be set to the index of the first
  121730. ** byte of the token in the input buffer. *piEndOffset should be set
  121731. ** to the index of the first byte just past the end of the token in
  121732. ** the input buffer.
  121733. **
  121734. ** The buffer *ppToken is set to point at is managed by the tokenizer
  121735. ** implementation. It is only required to be valid until the next call
  121736. ** to xNext() or xClose().
  121737. */
  121738. /* TODO(shess) current implementation requires pInput to be
  121739. ** nul-terminated. This should either be fixed, or pInput/nBytes
  121740. ** should be converted to zInput.
  121741. */
  121742. int (*xNext)(
  121743. sqlite3_tokenizer_cursor *pCursor, /* Tokenizer cursor */
  121744. const char **ppToken, int *pnBytes, /* OUT: Normalized text for token */
  121745. int *piStartOffset, /* OUT: Byte offset of token in input buffer */
  121746. int *piEndOffset, /* OUT: Byte offset of end of token in input buffer */
  121747. int *piPosition /* OUT: Number of tokens returned before this one */
  121748. );
  121749. /***********************************************************************
  121750. ** Methods below this point are only available if iVersion>=1.
  121751. */
  121752. /*
  121753. ** Configure the language id of a tokenizer cursor.
  121754. */
  121755. int (*xLanguageid)(sqlite3_tokenizer_cursor *pCsr, int iLangid);
  121756. };
  121757. struct sqlite3_tokenizer {
  121758. const sqlite3_tokenizer_module *pModule; /* The module for this tokenizer */
  121759. /* Tokenizer implementations will typically add additional fields */
  121760. };
  121761. struct sqlite3_tokenizer_cursor {
  121762. sqlite3_tokenizer *pTokenizer; /* Tokenizer for this cursor. */
  121763. /* Tokenizer implementations will typically add additional fields */
  121764. };
  121765. int fts3_global_term_cnt(int iTerm, int iCol);
  121766. int fts3_term_cnt(int iTerm, int iCol);
  121767. #endif /* _FTS3_TOKENIZER_H_ */
  121768. /************** End of fts3_tokenizer.h **************************************/
  121769. /************** Continuing where we left off in fts3Int.h ********************/
  121770. /************** Include fts3_hash.h in the middle of fts3Int.h ***************/
  121771. /************** Begin file fts3_hash.h ***************************************/
  121772. /*
  121773. ** 2001 September 22
  121774. **
  121775. ** The author disclaims copyright to this source code. In place of
  121776. ** a legal notice, here is a blessing:
  121777. **
  121778. ** May you do good and not evil.
  121779. ** May you find forgiveness for yourself and forgive others.
  121780. ** May you share freely, never taking more than you give.
  121781. **
  121782. *************************************************************************
  121783. ** This is the header file for the generic hash-table implementation
  121784. ** used in SQLite. We've modified it slightly to serve as a standalone
  121785. ** hash table implementation for the full-text indexing module.
  121786. **
  121787. */
  121788. #ifndef _FTS3_HASH_H_
  121789. #define _FTS3_HASH_H_
  121790. /* Forward declarations of structures. */
  121791. typedef struct Fts3Hash Fts3Hash;
  121792. typedef struct Fts3HashElem Fts3HashElem;
  121793. /* A complete hash table is an instance of the following structure.
  121794. ** The internals of this structure are intended to be opaque -- client
  121795. ** code should not attempt to access or modify the fields of this structure
  121796. ** directly. Change this structure only by using the routines below.
  121797. ** However, many of the "procedures" and "functions" for modifying and
  121798. ** accessing this structure are really macros, so we can't really make
  121799. ** this structure opaque.
  121800. */
  121801. struct Fts3Hash {
  121802. char keyClass; /* HASH_INT, _POINTER, _STRING, _BINARY */
  121803. char copyKey; /* True if copy of key made on insert */
  121804. int count; /* Number of entries in this table */
  121805. Fts3HashElem *first; /* The first element of the array */
  121806. int htsize; /* Number of buckets in the hash table */
  121807. struct _fts3ht { /* the hash table */
  121808. int count; /* Number of entries with this hash */
  121809. Fts3HashElem *chain; /* Pointer to first entry with this hash */
  121810. } *ht;
  121811. };
  121812. /* Each element in the hash table is an instance of the following
  121813. ** structure. All elements are stored on a single doubly-linked list.
  121814. **
  121815. ** Again, this structure is intended to be opaque, but it can't really
  121816. ** be opaque because it is used by macros.
  121817. */
  121818. struct Fts3HashElem {
  121819. Fts3HashElem *next, *prev; /* Next and previous elements in the table */
  121820. void *data; /* Data associated with this element */
  121821. void *pKey; int nKey; /* Key associated with this element */
  121822. };
  121823. /*
  121824. ** There are 2 different modes of operation for a hash table:
  121825. **
  121826. ** FTS3_HASH_STRING pKey points to a string that is nKey bytes long
  121827. ** (including the null-terminator, if any). Case
  121828. ** is respected in comparisons.
  121829. **
  121830. ** FTS3_HASH_BINARY pKey points to binary data nKey bytes long.
  121831. ** memcmp() is used to compare keys.
  121832. **
  121833. ** A copy of the key is made if the copyKey parameter to fts3HashInit is 1.
  121834. */
  121835. #define FTS3_HASH_STRING 1
  121836. #define FTS3_HASH_BINARY 2
  121837. /*
  121838. ** Access routines. To delete, insert a NULL pointer.
  121839. */
  121840. SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey);
  121841. SQLITE_PRIVATE void *sqlite3Fts3HashInsert(Fts3Hash*, const void *pKey, int nKey, void *pData);
  121842. SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash*, const void *pKey, int nKey);
  121843. SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash*);
  121844. SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(const Fts3Hash *, const void *, int);
  121845. /*
  121846. ** Shorthand for the functions above
  121847. */
  121848. #define fts3HashInit sqlite3Fts3HashInit
  121849. #define fts3HashInsert sqlite3Fts3HashInsert
  121850. #define fts3HashFind sqlite3Fts3HashFind
  121851. #define fts3HashClear sqlite3Fts3HashClear
  121852. #define fts3HashFindElem sqlite3Fts3HashFindElem
  121853. /*
  121854. ** Macros for looping over all elements of a hash table. The idiom is
  121855. ** like this:
  121856. **
  121857. ** Fts3Hash h;
  121858. ** Fts3HashElem *p;
  121859. ** ...
  121860. ** for(p=fts3HashFirst(&h); p; p=fts3HashNext(p)){
  121861. ** SomeStructure *pData = fts3HashData(p);
  121862. ** // do something with pData
  121863. ** }
  121864. */
  121865. #define fts3HashFirst(H) ((H)->first)
  121866. #define fts3HashNext(E) ((E)->next)
  121867. #define fts3HashData(E) ((E)->data)
  121868. #define fts3HashKey(E) ((E)->pKey)
  121869. #define fts3HashKeysize(E) ((E)->nKey)
  121870. /*
  121871. ** Number of entries in a hash table
  121872. */
  121873. #define fts3HashCount(H) ((H)->count)
  121874. #endif /* _FTS3_HASH_H_ */
  121875. /************** End of fts3_hash.h *******************************************/
  121876. /************** Continuing where we left off in fts3Int.h ********************/
  121877. /*
  121878. ** This constant determines the maximum depth of an FTS expression tree
  121879. ** that the library will create and use. FTS uses recursion to perform
  121880. ** various operations on the query tree, so the disadvantage of a large
  121881. ** limit is that it may allow very large queries to use large amounts
  121882. ** of stack space (perhaps causing a stack overflow).
  121883. */
  121884. #ifndef SQLITE_FTS3_MAX_EXPR_DEPTH
  121885. # define SQLITE_FTS3_MAX_EXPR_DEPTH 12
  121886. #endif
  121887. /*
  121888. ** This constant controls how often segments are merged. Once there are
  121889. ** FTS3_MERGE_COUNT segments of level N, they are merged into a single
  121890. ** segment of level N+1.
  121891. */
  121892. #define FTS3_MERGE_COUNT 16
  121893. /*
  121894. ** This is the maximum amount of data (in bytes) to store in the
  121895. ** Fts3Table.pendingTerms hash table. Normally, the hash table is
  121896. ** populated as documents are inserted/updated/deleted in a transaction
  121897. ** and used to create a new segment when the transaction is committed.
  121898. ** However if this limit is reached midway through a transaction, a new
  121899. ** segment is created and the hash table cleared immediately.
  121900. */
  121901. #define FTS3_MAX_PENDING_DATA (1*1024*1024)
  121902. /*
  121903. ** Macro to return the number of elements in an array. SQLite has a
  121904. ** similar macro called ArraySize(). Use a different name to avoid
  121905. ** a collision when building an amalgamation with built-in FTS3.
  121906. */
  121907. #define SizeofArray(X) ((int)(sizeof(X)/sizeof(X[0])))
  121908. #ifndef MIN
  121909. # define MIN(x,y) ((x)<(y)?(x):(y))
  121910. #endif
  121911. #ifndef MAX
  121912. # define MAX(x,y) ((x)>(y)?(x):(y))
  121913. #endif
  121914. /*
  121915. ** Maximum length of a varint encoded integer. The varint format is different
  121916. ** from that used by SQLite, so the maximum length is 10, not 9.
  121917. */
  121918. #define FTS3_VARINT_MAX 10
  121919. /*
  121920. ** FTS4 virtual tables may maintain multiple indexes - one index of all terms
  121921. ** in the document set and zero or more prefix indexes. All indexes are stored
  121922. ** as one or more b+-trees in the %_segments and %_segdir tables.
  121923. **
  121924. ** It is possible to determine which index a b+-tree belongs to based on the
  121925. ** value stored in the "%_segdir.level" column. Given this value L, the index
  121926. ** that the b+-tree belongs to is (L<<10). In other words, all b+-trees with
  121927. ** level values between 0 and 1023 (inclusive) belong to index 0, all levels
  121928. ** between 1024 and 2047 to index 1, and so on.
  121929. **
  121930. ** It is considered impossible for an index to use more than 1024 levels. In
  121931. ** theory though this may happen, but only after at least
  121932. ** (FTS3_MERGE_COUNT^1024) separate flushes of the pending-terms tables.
  121933. */
  121934. #define FTS3_SEGDIR_MAXLEVEL 1024
  121935. #define FTS3_SEGDIR_MAXLEVEL_STR "1024"
  121936. /*
  121937. ** The testcase() macro is only used by the amalgamation. If undefined,
  121938. ** make it a no-op.
  121939. */
  121940. #ifndef testcase
  121941. # define testcase(X)
  121942. #endif
  121943. /*
  121944. ** Terminator values for position-lists and column-lists.
  121945. */
  121946. #define POS_COLUMN (1) /* Column-list terminator */
  121947. #define POS_END (0) /* Position-list terminator */
  121948. /*
  121949. ** This section provides definitions to allow the
  121950. ** FTS3 extension to be compiled outside of the
  121951. ** amalgamation.
  121952. */
  121953. #ifndef SQLITE_AMALGAMATION
  121954. /*
  121955. ** Macros indicating that conditional expressions are always true or
  121956. ** false.
  121957. */
  121958. #ifdef SQLITE_COVERAGE_TEST
  121959. # define ALWAYS(x) (1)
  121960. # define NEVER(X) (0)
  121961. #else
  121962. # define ALWAYS(x) (x)
  121963. # define NEVER(x) (x)
  121964. #endif
  121965. /*
  121966. ** Internal types used by SQLite.
  121967. */
  121968. typedef unsigned char u8; /* 1-byte (or larger) unsigned integer */
  121969. typedef short int i16; /* 2-byte (or larger) signed integer */
  121970. typedef unsigned int u32; /* 4-byte unsigned integer */
  121971. typedef sqlite3_uint64 u64; /* 8-byte unsigned integer */
  121972. typedef sqlite3_int64 i64; /* 8-byte signed integer */
  121973. /*
  121974. ** Macro used to suppress compiler warnings for unused parameters.
  121975. */
  121976. #define UNUSED_PARAMETER(x) (void)(x)
  121977. /*
  121978. ** Activate assert() only if SQLITE_TEST is enabled.
  121979. */
  121980. #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
  121981. # define NDEBUG 1
  121982. #endif
  121983. /*
  121984. ** The TESTONLY macro is used to enclose variable declarations or
  121985. ** other bits of code that are needed to support the arguments
  121986. ** within testcase() and assert() macros.
  121987. */
  121988. #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
  121989. # define TESTONLY(X) X
  121990. #else
  121991. # define TESTONLY(X)
  121992. #endif
  121993. #endif /* SQLITE_AMALGAMATION */
  121994. #ifdef SQLITE_DEBUG
  121995. SQLITE_PRIVATE int sqlite3Fts3Corrupt(void);
  121996. # define FTS_CORRUPT_VTAB sqlite3Fts3Corrupt()
  121997. #else
  121998. # define FTS_CORRUPT_VTAB SQLITE_CORRUPT_VTAB
  121999. #endif
  122000. typedef struct Fts3Table Fts3Table;
  122001. typedef struct Fts3Cursor Fts3Cursor;
  122002. typedef struct Fts3Expr Fts3Expr;
  122003. typedef struct Fts3Phrase Fts3Phrase;
  122004. typedef struct Fts3PhraseToken Fts3PhraseToken;
  122005. typedef struct Fts3Doclist Fts3Doclist;
  122006. typedef struct Fts3SegFilter Fts3SegFilter;
  122007. typedef struct Fts3DeferredToken Fts3DeferredToken;
  122008. typedef struct Fts3SegReader Fts3SegReader;
  122009. typedef struct Fts3MultiSegReader Fts3MultiSegReader;
  122010. /*
  122011. ** A connection to a fulltext index is an instance of the following
  122012. ** structure. The xCreate and xConnect methods create an instance
  122013. ** of this structure and xDestroy and xDisconnect free that instance.
  122014. ** All other methods receive a pointer to the structure as one of their
  122015. ** arguments.
  122016. */
  122017. struct Fts3Table {
  122018. sqlite3_vtab base; /* Base class used by SQLite core */
  122019. sqlite3 *db; /* The database connection */
  122020. const char *zDb; /* logical database name */
  122021. const char *zName; /* virtual table name */
  122022. int nColumn; /* number of named columns in virtual table */
  122023. char **azColumn; /* column names. malloced */
  122024. u8 *abNotindexed; /* True for 'notindexed' columns */
  122025. sqlite3_tokenizer *pTokenizer; /* tokenizer for inserts and queries */
  122026. char *zContentTbl; /* content=xxx option, or NULL */
  122027. char *zLanguageid; /* languageid=xxx option, or NULL */
  122028. int nAutoincrmerge; /* Value configured by 'automerge' */
  122029. u32 nLeafAdd; /* Number of leaf blocks added this trans */
  122030. /* Precompiled statements used by the implementation. Each of these
  122031. ** statements is run and reset within a single virtual table API call.
  122032. */
  122033. sqlite3_stmt *aStmt[40];
  122034. char *zReadExprlist;
  122035. char *zWriteExprlist;
  122036. int nNodeSize; /* Soft limit for node size */
  122037. u8 bFts4; /* True for FTS4, false for FTS3 */
  122038. u8 bHasStat; /* True if %_stat table exists (2==unknown) */
  122039. u8 bHasDocsize; /* True if %_docsize table exists */
  122040. u8 bDescIdx; /* True if doclists are in reverse order */
  122041. u8 bIgnoreSavepoint; /* True to ignore xSavepoint invocations */
  122042. int nPgsz; /* Page size for host database */
  122043. char *zSegmentsTbl; /* Name of %_segments table */
  122044. sqlite3_blob *pSegments; /* Blob handle open on %_segments table */
  122045. /*
  122046. ** The following array of hash tables is used to buffer pending index
  122047. ** updates during transactions. All pending updates buffered at any one
  122048. ** time must share a common language-id (see the FTS4 langid= feature).
  122049. ** The current language id is stored in variable iPrevLangid.
  122050. **
  122051. ** A single FTS4 table may have multiple full-text indexes. For each index
  122052. ** there is an entry in the aIndex[] array. Index 0 is an index of all the
  122053. ** terms that appear in the document set. Each subsequent index in aIndex[]
  122054. ** is an index of prefixes of a specific length.
  122055. **
  122056. ** Variable nPendingData contains an estimate the memory consumed by the
  122057. ** pending data structures, including hash table overhead, but not including
  122058. ** malloc overhead. When nPendingData exceeds nMaxPendingData, all hash
  122059. ** tables are flushed to disk. Variable iPrevDocid is the docid of the most
  122060. ** recently inserted record.
  122061. */
  122062. int nIndex; /* Size of aIndex[] */
  122063. struct Fts3Index {
  122064. int nPrefix; /* Prefix length (0 for main terms index) */
  122065. Fts3Hash hPending; /* Pending terms table for this index */
  122066. } *aIndex;
  122067. int nMaxPendingData; /* Max pending data before flush to disk */
  122068. int nPendingData; /* Current bytes of pending data */
  122069. sqlite_int64 iPrevDocid; /* Docid of most recently inserted document */
  122070. int iPrevLangid; /* Langid of recently inserted document */
  122071. #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
  122072. /* State variables used for validating that the transaction control
  122073. ** methods of the virtual table are called at appropriate times. These
  122074. ** values do not contribute to FTS functionality; they are used for
  122075. ** verifying the operation of the SQLite core.
  122076. */
  122077. int inTransaction; /* True after xBegin but before xCommit/xRollback */
  122078. int mxSavepoint; /* Largest valid xSavepoint integer */
  122079. #endif
  122080. #ifdef SQLITE_TEST
  122081. /* True to disable the incremental doclist optimization. This is controled
  122082. ** by special insert command 'test-no-incr-doclist'. */
  122083. int bNoIncrDoclist;
  122084. #endif
  122085. };
  122086. /*
  122087. ** When the core wants to read from the virtual table, it creates a
  122088. ** virtual table cursor (an instance of the following structure) using
  122089. ** the xOpen method. Cursors are destroyed using the xClose method.
  122090. */
  122091. struct Fts3Cursor {
  122092. sqlite3_vtab_cursor base; /* Base class used by SQLite core */
  122093. i16 eSearch; /* Search strategy (see below) */
  122094. u8 isEof; /* True if at End Of Results */
  122095. u8 isRequireSeek; /* True if must seek pStmt to %_content row */
  122096. sqlite3_stmt *pStmt; /* Prepared statement in use by the cursor */
  122097. Fts3Expr *pExpr; /* Parsed MATCH query string */
  122098. int iLangid; /* Language being queried for */
  122099. int nPhrase; /* Number of matchable phrases in query */
  122100. Fts3DeferredToken *pDeferred; /* Deferred search tokens, if any */
  122101. sqlite3_int64 iPrevId; /* Previous id read from aDoclist */
  122102. char *pNextId; /* Pointer into the body of aDoclist */
  122103. char *aDoclist; /* List of docids for full-text queries */
  122104. int nDoclist; /* Size of buffer at aDoclist */
  122105. u8 bDesc; /* True to sort in descending order */
  122106. int eEvalmode; /* An FTS3_EVAL_XX constant */
  122107. int nRowAvg; /* Average size of database rows, in pages */
  122108. sqlite3_int64 nDoc; /* Documents in table */
  122109. i64 iMinDocid; /* Minimum docid to return */
  122110. i64 iMaxDocid; /* Maximum docid to return */
  122111. int isMatchinfoNeeded; /* True when aMatchinfo[] needs filling in */
  122112. u32 *aMatchinfo; /* Information about most recent match */
  122113. int nMatchinfo; /* Number of elements in aMatchinfo[] */
  122114. char *zMatchinfo; /* Matchinfo specification */
  122115. };
  122116. #define FTS3_EVAL_FILTER 0
  122117. #define FTS3_EVAL_NEXT 1
  122118. #define FTS3_EVAL_MATCHINFO 2
  122119. /*
  122120. ** The Fts3Cursor.eSearch member is always set to one of the following.
  122121. ** Actualy, Fts3Cursor.eSearch can be greater than or equal to
  122122. ** FTS3_FULLTEXT_SEARCH. If so, then Fts3Cursor.eSearch - 2 is the index
  122123. ** of the column to be searched. For example, in
  122124. **
  122125. ** CREATE VIRTUAL TABLE ex1 USING fts3(a,b,c,d);
  122126. ** SELECT docid FROM ex1 WHERE b MATCH 'one two three';
  122127. **
  122128. ** Because the LHS of the MATCH operator is 2nd column "b",
  122129. ** Fts3Cursor.eSearch will be set to FTS3_FULLTEXT_SEARCH+1. (+0 for a,
  122130. ** +1 for b, +2 for c, +3 for d.) If the LHS of MATCH were "ex1"
  122131. ** indicating that all columns should be searched,
  122132. ** then eSearch would be set to FTS3_FULLTEXT_SEARCH+4.
  122133. */
  122134. #define FTS3_FULLSCAN_SEARCH 0 /* Linear scan of %_content table */
  122135. #define FTS3_DOCID_SEARCH 1 /* Lookup by rowid on %_content table */
  122136. #define FTS3_FULLTEXT_SEARCH 2 /* Full-text index search */
  122137. /*
  122138. ** The lower 16-bits of the sqlite3_index_info.idxNum value set by
  122139. ** the xBestIndex() method contains the Fts3Cursor.eSearch value described
  122140. ** above. The upper 16-bits contain a combination of the following
  122141. ** bits, used to describe extra constraints on full-text searches.
  122142. */
  122143. #define FTS3_HAVE_LANGID 0x00010000 /* languageid=? */
  122144. #define FTS3_HAVE_DOCID_GE 0x00020000 /* docid>=? */
  122145. #define FTS3_HAVE_DOCID_LE 0x00040000 /* docid<=? */
  122146. struct Fts3Doclist {
  122147. char *aAll; /* Array containing doclist (or NULL) */
  122148. int nAll; /* Size of a[] in bytes */
  122149. char *pNextDocid; /* Pointer to next docid */
  122150. sqlite3_int64 iDocid; /* Current docid (if pList!=0) */
  122151. int bFreeList; /* True if pList should be sqlite3_free()d */
  122152. char *pList; /* Pointer to position list following iDocid */
  122153. int nList; /* Length of position list */
  122154. };
  122155. /*
  122156. ** A "phrase" is a sequence of one or more tokens that must match in
  122157. ** sequence. A single token is the base case and the most common case.
  122158. ** For a sequence of tokens contained in double-quotes (i.e. "one two three")
  122159. ** nToken will be the number of tokens in the string.
  122160. */
  122161. struct Fts3PhraseToken {
  122162. char *z; /* Text of the token */
  122163. int n; /* Number of bytes in buffer z */
  122164. int isPrefix; /* True if token ends with a "*" character */
  122165. int bFirst; /* True if token must appear at position 0 */
  122166. /* Variables above this point are populated when the expression is
  122167. ** parsed (by code in fts3_expr.c). Below this point the variables are
  122168. ** used when evaluating the expression. */
  122169. Fts3DeferredToken *pDeferred; /* Deferred token object for this token */
  122170. Fts3MultiSegReader *pSegcsr; /* Segment-reader for this token */
  122171. };
  122172. struct Fts3Phrase {
  122173. /* Cache of doclist for this phrase. */
  122174. Fts3Doclist doclist;
  122175. int bIncr; /* True if doclist is loaded incrementally */
  122176. int iDoclistToken;
  122177. /* Variables below this point are populated by fts3_expr.c when parsing
  122178. ** a MATCH expression. Everything above is part of the evaluation phase.
  122179. */
  122180. int nToken; /* Number of tokens in the phrase */
  122181. int iColumn; /* Index of column this phrase must match */
  122182. Fts3PhraseToken aToken[1]; /* One entry for each token in the phrase */
  122183. };
  122184. /*
  122185. ** A tree of these objects forms the RHS of a MATCH operator.
  122186. **
  122187. ** If Fts3Expr.eType is FTSQUERY_PHRASE and isLoaded is true, then aDoclist
  122188. ** points to a malloced buffer, size nDoclist bytes, containing the results
  122189. ** of this phrase query in FTS3 doclist format. As usual, the initial
  122190. ** "Length" field found in doclists stored on disk is omitted from this
  122191. ** buffer.
  122192. **
  122193. ** Variable aMI is used only for FTSQUERY_NEAR nodes to store the global
  122194. ** matchinfo data. If it is not NULL, it points to an array of size nCol*3,
  122195. ** where nCol is the number of columns in the queried FTS table. The array
  122196. ** is populated as follows:
  122197. **
  122198. ** aMI[iCol*3 + 0] = Undefined
  122199. ** aMI[iCol*3 + 1] = Number of occurrences
  122200. ** aMI[iCol*3 + 2] = Number of rows containing at least one instance
  122201. **
  122202. ** The aMI array is allocated using sqlite3_malloc(). It should be freed
  122203. ** when the expression node is.
  122204. */
  122205. struct Fts3Expr {
  122206. int eType; /* One of the FTSQUERY_XXX values defined below */
  122207. int nNear; /* Valid if eType==FTSQUERY_NEAR */
  122208. Fts3Expr *pParent; /* pParent->pLeft==this or pParent->pRight==this */
  122209. Fts3Expr *pLeft; /* Left operand */
  122210. Fts3Expr *pRight; /* Right operand */
  122211. Fts3Phrase *pPhrase; /* Valid if eType==FTSQUERY_PHRASE */
  122212. /* The following are used by the fts3_eval.c module. */
  122213. sqlite3_int64 iDocid; /* Current docid */
  122214. u8 bEof; /* True this expression is at EOF already */
  122215. u8 bStart; /* True if iDocid is valid */
  122216. u8 bDeferred; /* True if this expression is entirely deferred */
  122217. u32 *aMI;
  122218. };
  122219. /*
  122220. ** Candidate values for Fts3Query.eType. Note that the order of the first
  122221. ** four values is in order of precedence when parsing expressions. For
  122222. ** example, the following:
  122223. **
  122224. ** "a OR b AND c NOT d NEAR e"
  122225. **
  122226. ** is equivalent to:
  122227. **
  122228. ** "a OR (b AND (c NOT (d NEAR e)))"
  122229. */
  122230. #define FTSQUERY_NEAR 1
  122231. #define FTSQUERY_NOT 2
  122232. #define FTSQUERY_AND 3
  122233. #define FTSQUERY_OR 4
  122234. #define FTSQUERY_PHRASE 5
  122235. /* fts3_write.c */
  122236. SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(sqlite3_vtab*,int,sqlite3_value**,sqlite3_int64*);
  122237. SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *);
  122238. SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *);
  122239. SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *);
  122240. SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(int, int, sqlite3_int64,
  122241. sqlite3_int64, sqlite3_int64, const char *, int, Fts3SegReader**);
  122242. SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(
  122243. Fts3Table*,int,const char*,int,int,Fts3SegReader**);
  122244. SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *);
  122245. SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(Fts3Table*, int, int, int, sqlite3_stmt **);
  122246. SQLITE_PRIVATE int sqlite3Fts3ReadBlock(Fts3Table*, sqlite3_int64, char **, int*, int*);
  122247. SQLITE_PRIVATE int sqlite3Fts3SelectDoctotal(Fts3Table *, sqlite3_stmt **);
  122248. SQLITE_PRIVATE int sqlite3Fts3SelectDocsize(Fts3Table *, sqlite3_int64, sqlite3_stmt **);
  122249. #ifndef SQLITE_DISABLE_FTS4_DEFERRED
  122250. SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *);
  122251. SQLITE_PRIVATE int sqlite3Fts3DeferToken(Fts3Cursor *, Fts3PhraseToken *, int);
  122252. SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *);
  122253. SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *);
  122254. SQLITE_PRIVATE int sqlite3Fts3DeferredTokenList(Fts3DeferredToken *, char **, int *);
  122255. #else
  122256. # define sqlite3Fts3FreeDeferredTokens(x)
  122257. # define sqlite3Fts3DeferToken(x,y,z) SQLITE_OK
  122258. # define sqlite3Fts3CacheDeferredDoclists(x) SQLITE_OK
  122259. # define sqlite3Fts3FreeDeferredDoclists(x)
  122260. # define sqlite3Fts3DeferredTokenList(x,y,z) SQLITE_OK
  122261. #endif
  122262. SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *);
  122263. SQLITE_PRIVATE int sqlite3Fts3MaxLevel(Fts3Table *, int *);
  122264. /* Special values interpreted by sqlite3SegReaderCursor() */
  122265. #define FTS3_SEGCURSOR_PENDING -1
  122266. #define FTS3_SEGCURSOR_ALL -2
  122267. SQLITE_PRIVATE int sqlite3Fts3SegReaderStart(Fts3Table*, Fts3MultiSegReader*, Fts3SegFilter*);
  122268. SQLITE_PRIVATE int sqlite3Fts3SegReaderStep(Fts3Table *, Fts3MultiSegReader *);
  122269. SQLITE_PRIVATE void sqlite3Fts3SegReaderFinish(Fts3MultiSegReader *);
  122270. SQLITE_PRIVATE int sqlite3Fts3SegReaderCursor(Fts3Table *,
  122271. int, int, int, const char *, int, int, int, Fts3MultiSegReader *);
  122272. /* Flags allowed as part of the 4th argument to SegmentReaderIterate() */
  122273. #define FTS3_SEGMENT_REQUIRE_POS 0x00000001
  122274. #define FTS3_SEGMENT_IGNORE_EMPTY 0x00000002
  122275. #define FTS3_SEGMENT_COLUMN_FILTER 0x00000004
  122276. #define FTS3_SEGMENT_PREFIX 0x00000008
  122277. #define FTS3_SEGMENT_SCAN 0x00000010
  122278. #define FTS3_SEGMENT_FIRST 0x00000020
  122279. /* Type passed as 4th argument to SegmentReaderIterate() */
  122280. struct Fts3SegFilter {
  122281. const char *zTerm;
  122282. int nTerm;
  122283. int iCol;
  122284. int flags;
  122285. };
  122286. struct Fts3MultiSegReader {
  122287. /* Used internally by sqlite3Fts3SegReaderXXX() calls */
  122288. Fts3SegReader **apSegment; /* Array of Fts3SegReader objects */
  122289. int nSegment; /* Size of apSegment array */
  122290. int nAdvance; /* How many seg-readers to advance */
  122291. Fts3SegFilter *pFilter; /* Pointer to filter object */
  122292. char *aBuffer; /* Buffer to merge doclists in */
  122293. int nBuffer; /* Allocated size of aBuffer[] in bytes */
  122294. int iColFilter; /* If >=0, filter for this column */
  122295. int bRestart;
  122296. /* Used by fts3.c only. */
  122297. int nCost; /* Cost of running iterator */
  122298. int bLookup; /* True if a lookup of a single entry. */
  122299. /* Output values. Valid only after Fts3SegReaderStep() returns SQLITE_ROW. */
  122300. char *zTerm; /* Pointer to term buffer */
  122301. int nTerm; /* Size of zTerm in bytes */
  122302. char *aDoclist; /* Pointer to doclist buffer */
  122303. int nDoclist; /* Size of aDoclist[] in bytes */
  122304. };
  122305. SQLITE_PRIVATE int sqlite3Fts3Incrmerge(Fts3Table*,int,int);
  122306. #define fts3GetVarint32(p, piVal) ( \
  122307. (*(u8*)(p)&0x80) ? sqlite3Fts3GetVarint32(p, piVal) : (*piVal=*(u8*)(p), 1) \
  122308. )
  122309. /* fts3.c */
  122310. SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *, sqlite3_int64);
  122311. SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *, sqlite_int64 *);
  122312. SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *, int *);
  122313. SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64);
  122314. SQLITE_PRIVATE void sqlite3Fts3Dequote(char *);
  122315. SQLITE_PRIVATE void sqlite3Fts3DoclistPrev(int,char*,int,char**,sqlite3_int64*,int*,u8*);
  122316. SQLITE_PRIVATE int sqlite3Fts3EvalPhraseStats(Fts3Cursor *, Fts3Expr *, u32 *);
  122317. SQLITE_PRIVATE int sqlite3Fts3FirstFilter(sqlite3_int64, char *, int, char *);
  122318. SQLITE_PRIVATE void sqlite3Fts3CreateStatTable(int*, Fts3Table*);
  122319. /* fts3_tokenizer.c */
  122320. SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *, int *);
  122321. SQLITE_PRIVATE int sqlite3Fts3InitHashTable(sqlite3 *, Fts3Hash *, const char *);
  122322. SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(Fts3Hash *pHash, const char *,
  122323. sqlite3_tokenizer **, char **
  122324. );
  122325. SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char);
  122326. /* fts3_snippet.c */
  122327. SQLITE_PRIVATE void sqlite3Fts3Offsets(sqlite3_context*, Fts3Cursor*);
  122328. SQLITE_PRIVATE void sqlite3Fts3Snippet(sqlite3_context *, Fts3Cursor *, const char *,
  122329. const char *, const char *, int, int
  122330. );
  122331. SQLITE_PRIVATE void sqlite3Fts3Matchinfo(sqlite3_context *, Fts3Cursor *, const char *);
  122332. /* fts3_expr.c */
  122333. SQLITE_PRIVATE int sqlite3Fts3ExprParse(sqlite3_tokenizer *, int,
  122334. char **, int, int, int, const char *, int, Fts3Expr **, char **
  122335. );
  122336. SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *);
  122337. #ifdef SQLITE_TEST
  122338. SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3 *db);
  122339. SQLITE_PRIVATE int sqlite3Fts3InitTerm(sqlite3 *db);
  122340. #endif
  122341. SQLITE_PRIVATE int sqlite3Fts3OpenTokenizer(sqlite3_tokenizer *, int, const char *, int,
  122342. sqlite3_tokenizer_cursor **
  122343. );
  122344. /* fts3_aux.c */
  122345. SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db);
  122346. SQLITE_PRIVATE void sqlite3Fts3EvalPhraseCleanup(Fts3Phrase *);
  122347. SQLITE_PRIVATE int sqlite3Fts3MsrIncrStart(
  122348. Fts3Table*, Fts3MultiSegReader*, int, const char*, int);
  122349. SQLITE_PRIVATE int sqlite3Fts3MsrIncrNext(
  122350. Fts3Table *, Fts3MultiSegReader *, sqlite3_int64 *, char **, int *);
  122351. SQLITE_PRIVATE int sqlite3Fts3EvalPhrasePoslist(Fts3Cursor *, Fts3Expr *, int iCol, char **);
  122352. SQLITE_PRIVATE int sqlite3Fts3MsrOvfl(Fts3Cursor *, Fts3MultiSegReader *, int *);
  122353. SQLITE_PRIVATE int sqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr);
  122354. /* fts3_tokenize_vtab.c */
  122355. SQLITE_PRIVATE int sqlite3Fts3InitTok(sqlite3*, Fts3Hash *);
  122356. /* fts3_unicode2.c (functions generated by parsing unicode text files) */
  122357. #ifndef SQLITE_DISABLE_FTS3_UNICODE
  122358. SQLITE_PRIVATE int sqlite3FtsUnicodeFold(int, int);
  122359. SQLITE_PRIVATE int sqlite3FtsUnicodeIsalnum(int);
  122360. SQLITE_PRIVATE int sqlite3FtsUnicodeIsdiacritic(int);
  122361. #endif
  122362. #endif /* !SQLITE_CORE || SQLITE_ENABLE_FTS3 */
  122363. #endif /* _FTSINT_H */
  122364. /************** End of fts3Int.h *********************************************/
  122365. /************** Continuing where we left off in fts3.c ***********************/
  122366. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  122367. #if defined(SQLITE_ENABLE_FTS3) && !defined(SQLITE_CORE)
  122368. # define SQLITE_CORE 1
  122369. #endif
  122370. /* #include <assert.h> */
  122371. /* #include <stdlib.h> */
  122372. /* #include <stddef.h> */
  122373. /* #include <stdio.h> */
  122374. /* #include <string.h> */
  122375. /* #include <stdarg.h> */
  122376. #ifndef SQLITE_CORE
  122377. SQLITE_EXTENSION_INIT1
  122378. #endif
  122379. static int fts3EvalNext(Fts3Cursor *pCsr);
  122380. static int fts3EvalStart(Fts3Cursor *pCsr);
  122381. static int fts3TermSegReaderCursor(
  122382. Fts3Cursor *, const char *, int, int, Fts3MultiSegReader **);
  122383. /*
  122384. ** Write a 64-bit variable-length integer to memory starting at p[0].
  122385. ** The length of data written will be between 1 and FTS3_VARINT_MAX bytes.
  122386. ** The number of bytes written is returned.
  122387. */
  122388. SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *p, sqlite_int64 v){
  122389. unsigned char *q = (unsigned char *) p;
  122390. sqlite_uint64 vu = v;
  122391. do{
  122392. *q++ = (unsigned char) ((vu & 0x7f) | 0x80);
  122393. vu >>= 7;
  122394. }while( vu!=0 );
  122395. q[-1] &= 0x7f; /* turn off high bit in final byte */
  122396. assert( q - (unsigned char *)p <= FTS3_VARINT_MAX );
  122397. return (int) (q - (unsigned char *)p);
  122398. }
  122399. #define GETVARINT_STEP(v, ptr, shift, mask1, mask2, var, ret) \
  122400. v = (v & mask1) | ( (*ptr++) << shift ); \
  122401. if( (v & mask2)==0 ){ var = v; return ret; }
  122402. #define GETVARINT_INIT(v, ptr, shift, mask1, mask2, var, ret) \
  122403. v = (*ptr++); \
  122404. if( (v & mask2)==0 ){ var = v; return ret; }
  122405. /*
  122406. ** Read a 64-bit variable-length integer from memory starting at p[0].
  122407. ** Return the number of bytes read, or 0 on error.
  122408. ** The value is stored in *v.
  122409. */
  122410. SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *p, sqlite_int64 *v){
  122411. const char *pStart = p;
  122412. u32 a;
  122413. u64 b;
  122414. int shift;
  122415. GETVARINT_INIT(a, p, 0, 0x00, 0x80, *v, 1);
  122416. GETVARINT_STEP(a, p, 7, 0x7F, 0x4000, *v, 2);
  122417. GETVARINT_STEP(a, p, 14, 0x3FFF, 0x200000, *v, 3);
  122418. GETVARINT_STEP(a, p, 21, 0x1FFFFF, 0x10000000, *v, 4);
  122419. b = (a & 0x0FFFFFFF );
  122420. for(shift=28; shift<=63; shift+=7){
  122421. u64 c = *p++;
  122422. b += (c&0x7F) << shift;
  122423. if( (c & 0x80)==0 ) break;
  122424. }
  122425. *v = b;
  122426. return (int)(p - pStart);
  122427. }
  122428. /*
  122429. ** Similar to sqlite3Fts3GetVarint(), except that the output is truncated to a
  122430. ** 32-bit integer before it is returned.
  122431. */
  122432. SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *p, int *pi){
  122433. u32 a;
  122434. #ifndef fts3GetVarint32
  122435. GETVARINT_INIT(a, p, 0, 0x00, 0x80, *pi, 1);
  122436. #else
  122437. a = (*p++);
  122438. assert( a & 0x80 );
  122439. #endif
  122440. GETVARINT_STEP(a, p, 7, 0x7F, 0x4000, *pi, 2);
  122441. GETVARINT_STEP(a, p, 14, 0x3FFF, 0x200000, *pi, 3);
  122442. GETVARINT_STEP(a, p, 21, 0x1FFFFF, 0x10000000, *pi, 4);
  122443. a = (a & 0x0FFFFFFF );
  122444. *pi = (int)(a | ((u32)(*p & 0x0F) << 28));
  122445. return 5;
  122446. }
  122447. /*
  122448. ** Return the number of bytes required to encode v as a varint
  122449. */
  122450. SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64 v){
  122451. int i = 0;
  122452. do{
  122453. i++;
  122454. v >>= 7;
  122455. }while( v!=0 );
  122456. return i;
  122457. }
  122458. /*
  122459. ** Convert an SQL-style quoted string into a normal string by removing
  122460. ** the quote characters. The conversion is done in-place. If the
  122461. ** input does not begin with a quote character, then this routine
  122462. ** is a no-op.
  122463. **
  122464. ** Examples:
  122465. **
  122466. ** "abc" becomes abc
  122467. ** 'xyz' becomes xyz
  122468. ** [pqr] becomes pqr
  122469. ** `mno` becomes mno
  122470. **
  122471. */
  122472. SQLITE_PRIVATE void sqlite3Fts3Dequote(char *z){
  122473. char quote; /* Quote character (if any ) */
  122474. quote = z[0];
  122475. if( quote=='[' || quote=='\'' || quote=='"' || quote=='`' ){
  122476. int iIn = 1; /* Index of next byte to read from input */
  122477. int iOut = 0; /* Index of next byte to write to output */
  122478. /* If the first byte was a '[', then the close-quote character is a ']' */
  122479. if( quote=='[' ) quote = ']';
  122480. while( ALWAYS(z[iIn]) ){
  122481. if( z[iIn]==quote ){
  122482. if( z[iIn+1]!=quote ) break;
  122483. z[iOut++] = quote;
  122484. iIn += 2;
  122485. }else{
  122486. z[iOut++] = z[iIn++];
  122487. }
  122488. }
  122489. z[iOut] = '\0';
  122490. }
  122491. }
  122492. /*
  122493. ** Read a single varint from the doclist at *pp and advance *pp to point
  122494. ** to the first byte past the end of the varint. Add the value of the varint
  122495. ** to *pVal.
  122496. */
  122497. static void fts3GetDeltaVarint(char **pp, sqlite3_int64 *pVal){
  122498. sqlite3_int64 iVal;
  122499. *pp += sqlite3Fts3GetVarint(*pp, &iVal);
  122500. *pVal += iVal;
  122501. }
  122502. /*
  122503. ** When this function is called, *pp points to the first byte following a
  122504. ** varint that is part of a doclist (or position-list, or any other list
  122505. ** of varints). This function moves *pp to point to the start of that varint,
  122506. ** and sets *pVal by the varint value.
  122507. **
  122508. ** Argument pStart points to the first byte of the doclist that the
  122509. ** varint is part of.
  122510. */
  122511. static void fts3GetReverseVarint(
  122512. char **pp,
  122513. char *pStart,
  122514. sqlite3_int64 *pVal
  122515. ){
  122516. sqlite3_int64 iVal;
  122517. char *p;
  122518. /* Pointer p now points at the first byte past the varint we are
  122519. ** interested in. So, unless the doclist is corrupt, the 0x80 bit is
  122520. ** clear on character p[-1]. */
  122521. for(p = (*pp)-2; p>=pStart && *p&0x80; p--);
  122522. p++;
  122523. *pp = p;
  122524. sqlite3Fts3GetVarint(p, &iVal);
  122525. *pVal = iVal;
  122526. }
  122527. /*
  122528. ** The xDisconnect() virtual table method.
  122529. */
  122530. static int fts3DisconnectMethod(sqlite3_vtab *pVtab){
  122531. Fts3Table *p = (Fts3Table *)pVtab;
  122532. int i;
  122533. assert( p->nPendingData==0 );
  122534. assert( p->pSegments==0 );
  122535. /* Free any prepared statements held */
  122536. for(i=0; i<SizeofArray(p->aStmt); i++){
  122537. sqlite3_finalize(p->aStmt[i]);
  122538. }
  122539. sqlite3_free(p->zSegmentsTbl);
  122540. sqlite3_free(p->zReadExprlist);
  122541. sqlite3_free(p->zWriteExprlist);
  122542. sqlite3_free(p->zContentTbl);
  122543. sqlite3_free(p->zLanguageid);
  122544. /* Invoke the tokenizer destructor to free the tokenizer. */
  122545. p->pTokenizer->pModule->xDestroy(p->pTokenizer);
  122546. sqlite3_free(p);
  122547. return SQLITE_OK;
  122548. }
  122549. /*
  122550. ** Construct one or more SQL statements from the format string given
  122551. ** and then evaluate those statements. The success code is written
  122552. ** into *pRc.
  122553. **
  122554. ** If *pRc is initially non-zero then this routine is a no-op.
  122555. */
  122556. static void fts3DbExec(
  122557. int *pRc, /* Success code */
  122558. sqlite3 *db, /* Database in which to run SQL */
  122559. const char *zFormat, /* Format string for SQL */
  122560. ... /* Arguments to the format string */
  122561. ){
  122562. va_list ap;
  122563. char *zSql;
  122564. if( *pRc ) return;
  122565. va_start(ap, zFormat);
  122566. zSql = sqlite3_vmprintf(zFormat, ap);
  122567. va_end(ap);
  122568. if( zSql==0 ){
  122569. *pRc = SQLITE_NOMEM;
  122570. }else{
  122571. *pRc = sqlite3_exec(db, zSql, 0, 0, 0);
  122572. sqlite3_free(zSql);
  122573. }
  122574. }
  122575. /*
  122576. ** The xDestroy() virtual table method.
  122577. */
  122578. static int fts3DestroyMethod(sqlite3_vtab *pVtab){
  122579. Fts3Table *p = (Fts3Table *)pVtab;
  122580. int rc = SQLITE_OK; /* Return code */
  122581. const char *zDb = p->zDb; /* Name of database (e.g. "main", "temp") */
  122582. sqlite3 *db = p->db; /* Database handle */
  122583. /* Drop the shadow tables */
  122584. if( p->zContentTbl==0 ){
  122585. fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_content'", zDb, p->zName);
  122586. }
  122587. fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segments'", zDb,p->zName);
  122588. fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segdir'", zDb, p->zName);
  122589. fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_docsize'", zDb, p->zName);
  122590. fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_stat'", zDb, p->zName);
  122591. /* If everything has worked, invoke fts3DisconnectMethod() to free the
  122592. ** memory associated with the Fts3Table structure and return SQLITE_OK.
  122593. ** Otherwise, return an SQLite error code.
  122594. */
  122595. return (rc==SQLITE_OK ? fts3DisconnectMethod(pVtab) : rc);
  122596. }
  122597. /*
  122598. ** Invoke sqlite3_declare_vtab() to declare the schema for the FTS3 table
  122599. ** passed as the first argument. This is done as part of the xConnect()
  122600. ** and xCreate() methods.
  122601. **
  122602. ** If *pRc is non-zero when this function is called, it is a no-op.
  122603. ** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
  122604. ** before returning.
  122605. */
  122606. static void fts3DeclareVtab(int *pRc, Fts3Table *p){
  122607. if( *pRc==SQLITE_OK ){
  122608. int i; /* Iterator variable */
  122609. int rc; /* Return code */
  122610. char *zSql; /* SQL statement passed to declare_vtab() */
  122611. char *zCols; /* List of user defined columns */
  122612. const char *zLanguageid;
  122613. zLanguageid = (p->zLanguageid ? p->zLanguageid : "__langid");
  122614. sqlite3_vtab_config(p->db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1);
  122615. /* Create a list of user columns for the virtual table */
  122616. zCols = sqlite3_mprintf("%Q, ", p->azColumn[0]);
  122617. for(i=1; zCols && i<p->nColumn; i++){
  122618. zCols = sqlite3_mprintf("%z%Q, ", zCols, p->azColumn[i]);
  122619. }
  122620. /* Create the whole "CREATE TABLE" statement to pass to SQLite */
  122621. zSql = sqlite3_mprintf(
  122622. "CREATE TABLE x(%s %Q HIDDEN, docid HIDDEN, %Q HIDDEN)",
  122623. zCols, p->zName, zLanguageid
  122624. );
  122625. if( !zCols || !zSql ){
  122626. rc = SQLITE_NOMEM;
  122627. }else{
  122628. rc = sqlite3_declare_vtab(p->db, zSql);
  122629. }
  122630. sqlite3_free(zSql);
  122631. sqlite3_free(zCols);
  122632. *pRc = rc;
  122633. }
  122634. }
  122635. /*
  122636. ** Create the %_stat table if it does not already exist.
  122637. */
  122638. SQLITE_PRIVATE void sqlite3Fts3CreateStatTable(int *pRc, Fts3Table *p){
  122639. fts3DbExec(pRc, p->db,
  122640. "CREATE TABLE IF NOT EXISTS %Q.'%q_stat'"
  122641. "(id INTEGER PRIMARY KEY, value BLOB);",
  122642. p->zDb, p->zName
  122643. );
  122644. if( (*pRc)==SQLITE_OK ) p->bHasStat = 1;
  122645. }
  122646. /*
  122647. ** Create the backing store tables (%_content, %_segments and %_segdir)
  122648. ** required by the FTS3 table passed as the only argument. This is done
  122649. ** as part of the vtab xCreate() method.
  122650. **
  122651. ** If the p->bHasDocsize boolean is true (indicating that this is an
  122652. ** FTS4 table, not an FTS3 table) then also create the %_docsize and
  122653. ** %_stat tables required by FTS4.
  122654. */
  122655. static int fts3CreateTables(Fts3Table *p){
  122656. int rc = SQLITE_OK; /* Return code */
  122657. int i; /* Iterator variable */
  122658. sqlite3 *db = p->db; /* The database connection */
  122659. if( p->zContentTbl==0 ){
  122660. const char *zLanguageid = p->zLanguageid;
  122661. char *zContentCols; /* Columns of %_content table */
  122662. /* Create a list of user columns for the content table */
  122663. zContentCols = sqlite3_mprintf("docid INTEGER PRIMARY KEY");
  122664. for(i=0; zContentCols && i<p->nColumn; i++){
  122665. char *z = p->azColumn[i];
  122666. zContentCols = sqlite3_mprintf("%z, 'c%d%q'", zContentCols, i, z);
  122667. }
  122668. if( zLanguageid && zContentCols ){
  122669. zContentCols = sqlite3_mprintf("%z, langid", zContentCols, zLanguageid);
  122670. }
  122671. if( zContentCols==0 ) rc = SQLITE_NOMEM;
  122672. /* Create the content table */
  122673. fts3DbExec(&rc, db,
  122674. "CREATE TABLE %Q.'%q_content'(%s)",
  122675. p->zDb, p->zName, zContentCols
  122676. );
  122677. sqlite3_free(zContentCols);
  122678. }
  122679. /* Create other tables */
  122680. fts3DbExec(&rc, db,
  122681. "CREATE TABLE %Q.'%q_segments'(blockid INTEGER PRIMARY KEY, block BLOB);",
  122682. p->zDb, p->zName
  122683. );
  122684. fts3DbExec(&rc, db,
  122685. "CREATE TABLE %Q.'%q_segdir'("
  122686. "level INTEGER,"
  122687. "idx INTEGER,"
  122688. "start_block INTEGER,"
  122689. "leaves_end_block INTEGER,"
  122690. "end_block INTEGER,"
  122691. "root BLOB,"
  122692. "PRIMARY KEY(level, idx)"
  122693. ");",
  122694. p->zDb, p->zName
  122695. );
  122696. if( p->bHasDocsize ){
  122697. fts3DbExec(&rc, db,
  122698. "CREATE TABLE %Q.'%q_docsize'(docid INTEGER PRIMARY KEY, size BLOB);",
  122699. p->zDb, p->zName
  122700. );
  122701. }
  122702. assert( p->bHasStat==p->bFts4 );
  122703. if( p->bHasStat ){
  122704. sqlite3Fts3CreateStatTable(&rc, p);
  122705. }
  122706. return rc;
  122707. }
  122708. /*
  122709. ** Store the current database page-size in bytes in p->nPgsz.
  122710. **
  122711. ** If *pRc is non-zero when this function is called, it is a no-op.
  122712. ** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
  122713. ** before returning.
  122714. */
  122715. static void fts3DatabasePageSize(int *pRc, Fts3Table *p){
  122716. if( *pRc==SQLITE_OK ){
  122717. int rc; /* Return code */
  122718. char *zSql; /* SQL text "PRAGMA %Q.page_size" */
  122719. sqlite3_stmt *pStmt; /* Compiled "PRAGMA %Q.page_size" statement */
  122720. zSql = sqlite3_mprintf("PRAGMA %Q.page_size", p->zDb);
  122721. if( !zSql ){
  122722. rc = SQLITE_NOMEM;
  122723. }else{
  122724. rc = sqlite3_prepare(p->db, zSql, -1, &pStmt, 0);
  122725. if( rc==SQLITE_OK ){
  122726. sqlite3_step(pStmt);
  122727. p->nPgsz = sqlite3_column_int(pStmt, 0);
  122728. rc = sqlite3_finalize(pStmt);
  122729. }else if( rc==SQLITE_AUTH ){
  122730. p->nPgsz = 1024;
  122731. rc = SQLITE_OK;
  122732. }
  122733. }
  122734. assert( p->nPgsz>0 || rc!=SQLITE_OK );
  122735. sqlite3_free(zSql);
  122736. *pRc = rc;
  122737. }
  122738. }
  122739. /*
  122740. ** "Special" FTS4 arguments are column specifications of the following form:
  122741. **
  122742. ** <key> = <value>
  122743. **
  122744. ** There may not be whitespace surrounding the "=" character. The <value>
  122745. ** term may be quoted, but the <key> may not.
  122746. */
  122747. static int fts3IsSpecialColumn(
  122748. const char *z,
  122749. int *pnKey,
  122750. char **pzValue
  122751. ){
  122752. char *zValue;
  122753. const char *zCsr = z;
  122754. while( *zCsr!='=' ){
  122755. if( *zCsr=='\0' ) return 0;
  122756. zCsr++;
  122757. }
  122758. *pnKey = (int)(zCsr-z);
  122759. zValue = sqlite3_mprintf("%s", &zCsr[1]);
  122760. if( zValue ){
  122761. sqlite3Fts3Dequote(zValue);
  122762. }
  122763. *pzValue = zValue;
  122764. return 1;
  122765. }
  122766. /*
  122767. ** Append the output of a printf() style formatting to an existing string.
  122768. */
  122769. static void fts3Appendf(
  122770. int *pRc, /* IN/OUT: Error code */
  122771. char **pz, /* IN/OUT: Pointer to string buffer */
  122772. const char *zFormat, /* Printf format string to append */
  122773. ... /* Arguments for printf format string */
  122774. ){
  122775. if( *pRc==SQLITE_OK ){
  122776. va_list ap;
  122777. char *z;
  122778. va_start(ap, zFormat);
  122779. z = sqlite3_vmprintf(zFormat, ap);
  122780. va_end(ap);
  122781. if( z && *pz ){
  122782. char *z2 = sqlite3_mprintf("%s%s", *pz, z);
  122783. sqlite3_free(z);
  122784. z = z2;
  122785. }
  122786. if( z==0 ) *pRc = SQLITE_NOMEM;
  122787. sqlite3_free(*pz);
  122788. *pz = z;
  122789. }
  122790. }
  122791. /*
  122792. ** Return a copy of input string zInput enclosed in double-quotes (") and
  122793. ** with all double quote characters escaped. For example:
  122794. **
  122795. ** fts3QuoteId("un \"zip\"") -> "un \"\"zip\"\""
  122796. **
  122797. ** The pointer returned points to memory obtained from sqlite3_malloc(). It
  122798. ** is the callers responsibility to call sqlite3_free() to release this
  122799. ** memory.
  122800. */
  122801. static char *fts3QuoteId(char const *zInput){
  122802. int nRet;
  122803. char *zRet;
  122804. nRet = 2 + (int)strlen(zInput)*2 + 1;
  122805. zRet = sqlite3_malloc(nRet);
  122806. if( zRet ){
  122807. int i;
  122808. char *z = zRet;
  122809. *(z++) = '"';
  122810. for(i=0; zInput[i]; i++){
  122811. if( zInput[i]=='"' ) *(z++) = '"';
  122812. *(z++) = zInput[i];
  122813. }
  122814. *(z++) = '"';
  122815. *(z++) = '\0';
  122816. }
  122817. return zRet;
  122818. }
  122819. /*
  122820. ** Return a list of comma separated SQL expressions and a FROM clause that
  122821. ** could be used in a SELECT statement such as the following:
  122822. **
  122823. ** SELECT <list of expressions> FROM %_content AS x ...
  122824. **
  122825. ** to return the docid, followed by each column of text data in order
  122826. ** from left to write. If parameter zFunc is not NULL, then instead of
  122827. ** being returned directly each column of text data is passed to an SQL
  122828. ** function named zFunc first. For example, if zFunc is "unzip" and the
  122829. ** table has the three user-defined columns "a", "b", and "c", the following
  122830. ** string is returned:
  122831. **
  122832. ** "docid, unzip(x.'a'), unzip(x.'b'), unzip(x.'c') FROM %_content AS x"
  122833. **
  122834. ** The pointer returned points to a buffer allocated by sqlite3_malloc(). It
  122835. ** is the responsibility of the caller to eventually free it.
  122836. **
  122837. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and
  122838. ** a NULL pointer is returned). Otherwise, if an OOM error is encountered
  122839. ** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If
  122840. ** no error occurs, *pRc is left unmodified.
  122841. */
  122842. static char *fts3ReadExprList(Fts3Table *p, const char *zFunc, int *pRc){
  122843. char *zRet = 0;
  122844. char *zFree = 0;
  122845. char *zFunction;
  122846. int i;
  122847. if( p->zContentTbl==0 ){
  122848. if( !zFunc ){
  122849. zFunction = "";
  122850. }else{
  122851. zFree = zFunction = fts3QuoteId(zFunc);
  122852. }
  122853. fts3Appendf(pRc, &zRet, "docid");
  122854. for(i=0; i<p->nColumn; i++){
  122855. fts3Appendf(pRc, &zRet, ",%s(x.'c%d%q')", zFunction, i, p->azColumn[i]);
  122856. }
  122857. if( p->zLanguageid ){
  122858. fts3Appendf(pRc, &zRet, ", x.%Q", "langid");
  122859. }
  122860. sqlite3_free(zFree);
  122861. }else{
  122862. fts3Appendf(pRc, &zRet, "rowid");
  122863. for(i=0; i<p->nColumn; i++){
  122864. fts3Appendf(pRc, &zRet, ", x.'%q'", p->azColumn[i]);
  122865. }
  122866. if( p->zLanguageid ){
  122867. fts3Appendf(pRc, &zRet, ", x.%Q", p->zLanguageid);
  122868. }
  122869. }
  122870. fts3Appendf(pRc, &zRet, " FROM '%q'.'%q%s' AS x",
  122871. p->zDb,
  122872. (p->zContentTbl ? p->zContentTbl : p->zName),
  122873. (p->zContentTbl ? "" : "_content")
  122874. );
  122875. return zRet;
  122876. }
  122877. /*
  122878. ** Return a list of N comma separated question marks, where N is the number
  122879. ** of columns in the %_content table (one for the docid plus one for each
  122880. ** user-defined text column).
  122881. **
  122882. ** If argument zFunc is not NULL, then all but the first question mark
  122883. ** is preceded by zFunc and an open bracket, and followed by a closed
  122884. ** bracket. For example, if zFunc is "zip" and the FTS3 table has three
  122885. ** user-defined text columns, the following string is returned:
  122886. **
  122887. ** "?, zip(?), zip(?), zip(?)"
  122888. **
  122889. ** The pointer returned points to a buffer allocated by sqlite3_malloc(). It
  122890. ** is the responsibility of the caller to eventually free it.
  122891. **
  122892. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and
  122893. ** a NULL pointer is returned). Otherwise, if an OOM error is encountered
  122894. ** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If
  122895. ** no error occurs, *pRc is left unmodified.
  122896. */
  122897. static char *fts3WriteExprList(Fts3Table *p, const char *zFunc, int *pRc){
  122898. char *zRet = 0;
  122899. char *zFree = 0;
  122900. char *zFunction;
  122901. int i;
  122902. if( !zFunc ){
  122903. zFunction = "";
  122904. }else{
  122905. zFree = zFunction = fts3QuoteId(zFunc);
  122906. }
  122907. fts3Appendf(pRc, &zRet, "?");
  122908. for(i=0; i<p->nColumn; i++){
  122909. fts3Appendf(pRc, &zRet, ",%s(?)", zFunction);
  122910. }
  122911. if( p->zLanguageid ){
  122912. fts3Appendf(pRc, &zRet, ", ?");
  122913. }
  122914. sqlite3_free(zFree);
  122915. return zRet;
  122916. }
  122917. /*
  122918. ** This function interprets the string at (*pp) as a non-negative integer
  122919. ** value. It reads the integer and sets *pnOut to the value read, then
  122920. ** sets *pp to point to the byte immediately following the last byte of
  122921. ** the integer value.
  122922. **
  122923. ** Only decimal digits ('0'..'9') may be part of an integer value.
  122924. **
  122925. ** If *pp does not being with a decimal digit SQLITE_ERROR is returned and
  122926. ** the output value undefined. Otherwise SQLITE_OK is returned.
  122927. **
  122928. ** This function is used when parsing the "prefix=" FTS4 parameter.
  122929. */
  122930. static int fts3GobbleInt(const char **pp, int *pnOut){
  122931. const char *p; /* Iterator pointer */
  122932. int nInt = 0; /* Output value */
  122933. for(p=*pp; p[0]>='0' && p[0]<='9'; p++){
  122934. nInt = nInt * 10 + (p[0] - '0');
  122935. }
  122936. if( p==*pp ) return SQLITE_ERROR;
  122937. *pnOut = nInt;
  122938. *pp = p;
  122939. return SQLITE_OK;
  122940. }
  122941. /*
  122942. ** This function is called to allocate an array of Fts3Index structures
  122943. ** representing the indexes maintained by the current FTS table. FTS tables
  122944. ** always maintain the main "terms" index, but may also maintain one or
  122945. ** more "prefix" indexes, depending on the value of the "prefix=" parameter
  122946. ** (if any) specified as part of the CREATE VIRTUAL TABLE statement.
  122947. **
  122948. ** Argument zParam is passed the value of the "prefix=" option if one was
  122949. ** specified, or NULL otherwise.
  122950. **
  122951. ** If no error occurs, SQLITE_OK is returned and *apIndex set to point to
  122952. ** the allocated array. *pnIndex is set to the number of elements in the
  122953. ** array. If an error does occur, an SQLite error code is returned.
  122954. **
  122955. ** Regardless of whether or not an error is returned, it is the responsibility
  122956. ** of the caller to call sqlite3_free() on the output array to free it.
  122957. */
  122958. static int fts3PrefixParameter(
  122959. const char *zParam, /* ABC in prefix=ABC parameter to parse */
  122960. int *pnIndex, /* OUT: size of *apIndex[] array */
  122961. struct Fts3Index **apIndex /* OUT: Array of indexes for this table */
  122962. ){
  122963. struct Fts3Index *aIndex; /* Allocated array */
  122964. int nIndex = 1; /* Number of entries in array */
  122965. if( zParam && zParam[0] ){
  122966. const char *p;
  122967. nIndex++;
  122968. for(p=zParam; *p; p++){
  122969. if( *p==',' ) nIndex++;
  122970. }
  122971. }
  122972. aIndex = sqlite3_malloc(sizeof(struct Fts3Index) * nIndex);
  122973. *apIndex = aIndex;
  122974. *pnIndex = nIndex;
  122975. if( !aIndex ){
  122976. return SQLITE_NOMEM;
  122977. }
  122978. memset(aIndex, 0, sizeof(struct Fts3Index) * nIndex);
  122979. if( zParam ){
  122980. const char *p = zParam;
  122981. int i;
  122982. for(i=1; i<nIndex; i++){
  122983. int nPrefix;
  122984. if( fts3GobbleInt(&p, &nPrefix) ) return SQLITE_ERROR;
  122985. aIndex[i].nPrefix = nPrefix;
  122986. p++;
  122987. }
  122988. }
  122989. return SQLITE_OK;
  122990. }
  122991. /*
  122992. ** This function is called when initializing an FTS4 table that uses the
  122993. ** content=xxx option. It determines the number of and names of the columns
  122994. ** of the new FTS4 table.
  122995. **
  122996. ** The third argument passed to this function is the value passed to the
  122997. ** config=xxx option (i.e. "xxx"). This function queries the database for
  122998. ** a table of that name. If found, the output variables are populated
  122999. ** as follows:
  123000. **
  123001. ** *pnCol: Set to the number of columns table xxx has,
  123002. **
  123003. ** *pnStr: Set to the total amount of space required to store a copy
  123004. ** of each columns name, including the nul-terminator.
  123005. **
  123006. ** *pazCol: Set to point to an array of *pnCol strings. Each string is
  123007. ** the name of the corresponding column in table xxx. The array
  123008. ** and its contents are allocated using a single allocation. It
  123009. ** is the responsibility of the caller to free this allocation
  123010. ** by eventually passing the *pazCol value to sqlite3_free().
  123011. **
  123012. ** If the table cannot be found, an error code is returned and the output
  123013. ** variables are undefined. Or, if an OOM is encountered, SQLITE_NOMEM is
  123014. ** returned (and the output variables are undefined).
  123015. */
  123016. static int fts3ContentColumns(
  123017. sqlite3 *db, /* Database handle */
  123018. const char *zDb, /* Name of db (i.e. "main", "temp" etc.) */
  123019. const char *zTbl, /* Name of content table */
  123020. const char ***pazCol, /* OUT: Malloc'd array of column names */
  123021. int *pnCol, /* OUT: Size of array *pazCol */
  123022. int *pnStr /* OUT: Bytes of string content */
  123023. ){
  123024. int rc = SQLITE_OK; /* Return code */
  123025. char *zSql; /* "SELECT *" statement on zTbl */
  123026. sqlite3_stmt *pStmt = 0; /* Compiled version of zSql */
  123027. zSql = sqlite3_mprintf("SELECT * FROM %Q.%Q", zDb, zTbl);
  123028. if( !zSql ){
  123029. rc = SQLITE_NOMEM;
  123030. }else{
  123031. rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
  123032. }
  123033. sqlite3_free(zSql);
  123034. if( rc==SQLITE_OK ){
  123035. const char **azCol; /* Output array */
  123036. int nStr = 0; /* Size of all column names (incl. 0x00) */
  123037. int nCol; /* Number of table columns */
  123038. int i; /* Used to iterate through columns */
  123039. /* Loop through the returned columns. Set nStr to the number of bytes of
  123040. ** space required to store a copy of each column name, including the
  123041. ** nul-terminator byte. */
  123042. nCol = sqlite3_column_count(pStmt);
  123043. for(i=0; i<nCol; i++){
  123044. const char *zCol = sqlite3_column_name(pStmt, i);
  123045. nStr += (int)strlen(zCol) + 1;
  123046. }
  123047. /* Allocate and populate the array to return. */
  123048. azCol = (const char **)sqlite3_malloc(sizeof(char *) * nCol + nStr);
  123049. if( azCol==0 ){
  123050. rc = SQLITE_NOMEM;
  123051. }else{
  123052. char *p = (char *)&azCol[nCol];
  123053. for(i=0; i<nCol; i++){
  123054. const char *zCol = sqlite3_column_name(pStmt, i);
  123055. int n = (int)strlen(zCol)+1;
  123056. memcpy(p, zCol, n);
  123057. azCol[i] = p;
  123058. p += n;
  123059. }
  123060. }
  123061. sqlite3_finalize(pStmt);
  123062. /* Set the output variables. */
  123063. *pnCol = nCol;
  123064. *pnStr = nStr;
  123065. *pazCol = azCol;
  123066. }
  123067. return rc;
  123068. }
  123069. /*
  123070. ** This function is the implementation of both the xConnect and xCreate
  123071. ** methods of the FTS3 virtual table.
  123072. **
  123073. ** The argv[] array contains the following:
  123074. **
  123075. ** argv[0] -> module name ("fts3" or "fts4")
  123076. ** argv[1] -> database name
  123077. ** argv[2] -> table name
  123078. ** argv[...] -> "column name" and other module argument fields.
  123079. */
  123080. static int fts3InitVtab(
  123081. int isCreate, /* True for xCreate, false for xConnect */
  123082. sqlite3 *db, /* The SQLite database connection */
  123083. void *pAux, /* Hash table containing tokenizers */
  123084. int argc, /* Number of elements in argv array */
  123085. const char * const *argv, /* xCreate/xConnect argument array */
  123086. sqlite3_vtab **ppVTab, /* Write the resulting vtab structure here */
  123087. char **pzErr /* Write any error message here */
  123088. ){
  123089. Fts3Hash *pHash = (Fts3Hash *)pAux;
  123090. Fts3Table *p = 0; /* Pointer to allocated vtab */
  123091. int rc = SQLITE_OK; /* Return code */
  123092. int i; /* Iterator variable */
  123093. int nByte; /* Size of allocation used for *p */
  123094. int iCol; /* Column index */
  123095. int nString = 0; /* Bytes required to hold all column names */
  123096. int nCol = 0; /* Number of columns in the FTS table */
  123097. char *zCsr; /* Space for holding column names */
  123098. int nDb; /* Bytes required to hold database name */
  123099. int nName; /* Bytes required to hold table name */
  123100. int isFts4 = (argv[0][3]=='4'); /* True for FTS4, false for FTS3 */
  123101. const char **aCol; /* Array of column names */
  123102. sqlite3_tokenizer *pTokenizer = 0; /* Tokenizer for this table */
  123103. int nIndex; /* Size of aIndex[] array */
  123104. struct Fts3Index *aIndex = 0; /* Array of indexes for this table */
  123105. /* The results of parsing supported FTS4 key=value options: */
  123106. int bNoDocsize = 0; /* True to omit %_docsize table */
  123107. int bDescIdx = 0; /* True to store descending indexes */
  123108. char *zPrefix = 0; /* Prefix parameter value (or NULL) */
  123109. char *zCompress = 0; /* compress=? parameter (or NULL) */
  123110. char *zUncompress = 0; /* uncompress=? parameter (or NULL) */
  123111. char *zContent = 0; /* content=? parameter (or NULL) */
  123112. char *zLanguageid = 0; /* languageid=? parameter (or NULL) */
  123113. char **azNotindexed = 0; /* The set of notindexed= columns */
  123114. int nNotindexed = 0; /* Size of azNotindexed[] array */
  123115. assert( strlen(argv[0])==4 );
  123116. assert( (sqlite3_strnicmp(argv[0], "fts4", 4)==0 && isFts4)
  123117. || (sqlite3_strnicmp(argv[0], "fts3", 4)==0 && !isFts4)
  123118. );
  123119. nDb = (int)strlen(argv[1]) + 1;
  123120. nName = (int)strlen(argv[2]) + 1;
  123121. nByte = sizeof(const char *) * (argc-2);
  123122. aCol = (const char **)sqlite3_malloc(nByte);
  123123. if( aCol ){
  123124. memset((void*)aCol, 0, nByte);
  123125. azNotindexed = (char **)sqlite3_malloc(nByte);
  123126. }
  123127. if( azNotindexed ){
  123128. memset(azNotindexed, 0, nByte);
  123129. }
  123130. if( !aCol || !azNotindexed ){
  123131. rc = SQLITE_NOMEM;
  123132. goto fts3_init_out;
  123133. }
  123134. /* Loop through all of the arguments passed by the user to the FTS3/4
  123135. ** module (i.e. all the column names and special arguments). This loop
  123136. ** does the following:
  123137. **
  123138. ** + Figures out the number of columns the FTSX table will have, and
  123139. ** the number of bytes of space that must be allocated to store copies
  123140. ** of the column names.
  123141. **
  123142. ** + If there is a tokenizer specification included in the arguments,
  123143. ** initializes the tokenizer pTokenizer.
  123144. */
  123145. for(i=3; rc==SQLITE_OK && i<argc; i++){
  123146. char const *z = argv[i];
  123147. int nKey;
  123148. char *zVal;
  123149. /* Check if this is a tokenizer specification */
  123150. if( !pTokenizer
  123151. && strlen(z)>8
  123152. && 0==sqlite3_strnicmp(z, "tokenize", 8)
  123153. && 0==sqlite3Fts3IsIdChar(z[8])
  123154. ){
  123155. rc = sqlite3Fts3InitTokenizer(pHash, &z[9], &pTokenizer, pzErr);
  123156. }
  123157. /* Check if it is an FTS4 special argument. */
  123158. else if( isFts4 && fts3IsSpecialColumn(z, &nKey, &zVal) ){
  123159. struct Fts4Option {
  123160. const char *zOpt;
  123161. int nOpt;
  123162. } aFts4Opt[] = {
  123163. { "matchinfo", 9 }, /* 0 -> MATCHINFO */
  123164. { "prefix", 6 }, /* 1 -> PREFIX */
  123165. { "compress", 8 }, /* 2 -> COMPRESS */
  123166. { "uncompress", 10 }, /* 3 -> UNCOMPRESS */
  123167. { "order", 5 }, /* 4 -> ORDER */
  123168. { "content", 7 }, /* 5 -> CONTENT */
  123169. { "languageid", 10 }, /* 6 -> LANGUAGEID */
  123170. { "notindexed", 10 } /* 7 -> NOTINDEXED */
  123171. };
  123172. int iOpt;
  123173. if( !zVal ){
  123174. rc = SQLITE_NOMEM;
  123175. }else{
  123176. for(iOpt=0; iOpt<SizeofArray(aFts4Opt); iOpt++){
  123177. struct Fts4Option *pOp = &aFts4Opt[iOpt];
  123178. if( nKey==pOp->nOpt && !sqlite3_strnicmp(z, pOp->zOpt, pOp->nOpt) ){
  123179. break;
  123180. }
  123181. }
  123182. if( iOpt==SizeofArray(aFts4Opt) ){
  123183. *pzErr = sqlite3_mprintf("unrecognized parameter: %s", z);
  123184. rc = SQLITE_ERROR;
  123185. }else{
  123186. switch( iOpt ){
  123187. case 0: /* MATCHINFO */
  123188. if( strlen(zVal)!=4 || sqlite3_strnicmp(zVal, "fts3", 4) ){
  123189. *pzErr = sqlite3_mprintf("unrecognized matchinfo: %s", zVal);
  123190. rc = SQLITE_ERROR;
  123191. }
  123192. bNoDocsize = 1;
  123193. break;
  123194. case 1: /* PREFIX */
  123195. sqlite3_free(zPrefix);
  123196. zPrefix = zVal;
  123197. zVal = 0;
  123198. break;
  123199. case 2: /* COMPRESS */
  123200. sqlite3_free(zCompress);
  123201. zCompress = zVal;
  123202. zVal = 0;
  123203. break;
  123204. case 3: /* UNCOMPRESS */
  123205. sqlite3_free(zUncompress);
  123206. zUncompress = zVal;
  123207. zVal = 0;
  123208. break;
  123209. case 4: /* ORDER */
  123210. if( (strlen(zVal)!=3 || sqlite3_strnicmp(zVal, "asc", 3))
  123211. && (strlen(zVal)!=4 || sqlite3_strnicmp(zVal, "desc", 4))
  123212. ){
  123213. *pzErr = sqlite3_mprintf("unrecognized order: %s", zVal);
  123214. rc = SQLITE_ERROR;
  123215. }
  123216. bDescIdx = (zVal[0]=='d' || zVal[0]=='D');
  123217. break;
  123218. case 5: /* CONTENT */
  123219. sqlite3_free(zContent);
  123220. zContent = zVal;
  123221. zVal = 0;
  123222. break;
  123223. case 6: /* LANGUAGEID */
  123224. assert( iOpt==6 );
  123225. sqlite3_free(zLanguageid);
  123226. zLanguageid = zVal;
  123227. zVal = 0;
  123228. break;
  123229. case 7: /* NOTINDEXED */
  123230. azNotindexed[nNotindexed++] = zVal;
  123231. zVal = 0;
  123232. break;
  123233. }
  123234. }
  123235. sqlite3_free(zVal);
  123236. }
  123237. }
  123238. /* Otherwise, the argument is a column name. */
  123239. else {
  123240. nString += (int)(strlen(z) + 1);
  123241. aCol[nCol++] = z;
  123242. }
  123243. }
  123244. /* If a content=xxx option was specified, the following:
  123245. **
  123246. ** 1. Ignore any compress= and uncompress= options.
  123247. **
  123248. ** 2. If no column names were specified as part of the CREATE VIRTUAL
  123249. ** TABLE statement, use all columns from the content table.
  123250. */
  123251. if( rc==SQLITE_OK && zContent ){
  123252. sqlite3_free(zCompress);
  123253. sqlite3_free(zUncompress);
  123254. zCompress = 0;
  123255. zUncompress = 0;
  123256. if( nCol==0 ){
  123257. sqlite3_free((void*)aCol);
  123258. aCol = 0;
  123259. rc = fts3ContentColumns(db, argv[1], zContent, &aCol, &nCol, &nString);
  123260. /* If a languageid= option was specified, remove the language id
  123261. ** column from the aCol[] array. */
  123262. if( rc==SQLITE_OK && zLanguageid ){
  123263. int j;
  123264. for(j=0; j<nCol; j++){
  123265. if( sqlite3_stricmp(zLanguageid, aCol[j])==0 ){
  123266. int k;
  123267. for(k=j; k<nCol; k++) aCol[k] = aCol[k+1];
  123268. nCol--;
  123269. break;
  123270. }
  123271. }
  123272. }
  123273. }
  123274. }
  123275. if( rc!=SQLITE_OK ) goto fts3_init_out;
  123276. if( nCol==0 ){
  123277. assert( nString==0 );
  123278. aCol[0] = "content";
  123279. nString = 8;
  123280. nCol = 1;
  123281. }
  123282. if( pTokenizer==0 ){
  123283. rc = sqlite3Fts3InitTokenizer(pHash, "simple", &pTokenizer, pzErr);
  123284. if( rc!=SQLITE_OK ) goto fts3_init_out;
  123285. }
  123286. assert( pTokenizer );
  123287. rc = fts3PrefixParameter(zPrefix, &nIndex, &aIndex);
  123288. if( rc==SQLITE_ERROR ){
  123289. assert( zPrefix );
  123290. *pzErr = sqlite3_mprintf("error parsing prefix parameter: %s", zPrefix);
  123291. }
  123292. if( rc!=SQLITE_OK ) goto fts3_init_out;
  123293. /* Allocate and populate the Fts3Table structure. */
  123294. nByte = sizeof(Fts3Table) + /* Fts3Table */
  123295. nCol * sizeof(char *) + /* azColumn */
  123296. nIndex * sizeof(struct Fts3Index) + /* aIndex */
  123297. nCol * sizeof(u8) + /* abNotindexed */
  123298. nName + /* zName */
  123299. nDb + /* zDb */
  123300. nString; /* Space for azColumn strings */
  123301. p = (Fts3Table*)sqlite3_malloc(nByte);
  123302. if( p==0 ){
  123303. rc = SQLITE_NOMEM;
  123304. goto fts3_init_out;
  123305. }
  123306. memset(p, 0, nByte);
  123307. p->db = db;
  123308. p->nColumn = nCol;
  123309. p->nPendingData = 0;
  123310. p->azColumn = (char **)&p[1];
  123311. p->pTokenizer = pTokenizer;
  123312. p->nMaxPendingData = FTS3_MAX_PENDING_DATA;
  123313. p->bHasDocsize = (isFts4 && bNoDocsize==0);
  123314. p->bHasStat = isFts4;
  123315. p->bFts4 = isFts4;
  123316. p->bDescIdx = bDescIdx;
  123317. p->nAutoincrmerge = 0xff; /* 0xff means setting unknown */
  123318. p->zContentTbl = zContent;
  123319. p->zLanguageid = zLanguageid;
  123320. zContent = 0;
  123321. zLanguageid = 0;
  123322. TESTONLY( p->inTransaction = -1 );
  123323. TESTONLY( p->mxSavepoint = -1 );
  123324. p->aIndex = (struct Fts3Index *)&p->azColumn[nCol];
  123325. memcpy(p->aIndex, aIndex, sizeof(struct Fts3Index) * nIndex);
  123326. p->nIndex = nIndex;
  123327. for(i=0; i<nIndex; i++){
  123328. fts3HashInit(&p->aIndex[i].hPending, FTS3_HASH_STRING, 1);
  123329. }
  123330. p->abNotindexed = (u8 *)&p->aIndex[nIndex];
  123331. /* Fill in the zName and zDb fields of the vtab structure. */
  123332. zCsr = (char *)&p->abNotindexed[nCol];
  123333. p->zName = zCsr;
  123334. memcpy(zCsr, argv[2], nName);
  123335. zCsr += nName;
  123336. p->zDb = zCsr;
  123337. memcpy(zCsr, argv[1], nDb);
  123338. zCsr += nDb;
  123339. /* Fill in the azColumn array */
  123340. for(iCol=0; iCol<nCol; iCol++){
  123341. char *z;
  123342. int n = 0;
  123343. z = (char *)sqlite3Fts3NextToken(aCol[iCol], &n);
  123344. memcpy(zCsr, z, n);
  123345. zCsr[n] = '\0';
  123346. sqlite3Fts3Dequote(zCsr);
  123347. p->azColumn[iCol] = zCsr;
  123348. zCsr += n+1;
  123349. assert( zCsr <= &((char *)p)[nByte] );
  123350. }
  123351. /* Fill in the abNotindexed array */
  123352. for(iCol=0; iCol<nCol; iCol++){
  123353. int n = (int)strlen(p->azColumn[iCol]);
  123354. for(i=0; i<nNotindexed; i++){
  123355. char *zNot = azNotindexed[i];
  123356. if( zNot && n==(int)strlen(zNot)
  123357. && 0==sqlite3_strnicmp(p->azColumn[iCol], zNot, n)
  123358. ){
  123359. p->abNotindexed[iCol] = 1;
  123360. sqlite3_free(zNot);
  123361. azNotindexed[i] = 0;
  123362. }
  123363. }
  123364. }
  123365. for(i=0; i<nNotindexed; i++){
  123366. if( azNotindexed[i] ){
  123367. *pzErr = sqlite3_mprintf("no such column: %s", azNotindexed[i]);
  123368. rc = SQLITE_ERROR;
  123369. }
  123370. }
  123371. if( rc==SQLITE_OK && (zCompress==0)!=(zUncompress==0) ){
  123372. char const *zMiss = (zCompress==0 ? "compress" : "uncompress");
  123373. rc = SQLITE_ERROR;
  123374. *pzErr = sqlite3_mprintf("missing %s parameter in fts4 constructor", zMiss);
  123375. }
  123376. p->zReadExprlist = fts3ReadExprList(p, zUncompress, &rc);
  123377. p->zWriteExprlist = fts3WriteExprList(p, zCompress, &rc);
  123378. if( rc!=SQLITE_OK ) goto fts3_init_out;
  123379. /* If this is an xCreate call, create the underlying tables in the
  123380. ** database. TODO: For xConnect(), it could verify that said tables exist.
  123381. */
  123382. if( isCreate ){
  123383. rc = fts3CreateTables(p);
  123384. }
  123385. /* Check to see if a legacy fts3 table has been "upgraded" by the
  123386. ** addition of a %_stat table so that it can use incremental merge.
  123387. */
  123388. if( !isFts4 && !isCreate ){
  123389. p->bHasStat = 2;
  123390. }
  123391. /* Figure out the page-size for the database. This is required in order to
  123392. ** estimate the cost of loading large doclists from the database. */
  123393. fts3DatabasePageSize(&rc, p);
  123394. p->nNodeSize = p->nPgsz-35;
  123395. /* Declare the table schema to SQLite. */
  123396. fts3DeclareVtab(&rc, p);
  123397. fts3_init_out:
  123398. sqlite3_free(zPrefix);
  123399. sqlite3_free(aIndex);
  123400. sqlite3_free(zCompress);
  123401. sqlite3_free(zUncompress);
  123402. sqlite3_free(zContent);
  123403. sqlite3_free(zLanguageid);
  123404. for(i=0; i<nNotindexed; i++) sqlite3_free(azNotindexed[i]);
  123405. sqlite3_free((void *)aCol);
  123406. sqlite3_free((void *)azNotindexed);
  123407. if( rc!=SQLITE_OK ){
  123408. if( p ){
  123409. fts3DisconnectMethod((sqlite3_vtab *)p);
  123410. }else if( pTokenizer ){
  123411. pTokenizer->pModule->xDestroy(pTokenizer);
  123412. }
  123413. }else{
  123414. assert( p->pSegments==0 );
  123415. *ppVTab = &p->base;
  123416. }
  123417. return rc;
  123418. }
  123419. /*
  123420. ** The xConnect() and xCreate() methods for the virtual table. All the
  123421. ** work is done in function fts3InitVtab().
  123422. */
  123423. static int fts3ConnectMethod(
  123424. sqlite3 *db, /* Database connection */
  123425. void *pAux, /* Pointer to tokenizer hash table */
  123426. int argc, /* Number of elements in argv array */
  123427. const char * const *argv, /* xCreate/xConnect argument array */
  123428. sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
  123429. char **pzErr /* OUT: sqlite3_malloc'd error message */
  123430. ){
  123431. return fts3InitVtab(0, db, pAux, argc, argv, ppVtab, pzErr);
  123432. }
  123433. static int fts3CreateMethod(
  123434. sqlite3 *db, /* Database connection */
  123435. void *pAux, /* Pointer to tokenizer hash table */
  123436. int argc, /* Number of elements in argv array */
  123437. const char * const *argv, /* xCreate/xConnect argument array */
  123438. sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
  123439. char **pzErr /* OUT: sqlite3_malloc'd error message */
  123440. ){
  123441. return fts3InitVtab(1, db, pAux, argc, argv, ppVtab, pzErr);
  123442. }
  123443. /*
  123444. ** Set the pIdxInfo->estimatedRows variable to nRow. Unless this
  123445. ** extension is currently being used by a version of SQLite too old to
  123446. ** support estimatedRows. In that case this function is a no-op.
  123447. */
  123448. static void fts3SetEstimatedRows(sqlite3_index_info *pIdxInfo, i64 nRow){
  123449. #if SQLITE_VERSION_NUMBER>=3008002
  123450. if( sqlite3_libversion_number()>=3008002 ){
  123451. pIdxInfo->estimatedRows = nRow;
  123452. }
  123453. #endif
  123454. }
  123455. /*
  123456. ** Implementation of the xBestIndex method for FTS3 tables. There
  123457. ** are three possible strategies, in order of preference:
  123458. **
  123459. ** 1. Direct lookup by rowid or docid.
  123460. ** 2. Full-text search using a MATCH operator on a non-docid column.
  123461. ** 3. Linear scan of %_content table.
  123462. */
  123463. static int fts3BestIndexMethod(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){
  123464. Fts3Table *p = (Fts3Table *)pVTab;
  123465. int i; /* Iterator variable */
  123466. int iCons = -1; /* Index of constraint to use */
  123467. int iLangidCons = -1; /* Index of langid=x constraint, if present */
  123468. int iDocidGe = -1; /* Index of docid>=x constraint, if present */
  123469. int iDocidLe = -1; /* Index of docid<=x constraint, if present */
  123470. int iIdx;
  123471. /* By default use a full table scan. This is an expensive option,
  123472. ** so search through the constraints to see if a more efficient
  123473. ** strategy is possible.
  123474. */
  123475. pInfo->idxNum = FTS3_FULLSCAN_SEARCH;
  123476. pInfo->estimatedCost = 5000000;
  123477. for(i=0; i<pInfo->nConstraint; i++){
  123478. int bDocid; /* True if this constraint is on docid */
  123479. struct sqlite3_index_constraint *pCons = &pInfo->aConstraint[i];
  123480. if( pCons->usable==0 ){
  123481. if( pCons->op==SQLITE_INDEX_CONSTRAINT_MATCH ){
  123482. /* There exists an unusable MATCH constraint. This means that if
  123483. ** the planner does elect to use the results of this call as part
  123484. ** of the overall query plan the user will see an "unable to use
  123485. ** function MATCH in the requested context" error. To discourage
  123486. ** this, return a very high cost here. */
  123487. pInfo->idxNum = FTS3_FULLSCAN_SEARCH;
  123488. pInfo->estimatedCost = 1e50;
  123489. fts3SetEstimatedRows(pInfo, ((sqlite3_int64)1) << 50);
  123490. return SQLITE_OK;
  123491. }
  123492. continue;
  123493. }
  123494. bDocid = (pCons->iColumn<0 || pCons->iColumn==p->nColumn+1);
  123495. /* A direct lookup on the rowid or docid column. Assign a cost of 1.0. */
  123496. if( iCons<0 && pCons->op==SQLITE_INDEX_CONSTRAINT_EQ && bDocid ){
  123497. pInfo->idxNum = FTS3_DOCID_SEARCH;
  123498. pInfo->estimatedCost = 1.0;
  123499. iCons = i;
  123500. }
  123501. /* A MATCH constraint. Use a full-text search.
  123502. **
  123503. ** If there is more than one MATCH constraint available, use the first
  123504. ** one encountered. If there is both a MATCH constraint and a direct
  123505. ** rowid/docid lookup, prefer the MATCH strategy. This is done even
  123506. ** though the rowid/docid lookup is faster than a MATCH query, selecting
  123507. ** it would lead to an "unable to use function MATCH in the requested
  123508. ** context" error.
  123509. */
  123510. if( pCons->op==SQLITE_INDEX_CONSTRAINT_MATCH
  123511. && pCons->iColumn>=0 && pCons->iColumn<=p->nColumn
  123512. ){
  123513. pInfo->idxNum = FTS3_FULLTEXT_SEARCH + pCons->iColumn;
  123514. pInfo->estimatedCost = 2.0;
  123515. iCons = i;
  123516. }
  123517. /* Equality constraint on the langid column */
  123518. if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ
  123519. && pCons->iColumn==p->nColumn + 2
  123520. ){
  123521. iLangidCons = i;
  123522. }
  123523. if( bDocid ){
  123524. switch( pCons->op ){
  123525. case SQLITE_INDEX_CONSTRAINT_GE:
  123526. case SQLITE_INDEX_CONSTRAINT_GT:
  123527. iDocidGe = i;
  123528. break;
  123529. case SQLITE_INDEX_CONSTRAINT_LE:
  123530. case SQLITE_INDEX_CONSTRAINT_LT:
  123531. iDocidLe = i;
  123532. break;
  123533. }
  123534. }
  123535. }
  123536. iIdx = 1;
  123537. if( iCons>=0 ){
  123538. pInfo->aConstraintUsage[iCons].argvIndex = iIdx++;
  123539. pInfo->aConstraintUsage[iCons].omit = 1;
  123540. }
  123541. if( iLangidCons>=0 ){
  123542. pInfo->idxNum |= FTS3_HAVE_LANGID;
  123543. pInfo->aConstraintUsage[iLangidCons].argvIndex = iIdx++;
  123544. }
  123545. if( iDocidGe>=0 ){
  123546. pInfo->idxNum |= FTS3_HAVE_DOCID_GE;
  123547. pInfo->aConstraintUsage[iDocidGe].argvIndex = iIdx++;
  123548. }
  123549. if( iDocidLe>=0 ){
  123550. pInfo->idxNum |= FTS3_HAVE_DOCID_LE;
  123551. pInfo->aConstraintUsage[iDocidLe].argvIndex = iIdx++;
  123552. }
  123553. /* Regardless of the strategy selected, FTS can deliver rows in rowid (or
  123554. ** docid) order. Both ascending and descending are possible.
  123555. */
  123556. if( pInfo->nOrderBy==1 ){
  123557. struct sqlite3_index_orderby *pOrder = &pInfo->aOrderBy[0];
  123558. if( pOrder->iColumn<0 || pOrder->iColumn==p->nColumn+1 ){
  123559. if( pOrder->desc ){
  123560. pInfo->idxStr = "DESC";
  123561. }else{
  123562. pInfo->idxStr = "ASC";
  123563. }
  123564. pInfo->orderByConsumed = 1;
  123565. }
  123566. }
  123567. assert( p->pSegments==0 );
  123568. return SQLITE_OK;
  123569. }
  123570. /*
  123571. ** Implementation of xOpen method.
  123572. */
  123573. static int fts3OpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
  123574. sqlite3_vtab_cursor *pCsr; /* Allocated cursor */
  123575. UNUSED_PARAMETER(pVTab);
  123576. /* Allocate a buffer large enough for an Fts3Cursor structure. If the
  123577. ** allocation succeeds, zero it and return SQLITE_OK. Otherwise,
  123578. ** if the allocation fails, return SQLITE_NOMEM.
  123579. */
  123580. *ppCsr = pCsr = (sqlite3_vtab_cursor *)sqlite3_malloc(sizeof(Fts3Cursor));
  123581. if( !pCsr ){
  123582. return SQLITE_NOMEM;
  123583. }
  123584. memset(pCsr, 0, sizeof(Fts3Cursor));
  123585. return SQLITE_OK;
  123586. }
  123587. /*
  123588. ** Close the cursor. For additional information see the documentation
  123589. ** on the xClose method of the virtual table interface.
  123590. */
  123591. static int fts3CloseMethod(sqlite3_vtab_cursor *pCursor){
  123592. Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
  123593. assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
  123594. sqlite3_finalize(pCsr->pStmt);
  123595. sqlite3Fts3ExprFree(pCsr->pExpr);
  123596. sqlite3Fts3FreeDeferredTokens(pCsr);
  123597. sqlite3_free(pCsr->aDoclist);
  123598. sqlite3_free(pCsr->aMatchinfo);
  123599. assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
  123600. sqlite3_free(pCsr);
  123601. return SQLITE_OK;
  123602. }
  123603. /*
  123604. ** If pCsr->pStmt has not been prepared (i.e. if pCsr->pStmt==0), then
  123605. ** compose and prepare an SQL statement of the form:
  123606. **
  123607. ** "SELECT <columns> FROM %_content WHERE rowid = ?"
  123608. **
  123609. ** (or the equivalent for a content=xxx table) and set pCsr->pStmt to
  123610. ** it. If an error occurs, return an SQLite error code.
  123611. **
  123612. ** Otherwise, set *ppStmt to point to pCsr->pStmt and return SQLITE_OK.
  123613. */
  123614. static int fts3CursorSeekStmt(Fts3Cursor *pCsr, sqlite3_stmt **ppStmt){
  123615. int rc = SQLITE_OK;
  123616. if( pCsr->pStmt==0 ){
  123617. Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
  123618. char *zSql;
  123619. zSql = sqlite3_mprintf("SELECT %s WHERE rowid = ?", p->zReadExprlist);
  123620. if( !zSql ) return SQLITE_NOMEM;
  123621. rc = sqlite3_prepare_v2(p->db, zSql, -1, &pCsr->pStmt, 0);
  123622. sqlite3_free(zSql);
  123623. }
  123624. *ppStmt = pCsr->pStmt;
  123625. return rc;
  123626. }
  123627. /*
  123628. ** Position the pCsr->pStmt statement so that it is on the row
  123629. ** of the %_content table that contains the last match. Return
  123630. ** SQLITE_OK on success.
  123631. */
  123632. static int fts3CursorSeek(sqlite3_context *pContext, Fts3Cursor *pCsr){
  123633. int rc = SQLITE_OK;
  123634. if( pCsr->isRequireSeek ){
  123635. sqlite3_stmt *pStmt = 0;
  123636. rc = fts3CursorSeekStmt(pCsr, &pStmt);
  123637. if( rc==SQLITE_OK ){
  123638. sqlite3_bind_int64(pCsr->pStmt, 1, pCsr->iPrevId);
  123639. pCsr->isRequireSeek = 0;
  123640. if( SQLITE_ROW==sqlite3_step(pCsr->pStmt) ){
  123641. return SQLITE_OK;
  123642. }else{
  123643. rc = sqlite3_reset(pCsr->pStmt);
  123644. if( rc==SQLITE_OK && ((Fts3Table *)pCsr->base.pVtab)->zContentTbl==0 ){
  123645. /* If no row was found and no error has occurred, then the %_content
  123646. ** table is missing a row that is present in the full-text index.
  123647. ** The data structures are corrupt. */
  123648. rc = FTS_CORRUPT_VTAB;
  123649. pCsr->isEof = 1;
  123650. }
  123651. }
  123652. }
  123653. }
  123654. if( rc!=SQLITE_OK && pContext ){
  123655. sqlite3_result_error_code(pContext, rc);
  123656. }
  123657. return rc;
  123658. }
  123659. /*
  123660. ** This function is used to process a single interior node when searching
  123661. ** a b-tree for a term or term prefix. The node data is passed to this
  123662. ** function via the zNode/nNode parameters. The term to search for is
  123663. ** passed in zTerm/nTerm.
  123664. **
  123665. ** If piFirst is not NULL, then this function sets *piFirst to the blockid
  123666. ** of the child node that heads the sub-tree that may contain the term.
  123667. **
  123668. ** If piLast is not NULL, then *piLast is set to the right-most child node
  123669. ** that heads a sub-tree that may contain a term for which zTerm/nTerm is
  123670. ** a prefix.
  123671. **
  123672. ** If an OOM error occurs, SQLITE_NOMEM is returned. Otherwise, SQLITE_OK.
  123673. */
  123674. static int fts3ScanInteriorNode(
  123675. const char *zTerm, /* Term to select leaves for */
  123676. int nTerm, /* Size of term zTerm in bytes */
  123677. const char *zNode, /* Buffer containing segment interior node */
  123678. int nNode, /* Size of buffer at zNode */
  123679. sqlite3_int64 *piFirst, /* OUT: Selected child node */
  123680. sqlite3_int64 *piLast /* OUT: Selected child node */
  123681. ){
  123682. int rc = SQLITE_OK; /* Return code */
  123683. const char *zCsr = zNode; /* Cursor to iterate through node */
  123684. const char *zEnd = &zCsr[nNode];/* End of interior node buffer */
  123685. char *zBuffer = 0; /* Buffer to load terms into */
  123686. int nAlloc = 0; /* Size of allocated buffer */
  123687. int isFirstTerm = 1; /* True when processing first term on page */
  123688. sqlite3_int64 iChild; /* Block id of child node to descend to */
  123689. /* Skip over the 'height' varint that occurs at the start of every
  123690. ** interior node. Then load the blockid of the left-child of the b-tree
  123691. ** node into variable iChild.
  123692. **
  123693. ** Even if the data structure on disk is corrupted, this (reading two
  123694. ** varints from the buffer) does not risk an overread. If zNode is a
  123695. ** root node, then the buffer comes from a SELECT statement. SQLite does
  123696. ** not make this guarantee explicitly, but in practice there are always
  123697. ** either more than 20 bytes of allocated space following the nNode bytes of
  123698. ** contents, or two zero bytes. Or, if the node is read from the %_segments
  123699. ** table, then there are always 20 bytes of zeroed padding following the
  123700. ** nNode bytes of content (see sqlite3Fts3ReadBlock() for details).
  123701. */
  123702. zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
  123703. zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
  123704. if( zCsr>zEnd ){
  123705. return FTS_CORRUPT_VTAB;
  123706. }
  123707. while( zCsr<zEnd && (piFirst || piLast) ){
  123708. int cmp; /* memcmp() result */
  123709. int nSuffix; /* Size of term suffix */
  123710. int nPrefix = 0; /* Size of term prefix */
  123711. int nBuffer; /* Total term size */
  123712. /* Load the next term on the node into zBuffer. Use realloc() to expand
  123713. ** the size of zBuffer if required. */
  123714. if( !isFirstTerm ){
  123715. zCsr += fts3GetVarint32(zCsr, &nPrefix);
  123716. }
  123717. isFirstTerm = 0;
  123718. zCsr += fts3GetVarint32(zCsr, &nSuffix);
  123719. if( nPrefix<0 || nSuffix<0 || &zCsr[nSuffix]>zEnd ){
  123720. rc = FTS_CORRUPT_VTAB;
  123721. goto finish_scan;
  123722. }
  123723. if( nPrefix+nSuffix>nAlloc ){
  123724. char *zNew;
  123725. nAlloc = (nPrefix+nSuffix) * 2;
  123726. zNew = (char *)sqlite3_realloc(zBuffer, nAlloc);
  123727. if( !zNew ){
  123728. rc = SQLITE_NOMEM;
  123729. goto finish_scan;
  123730. }
  123731. zBuffer = zNew;
  123732. }
  123733. assert( zBuffer );
  123734. memcpy(&zBuffer[nPrefix], zCsr, nSuffix);
  123735. nBuffer = nPrefix + nSuffix;
  123736. zCsr += nSuffix;
  123737. /* Compare the term we are searching for with the term just loaded from
  123738. ** the interior node. If the specified term is greater than or equal
  123739. ** to the term from the interior node, then all terms on the sub-tree
  123740. ** headed by node iChild are smaller than zTerm. No need to search
  123741. ** iChild.
  123742. **
  123743. ** If the interior node term is larger than the specified term, then
  123744. ** the tree headed by iChild may contain the specified term.
  123745. */
  123746. cmp = memcmp(zTerm, zBuffer, (nBuffer>nTerm ? nTerm : nBuffer));
  123747. if( piFirst && (cmp<0 || (cmp==0 && nBuffer>nTerm)) ){
  123748. *piFirst = iChild;
  123749. piFirst = 0;
  123750. }
  123751. if( piLast && cmp<0 ){
  123752. *piLast = iChild;
  123753. piLast = 0;
  123754. }
  123755. iChild++;
  123756. };
  123757. if( piFirst ) *piFirst = iChild;
  123758. if( piLast ) *piLast = iChild;
  123759. finish_scan:
  123760. sqlite3_free(zBuffer);
  123761. return rc;
  123762. }
  123763. /*
  123764. ** The buffer pointed to by argument zNode (size nNode bytes) contains an
  123765. ** interior node of a b-tree segment. The zTerm buffer (size nTerm bytes)
  123766. ** contains a term. This function searches the sub-tree headed by the zNode
  123767. ** node for the range of leaf nodes that may contain the specified term
  123768. ** or terms for which the specified term is a prefix.
  123769. **
  123770. ** If piLeaf is not NULL, then *piLeaf is set to the blockid of the
  123771. ** left-most leaf node in the tree that may contain the specified term.
  123772. ** If piLeaf2 is not NULL, then *piLeaf2 is set to the blockid of the
  123773. ** right-most leaf node that may contain a term for which the specified
  123774. ** term is a prefix.
  123775. **
  123776. ** It is possible that the range of returned leaf nodes does not contain
  123777. ** the specified term or any terms for which it is a prefix. However, if the
  123778. ** segment does contain any such terms, they are stored within the identified
  123779. ** range. Because this function only inspects interior segment nodes (and
  123780. ** never loads leaf nodes into memory), it is not possible to be sure.
  123781. **
  123782. ** If an error occurs, an error code other than SQLITE_OK is returned.
  123783. */
  123784. static int fts3SelectLeaf(
  123785. Fts3Table *p, /* Virtual table handle */
  123786. const char *zTerm, /* Term to select leaves for */
  123787. int nTerm, /* Size of term zTerm in bytes */
  123788. const char *zNode, /* Buffer containing segment interior node */
  123789. int nNode, /* Size of buffer at zNode */
  123790. sqlite3_int64 *piLeaf, /* Selected leaf node */
  123791. sqlite3_int64 *piLeaf2 /* Selected leaf node */
  123792. ){
  123793. int rc; /* Return code */
  123794. int iHeight; /* Height of this node in tree */
  123795. assert( piLeaf || piLeaf2 );
  123796. fts3GetVarint32(zNode, &iHeight);
  123797. rc = fts3ScanInteriorNode(zTerm, nTerm, zNode, nNode, piLeaf, piLeaf2);
  123798. assert( !piLeaf2 || !piLeaf || rc!=SQLITE_OK || (*piLeaf<=*piLeaf2) );
  123799. if( rc==SQLITE_OK && iHeight>1 ){
  123800. char *zBlob = 0; /* Blob read from %_segments table */
  123801. int nBlob; /* Size of zBlob in bytes */
  123802. if( piLeaf && piLeaf2 && (*piLeaf!=*piLeaf2) ){
  123803. rc = sqlite3Fts3ReadBlock(p, *piLeaf, &zBlob, &nBlob, 0);
  123804. if( rc==SQLITE_OK ){
  123805. rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, 0);
  123806. }
  123807. sqlite3_free(zBlob);
  123808. piLeaf = 0;
  123809. zBlob = 0;
  123810. }
  123811. if( rc==SQLITE_OK ){
  123812. rc = sqlite3Fts3ReadBlock(p, piLeaf?*piLeaf:*piLeaf2, &zBlob, &nBlob, 0);
  123813. }
  123814. if( rc==SQLITE_OK ){
  123815. rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, piLeaf2);
  123816. }
  123817. sqlite3_free(zBlob);
  123818. }
  123819. return rc;
  123820. }
  123821. /*
  123822. ** This function is used to create delta-encoded serialized lists of FTS3
  123823. ** varints. Each call to this function appends a single varint to a list.
  123824. */
  123825. static void fts3PutDeltaVarint(
  123826. char **pp, /* IN/OUT: Output pointer */
  123827. sqlite3_int64 *piPrev, /* IN/OUT: Previous value written to list */
  123828. sqlite3_int64 iVal /* Write this value to the list */
  123829. ){
  123830. assert( iVal-*piPrev > 0 || (*piPrev==0 && iVal==0) );
  123831. *pp += sqlite3Fts3PutVarint(*pp, iVal-*piPrev);
  123832. *piPrev = iVal;
  123833. }
  123834. /*
  123835. ** When this function is called, *ppPoslist is assumed to point to the
  123836. ** start of a position-list. After it returns, *ppPoslist points to the
  123837. ** first byte after the position-list.
  123838. **
  123839. ** A position list is list of positions (delta encoded) and columns for
  123840. ** a single document record of a doclist. So, in other words, this
  123841. ** routine advances *ppPoslist so that it points to the next docid in
  123842. ** the doclist, or to the first byte past the end of the doclist.
  123843. **
  123844. ** If pp is not NULL, then the contents of the position list are copied
  123845. ** to *pp. *pp is set to point to the first byte past the last byte copied
  123846. ** before this function returns.
  123847. */
  123848. static void fts3PoslistCopy(char **pp, char **ppPoslist){
  123849. char *pEnd = *ppPoslist;
  123850. char c = 0;
  123851. /* The end of a position list is marked by a zero encoded as an FTS3
  123852. ** varint. A single POS_END (0) byte. Except, if the 0 byte is preceded by
  123853. ** a byte with the 0x80 bit set, then it is not a varint 0, but the tail
  123854. ** of some other, multi-byte, value.
  123855. **
  123856. ** The following while-loop moves pEnd to point to the first byte that is not
  123857. ** immediately preceded by a byte with the 0x80 bit set. Then increments
  123858. ** pEnd once more so that it points to the byte immediately following the
  123859. ** last byte in the position-list.
  123860. */
  123861. while( *pEnd | c ){
  123862. c = *pEnd++ & 0x80;
  123863. testcase( c!=0 && (*pEnd)==0 );
  123864. }
  123865. pEnd++; /* Advance past the POS_END terminator byte */
  123866. if( pp ){
  123867. int n = (int)(pEnd - *ppPoslist);
  123868. char *p = *pp;
  123869. memcpy(p, *ppPoslist, n);
  123870. p += n;
  123871. *pp = p;
  123872. }
  123873. *ppPoslist = pEnd;
  123874. }
  123875. /*
  123876. ** When this function is called, *ppPoslist is assumed to point to the
  123877. ** start of a column-list. After it returns, *ppPoslist points to the
  123878. ** to the terminator (POS_COLUMN or POS_END) byte of the column-list.
  123879. **
  123880. ** A column-list is list of delta-encoded positions for a single column
  123881. ** within a single document within a doclist.
  123882. **
  123883. ** The column-list is terminated either by a POS_COLUMN varint (1) or
  123884. ** a POS_END varint (0). This routine leaves *ppPoslist pointing to
  123885. ** the POS_COLUMN or POS_END that terminates the column-list.
  123886. **
  123887. ** If pp is not NULL, then the contents of the column-list are copied
  123888. ** to *pp. *pp is set to point to the first byte past the last byte copied
  123889. ** before this function returns. The POS_COLUMN or POS_END terminator
  123890. ** is not copied into *pp.
  123891. */
  123892. static void fts3ColumnlistCopy(char **pp, char **ppPoslist){
  123893. char *pEnd = *ppPoslist;
  123894. char c = 0;
  123895. /* A column-list is terminated by either a 0x01 or 0x00 byte that is
  123896. ** not part of a multi-byte varint.
  123897. */
  123898. while( 0xFE & (*pEnd | c) ){
  123899. c = *pEnd++ & 0x80;
  123900. testcase( c!=0 && ((*pEnd)&0xfe)==0 );
  123901. }
  123902. if( pp ){
  123903. int n = (int)(pEnd - *ppPoslist);
  123904. char *p = *pp;
  123905. memcpy(p, *ppPoslist, n);
  123906. p += n;
  123907. *pp = p;
  123908. }
  123909. *ppPoslist = pEnd;
  123910. }
  123911. /*
  123912. ** Value used to signify the end of an position-list. This is safe because
  123913. ** it is not possible to have a document with 2^31 terms.
  123914. */
  123915. #define POSITION_LIST_END 0x7fffffff
  123916. /*
  123917. ** This function is used to help parse position-lists. When this function is
  123918. ** called, *pp may point to the start of the next varint in the position-list
  123919. ** being parsed, or it may point to 1 byte past the end of the position-list
  123920. ** (in which case **pp will be a terminator bytes POS_END (0) or
  123921. ** (1)).
  123922. **
  123923. ** If *pp points past the end of the current position-list, set *pi to
  123924. ** POSITION_LIST_END and return. Otherwise, read the next varint from *pp,
  123925. ** increment the current value of *pi by the value read, and set *pp to
  123926. ** point to the next value before returning.
  123927. **
  123928. ** Before calling this routine *pi must be initialized to the value of
  123929. ** the previous position, or zero if we are reading the first position
  123930. ** in the position-list. Because positions are delta-encoded, the value
  123931. ** of the previous position is needed in order to compute the value of
  123932. ** the next position.
  123933. */
  123934. static void fts3ReadNextPos(
  123935. char **pp, /* IN/OUT: Pointer into position-list buffer */
  123936. sqlite3_int64 *pi /* IN/OUT: Value read from position-list */
  123937. ){
  123938. if( (**pp)&0xFE ){
  123939. fts3GetDeltaVarint(pp, pi);
  123940. *pi -= 2;
  123941. }else{
  123942. *pi = POSITION_LIST_END;
  123943. }
  123944. }
  123945. /*
  123946. ** If parameter iCol is not 0, write an POS_COLUMN (1) byte followed by
  123947. ** the value of iCol encoded as a varint to *pp. This will start a new
  123948. ** column list.
  123949. **
  123950. ** Set *pp to point to the byte just after the last byte written before
  123951. ** returning (do not modify it if iCol==0). Return the total number of bytes
  123952. ** written (0 if iCol==0).
  123953. */
  123954. static int fts3PutColNumber(char **pp, int iCol){
  123955. int n = 0; /* Number of bytes written */
  123956. if( iCol ){
  123957. char *p = *pp; /* Output pointer */
  123958. n = 1 + sqlite3Fts3PutVarint(&p[1], iCol);
  123959. *p = 0x01;
  123960. *pp = &p[n];
  123961. }
  123962. return n;
  123963. }
  123964. /*
  123965. ** Compute the union of two position lists. The output written
  123966. ** into *pp contains all positions of both *pp1 and *pp2 in sorted
  123967. ** order and with any duplicates removed. All pointers are
  123968. ** updated appropriately. The caller is responsible for insuring
  123969. ** that there is enough space in *pp to hold the complete output.
  123970. */
  123971. static void fts3PoslistMerge(
  123972. char **pp, /* Output buffer */
  123973. char **pp1, /* Left input list */
  123974. char **pp2 /* Right input list */
  123975. ){
  123976. char *p = *pp;
  123977. char *p1 = *pp1;
  123978. char *p2 = *pp2;
  123979. while( *p1 || *p2 ){
  123980. int iCol1; /* The current column index in pp1 */
  123981. int iCol2; /* The current column index in pp2 */
  123982. if( *p1==POS_COLUMN ) fts3GetVarint32(&p1[1], &iCol1);
  123983. else if( *p1==POS_END ) iCol1 = POSITION_LIST_END;
  123984. else iCol1 = 0;
  123985. if( *p2==POS_COLUMN ) fts3GetVarint32(&p2[1], &iCol2);
  123986. else if( *p2==POS_END ) iCol2 = POSITION_LIST_END;
  123987. else iCol2 = 0;
  123988. if( iCol1==iCol2 ){
  123989. sqlite3_int64 i1 = 0; /* Last position from pp1 */
  123990. sqlite3_int64 i2 = 0; /* Last position from pp2 */
  123991. sqlite3_int64 iPrev = 0;
  123992. int n = fts3PutColNumber(&p, iCol1);
  123993. p1 += n;
  123994. p2 += n;
  123995. /* At this point, both p1 and p2 point to the start of column-lists
  123996. ** for the same column (the column with index iCol1 and iCol2).
  123997. ** A column-list is a list of non-negative delta-encoded varints, each
  123998. ** incremented by 2 before being stored. Each list is terminated by a
  123999. ** POS_END (0) or POS_COLUMN (1). The following block merges the two lists
  124000. ** and writes the results to buffer p. p is left pointing to the byte
  124001. ** after the list written. No terminator (POS_END or POS_COLUMN) is
  124002. ** written to the output.
  124003. */
  124004. fts3GetDeltaVarint(&p1, &i1);
  124005. fts3GetDeltaVarint(&p2, &i2);
  124006. do {
  124007. fts3PutDeltaVarint(&p, &iPrev, (i1<i2) ? i1 : i2);
  124008. iPrev -= 2;
  124009. if( i1==i2 ){
  124010. fts3ReadNextPos(&p1, &i1);
  124011. fts3ReadNextPos(&p2, &i2);
  124012. }else if( i1<i2 ){
  124013. fts3ReadNextPos(&p1, &i1);
  124014. }else{
  124015. fts3ReadNextPos(&p2, &i2);
  124016. }
  124017. }while( i1!=POSITION_LIST_END || i2!=POSITION_LIST_END );
  124018. }else if( iCol1<iCol2 ){
  124019. p1 += fts3PutColNumber(&p, iCol1);
  124020. fts3ColumnlistCopy(&p, &p1);
  124021. }else{
  124022. p2 += fts3PutColNumber(&p, iCol2);
  124023. fts3ColumnlistCopy(&p, &p2);
  124024. }
  124025. }
  124026. *p++ = POS_END;
  124027. *pp = p;
  124028. *pp1 = p1 + 1;
  124029. *pp2 = p2 + 1;
  124030. }
  124031. /*
  124032. ** This function is used to merge two position lists into one. When it is
  124033. ** called, *pp1 and *pp2 must both point to position lists. A position-list is
  124034. ** the part of a doclist that follows each document id. For example, if a row
  124035. ** contains:
  124036. **
  124037. ** 'a b c'|'x y z'|'a b b a'
  124038. **
  124039. ** Then the position list for this row for token 'b' would consist of:
  124040. **
  124041. ** 0x02 0x01 0x02 0x03 0x03 0x00
  124042. **
  124043. ** When this function returns, both *pp1 and *pp2 are left pointing to the
  124044. ** byte following the 0x00 terminator of their respective position lists.
  124045. **
  124046. ** If isSaveLeft is 0, an entry is added to the output position list for
  124047. ** each position in *pp2 for which there exists one or more positions in
  124048. ** *pp1 so that (pos(*pp2)>pos(*pp1) && pos(*pp2)-pos(*pp1)<=nToken). i.e.
  124049. ** when the *pp1 token appears before the *pp2 token, but not more than nToken
  124050. ** slots before it.
  124051. **
  124052. ** e.g. nToken==1 searches for adjacent positions.
  124053. */
  124054. static int fts3PoslistPhraseMerge(
  124055. char **pp, /* IN/OUT: Preallocated output buffer */
  124056. int nToken, /* Maximum difference in token positions */
  124057. int isSaveLeft, /* Save the left position */
  124058. int isExact, /* If *pp1 is exactly nTokens before *pp2 */
  124059. char **pp1, /* IN/OUT: Left input list */
  124060. char **pp2 /* IN/OUT: Right input list */
  124061. ){
  124062. char *p = *pp;
  124063. char *p1 = *pp1;
  124064. char *p2 = *pp2;
  124065. int iCol1 = 0;
  124066. int iCol2 = 0;
  124067. /* Never set both isSaveLeft and isExact for the same invocation. */
  124068. assert( isSaveLeft==0 || isExact==0 );
  124069. assert( p!=0 && *p1!=0 && *p2!=0 );
  124070. if( *p1==POS_COLUMN ){
  124071. p1++;
  124072. p1 += fts3GetVarint32(p1, &iCol1);
  124073. }
  124074. if( *p2==POS_COLUMN ){
  124075. p2++;
  124076. p2 += fts3GetVarint32(p2, &iCol2);
  124077. }
  124078. while( 1 ){
  124079. if( iCol1==iCol2 ){
  124080. char *pSave = p;
  124081. sqlite3_int64 iPrev = 0;
  124082. sqlite3_int64 iPos1 = 0;
  124083. sqlite3_int64 iPos2 = 0;
  124084. if( iCol1 ){
  124085. *p++ = POS_COLUMN;
  124086. p += sqlite3Fts3PutVarint(p, iCol1);
  124087. }
  124088. assert( *p1!=POS_END && *p1!=POS_COLUMN );
  124089. assert( *p2!=POS_END && *p2!=POS_COLUMN );
  124090. fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
  124091. fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
  124092. while( 1 ){
  124093. if( iPos2==iPos1+nToken
  124094. || (isExact==0 && iPos2>iPos1 && iPos2<=iPos1+nToken)
  124095. ){
  124096. sqlite3_int64 iSave;
  124097. iSave = isSaveLeft ? iPos1 : iPos2;
  124098. fts3PutDeltaVarint(&p, &iPrev, iSave+2); iPrev -= 2;
  124099. pSave = 0;
  124100. assert( p );
  124101. }
  124102. if( (!isSaveLeft && iPos2<=(iPos1+nToken)) || iPos2<=iPos1 ){
  124103. if( (*p2&0xFE)==0 ) break;
  124104. fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
  124105. }else{
  124106. if( (*p1&0xFE)==0 ) break;
  124107. fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
  124108. }
  124109. }
  124110. if( pSave ){
  124111. assert( pp && p );
  124112. p = pSave;
  124113. }
  124114. fts3ColumnlistCopy(0, &p1);
  124115. fts3ColumnlistCopy(0, &p2);
  124116. assert( (*p1&0xFE)==0 && (*p2&0xFE)==0 );
  124117. if( 0==*p1 || 0==*p2 ) break;
  124118. p1++;
  124119. p1 += fts3GetVarint32(p1, &iCol1);
  124120. p2++;
  124121. p2 += fts3GetVarint32(p2, &iCol2);
  124122. }
  124123. /* Advance pointer p1 or p2 (whichever corresponds to the smaller of
  124124. ** iCol1 and iCol2) so that it points to either the 0x00 that marks the
  124125. ** end of the position list, or the 0x01 that precedes the next
  124126. ** column-number in the position list.
  124127. */
  124128. else if( iCol1<iCol2 ){
  124129. fts3ColumnlistCopy(0, &p1);
  124130. if( 0==*p1 ) break;
  124131. p1++;
  124132. p1 += fts3GetVarint32(p1, &iCol1);
  124133. }else{
  124134. fts3ColumnlistCopy(0, &p2);
  124135. if( 0==*p2 ) break;
  124136. p2++;
  124137. p2 += fts3GetVarint32(p2, &iCol2);
  124138. }
  124139. }
  124140. fts3PoslistCopy(0, &p2);
  124141. fts3PoslistCopy(0, &p1);
  124142. *pp1 = p1;
  124143. *pp2 = p2;
  124144. if( *pp==p ){
  124145. return 0;
  124146. }
  124147. *p++ = 0x00;
  124148. *pp = p;
  124149. return 1;
  124150. }
  124151. /*
  124152. ** Merge two position-lists as required by the NEAR operator. The argument
  124153. ** position lists correspond to the left and right phrases of an expression
  124154. ** like:
  124155. **
  124156. ** "phrase 1" NEAR "phrase number 2"
  124157. **
  124158. ** Position list *pp1 corresponds to the left-hand side of the NEAR
  124159. ** expression and *pp2 to the right. As usual, the indexes in the position
  124160. ** lists are the offsets of the last token in each phrase (tokens "1" and "2"
  124161. ** in the example above).
  124162. **
  124163. ** The output position list - written to *pp - is a copy of *pp2 with those
  124164. ** entries that are not sufficiently NEAR entries in *pp1 removed.
  124165. */
  124166. static int fts3PoslistNearMerge(
  124167. char **pp, /* Output buffer */
  124168. char *aTmp, /* Temporary buffer space */
  124169. int nRight, /* Maximum difference in token positions */
  124170. int nLeft, /* Maximum difference in token positions */
  124171. char **pp1, /* IN/OUT: Left input list */
  124172. char **pp2 /* IN/OUT: Right input list */
  124173. ){
  124174. char *p1 = *pp1;
  124175. char *p2 = *pp2;
  124176. char *pTmp1 = aTmp;
  124177. char *pTmp2;
  124178. char *aTmp2;
  124179. int res = 1;
  124180. fts3PoslistPhraseMerge(&pTmp1, nRight, 0, 0, pp1, pp2);
  124181. aTmp2 = pTmp2 = pTmp1;
  124182. *pp1 = p1;
  124183. *pp2 = p2;
  124184. fts3PoslistPhraseMerge(&pTmp2, nLeft, 1, 0, pp2, pp1);
  124185. if( pTmp1!=aTmp && pTmp2!=aTmp2 ){
  124186. fts3PoslistMerge(pp, &aTmp, &aTmp2);
  124187. }else if( pTmp1!=aTmp ){
  124188. fts3PoslistCopy(pp, &aTmp);
  124189. }else if( pTmp2!=aTmp2 ){
  124190. fts3PoslistCopy(pp, &aTmp2);
  124191. }else{
  124192. res = 0;
  124193. }
  124194. return res;
  124195. }
  124196. /*
  124197. ** An instance of this function is used to merge together the (potentially
  124198. ** large number of) doclists for each term that matches a prefix query.
  124199. ** See function fts3TermSelectMerge() for details.
  124200. */
  124201. typedef struct TermSelect TermSelect;
  124202. struct TermSelect {
  124203. char *aaOutput[16]; /* Malloc'd output buffers */
  124204. int anOutput[16]; /* Size each output buffer in bytes */
  124205. };
  124206. /*
  124207. ** This function is used to read a single varint from a buffer. Parameter
  124208. ** pEnd points 1 byte past the end of the buffer. When this function is
  124209. ** called, if *pp points to pEnd or greater, then the end of the buffer
  124210. ** has been reached. In this case *pp is set to 0 and the function returns.
  124211. **
  124212. ** If *pp does not point to or past pEnd, then a single varint is read
  124213. ** from *pp. *pp is then set to point 1 byte past the end of the read varint.
  124214. **
  124215. ** If bDescIdx is false, the value read is added to *pVal before returning.
  124216. ** If it is true, the value read is subtracted from *pVal before this
  124217. ** function returns.
  124218. */
  124219. static void fts3GetDeltaVarint3(
  124220. char **pp, /* IN/OUT: Point to read varint from */
  124221. char *pEnd, /* End of buffer */
  124222. int bDescIdx, /* True if docids are descending */
  124223. sqlite3_int64 *pVal /* IN/OUT: Integer value */
  124224. ){
  124225. if( *pp>=pEnd ){
  124226. *pp = 0;
  124227. }else{
  124228. sqlite3_int64 iVal;
  124229. *pp += sqlite3Fts3GetVarint(*pp, &iVal);
  124230. if( bDescIdx ){
  124231. *pVal -= iVal;
  124232. }else{
  124233. *pVal += iVal;
  124234. }
  124235. }
  124236. }
  124237. /*
  124238. ** This function is used to write a single varint to a buffer. The varint
  124239. ** is written to *pp. Before returning, *pp is set to point 1 byte past the
  124240. ** end of the value written.
  124241. **
  124242. ** If *pbFirst is zero when this function is called, the value written to
  124243. ** the buffer is that of parameter iVal.
  124244. **
  124245. ** If *pbFirst is non-zero when this function is called, then the value
  124246. ** written is either (iVal-*piPrev) (if bDescIdx is zero) or (*piPrev-iVal)
  124247. ** (if bDescIdx is non-zero).
  124248. **
  124249. ** Before returning, this function always sets *pbFirst to 1 and *piPrev
  124250. ** to the value of parameter iVal.
  124251. */
  124252. static void fts3PutDeltaVarint3(
  124253. char **pp, /* IN/OUT: Output pointer */
  124254. int bDescIdx, /* True for descending docids */
  124255. sqlite3_int64 *piPrev, /* IN/OUT: Previous value written to list */
  124256. int *pbFirst, /* IN/OUT: True after first int written */
  124257. sqlite3_int64 iVal /* Write this value to the list */
  124258. ){
  124259. sqlite3_int64 iWrite;
  124260. if( bDescIdx==0 || *pbFirst==0 ){
  124261. iWrite = iVal - *piPrev;
  124262. }else{
  124263. iWrite = *piPrev - iVal;
  124264. }
  124265. assert( *pbFirst || *piPrev==0 );
  124266. assert( *pbFirst==0 || iWrite>0 );
  124267. *pp += sqlite3Fts3PutVarint(*pp, iWrite);
  124268. *piPrev = iVal;
  124269. *pbFirst = 1;
  124270. }
  124271. /*
  124272. ** This macro is used by various functions that merge doclists. The two
  124273. ** arguments are 64-bit docid values. If the value of the stack variable
  124274. ** bDescDoclist is 0 when this macro is invoked, then it returns (i1-i2).
  124275. ** Otherwise, (i2-i1).
  124276. **
  124277. ** Using this makes it easier to write code that can merge doclists that are
  124278. ** sorted in either ascending or descending order.
  124279. */
  124280. #define DOCID_CMP(i1, i2) ((bDescDoclist?-1:1) * (i1-i2))
  124281. /*
  124282. ** This function does an "OR" merge of two doclists (output contains all
  124283. ** positions contained in either argument doclist). If the docids in the
  124284. ** input doclists are sorted in ascending order, parameter bDescDoclist
  124285. ** should be false. If they are sorted in ascending order, it should be
  124286. ** passed a non-zero value.
  124287. **
  124288. ** If no error occurs, *paOut is set to point at an sqlite3_malloc'd buffer
  124289. ** containing the output doclist and SQLITE_OK is returned. In this case
  124290. ** *pnOut is set to the number of bytes in the output doclist.
  124291. **
  124292. ** If an error occurs, an SQLite error code is returned. The output values
  124293. ** are undefined in this case.
  124294. */
  124295. static int fts3DoclistOrMerge(
  124296. int bDescDoclist, /* True if arguments are desc */
  124297. char *a1, int n1, /* First doclist */
  124298. char *a2, int n2, /* Second doclist */
  124299. char **paOut, int *pnOut /* OUT: Malloc'd doclist */
  124300. ){
  124301. sqlite3_int64 i1 = 0;
  124302. sqlite3_int64 i2 = 0;
  124303. sqlite3_int64 iPrev = 0;
  124304. char *pEnd1 = &a1[n1];
  124305. char *pEnd2 = &a2[n2];
  124306. char *p1 = a1;
  124307. char *p2 = a2;
  124308. char *p;
  124309. char *aOut;
  124310. int bFirstOut = 0;
  124311. *paOut = 0;
  124312. *pnOut = 0;
  124313. /* Allocate space for the output. Both the input and output doclists
  124314. ** are delta encoded. If they are in ascending order (bDescDoclist==0),
  124315. ** then the first docid in each list is simply encoded as a varint. For
  124316. ** each subsequent docid, the varint stored is the difference between the
  124317. ** current and previous docid (a positive number - since the list is in
  124318. ** ascending order).
  124319. **
  124320. ** The first docid written to the output is therefore encoded using the
  124321. ** same number of bytes as it is in whichever of the input lists it is
  124322. ** read from. And each subsequent docid read from the same input list
  124323. ** consumes either the same or less bytes as it did in the input (since
  124324. ** the difference between it and the previous value in the output must
  124325. ** be a positive value less than or equal to the delta value read from
  124326. ** the input list). The same argument applies to all but the first docid
  124327. ** read from the 'other' list. And to the contents of all position lists
  124328. ** that will be copied and merged from the input to the output.
  124329. **
  124330. ** However, if the first docid copied to the output is a negative number,
  124331. ** then the encoding of the first docid from the 'other' input list may
  124332. ** be larger in the output than it was in the input (since the delta value
  124333. ** may be a larger positive integer than the actual docid).
  124334. **
  124335. ** The space required to store the output is therefore the sum of the
  124336. ** sizes of the two inputs, plus enough space for exactly one of the input
  124337. ** docids to grow.
  124338. **
  124339. ** A symetric argument may be made if the doclists are in descending
  124340. ** order.
  124341. */
  124342. aOut = sqlite3_malloc(n1+n2+FTS3_VARINT_MAX-1);
  124343. if( !aOut ) return SQLITE_NOMEM;
  124344. p = aOut;
  124345. fts3GetDeltaVarint3(&p1, pEnd1, 0, &i1);
  124346. fts3GetDeltaVarint3(&p2, pEnd2, 0, &i2);
  124347. while( p1 || p2 ){
  124348. sqlite3_int64 iDiff = DOCID_CMP(i1, i2);
  124349. if( p2 && p1 && iDiff==0 ){
  124350. fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
  124351. fts3PoslistMerge(&p, &p1, &p2);
  124352. fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
  124353. fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
  124354. }else if( !p2 || (p1 && iDiff<0) ){
  124355. fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
  124356. fts3PoslistCopy(&p, &p1);
  124357. fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
  124358. }else{
  124359. fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i2);
  124360. fts3PoslistCopy(&p, &p2);
  124361. fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
  124362. }
  124363. }
  124364. *paOut = aOut;
  124365. *pnOut = (int)(p-aOut);
  124366. assert( *pnOut<=n1+n2+FTS3_VARINT_MAX-1 );
  124367. return SQLITE_OK;
  124368. }
  124369. /*
  124370. ** This function does a "phrase" merge of two doclists. In a phrase merge,
  124371. ** the output contains a copy of each position from the right-hand input
  124372. ** doclist for which there is a position in the left-hand input doclist
  124373. ** exactly nDist tokens before it.
  124374. **
  124375. ** If the docids in the input doclists are sorted in ascending order,
  124376. ** parameter bDescDoclist should be false. If they are sorted in ascending
  124377. ** order, it should be passed a non-zero value.
  124378. **
  124379. ** The right-hand input doclist is overwritten by this function.
  124380. */
  124381. static void fts3DoclistPhraseMerge(
  124382. int bDescDoclist, /* True if arguments are desc */
  124383. int nDist, /* Distance from left to right (1=adjacent) */
  124384. char *aLeft, int nLeft, /* Left doclist */
  124385. char *aRight, int *pnRight /* IN/OUT: Right/output doclist */
  124386. ){
  124387. sqlite3_int64 i1 = 0;
  124388. sqlite3_int64 i2 = 0;
  124389. sqlite3_int64 iPrev = 0;
  124390. char *pEnd1 = &aLeft[nLeft];
  124391. char *pEnd2 = &aRight[*pnRight];
  124392. char *p1 = aLeft;
  124393. char *p2 = aRight;
  124394. char *p;
  124395. int bFirstOut = 0;
  124396. char *aOut = aRight;
  124397. assert( nDist>0 );
  124398. p = aOut;
  124399. fts3GetDeltaVarint3(&p1, pEnd1, 0, &i1);
  124400. fts3GetDeltaVarint3(&p2, pEnd2, 0, &i2);
  124401. while( p1 && p2 ){
  124402. sqlite3_int64 iDiff = DOCID_CMP(i1, i2);
  124403. if( iDiff==0 ){
  124404. char *pSave = p;
  124405. sqlite3_int64 iPrevSave = iPrev;
  124406. int bFirstOutSave = bFirstOut;
  124407. fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
  124408. if( 0==fts3PoslistPhraseMerge(&p, nDist, 0, 1, &p1, &p2) ){
  124409. p = pSave;
  124410. iPrev = iPrevSave;
  124411. bFirstOut = bFirstOutSave;
  124412. }
  124413. fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
  124414. fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
  124415. }else if( iDiff<0 ){
  124416. fts3PoslistCopy(0, &p1);
  124417. fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
  124418. }else{
  124419. fts3PoslistCopy(0, &p2);
  124420. fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
  124421. }
  124422. }
  124423. *pnRight = (int)(p - aOut);
  124424. }
  124425. /*
  124426. ** Argument pList points to a position list nList bytes in size. This
  124427. ** function checks to see if the position list contains any entries for
  124428. ** a token in position 0 (of any column). If so, it writes argument iDelta
  124429. ** to the output buffer pOut, followed by a position list consisting only
  124430. ** of the entries from pList at position 0, and terminated by an 0x00 byte.
  124431. ** The value returned is the number of bytes written to pOut (if any).
  124432. */
  124433. SQLITE_PRIVATE int sqlite3Fts3FirstFilter(
  124434. sqlite3_int64 iDelta, /* Varint that may be written to pOut */
  124435. char *pList, /* Position list (no 0x00 term) */
  124436. int nList, /* Size of pList in bytes */
  124437. char *pOut /* Write output here */
  124438. ){
  124439. int nOut = 0;
  124440. int bWritten = 0; /* True once iDelta has been written */
  124441. char *p = pList;
  124442. char *pEnd = &pList[nList];
  124443. if( *p!=0x01 ){
  124444. if( *p==0x02 ){
  124445. nOut += sqlite3Fts3PutVarint(&pOut[nOut], iDelta);
  124446. pOut[nOut++] = 0x02;
  124447. bWritten = 1;
  124448. }
  124449. fts3ColumnlistCopy(0, &p);
  124450. }
  124451. while( p<pEnd && *p==0x01 ){
  124452. sqlite3_int64 iCol;
  124453. p++;
  124454. p += sqlite3Fts3GetVarint(p, &iCol);
  124455. if( *p==0x02 ){
  124456. if( bWritten==0 ){
  124457. nOut += sqlite3Fts3PutVarint(&pOut[nOut], iDelta);
  124458. bWritten = 1;
  124459. }
  124460. pOut[nOut++] = 0x01;
  124461. nOut += sqlite3Fts3PutVarint(&pOut[nOut], iCol);
  124462. pOut[nOut++] = 0x02;
  124463. }
  124464. fts3ColumnlistCopy(0, &p);
  124465. }
  124466. if( bWritten ){
  124467. pOut[nOut++] = 0x00;
  124468. }
  124469. return nOut;
  124470. }
  124471. /*
  124472. ** Merge all doclists in the TermSelect.aaOutput[] array into a single
  124473. ** doclist stored in TermSelect.aaOutput[0]. If successful, delete all
  124474. ** other doclists (except the aaOutput[0] one) and return SQLITE_OK.
  124475. **
  124476. ** If an OOM error occurs, return SQLITE_NOMEM. In this case it is
  124477. ** the responsibility of the caller to free any doclists left in the
  124478. ** TermSelect.aaOutput[] array.
  124479. */
  124480. static int fts3TermSelectFinishMerge(Fts3Table *p, TermSelect *pTS){
  124481. char *aOut = 0;
  124482. int nOut = 0;
  124483. int i;
  124484. /* Loop through the doclists in the aaOutput[] array. Merge them all
  124485. ** into a single doclist.
  124486. */
  124487. for(i=0; i<SizeofArray(pTS->aaOutput); i++){
  124488. if( pTS->aaOutput[i] ){
  124489. if( !aOut ){
  124490. aOut = pTS->aaOutput[i];
  124491. nOut = pTS->anOutput[i];
  124492. pTS->aaOutput[i] = 0;
  124493. }else{
  124494. int nNew;
  124495. char *aNew;
  124496. int rc = fts3DoclistOrMerge(p->bDescIdx,
  124497. pTS->aaOutput[i], pTS->anOutput[i], aOut, nOut, &aNew, &nNew
  124498. );
  124499. if( rc!=SQLITE_OK ){
  124500. sqlite3_free(aOut);
  124501. return rc;
  124502. }
  124503. sqlite3_free(pTS->aaOutput[i]);
  124504. sqlite3_free(aOut);
  124505. pTS->aaOutput[i] = 0;
  124506. aOut = aNew;
  124507. nOut = nNew;
  124508. }
  124509. }
  124510. }
  124511. pTS->aaOutput[0] = aOut;
  124512. pTS->anOutput[0] = nOut;
  124513. return SQLITE_OK;
  124514. }
  124515. /*
  124516. ** Merge the doclist aDoclist/nDoclist into the TermSelect object passed
  124517. ** as the first argument. The merge is an "OR" merge (see function
  124518. ** fts3DoclistOrMerge() for details).
  124519. **
  124520. ** This function is called with the doclist for each term that matches
  124521. ** a queried prefix. It merges all these doclists into one, the doclist
  124522. ** for the specified prefix. Since there can be a very large number of
  124523. ** doclists to merge, the merging is done pair-wise using the TermSelect
  124524. ** object.
  124525. **
  124526. ** This function returns SQLITE_OK if the merge is successful, or an
  124527. ** SQLite error code (SQLITE_NOMEM) if an error occurs.
  124528. */
  124529. static int fts3TermSelectMerge(
  124530. Fts3Table *p, /* FTS table handle */
  124531. TermSelect *pTS, /* TermSelect object to merge into */
  124532. char *aDoclist, /* Pointer to doclist */
  124533. int nDoclist /* Size of aDoclist in bytes */
  124534. ){
  124535. if( pTS->aaOutput[0]==0 ){
  124536. /* If this is the first term selected, copy the doclist to the output
  124537. ** buffer using memcpy(). */
  124538. pTS->aaOutput[0] = sqlite3_malloc(nDoclist);
  124539. pTS->anOutput[0] = nDoclist;
  124540. if( pTS->aaOutput[0] ){
  124541. memcpy(pTS->aaOutput[0], aDoclist, nDoclist);
  124542. }else{
  124543. return SQLITE_NOMEM;
  124544. }
  124545. }else{
  124546. char *aMerge = aDoclist;
  124547. int nMerge = nDoclist;
  124548. int iOut;
  124549. for(iOut=0; iOut<SizeofArray(pTS->aaOutput); iOut++){
  124550. if( pTS->aaOutput[iOut]==0 ){
  124551. assert( iOut>0 );
  124552. pTS->aaOutput[iOut] = aMerge;
  124553. pTS->anOutput[iOut] = nMerge;
  124554. break;
  124555. }else{
  124556. char *aNew;
  124557. int nNew;
  124558. int rc = fts3DoclistOrMerge(p->bDescIdx, aMerge, nMerge,
  124559. pTS->aaOutput[iOut], pTS->anOutput[iOut], &aNew, &nNew
  124560. );
  124561. if( rc!=SQLITE_OK ){
  124562. if( aMerge!=aDoclist ) sqlite3_free(aMerge);
  124563. return rc;
  124564. }
  124565. if( aMerge!=aDoclist ) sqlite3_free(aMerge);
  124566. sqlite3_free(pTS->aaOutput[iOut]);
  124567. pTS->aaOutput[iOut] = 0;
  124568. aMerge = aNew;
  124569. nMerge = nNew;
  124570. if( (iOut+1)==SizeofArray(pTS->aaOutput) ){
  124571. pTS->aaOutput[iOut] = aMerge;
  124572. pTS->anOutput[iOut] = nMerge;
  124573. }
  124574. }
  124575. }
  124576. }
  124577. return SQLITE_OK;
  124578. }
  124579. /*
  124580. ** Append SegReader object pNew to the end of the pCsr->apSegment[] array.
  124581. */
  124582. static int fts3SegReaderCursorAppend(
  124583. Fts3MultiSegReader *pCsr,
  124584. Fts3SegReader *pNew
  124585. ){
  124586. if( (pCsr->nSegment%16)==0 ){
  124587. Fts3SegReader **apNew;
  124588. int nByte = (pCsr->nSegment + 16)*sizeof(Fts3SegReader*);
  124589. apNew = (Fts3SegReader **)sqlite3_realloc(pCsr->apSegment, nByte);
  124590. if( !apNew ){
  124591. sqlite3Fts3SegReaderFree(pNew);
  124592. return SQLITE_NOMEM;
  124593. }
  124594. pCsr->apSegment = apNew;
  124595. }
  124596. pCsr->apSegment[pCsr->nSegment++] = pNew;
  124597. return SQLITE_OK;
  124598. }
  124599. /*
  124600. ** Add seg-reader objects to the Fts3MultiSegReader object passed as the
  124601. ** 8th argument.
  124602. **
  124603. ** This function returns SQLITE_OK if successful, or an SQLite error code
  124604. ** otherwise.
  124605. */
  124606. static int fts3SegReaderCursor(
  124607. Fts3Table *p, /* FTS3 table handle */
  124608. int iLangid, /* Language id */
  124609. int iIndex, /* Index to search (from 0 to p->nIndex-1) */
  124610. int iLevel, /* Level of segments to scan */
  124611. const char *zTerm, /* Term to query for */
  124612. int nTerm, /* Size of zTerm in bytes */
  124613. int isPrefix, /* True for a prefix search */
  124614. int isScan, /* True to scan from zTerm to EOF */
  124615. Fts3MultiSegReader *pCsr /* Cursor object to populate */
  124616. ){
  124617. int rc = SQLITE_OK; /* Error code */
  124618. sqlite3_stmt *pStmt = 0; /* Statement to iterate through segments */
  124619. int rc2; /* Result of sqlite3_reset() */
  124620. /* If iLevel is less than 0 and this is not a scan, include a seg-reader
  124621. ** for the pending-terms. If this is a scan, then this call must be being
  124622. ** made by an fts4aux module, not an FTS table. In this case calling
  124623. ** Fts3SegReaderPending might segfault, as the data structures used by
  124624. ** fts4aux are not completely populated. So it's easiest to filter these
  124625. ** calls out here. */
  124626. if( iLevel<0 && p->aIndex ){
  124627. Fts3SegReader *pSeg = 0;
  124628. rc = sqlite3Fts3SegReaderPending(p, iIndex, zTerm, nTerm, isPrefix, &pSeg);
  124629. if( rc==SQLITE_OK && pSeg ){
  124630. rc = fts3SegReaderCursorAppend(pCsr, pSeg);
  124631. }
  124632. }
  124633. if( iLevel!=FTS3_SEGCURSOR_PENDING ){
  124634. if( rc==SQLITE_OK ){
  124635. rc = sqlite3Fts3AllSegdirs(p, iLangid, iIndex, iLevel, &pStmt);
  124636. }
  124637. while( rc==SQLITE_OK && SQLITE_ROW==(rc = sqlite3_step(pStmt)) ){
  124638. Fts3SegReader *pSeg = 0;
  124639. /* Read the values returned by the SELECT into local variables. */
  124640. sqlite3_int64 iStartBlock = sqlite3_column_int64(pStmt, 1);
  124641. sqlite3_int64 iLeavesEndBlock = sqlite3_column_int64(pStmt, 2);
  124642. sqlite3_int64 iEndBlock = sqlite3_column_int64(pStmt, 3);
  124643. int nRoot = sqlite3_column_bytes(pStmt, 4);
  124644. char const *zRoot = sqlite3_column_blob(pStmt, 4);
  124645. /* If zTerm is not NULL, and this segment is not stored entirely on its
  124646. ** root node, the range of leaves scanned can be reduced. Do this. */
  124647. if( iStartBlock && zTerm ){
  124648. sqlite3_int64 *pi = (isPrefix ? &iLeavesEndBlock : 0);
  124649. rc = fts3SelectLeaf(p, zTerm, nTerm, zRoot, nRoot, &iStartBlock, pi);
  124650. if( rc!=SQLITE_OK ) goto finished;
  124651. if( isPrefix==0 && isScan==0 ) iLeavesEndBlock = iStartBlock;
  124652. }
  124653. rc = sqlite3Fts3SegReaderNew(pCsr->nSegment+1,
  124654. (isPrefix==0 && isScan==0),
  124655. iStartBlock, iLeavesEndBlock,
  124656. iEndBlock, zRoot, nRoot, &pSeg
  124657. );
  124658. if( rc!=SQLITE_OK ) goto finished;
  124659. rc = fts3SegReaderCursorAppend(pCsr, pSeg);
  124660. }
  124661. }
  124662. finished:
  124663. rc2 = sqlite3_reset(pStmt);
  124664. if( rc==SQLITE_DONE ) rc = rc2;
  124665. return rc;
  124666. }
  124667. /*
  124668. ** Set up a cursor object for iterating through a full-text index or a
  124669. ** single level therein.
  124670. */
  124671. SQLITE_PRIVATE int sqlite3Fts3SegReaderCursor(
  124672. Fts3Table *p, /* FTS3 table handle */
  124673. int iLangid, /* Language-id to search */
  124674. int iIndex, /* Index to search (from 0 to p->nIndex-1) */
  124675. int iLevel, /* Level of segments to scan */
  124676. const char *zTerm, /* Term to query for */
  124677. int nTerm, /* Size of zTerm in bytes */
  124678. int isPrefix, /* True for a prefix search */
  124679. int isScan, /* True to scan from zTerm to EOF */
  124680. Fts3MultiSegReader *pCsr /* Cursor object to populate */
  124681. ){
  124682. assert( iIndex>=0 && iIndex<p->nIndex );
  124683. assert( iLevel==FTS3_SEGCURSOR_ALL
  124684. || iLevel==FTS3_SEGCURSOR_PENDING
  124685. || iLevel>=0
  124686. );
  124687. assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
  124688. assert( FTS3_SEGCURSOR_ALL<0 && FTS3_SEGCURSOR_PENDING<0 );
  124689. assert( isPrefix==0 || isScan==0 );
  124690. memset(pCsr, 0, sizeof(Fts3MultiSegReader));
  124691. return fts3SegReaderCursor(
  124692. p, iLangid, iIndex, iLevel, zTerm, nTerm, isPrefix, isScan, pCsr
  124693. );
  124694. }
  124695. /*
  124696. ** In addition to its current configuration, have the Fts3MultiSegReader
  124697. ** passed as the 4th argument also scan the doclist for term zTerm/nTerm.
  124698. **
  124699. ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
  124700. */
  124701. static int fts3SegReaderCursorAddZero(
  124702. Fts3Table *p, /* FTS virtual table handle */
  124703. int iLangid,
  124704. const char *zTerm, /* Term to scan doclist of */
  124705. int nTerm, /* Number of bytes in zTerm */
  124706. Fts3MultiSegReader *pCsr /* Fts3MultiSegReader to modify */
  124707. ){
  124708. return fts3SegReaderCursor(p,
  124709. iLangid, 0, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 0, 0,pCsr
  124710. );
  124711. }
  124712. /*
  124713. ** Open an Fts3MultiSegReader to scan the doclist for term zTerm/nTerm. Or,
  124714. ** if isPrefix is true, to scan the doclist for all terms for which
  124715. ** zTerm/nTerm is a prefix. If successful, return SQLITE_OK and write
  124716. ** a pointer to the new Fts3MultiSegReader to *ppSegcsr. Otherwise, return
  124717. ** an SQLite error code.
  124718. **
  124719. ** It is the responsibility of the caller to free this object by eventually
  124720. ** passing it to fts3SegReaderCursorFree()
  124721. **
  124722. ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
  124723. ** Output parameter *ppSegcsr is set to 0 if an error occurs.
  124724. */
  124725. static int fts3TermSegReaderCursor(
  124726. Fts3Cursor *pCsr, /* Virtual table cursor handle */
  124727. const char *zTerm, /* Term to query for */
  124728. int nTerm, /* Size of zTerm in bytes */
  124729. int isPrefix, /* True for a prefix search */
  124730. Fts3MultiSegReader **ppSegcsr /* OUT: Allocated seg-reader cursor */
  124731. ){
  124732. Fts3MultiSegReader *pSegcsr; /* Object to allocate and return */
  124733. int rc = SQLITE_NOMEM; /* Return code */
  124734. pSegcsr = sqlite3_malloc(sizeof(Fts3MultiSegReader));
  124735. if( pSegcsr ){
  124736. int i;
  124737. int bFound = 0; /* True once an index has been found */
  124738. Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
  124739. if( isPrefix ){
  124740. for(i=1; bFound==0 && i<p->nIndex; i++){
  124741. if( p->aIndex[i].nPrefix==nTerm ){
  124742. bFound = 1;
  124743. rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
  124744. i, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 0, 0, pSegcsr
  124745. );
  124746. pSegcsr->bLookup = 1;
  124747. }
  124748. }
  124749. for(i=1; bFound==0 && i<p->nIndex; i++){
  124750. if( p->aIndex[i].nPrefix==nTerm+1 ){
  124751. bFound = 1;
  124752. rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
  124753. i, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 1, 0, pSegcsr
  124754. );
  124755. if( rc==SQLITE_OK ){
  124756. rc = fts3SegReaderCursorAddZero(
  124757. p, pCsr->iLangid, zTerm, nTerm, pSegcsr
  124758. );
  124759. }
  124760. }
  124761. }
  124762. }
  124763. if( bFound==0 ){
  124764. rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
  124765. 0, FTS3_SEGCURSOR_ALL, zTerm, nTerm, isPrefix, 0, pSegcsr
  124766. );
  124767. pSegcsr->bLookup = !isPrefix;
  124768. }
  124769. }
  124770. *ppSegcsr = pSegcsr;
  124771. return rc;
  124772. }
  124773. /*
  124774. ** Free an Fts3MultiSegReader allocated by fts3TermSegReaderCursor().
  124775. */
  124776. static void fts3SegReaderCursorFree(Fts3MultiSegReader *pSegcsr){
  124777. sqlite3Fts3SegReaderFinish(pSegcsr);
  124778. sqlite3_free(pSegcsr);
  124779. }
  124780. /*
  124781. ** This function retrieves the doclist for the specified term (or term
  124782. ** prefix) from the database.
  124783. */
  124784. static int fts3TermSelect(
  124785. Fts3Table *p, /* Virtual table handle */
  124786. Fts3PhraseToken *pTok, /* Token to query for */
  124787. int iColumn, /* Column to query (or -ve for all columns) */
  124788. int *pnOut, /* OUT: Size of buffer at *ppOut */
  124789. char **ppOut /* OUT: Malloced result buffer */
  124790. ){
  124791. int rc; /* Return code */
  124792. Fts3MultiSegReader *pSegcsr; /* Seg-reader cursor for this term */
  124793. TermSelect tsc; /* Object for pair-wise doclist merging */
  124794. Fts3SegFilter filter; /* Segment term filter configuration */
  124795. pSegcsr = pTok->pSegcsr;
  124796. memset(&tsc, 0, sizeof(TermSelect));
  124797. filter.flags = FTS3_SEGMENT_IGNORE_EMPTY | FTS3_SEGMENT_REQUIRE_POS
  124798. | (pTok->isPrefix ? FTS3_SEGMENT_PREFIX : 0)
  124799. | (pTok->bFirst ? FTS3_SEGMENT_FIRST : 0)
  124800. | (iColumn<p->nColumn ? FTS3_SEGMENT_COLUMN_FILTER : 0);
  124801. filter.iCol = iColumn;
  124802. filter.zTerm = pTok->z;
  124803. filter.nTerm = pTok->n;
  124804. rc = sqlite3Fts3SegReaderStart(p, pSegcsr, &filter);
  124805. while( SQLITE_OK==rc
  124806. && SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, pSegcsr))
  124807. ){
  124808. rc = fts3TermSelectMerge(p, &tsc, pSegcsr->aDoclist, pSegcsr->nDoclist);
  124809. }
  124810. if( rc==SQLITE_OK ){
  124811. rc = fts3TermSelectFinishMerge(p, &tsc);
  124812. }
  124813. if( rc==SQLITE_OK ){
  124814. *ppOut = tsc.aaOutput[0];
  124815. *pnOut = tsc.anOutput[0];
  124816. }else{
  124817. int i;
  124818. for(i=0; i<SizeofArray(tsc.aaOutput); i++){
  124819. sqlite3_free(tsc.aaOutput[i]);
  124820. }
  124821. }
  124822. fts3SegReaderCursorFree(pSegcsr);
  124823. pTok->pSegcsr = 0;
  124824. return rc;
  124825. }
  124826. /*
  124827. ** This function counts the total number of docids in the doclist stored
  124828. ** in buffer aList[], size nList bytes.
  124829. **
  124830. ** If the isPoslist argument is true, then it is assumed that the doclist
  124831. ** contains a position-list following each docid. Otherwise, it is assumed
  124832. ** that the doclist is simply a list of docids stored as delta encoded
  124833. ** varints.
  124834. */
  124835. static int fts3DoclistCountDocids(char *aList, int nList){
  124836. int nDoc = 0; /* Return value */
  124837. if( aList ){
  124838. char *aEnd = &aList[nList]; /* Pointer to one byte after EOF */
  124839. char *p = aList; /* Cursor */
  124840. while( p<aEnd ){
  124841. nDoc++;
  124842. while( (*p++)&0x80 ); /* Skip docid varint */
  124843. fts3PoslistCopy(0, &p); /* Skip over position list */
  124844. }
  124845. }
  124846. return nDoc;
  124847. }
  124848. /*
  124849. ** Advance the cursor to the next row in the %_content table that
  124850. ** matches the search criteria. For a MATCH search, this will be
  124851. ** the next row that matches. For a full-table scan, this will be
  124852. ** simply the next row in the %_content table. For a docid lookup,
  124853. ** this routine simply sets the EOF flag.
  124854. **
  124855. ** Return SQLITE_OK if nothing goes wrong. SQLITE_OK is returned
  124856. ** even if we reach end-of-file. The fts3EofMethod() will be called
  124857. ** subsequently to determine whether or not an EOF was hit.
  124858. */
  124859. static int fts3NextMethod(sqlite3_vtab_cursor *pCursor){
  124860. int rc;
  124861. Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
  124862. if( pCsr->eSearch==FTS3_DOCID_SEARCH || pCsr->eSearch==FTS3_FULLSCAN_SEARCH ){
  124863. if( SQLITE_ROW!=sqlite3_step(pCsr->pStmt) ){
  124864. pCsr->isEof = 1;
  124865. rc = sqlite3_reset(pCsr->pStmt);
  124866. }else{
  124867. pCsr->iPrevId = sqlite3_column_int64(pCsr->pStmt, 0);
  124868. rc = SQLITE_OK;
  124869. }
  124870. }else{
  124871. rc = fts3EvalNext((Fts3Cursor *)pCursor);
  124872. }
  124873. assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
  124874. return rc;
  124875. }
  124876. /*
  124877. ** The following are copied from sqliteInt.h.
  124878. **
  124879. ** Constants for the largest and smallest possible 64-bit signed integers.
  124880. ** These macros are designed to work correctly on both 32-bit and 64-bit
  124881. ** compilers.
  124882. */
  124883. #ifndef SQLITE_AMALGAMATION
  124884. # define LARGEST_INT64 (0xffffffff|(((sqlite3_int64)0x7fffffff)<<32))
  124885. # define SMALLEST_INT64 (((sqlite3_int64)-1) - LARGEST_INT64)
  124886. #endif
  124887. /*
  124888. ** If the numeric type of argument pVal is "integer", then return it
  124889. ** converted to a 64-bit signed integer. Otherwise, return a copy of
  124890. ** the second parameter, iDefault.
  124891. */
  124892. static sqlite3_int64 fts3DocidRange(sqlite3_value *pVal, i64 iDefault){
  124893. if( pVal ){
  124894. int eType = sqlite3_value_numeric_type(pVal);
  124895. if( eType==SQLITE_INTEGER ){
  124896. return sqlite3_value_int64(pVal);
  124897. }
  124898. }
  124899. return iDefault;
  124900. }
  124901. /*
  124902. ** This is the xFilter interface for the virtual table. See
  124903. ** the virtual table xFilter method documentation for additional
  124904. ** information.
  124905. **
  124906. ** If idxNum==FTS3_FULLSCAN_SEARCH then do a full table scan against
  124907. ** the %_content table.
  124908. **
  124909. ** If idxNum==FTS3_DOCID_SEARCH then do a docid lookup for a single entry
  124910. ** in the %_content table.
  124911. **
  124912. ** If idxNum>=FTS3_FULLTEXT_SEARCH then use the full text index. The
  124913. ** column on the left-hand side of the MATCH operator is column
  124914. ** number idxNum-FTS3_FULLTEXT_SEARCH, 0 indexed. argv[0] is the right-hand
  124915. ** side of the MATCH operator.
  124916. */
  124917. static int fts3FilterMethod(
  124918. sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */
  124919. int idxNum, /* Strategy index */
  124920. const char *idxStr, /* Unused */
  124921. int nVal, /* Number of elements in apVal */
  124922. sqlite3_value **apVal /* Arguments for the indexing scheme */
  124923. ){
  124924. int rc;
  124925. char *zSql; /* SQL statement used to access %_content */
  124926. int eSearch;
  124927. Fts3Table *p = (Fts3Table *)pCursor->pVtab;
  124928. Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
  124929. sqlite3_value *pCons = 0; /* The MATCH or rowid constraint, if any */
  124930. sqlite3_value *pLangid = 0; /* The "langid = ?" constraint, if any */
  124931. sqlite3_value *pDocidGe = 0; /* The "docid >= ?" constraint, if any */
  124932. sqlite3_value *pDocidLe = 0; /* The "docid <= ?" constraint, if any */
  124933. int iIdx;
  124934. UNUSED_PARAMETER(idxStr);
  124935. UNUSED_PARAMETER(nVal);
  124936. eSearch = (idxNum & 0x0000FFFF);
  124937. assert( eSearch>=0 && eSearch<=(FTS3_FULLTEXT_SEARCH+p->nColumn) );
  124938. assert( p->pSegments==0 );
  124939. /* Collect arguments into local variables */
  124940. iIdx = 0;
  124941. if( eSearch!=FTS3_FULLSCAN_SEARCH ) pCons = apVal[iIdx++];
  124942. if( idxNum & FTS3_HAVE_LANGID ) pLangid = apVal[iIdx++];
  124943. if( idxNum & FTS3_HAVE_DOCID_GE ) pDocidGe = apVal[iIdx++];
  124944. if( idxNum & FTS3_HAVE_DOCID_LE ) pDocidLe = apVal[iIdx++];
  124945. assert( iIdx==nVal );
  124946. /* In case the cursor has been used before, clear it now. */
  124947. sqlite3_finalize(pCsr->pStmt);
  124948. sqlite3_free(pCsr->aDoclist);
  124949. sqlite3_free(pCsr->aMatchinfo);
  124950. sqlite3Fts3ExprFree(pCsr->pExpr);
  124951. memset(&pCursor[1], 0, sizeof(Fts3Cursor)-sizeof(sqlite3_vtab_cursor));
  124952. /* Set the lower and upper bounds on docids to return */
  124953. pCsr->iMinDocid = fts3DocidRange(pDocidGe, SMALLEST_INT64);
  124954. pCsr->iMaxDocid = fts3DocidRange(pDocidLe, LARGEST_INT64);
  124955. if( idxStr ){
  124956. pCsr->bDesc = (idxStr[0]=='D');
  124957. }else{
  124958. pCsr->bDesc = p->bDescIdx;
  124959. }
  124960. pCsr->eSearch = (i16)eSearch;
  124961. if( eSearch!=FTS3_DOCID_SEARCH && eSearch!=FTS3_FULLSCAN_SEARCH ){
  124962. int iCol = eSearch-FTS3_FULLTEXT_SEARCH;
  124963. const char *zQuery = (const char *)sqlite3_value_text(pCons);
  124964. if( zQuery==0 && sqlite3_value_type(pCons)!=SQLITE_NULL ){
  124965. return SQLITE_NOMEM;
  124966. }
  124967. pCsr->iLangid = 0;
  124968. if( pLangid ) pCsr->iLangid = sqlite3_value_int(pLangid);
  124969. assert( p->base.zErrMsg==0 );
  124970. rc = sqlite3Fts3ExprParse(p->pTokenizer, pCsr->iLangid,
  124971. p->azColumn, p->bFts4, p->nColumn, iCol, zQuery, -1, &pCsr->pExpr,
  124972. &p->base.zErrMsg
  124973. );
  124974. if( rc!=SQLITE_OK ){
  124975. return rc;
  124976. }
  124977. rc = fts3EvalStart(pCsr);
  124978. sqlite3Fts3SegmentsClose(p);
  124979. if( rc!=SQLITE_OK ) return rc;
  124980. pCsr->pNextId = pCsr->aDoclist;
  124981. pCsr->iPrevId = 0;
  124982. }
  124983. /* Compile a SELECT statement for this cursor. For a full-table-scan, the
  124984. ** statement loops through all rows of the %_content table. For a
  124985. ** full-text query or docid lookup, the statement retrieves a single
  124986. ** row by docid.
  124987. */
  124988. if( eSearch==FTS3_FULLSCAN_SEARCH ){
  124989. zSql = sqlite3_mprintf(
  124990. "SELECT %s ORDER BY rowid %s",
  124991. p->zReadExprlist, (pCsr->bDesc ? "DESC" : "ASC")
  124992. );
  124993. if( zSql ){
  124994. rc = sqlite3_prepare_v2(p->db, zSql, -1, &pCsr->pStmt, 0);
  124995. sqlite3_free(zSql);
  124996. }else{
  124997. rc = SQLITE_NOMEM;
  124998. }
  124999. }else if( eSearch==FTS3_DOCID_SEARCH ){
  125000. rc = fts3CursorSeekStmt(pCsr, &pCsr->pStmt);
  125001. if( rc==SQLITE_OK ){
  125002. rc = sqlite3_bind_value(pCsr->pStmt, 1, pCons);
  125003. }
  125004. }
  125005. if( rc!=SQLITE_OK ) return rc;
  125006. return fts3NextMethod(pCursor);
  125007. }
  125008. /*
  125009. ** This is the xEof method of the virtual table. SQLite calls this
  125010. ** routine to find out if it has reached the end of a result set.
  125011. */
  125012. static int fts3EofMethod(sqlite3_vtab_cursor *pCursor){
  125013. return ((Fts3Cursor *)pCursor)->isEof;
  125014. }
  125015. /*
  125016. ** This is the xRowid method. The SQLite core calls this routine to
  125017. ** retrieve the rowid for the current row of the result set. fts3
  125018. ** exposes %_content.docid as the rowid for the virtual table. The
  125019. ** rowid should be written to *pRowid.
  125020. */
  125021. static int fts3RowidMethod(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
  125022. Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
  125023. *pRowid = pCsr->iPrevId;
  125024. return SQLITE_OK;
  125025. }
  125026. /*
  125027. ** This is the xColumn method, called by SQLite to request a value from
  125028. ** the row that the supplied cursor currently points to.
  125029. **
  125030. ** If:
  125031. **
  125032. ** (iCol < p->nColumn) -> The value of the iCol'th user column.
  125033. ** (iCol == p->nColumn) -> Magic column with the same name as the table.
  125034. ** (iCol == p->nColumn+1) -> Docid column
  125035. ** (iCol == p->nColumn+2) -> Langid column
  125036. */
  125037. static int fts3ColumnMethod(
  125038. sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
  125039. sqlite3_context *pCtx, /* Context for sqlite3_result_xxx() calls */
  125040. int iCol /* Index of column to read value from */
  125041. ){
  125042. int rc = SQLITE_OK; /* Return Code */
  125043. Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
  125044. Fts3Table *p = (Fts3Table *)pCursor->pVtab;
  125045. /* The column value supplied by SQLite must be in range. */
  125046. assert( iCol>=0 && iCol<=p->nColumn+2 );
  125047. if( iCol==p->nColumn+1 ){
  125048. /* This call is a request for the "docid" column. Since "docid" is an
  125049. ** alias for "rowid", use the xRowid() method to obtain the value.
  125050. */
  125051. sqlite3_result_int64(pCtx, pCsr->iPrevId);
  125052. }else if( iCol==p->nColumn ){
  125053. /* The extra column whose name is the same as the table.
  125054. ** Return a blob which is a pointer to the cursor. */
  125055. sqlite3_result_blob(pCtx, &pCsr, sizeof(pCsr), SQLITE_TRANSIENT);
  125056. }else if( iCol==p->nColumn+2 && pCsr->pExpr ){
  125057. sqlite3_result_int64(pCtx, pCsr->iLangid);
  125058. }else{
  125059. /* The requested column is either a user column (one that contains
  125060. ** indexed data), or the language-id column. */
  125061. rc = fts3CursorSeek(0, pCsr);
  125062. if( rc==SQLITE_OK ){
  125063. if( iCol==p->nColumn+2 ){
  125064. int iLangid = 0;
  125065. if( p->zLanguageid ){
  125066. iLangid = sqlite3_column_int(pCsr->pStmt, p->nColumn+1);
  125067. }
  125068. sqlite3_result_int(pCtx, iLangid);
  125069. }else if( sqlite3_data_count(pCsr->pStmt)>(iCol+1) ){
  125070. sqlite3_result_value(pCtx, sqlite3_column_value(pCsr->pStmt, iCol+1));
  125071. }
  125072. }
  125073. }
  125074. assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
  125075. return rc;
  125076. }
  125077. /*
  125078. ** This function is the implementation of the xUpdate callback used by
  125079. ** FTS3 virtual tables. It is invoked by SQLite each time a row is to be
  125080. ** inserted, updated or deleted.
  125081. */
  125082. static int fts3UpdateMethod(
  125083. sqlite3_vtab *pVtab, /* Virtual table handle */
  125084. int nArg, /* Size of argument array */
  125085. sqlite3_value **apVal, /* Array of arguments */
  125086. sqlite_int64 *pRowid /* OUT: The affected (or effected) rowid */
  125087. ){
  125088. return sqlite3Fts3UpdateMethod(pVtab, nArg, apVal, pRowid);
  125089. }
  125090. /*
  125091. ** Implementation of xSync() method. Flush the contents of the pending-terms
  125092. ** hash-table to the database.
  125093. */
  125094. static int fts3SyncMethod(sqlite3_vtab *pVtab){
  125095. /* Following an incremental-merge operation, assuming that the input
  125096. ** segments are not completely consumed (the usual case), they are updated
  125097. ** in place to remove the entries that have already been merged. This
  125098. ** involves updating the leaf block that contains the smallest unmerged
  125099. ** entry and each block (if any) between the leaf and the root node. So
  125100. ** if the height of the input segment b-trees is N, and input segments
  125101. ** are merged eight at a time, updating the input segments at the end
  125102. ** of an incremental-merge requires writing (8*(1+N)) blocks. N is usually
  125103. ** small - often between 0 and 2. So the overhead of the incremental
  125104. ** merge is somewhere between 8 and 24 blocks. To avoid this overhead
  125105. ** dwarfing the actual productive work accomplished, the incremental merge
  125106. ** is only attempted if it will write at least 64 leaf blocks. Hence
  125107. ** nMinMerge.
  125108. **
  125109. ** Of course, updating the input segments also involves deleting a bunch
  125110. ** of blocks from the segments table. But this is not considered overhead
  125111. ** as it would also be required by a crisis-merge that used the same input
  125112. ** segments.
  125113. */
  125114. const u32 nMinMerge = 64; /* Minimum amount of incr-merge work to do */
  125115. Fts3Table *p = (Fts3Table*)pVtab;
  125116. int rc = sqlite3Fts3PendingTermsFlush(p);
  125117. if( rc==SQLITE_OK
  125118. && p->nLeafAdd>(nMinMerge/16)
  125119. && p->nAutoincrmerge && p->nAutoincrmerge!=0xff
  125120. ){
  125121. int mxLevel = 0; /* Maximum relative level value in db */
  125122. int A; /* Incr-merge parameter A */
  125123. rc = sqlite3Fts3MaxLevel(p, &mxLevel);
  125124. assert( rc==SQLITE_OK || mxLevel==0 );
  125125. A = p->nLeafAdd * mxLevel;
  125126. A += (A/2);
  125127. if( A>(int)nMinMerge ) rc = sqlite3Fts3Incrmerge(p, A, p->nAutoincrmerge);
  125128. }
  125129. sqlite3Fts3SegmentsClose(p);
  125130. return rc;
  125131. }
  125132. /*
  125133. ** If it is currently unknown whether or not the FTS table has an %_stat
  125134. ** table (if p->bHasStat==2), attempt to determine this (set p->bHasStat
  125135. ** to 0 or 1). Return SQLITE_OK if successful, or an SQLite error code
  125136. ** if an error occurs.
  125137. */
  125138. static int fts3SetHasStat(Fts3Table *p){
  125139. int rc = SQLITE_OK;
  125140. if( p->bHasStat==2 ){
  125141. const char *zFmt ="SELECT 1 FROM %Q.sqlite_master WHERE tbl_name='%q_stat'";
  125142. char *zSql = sqlite3_mprintf(zFmt, p->zDb, p->zName);
  125143. if( zSql ){
  125144. sqlite3_stmt *pStmt = 0;
  125145. rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
  125146. if( rc==SQLITE_OK ){
  125147. int bHasStat = (sqlite3_step(pStmt)==SQLITE_ROW);
  125148. rc = sqlite3_finalize(pStmt);
  125149. if( rc==SQLITE_OK ) p->bHasStat = bHasStat;
  125150. }
  125151. sqlite3_free(zSql);
  125152. }else{
  125153. rc = SQLITE_NOMEM;
  125154. }
  125155. }
  125156. return rc;
  125157. }
  125158. /*
  125159. ** Implementation of xBegin() method.
  125160. */
  125161. static int fts3BeginMethod(sqlite3_vtab *pVtab){
  125162. Fts3Table *p = (Fts3Table*)pVtab;
  125163. UNUSED_PARAMETER(pVtab);
  125164. assert( p->pSegments==0 );
  125165. assert( p->nPendingData==0 );
  125166. assert( p->inTransaction!=1 );
  125167. TESTONLY( p->inTransaction = 1 );
  125168. TESTONLY( p->mxSavepoint = -1; );
  125169. p->nLeafAdd = 0;
  125170. return fts3SetHasStat(p);
  125171. }
  125172. /*
  125173. ** Implementation of xCommit() method. This is a no-op. The contents of
  125174. ** the pending-terms hash-table have already been flushed into the database
  125175. ** by fts3SyncMethod().
  125176. */
  125177. static int fts3CommitMethod(sqlite3_vtab *pVtab){
  125178. TESTONLY( Fts3Table *p = (Fts3Table*)pVtab );
  125179. UNUSED_PARAMETER(pVtab);
  125180. assert( p->nPendingData==0 );
  125181. assert( p->inTransaction!=0 );
  125182. assert( p->pSegments==0 );
  125183. TESTONLY( p->inTransaction = 0 );
  125184. TESTONLY( p->mxSavepoint = -1; );
  125185. return SQLITE_OK;
  125186. }
  125187. /*
  125188. ** Implementation of xRollback(). Discard the contents of the pending-terms
  125189. ** hash-table. Any changes made to the database are reverted by SQLite.
  125190. */
  125191. static int fts3RollbackMethod(sqlite3_vtab *pVtab){
  125192. Fts3Table *p = (Fts3Table*)pVtab;
  125193. sqlite3Fts3PendingTermsClear(p);
  125194. assert( p->inTransaction!=0 );
  125195. TESTONLY( p->inTransaction = 0 );
  125196. TESTONLY( p->mxSavepoint = -1; );
  125197. return SQLITE_OK;
  125198. }
  125199. /*
  125200. ** When called, *ppPoslist must point to the byte immediately following the
  125201. ** end of a position-list. i.e. ( (*ppPoslist)[-1]==POS_END ). This function
  125202. ** moves *ppPoslist so that it instead points to the first byte of the
  125203. ** same position list.
  125204. */
  125205. static void fts3ReversePoslist(char *pStart, char **ppPoslist){
  125206. char *p = &(*ppPoslist)[-2];
  125207. char c = 0;
  125208. while( p>pStart && (c=*p--)==0 );
  125209. while( p>pStart && (*p & 0x80) | c ){
  125210. c = *p--;
  125211. }
  125212. if( p>pStart ){ p = &p[2]; }
  125213. while( *p++&0x80 );
  125214. *ppPoslist = p;
  125215. }
  125216. /*
  125217. ** Helper function used by the implementation of the overloaded snippet(),
  125218. ** offsets() and optimize() SQL functions.
  125219. **
  125220. ** If the value passed as the third argument is a blob of size
  125221. ** sizeof(Fts3Cursor*), then the blob contents are copied to the
  125222. ** output variable *ppCsr and SQLITE_OK is returned. Otherwise, an error
  125223. ** message is written to context pContext and SQLITE_ERROR returned. The
  125224. ** string passed via zFunc is used as part of the error message.
  125225. */
  125226. static int fts3FunctionArg(
  125227. sqlite3_context *pContext, /* SQL function call context */
  125228. const char *zFunc, /* Function name */
  125229. sqlite3_value *pVal, /* argv[0] passed to function */
  125230. Fts3Cursor **ppCsr /* OUT: Store cursor handle here */
  125231. ){
  125232. Fts3Cursor *pRet;
  125233. if( sqlite3_value_type(pVal)!=SQLITE_BLOB
  125234. || sqlite3_value_bytes(pVal)!=sizeof(Fts3Cursor *)
  125235. ){
  125236. char *zErr = sqlite3_mprintf("illegal first argument to %s", zFunc);
  125237. sqlite3_result_error(pContext, zErr, -1);
  125238. sqlite3_free(zErr);
  125239. return SQLITE_ERROR;
  125240. }
  125241. memcpy(&pRet, sqlite3_value_blob(pVal), sizeof(Fts3Cursor *));
  125242. *ppCsr = pRet;
  125243. return SQLITE_OK;
  125244. }
  125245. /*
  125246. ** Implementation of the snippet() function for FTS3
  125247. */
  125248. static void fts3SnippetFunc(
  125249. sqlite3_context *pContext, /* SQLite function call context */
  125250. int nVal, /* Size of apVal[] array */
  125251. sqlite3_value **apVal /* Array of arguments */
  125252. ){
  125253. Fts3Cursor *pCsr; /* Cursor handle passed through apVal[0] */
  125254. const char *zStart = "<b>";
  125255. const char *zEnd = "</b>";
  125256. const char *zEllipsis = "<b>...</b>";
  125257. int iCol = -1;
  125258. int nToken = 15; /* Default number of tokens in snippet */
  125259. /* There must be at least one argument passed to this function (otherwise
  125260. ** the non-overloaded version would have been called instead of this one).
  125261. */
  125262. assert( nVal>=1 );
  125263. if( nVal>6 ){
  125264. sqlite3_result_error(pContext,
  125265. "wrong number of arguments to function snippet()", -1);
  125266. return;
  125267. }
  125268. if( fts3FunctionArg(pContext, "snippet", apVal[0], &pCsr) ) return;
  125269. switch( nVal ){
  125270. case 6: nToken = sqlite3_value_int(apVal[5]);
  125271. case 5: iCol = sqlite3_value_int(apVal[4]);
  125272. case 4: zEllipsis = (const char*)sqlite3_value_text(apVal[3]);
  125273. case 3: zEnd = (const char*)sqlite3_value_text(apVal[2]);
  125274. case 2: zStart = (const char*)sqlite3_value_text(apVal[1]);
  125275. }
  125276. if( !zEllipsis || !zEnd || !zStart ){
  125277. sqlite3_result_error_nomem(pContext);
  125278. }else if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
  125279. sqlite3Fts3Snippet(pContext, pCsr, zStart, zEnd, zEllipsis, iCol, nToken);
  125280. }
  125281. }
  125282. /*
  125283. ** Implementation of the offsets() function for FTS3
  125284. */
  125285. static void fts3OffsetsFunc(
  125286. sqlite3_context *pContext, /* SQLite function call context */
  125287. int nVal, /* Size of argument array */
  125288. sqlite3_value **apVal /* Array of arguments */
  125289. ){
  125290. Fts3Cursor *pCsr; /* Cursor handle passed through apVal[0] */
  125291. UNUSED_PARAMETER(nVal);
  125292. assert( nVal==1 );
  125293. if( fts3FunctionArg(pContext, "offsets", apVal[0], &pCsr) ) return;
  125294. assert( pCsr );
  125295. if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
  125296. sqlite3Fts3Offsets(pContext, pCsr);
  125297. }
  125298. }
  125299. /*
  125300. ** Implementation of the special optimize() function for FTS3. This
  125301. ** function merges all segments in the database to a single segment.
  125302. ** Example usage is:
  125303. **
  125304. ** SELECT optimize(t) FROM t LIMIT 1;
  125305. **
  125306. ** where 't' is the name of an FTS3 table.
  125307. */
  125308. static void fts3OptimizeFunc(
  125309. sqlite3_context *pContext, /* SQLite function call context */
  125310. int nVal, /* Size of argument array */
  125311. sqlite3_value **apVal /* Array of arguments */
  125312. ){
  125313. int rc; /* Return code */
  125314. Fts3Table *p; /* Virtual table handle */
  125315. Fts3Cursor *pCursor; /* Cursor handle passed through apVal[0] */
  125316. UNUSED_PARAMETER(nVal);
  125317. assert( nVal==1 );
  125318. if( fts3FunctionArg(pContext, "optimize", apVal[0], &pCursor) ) return;
  125319. p = (Fts3Table *)pCursor->base.pVtab;
  125320. assert( p );
  125321. rc = sqlite3Fts3Optimize(p);
  125322. switch( rc ){
  125323. case SQLITE_OK:
  125324. sqlite3_result_text(pContext, "Index optimized", -1, SQLITE_STATIC);
  125325. break;
  125326. case SQLITE_DONE:
  125327. sqlite3_result_text(pContext, "Index already optimal", -1, SQLITE_STATIC);
  125328. break;
  125329. default:
  125330. sqlite3_result_error_code(pContext, rc);
  125331. break;
  125332. }
  125333. }
  125334. /*
  125335. ** Implementation of the matchinfo() function for FTS3
  125336. */
  125337. static void fts3MatchinfoFunc(
  125338. sqlite3_context *pContext, /* SQLite function call context */
  125339. int nVal, /* Size of argument array */
  125340. sqlite3_value **apVal /* Array of arguments */
  125341. ){
  125342. Fts3Cursor *pCsr; /* Cursor handle passed through apVal[0] */
  125343. assert( nVal==1 || nVal==2 );
  125344. if( SQLITE_OK==fts3FunctionArg(pContext, "matchinfo", apVal[0], &pCsr) ){
  125345. const char *zArg = 0;
  125346. if( nVal>1 ){
  125347. zArg = (const char *)sqlite3_value_text(apVal[1]);
  125348. }
  125349. sqlite3Fts3Matchinfo(pContext, pCsr, zArg);
  125350. }
  125351. }
  125352. /*
  125353. ** This routine implements the xFindFunction method for the FTS3
  125354. ** virtual table.
  125355. */
  125356. static int fts3FindFunctionMethod(
  125357. sqlite3_vtab *pVtab, /* Virtual table handle */
  125358. int nArg, /* Number of SQL function arguments */
  125359. const char *zName, /* Name of SQL function */
  125360. void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */
  125361. void **ppArg /* Unused */
  125362. ){
  125363. struct Overloaded {
  125364. const char *zName;
  125365. void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
  125366. } aOverload[] = {
  125367. { "snippet", fts3SnippetFunc },
  125368. { "offsets", fts3OffsetsFunc },
  125369. { "optimize", fts3OptimizeFunc },
  125370. { "matchinfo", fts3MatchinfoFunc },
  125371. };
  125372. int i; /* Iterator variable */
  125373. UNUSED_PARAMETER(pVtab);
  125374. UNUSED_PARAMETER(nArg);
  125375. UNUSED_PARAMETER(ppArg);
  125376. for(i=0; i<SizeofArray(aOverload); i++){
  125377. if( strcmp(zName, aOverload[i].zName)==0 ){
  125378. *pxFunc = aOverload[i].xFunc;
  125379. return 1;
  125380. }
  125381. }
  125382. /* No function of the specified name was found. Return 0. */
  125383. return 0;
  125384. }
  125385. /*
  125386. ** Implementation of FTS3 xRename method. Rename an fts3 table.
  125387. */
  125388. static int fts3RenameMethod(
  125389. sqlite3_vtab *pVtab, /* Virtual table handle */
  125390. const char *zName /* New name of table */
  125391. ){
  125392. Fts3Table *p = (Fts3Table *)pVtab;
  125393. sqlite3 *db = p->db; /* Database connection */
  125394. int rc; /* Return Code */
  125395. /* At this point it must be known if the %_stat table exists or not.
  125396. ** So bHasStat may not be 2. */
  125397. rc = fts3SetHasStat(p);
  125398. /* As it happens, the pending terms table is always empty here. This is
  125399. ** because an "ALTER TABLE RENAME TABLE" statement inside a transaction
  125400. ** always opens a savepoint transaction. And the xSavepoint() method
  125401. ** flushes the pending terms table. But leave the (no-op) call to
  125402. ** PendingTermsFlush() in in case that changes.
  125403. */
  125404. assert( p->nPendingData==0 );
  125405. if( rc==SQLITE_OK ){
  125406. rc = sqlite3Fts3PendingTermsFlush(p);
  125407. }
  125408. if( p->zContentTbl==0 ){
  125409. fts3DbExec(&rc, db,
  125410. "ALTER TABLE %Q.'%q_content' RENAME TO '%q_content';",
  125411. p->zDb, p->zName, zName
  125412. );
  125413. }
  125414. if( p->bHasDocsize ){
  125415. fts3DbExec(&rc, db,
  125416. "ALTER TABLE %Q.'%q_docsize' RENAME TO '%q_docsize';",
  125417. p->zDb, p->zName, zName
  125418. );
  125419. }
  125420. if( p->bHasStat ){
  125421. fts3DbExec(&rc, db,
  125422. "ALTER TABLE %Q.'%q_stat' RENAME TO '%q_stat';",
  125423. p->zDb, p->zName, zName
  125424. );
  125425. }
  125426. fts3DbExec(&rc, db,
  125427. "ALTER TABLE %Q.'%q_segments' RENAME TO '%q_segments';",
  125428. p->zDb, p->zName, zName
  125429. );
  125430. fts3DbExec(&rc, db,
  125431. "ALTER TABLE %Q.'%q_segdir' RENAME TO '%q_segdir';",
  125432. p->zDb, p->zName, zName
  125433. );
  125434. return rc;
  125435. }
  125436. /*
  125437. ** The xSavepoint() method.
  125438. **
  125439. ** Flush the contents of the pending-terms table to disk.
  125440. */
  125441. static int fts3SavepointMethod(sqlite3_vtab *pVtab, int iSavepoint){
  125442. int rc = SQLITE_OK;
  125443. UNUSED_PARAMETER(iSavepoint);
  125444. assert( ((Fts3Table *)pVtab)->inTransaction );
  125445. assert( ((Fts3Table *)pVtab)->mxSavepoint < iSavepoint );
  125446. TESTONLY( ((Fts3Table *)pVtab)->mxSavepoint = iSavepoint );
  125447. if( ((Fts3Table *)pVtab)->bIgnoreSavepoint==0 ){
  125448. rc = fts3SyncMethod(pVtab);
  125449. }
  125450. return rc;
  125451. }
  125452. /*
  125453. ** The xRelease() method.
  125454. **
  125455. ** This is a no-op.
  125456. */
  125457. static int fts3ReleaseMethod(sqlite3_vtab *pVtab, int iSavepoint){
  125458. TESTONLY( Fts3Table *p = (Fts3Table*)pVtab );
  125459. UNUSED_PARAMETER(iSavepoint);
  125460. UNUSED_PARAMETER(pVtab);
  125461. assert( p->inTransaction );
  125462. assert( p->mxSavepoint >= iSavepoint );
  125463. TESTONLY( p->mxSavepoint = iSavepoint-1 );
  125464. return SQLITE_OK;
  125465. }
  125466. /*
  125467. ** The xRollbackTo() method.
  125468. **
  125469. ** Discard the contents of the pending terms table.
  125470. */
  125471. static int fts3RollbackToMethod(sqlite3_vtab *pVtab, int iSavepoint){
  125472. Fts3Table *p = (Fts3Table*)pVtab;
  125473. UNUSED_PARAMETER(iSavepoint);
  125474. assert( p->inTransaction );
  125475. assert( p->mxSavepoint >= iSavepoint );
  125476. TESTONLY( p->mxSavepoint = iSavepoint );
  125477. sqlite3Fts3PendingTermsClear(p);
  125478. return SQLITE_OK;
  125479. }
  125480. static const sqlite3_module fts3Module = {
  125481. /* iVersion */ 2,
  125482. /* xCreate */ fts3CreateMethod,
  125483. /* xConnect */ fts3ConnectMethod,
  125484. /* xBestIndex */ fts3BestIndexMethod,
  125485. /* xDisconnect */ fts3DisconnectMethod,
  125486. /* xDestroy */ fts3DestroyMethod,
  125487. /* xOpen */ fts3OpenMethod,
  125488. /* xClose */ fts3CloseMethod,
  125489. /* xFilter */ fts3FilterMethod,
  125490. /* xNext */ fts3NextMethod,
  125491. /* xEof */ fts3EofMethod,
  125492. /* xColumn */ fts3ColumnMethod,
  125493. /* xRowid */ fts3RowidMethod,
  125494. /* xUpdate */ fts3UpdateMethod,
  125495. /* xBegin */ fts3BeginMethod,
  125496. /* xSync */ fts3SyncMethod,
  125497. /* xCommit */ fts3CommitMethod,
  125498. /* xRollback */ fts3RollbackMethod,
  125499. /* xFindFunction */ fts3FindFunctionMethod,
  125500. /* xRename */ fts3RenameMethod,
  125501. /* xSavepoint */ fts3SavepointMethod,
  125502. /* xRelease */ fts3ReleaseMethod,
  125503. /* xRollbackTo */ fts3RollbackToMethod,
  125504. };
  125505. /*
  125506. ** This function is registered as the module destructor (called when an
  125507. ** FTS3 enabled database connection is closed). It frees the memory
  125508. ** allocated for the tokenizer hash table.
  125509. */
  125510. static void hashDestroy(void *p){
  125511. Fts3Hash *pHash = (Fts3Hash *)p;
  125512. sqlite3Fts3HashClear(pHash);
  125513. sqlite3_free(pHash);
  125514. }
  125515. /*
  125516. ** The fts3 built-in tokenizers - "simple", "porter" and "icu"- are
  125517. ** implemented in files fts3_tokenizer1.c, fts3_porter.c and fts3_icu.c
  125518. ** respectively. The following three forward declarations are for functions
  125519. ** declared in these files used to retrieve the respective implementations.
  125520. **
  125521. ** Calling sqlite3Fts3SimpleTokenizerModule() sets the value pointed
  125522. ** to by the argument to point to the "simple" tokenizer implementation.
  125523. ** And so on.
  125524. */
  125525. SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
  125526. SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(sqlite3_tokenizer_module const**ppModule);
  125527. #ifndef SQLITE_DISABLE_FTS3_UNICODE
  125528. SQLITE_PRIVATE void sqlite3Fts3UnicodeTokenizer(sqlite3_tokenizer_module const**ppModule);
  125529. #endif
  125530. #ifdef SQLITE_ENABLE_ICU
  125531. SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(sqlite3_tokenizer_module const**ppModule);
  125532. #endif
  125533. /*
  125534. ** Initialize the fts3 extension. If this extension is built as part
  125535. ** of the sqlite library, then this function is called directly by
  125536. ** SQLite. If fts3 is built as a dynamically loadable extension, this
  125537. ** function is called by the sqlite3_extension_init() entry point.
  125538. */
  125539. SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db){
  125540. int rc = SQLITE_OK;
  125541. Fts3Hash *pHash = 0;
  125542. const sqlite3_tokenizer_module *pSimple = 0;
  125543. const sqlite3_tokenizer_module *pPorter = 0;
  125544. #ifndef SQLITE_DISABLE_FTS3_UNICODE
  125545. const sqlite3_tokenizer_module *pUnicode = 0;
  125546. #endif
  125547. #ifdef SQLITE_ENABLE_ICU
  125548. const sqlite3_tokenizer_module *pIcu = 0;
  125549. sqlite3Fts3IcuTokenizerModule(&pIcu);
  125550. #endif
  125551. #ifndef SQLITE_DISABLE_FTS3_UNICODE
  125552. sqlite3Fts3UnicodeTokenizer(&pUnicode);
  125553. #endif
  125554. #ifdef SQLITE_TEST
  125555. rc = sqlite3Fts3InitTerm(db);
  125556. if( rc!=SQLITE_OK ) return rc;
  125557. #endif
  125558. rc = sqlite3Fts3InitAux(db);
  125559. if( rc!=SQLITE_OK ) return rc;
  125560. sqlite3Fts3SimpleTokenizerModule(&pSimple);
  125561. sqlite3Fts3PorterTokenizerModule(&pPorter);
  125562. /* Allocate and initialize the hash-table used to store tokenizers. */
  125563. pHash = sqlite3_malloc(sizeof(Fts3Hash));
  125564. if( !pHash ){
  125565. rc = SQLITE_NOMEM;
  125566. }else{
  125567. sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
  125568. }
  125569. /* Load the built-in tokenizers into the hash table */
  125570. if( rc==SQLITE_OK ){
  125571. if( sqlite3Fts3HashInsert(pHash, "simple", 7, (void *)pSimple)
  125572. || sqlite3Fts3HashInsert(pHash, "porter", 7, (void *)pPorter)
  125573. #ifndef SQLITE_DISABLE_FTS3_UNICODE
  125574. || sqlite3Fts3HashInsert(pHash, "unicode61", 10, (void *)pUnicode)
  125575. #endif
  125576. #ifdef SQLITE_ENABLE_ICU
  125577. || (pIcu && sqlite3Fts3HashInsert(pHash, "icu", 4, (void *)pIcu))
  125578. #endif
  125579. ){
  125580. rc = SQLITE_NOMEM;
  125581. }
  125582. }
  125583. #ifdef SQLITE_TEST
  125584. if( rc==SQLITE_OK ){
  125585. rc = sqlite3Fts3ExprInitTestInterface(db);
  125586. }
  125587. #endif
  125588. /* Create the virtual table wrapper around the hash-table and overload
  125589. ** the two scalar functions. If this is successful, register the
  125590. ** module with sqlite.
  125591. */
  125592. if( SQLITE_OK==rc
  125593. && SQLITE_OK==(rc = sqlite3Fts3InitHashTable(db, pHash, "fts3_tokenizer"))
  125594. && SQLITE_OK==(rc = sqlite3_overload_function(db, "snippet", -1))
  125595. && SQLITE_OK==(rc = sqlite3_overload_function(db, "offsets", 1))
  125596. && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 1))
  125597. && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 2))
  125598. && SQLITE_OK==(rc = sqlite3_overload_function(db, "optimize", 1))
  125599. ){
  125600. rc = sqlite3_create_module_v2(
  125601. db, "fts3", &fts3Module, (void *)pHash, hashDestroy
  125602. );
  125603. if( rc==SQLITE_OK ){
  125604. rc = sqlite3_create_module_v2(
  125605. db, "fts4", &fts3Module, (void *)pHash, 0
  125606. );
  125607. }
  125608. if( rc==SQLITE_OK ){
  125609. rc = sqlite3Fts3InitTok(db, (void *)pHash);
  125610. }
  125611. return rc;
  125612. }
  125613. /* An error has occurred. Delete the hash table and return the error code. */
  125614. assert( rc!=SQLITE_OK );
  125615. if( pHash ){
  125616. sqlite3Fts3HashClear(pHash);
  125617. sqlite3_free(pHash);
  125618. }
  125619. return rc;
  125620. }
  125621. /*
  125622. ** Allocate an Fts3MultiSegReader for each token in the expression headed
  125623. ** by pExpr.
  125624. **
  125625. ** An Fts3SegReader object is a cursor that can seek or scan a range of
  125626. ** entries within a single segment b-tree. An Fts3MultiSegReader uses multiple
  125627. ** Fts3SegReader objects internally to provide an interface to seek or scan
  125628. ** within the union of all segments of a b-tree. Hence the name.
  125629. **
  125630. ** If the allocated Fts3MultiSegReader just seeks to a single entry in a
  125631. ** segment b-tree (if the term is not a prefix or it is a prefix for which
  125632. ** there exists prefix b-tree of the right length) then it may be traversed
  125633. ** and merged incrementally. Otherwise, it has to be merged into an in-memory
  125634. ** doclist and then traversed.
  125635. */
  125636. static void fts3EvalAllocateReaders(
  125637. Fts3Cursor *pCsr, /* FTS cursor handle */
  125638. Fts3Expr *pExpr, /* Allocate readers for this expression */
  125639. int *pnToken, /* OUT: Total number of tokens in phrase. */
  125640. int *pnOr, /* OUT: Total number of OR nodes in expr. */
  125641. int *pRc /* IN/OUT: Error code */
  125642. ){
  125643. if( pExpr && SQLITE_OK==*pRc ){
  125644. if( pExpr->eType==FTSQUERY_PHRASE ){
  125645. int i;
  125646. int nToken = pExpr->pPhrase->nToken;
  125647. *pnToken += nToken;
  125648. for(i=0; i<nToken; i++){
  125649. Fts3PhraseToken *pToken = &pExpr->pPhrase->aToken[i];
  125650. int rc = fts3TermSegReaderCursor(pCsr,
  125651. pToken->z, pToken->n, pToken->isPrefix, &pToken->pSegcsr
  125652. );
  125653. if( rc!=SQLITE_OK ){
  125654. *pRc = rc;
  125655. return;
  125656. }
  125657. }
  125658. assert( pExpr->pPhrase->iDoclistToken==0 );
  125659. pExpr->pPhrase->iDoclistToken = -1;
  125660. }else{
  125661. *pnOr += (pExpr->eType==FTSQUERY_OR);
  125662. fts3EvalAllocateReaders(pCsr, pExpr->pLeft, pnToken, pnOr, pRc);
  125663. fts3EvalAllocateReaders(pCsr, pExpr->pRight, pnToken, pnOr, pRc);
  125664. }
  125665. }
  125666. }
  125667. /*
  125668. ** Arguments pList/nList contain the doclist for token iToken of phrase p.
  125669. ** It is merged into the main doclist stored in p->doclist.aAll/nAll.
  125670. **
  125671. ** This function assumes that pList points to a buffer allocated using
  125672. ** sqlite3_malloc(). This function takes responsibility for eventually
  125673. ** freeing the buffer.
  125674. */
  125675. static void fts3EvalPhraseMergeToken(
  125676. Fts3Table *pTab, /* FTS Table pointer */
  125677. Fts3Phrase *p, /* Phrase to merge pList/nList into */
  125678. int iToken, /* Token pList/nList corresponds to */
  125679. char *pList, /* Pointer to doclist */
  125680. int nList /* Number of bytes in pList */
  125681. ){
  125682. assert( iToken!=p->iDoclistToken );
  125683. if( pList==0 ){
  125684. sqlite3_free(p->doclist.aAll);
  125685. p->doclist.aAll = 0;
  125686. p->doclist.nAll = 0;
  125687. }
  125688. else if( p->iDoclistToken<0 ){
  125689. p->doclist.aAll = pList;
  125690. p->doclist.nAll = nList;
  125691. }
  125692. else if( p->doclist.aAll==0 ){
  125693. sqlite3_free(pList);
  125694. }
  125695. else {
  125696. char *pLeft;
  125697. char *pRight;
  125698. int nLeft;
  125699. int nRight;
  125700. int nDiff;
  125701. if( p->iDoclistToken<iToken ){
  125702. pLeft = p->doclist.aAll;
  125703. nLeft = p->doclist.nAll;
  125704. pRight = pList;
  125705. nRight = nList;
  125706. nDiff = iToken - p->iDoclistToken;
  125707. }else{
  125708. pRight = p->doclist.aAll;
  125709. nRight = p->doclist.nAll;
  125710. pLeft = pList;
  125711. nLeft = nList;
  125712. nDiff = p->iDoclistToken - iToken;
  125713. }
  125714. fts3DoclistPhraseMerge(pTab->bDescIdx, nDiff, pLeft, nLeft, pRight,&nRight);
  125715. sqlite3_free(pLeft);
  125716. p->doclist.aAll = pRight;
  125717. p->doclist.nAll = nRight;
  125718. }
  125719. if( iToken>p->iDoclistToken ) p->iDoclistToken = iToken;
  125720. }
  125721. /*
  125722. ** Load the doclist for phrase p into p->doclist.aAll/nAll. The loaded doclist
  125723. ** does not take deferred tokens into account.
  125724. **
  125725. ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
  125726. */
  125727. static int fts3EvalPhraseLoad(
  125728. Fts3Cursor *pCsr, /* FTS Cursor handle */
  125729. Fts3Phrase *p /* Phrase object */
  125730. ){
  125731. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  125732. int iToken;
  125733. int rc = SQLITE_OK;
  125734. for(iToken=0; rc==SQLITE_OK && iToken<p->nToken; iToken++){
  125735. Fts3PhraseToken *pToken = &p->aToken[iToken];
  125736. assert( pToken->pDeferred==0 || pToken->pSegcsr==0 );
  125737. if( pToken->pSegcsr ){
  125738. int nThis = 0;
  125739. char *pThis = 0;
  125740. rc = fts3TermSelect(pTab, pToken, p->iColumn, &nThis, &pThis);
  125741. if( rc==SQLITE_OK ){
  125742. fts3EvalPhraseMergeToken(pTab, p, iToken, pThis, nThis);
  125743. }
  125744. }
  125745. assert( pToken->pSegcsr==0 );
  125746. }
  125747. return rc;
  125748. }
  125749. /*
  125750. ** This function is called on each phrase after the position lists for
  125751. ** any deferred tokens have been loaded into memory. It updates the phrases
  125752. ** current position list to include only those positions that are really
  125753. ** instances of the phrase (after considering deferred tokens). If this
  125754. ** means that the phrase does not appear in the current row, doclist.pList
  125755. ** and doclist.nList are both zeroed.
  125756. **
  125757. ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
  125758. */
  125759. static int fts3EvalDeferredPhrase(Fts3Cursor *pCsr, Fts3Phrase *pPhrase){
  125760. int iToken; /* Used to iterate through phrase tokens */
  125761. char *aPoslist = 0; /* Position list for deferred tokens */
  125762. int nPoslist = 0; /* Number of bytes in aPoslist */
  125763. int iPrev = -1; /* Token number of previous deferred token */
  125764. assert( pPhrase->doclist.bFreeList==0 );
  125765. for(iToken=0; iToken<pPhrase->nToken; iToken++){
  125766. Fts3PhraseToken *pToken = &pPhrase->aToken[iToken];
  125767. Fts3DeferredToken *pDeferred = pToken->pDeferred;
  125768. if( pDeferred ){
  125769. char *pList;
  125770. int nList;
  125771. int rc = sqlite3Fts3DeferredTokenList(pDeferred, &pList, &nList);
  125772. if( rc!=SQLITE_OK ) return rc;
  125773. if( pList==0 ){
  125774. sqlite3_free(aPoslist);
  125775. pPhrase->doclist.pList = 0;
  125776. pPhrase->doclist.nList = 0;
  125777. return SQLITE_OK;
  125778. }else if( aPoslist==0 ){
  125779. aPoslist = pList;
  125780. nPoslist = nList;
  125781. }else{
  125782. char *aOut = pList;
  125783. char *p1 = aPoslist;
  125784. char *p2 = aOut;
  125785. assert( iPrev>=0 );
  125786. fts3PoslistPhraseMerge(&aOut, iToken-iPrev, 0, 1, &p1, &p2);
  125787. sqlite3_free(aPoslist);
  125788. aPoslist = pList;
  125789. nPoslist = (int)(aOut - aPoslist);
  125790. if( nPoslist==0 ){
  125791. sqlite3_free(aPoslist);
  125792. pPhrase->doclist.pList = 0;
  125793. pPhrase->doclist.nList = 0;
  125794. return SQLITE_OK;
  125795. }
  125796. }
  125797. iPrev = iToken;
  125798. }
  125799. }
  125800. if( iPrev>=0 ){
  125801. int nMaxUndeferred = pPhrase->iDoclistToken;
  125802. if( nMaxUndeferred<0 ){
  125803. pPhrase->doclist.pList = aPoslist;
  125804. pPhrase->doclist.nList = nPoslist;
  125805. pPhrase->doclist.iDocid = pCsr->iPrevId;
  125806. pPhrase->doclist.bFreeList = 1;
  125807. }else{
  125808. int nDistance;
  125809. char *p1;
  125810. char *p2;
  125811. char *aOut;
  125812. if( nMaxUndeferred>iPrev ){
  125813. p1 = aPoslist;
  125814. p2 = pPhrase->doclist.pList;
  125815. nDistance = nMaxUndeferred - iPrev;
  125816. }else{
  125817. p1 = pPhrase->doclist.pList;
  125818. p2 = aPoslist;
  125819. nDistance = iPrev - nMaxUndeferred;
  125820. }
  125821. aOut = (char *)sqlite3_malloc(nPoslist+8);
  125822. if( !aOut ){
  125823. sqlite3_free(aPoslist);
  125824. return SQLITE_NOMEM;
  125825. }
  125826. pPhrase->doclist.pList = aOut;
  125827. if( fts3PoslistPhraseMerge(&aOut, nDistance, 0, 1, &p1, &p2) ){
  125828. pPhrase->doclist.bFreeList = 1;
  125829. pPhrase->doclist.nList = (int)(aOut - pPhrase->doclist.pList);
  125830. }else{
  125831. sqlite3_free(aOut);
  125832. pPhrase->doclist.pList = 0;
  125833. pPhrase->doclist.nList = 0;
  125834. }
  125835. sqlite3_free(aPoslist);
  125836. }
  125837. }
  125838. return SQLITE_OK;
  125839. }
  125840. /*
  125841. ** Maximum number of tokens a phrase may have to be considered for the
  125842. ** incremental doclists strategy.
  125843. */
  125844. #define MAX_INCR_PHRASE_TOKENS 4
  125845. /*
  125846. ** This function is called for each Fts3Phrase in a full-text query
  125847. ** expression to initialize the mechanism for returning rows. Once this
  125848. ** function has been called successfully on an Fts3Phrase, it may be
  125849. ** used with fts3EvalPhraseNext() to iterate through the matching docids.
  125850. **
  125851. ** If parameter bOptOk is true, then the phrase may (or may not) use the
  125852. ** incremental loading strategy. Otherwise, the entire doclist is loaded into
  125853. ** memory within this call.
  125854. **
  125855. ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
  125856. */
  125857. static int fts3EvalPhraseStart(Fts3Cursor *pCsr, int bOptOk, Fts3Phrase *p){
  125858. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  125859. int rc = SQLITE_OK; /* Error code */
  125860. int i;
  125861. /* Determine if doclists may be loaded from disk incrementally. This is
  125862. ** possible if the bOptOk argument is true, the FTS doclists will be
  125863. ** scanned in forward order, and the phrase consists of
  125864. ** MAX_INCR_PHRASE_TOKENS or fewer tokens, none of which are are "^first"
  125865. ** tokens or prefix tokens that cannot use a prefix-index. */
  125866. int bHaveIncr = 0;
  125867. int bIncrOk = (bOptOk
  125868. && pCsr->bDesc==pTab->bDescIdx
  125869. && p->nToken<=MAX_INCR_PHRASE_TOKENS && p->nToken>0
  125870. && p->nToken<=MAX_INCR_PHRASE_TOKENS && p->nToken>0
  125871. #ifdef SQLITE_TEST
  125872. && pTab->bNoIncrDoclist==0
  125873. #endif
  125874. );
  125875. for(i=0; bIncrOk==1 && i<p->nToken; i++){
  125876. Fts3PhraseToken *pToken = &p->aToken[i];
  125877. if( pToken->bFirst || (pToken->pSegcsr!=0 && !pToken->pSegcsr->bLookup) ){
  125878. bIncrOk = 0;
  125879. }
  125880. if( pToken->pSegcsr ) bHaveIncr = 1;
  125881. }
  125882. if( bIncrOk && bHaveIncr ){
  125883. /* Use the incremental approach. */
  125884. int iCol = (p->iColumn >= pTab->nColumn ? -1 : p->iColumn);
  125885. for(i=0; rc==SQLITE_OK && i<p->nToken; i++){
  125886. Fts3PhraseToken *pToken = &p->aToken[i];
  125887. Fts3MultiSegReader *pSegcsr = pToken->pSegcsr;
  125888. if( pSegcsr ){
  125889. rc = sqlite3Fts3MsrIncrStart(pTab, pSegcsr, iCol, pToken->z, pToken->n);
  125890. }
  125891. }
  125892. p->bIncr = 1;
  125893. }else{
  125894. /* Load the full doclist for the phrase into memory. */
  125895. rc = fts3EvalPhraseLoad(pCsr, p);
  125896. p->bIncr = 0;
  125897. }
  125898. assert( rc!=SQLITE_OK || p->nToken<1 || p->aToken[0].pSegcsr==0 || p->bIncr );
  125899. return rc;
  125900. }
  125901. /*
  125902. ** This function is used to iterate backwards (from the end to start)
  125903. ** through doclists. It is used by this module to iterate through phrase
  125904. ** doclists in reverse and by the fts3_write.c module to iterate through
  125905. ** pending-terms lists when writing to databases with "order=desc".
  125906. **
  125907. ** The doclist may be sorted in ascending (parameter bDescIdx==0) or
  125908. ** descending (parameter bDescIdx==1) order of docid. Regardless, this
  125909. ** function iterates from the end of the doclist to the beginning.
  125910. */
  125911. SQLITE_PRIVATE void sqlite3Fts3DoclistPrev(
  125912. int bDescIdx, /* True if the doclist is desc */
  125913. char *aDoclist, /* Pointer to entire doclist */
  125914. int nDoclist, /* Length of aDoclist in bytes */
  125915. char **ppIter, /* IN/OUT: Iterator pointer */
  125916. sqlite3_int64 *piDocid, /* IN/OUT: Docid pointer */
  125917. int *pnList, /* OUT: List length pointer */
  125918. u8 *pbEof /* OUT: End-of-file flag */
  125919. ){
  125920. char *p = *ppIter;
  125921. assert( nDoclist>0 );
  125922. assert( *pbEof==0 );
  125923. assert( p || *piDocid==0 );
  125924. assert( !p || (p>aDoclist && p<&aDoclist[nDoclist]) );
  125925. if( p==0 ){
  125926. sqlite3_int64 iDocid = 0;
  125927. char *pNext = 0;
  125928. char *pDocid = aDoclist;
  125929. char *pEnd = &aDoclist[nDoclist];
  125930. int iMul = 1;
  125931. while( pDocid<pEnd ){
  125932. sqlite3_int64 iDelta;
  125933. pDocid += sqlite3Fts3GetVarint(pDocid, &iDelta);
  125934. iDocid += (iMul * iDelta);
  125935. pNext = pDocid;
  125936. fts3PoslistCopy(0, &pDocid);
  125937. while( pDocid<pEnd && *pDocid==0 ) pDocid++;
  125938. iMul = (bDescIdx ? -1 : 1);
  125939. }
  125940. *pnList = (int)(pEnd - pNext);
  125941. *ppIter = pNext;
  125942. *piDocid = iDocid;
  125943. }else{
  125944. int iMul = (bDescIdx ? -1 : 1);
  125945. sqlite3_int64 iDelta;
  125946. fts3GetReverseVarint(&p, aDoclist, &iDelta);
  125947. *piDocid -= (iMul * iDelta);
  125948. if( p==aDoclist ){
  125949. *pbEof = 1;
  125950. }else{
  125951. char *pSave = p;
  125952. fts3ReversePoslist(aDoclist, &p);
  125953. *pnList = (int)(pSave - p);
  125954. }
  125955. *ppIter = p;
  125956. }
  125957. }
  125958. /*
  125959. ** Iterate forwards through a doclist.
  125960. */
  125961. SQLITE_PRIVATE void sqlite3Fts3DoclistNext(
  125962. int bDescIdx, /* True if the doclist is desc */
  125963. char *aDoclist, /* Pointer to entire doclist */
  125964. int nDoclist, /* Length of aDoclist in bytes */
  125965. char **ppIter, /* IN/OUT: Iterator pointer */
  125966. sqlite3_int64 *piDocid, /* IN/OUT: Docid pointer */
  125967. u8 *pbEof /* OUT: End-of-file flag */
  125968. ){
  125969. char *p = *ppIter;
  125970. assert( nDoclist>0 );
  125971. assert( *pbEof==0 );
  125972. assert( p || *piDocid==0 );
  125973. assert( !p || (p>=aDoclist && p<=&aDoclist[nDoclist]) );
  125974. if( p==0 ){
  125975. p = aDoclist;
  125976. p += sqlite3Fts3GetVarint(p, piDocid);
  125977. }else{
  125978. fts3PoslistCopy(0, &p);
  125979. if( p>=&aDoclist[nDoclist] ){
  125980. *pbEof = 1;
  125981. }else{
  125982. sqlite3_int64 iVar;
  125983. p += sqlite3Fts3GetVarint(p, &iVar);
  125984. *piDocid += ((bDescIdx ? -1 : 1) * iVar);
  125985. }
  125986. }
  125987. *ppIter = p;
  125988. }
  125989. /*
  125990. ** Advance the iterator pDL to the next entry in pDL->aAll/nAll. Set *pbEof
  125991. ** to true if EOF is reached.
  125992. */
  125993. static void fts3EvalDlPhraseNext(
  125994. Fts3Table *pTab,
  125995. Fts3Doclist *pDL,
  125996. u8 *pbEof
  125997. ){
  125998. char *pIter; /* Used to iterate through aAll */
  125999. char *pEnd = &pDL->aAll[pDL->nAll]; /* 1 byte past end of aAll */
  126000. if( pDL->pNextDocid ){
  126001. pIter = pDL->pNextDocid;
  126002. }else{
  126003. pIter = pDL->aAll;
  126004. }
  126005. if( pIter>=pEnd ){
  126006. /* We have already reached the end of this doclist. EOF. */
  126007. *pbEof = 1;
  126008. }else{
  126009. sqlite3_int64 iDelta;
  126010. pIter += sqlite3Fts3GetVarint(pIter, &iDelta);
  126011. if( pTab->bDescIdx==0 || pDL->pNextDocid==0 ){
  126012. pDL->iDocid += iDelta;
  126013. }else{
  126014. pDL->iDocid -= iDelta;
  126015. }
  126016. pDL->pList = pIter;
  126017. fts3PoslistCopy(0, &pIter);
  126018. pDL->nList = (int)(pIter - pDL->pList);
  126019. /* pIter now points just past the 0x00 that terminates the position-
  126020. ** list for document pDL->iDocid. However, if this position-list was
  126021. ** edited in place by fts3EvalNearTrim(), then pIter may not actually
  126022. ** point to the start of the next docid value. The following line deals
  126023. ** with this case by advancing pIter past the zero-padding added by
  126024. ** fts3EvalNearTrim(). */
  126025. while( pIter<pEnd && *pIter==0 ) pIter++;
  126026. pDL->pNextDocid = pIter;
  126027. assert( pIter>=&pDL->aAll[pDL->nAll] || *pIter );
  126028. *pbEof = 0;
  126029. }
  126030. }
  126031. /*
  126032. ** Helper type used by fts3EvalIncrPhraseNext() and incrPhraseTokenNext().
  126033. */
  126034. typedef struct TokenDoclist TokenDoclist;
  126035. struct TokenDoclist {
  126036. int bIgnore;
  126037. sqlite3_int64 iDocid;
  126038. char *pList;
  126039. int nList;
  126040. };
  126041. /*
  126042. ** Token pToken is an incrementally loaded token that is part of a
  126043. ** multi-token phrase. Advance it to the next matching document in the
  126044. ** database and populate output variable *p with the details of the new
  126045. ** entry. Or, if the iterator has reached EOF, set *pbEof to true.
  126046. **
  126047. ** If an error occurs, return an SQLite error code. Otherwise, return
  126048. ** SQLITE_OK.
  126049. */
  126050. static int incrPhraseTokenNext(
  126051. Fts3Table *pTab, /* Virtual table handle */
  126052. Fts3Phrase *pPhrase, /* Phrase to advance token of */
  126053. int iToken, /* Specific token to advance */
  126054. TokenDoclist *p, /* OUT: Docid and doclist for new entry */
  126055. u8 *pbEof /* OUT: True if iterator is at EOF */
  126056. ){
  126057. int rc = SQLITE_OK;
  126058. if( pPhrase->iDoclistToken==iToken ){
  126059. assert( p->bIgnore==0 );
  126060. assert( pPhrase->aToken[iToken].pSegcsr==0 );
  126061. fts3EvalDlPhraseNext(pTab, &pPhrase->doclist, pbEof);
  126062. p->pList = pPhrase->doclist.pList;
  126063. p->nList = pPhrase->doclist.nList;
  126064. p->iDocid = pPhrase->doclist.iDocid;
  126065. }else{
  126066. Fts3PhraseToken *pToken = &pPhrase->aToken[iToken];
  126067. assert( pToken->pDeferred==0 );
  126068. assert( pToken->pSegcsr || pPhrase->iDoclistToken>=0 );
  126069. if( pToken->pSegcsr ){
  126070. assert( p->bIgnore==0 );
  126071. rc = sqlite3Fts3MsrIncrNext(
  126072. pTab, pToken->pSegcsr, &p->iDocid, &p->pList, &p->nList
  126073. );
  126074. if( p->pList==0 ) *pbEof = 1;
  126075. }else{
  126076. p->bIgnore = 1;
  126077. }
  126078. }
  126079. return rc;
  126080. }
  126081. /*
  126082. ** The phrase iterator passed as the second argument:
  126083. **
  126084. ** * features at least one token that uses an incremental doclist, and
  126085. **
  126086. ** * does not contain any deferred tokens.
  126087. **
  126088. ** Advance it to the next matching documnent in the database and populate
  126089. ** the Fts3Doclist.pList and nList fields.
  126090. **
  126091. ** If there is no "next" entry and no error occurs, then *pbEof is set to
  126092. ** 1 before returning. Otherwise, if no error occurs and the iterator is
  126093. ** successfully advanced, *pbEof is set to 0.
  126094. **
  126095. ** If an error occurs, return an SQLite error code. Otherwise, return
  126096. ** SQLITE_OK.
  126097. */
  126098. static int fts3EvalIncrPhraseNext(
  126099. Fts3Cursor *pCsr, /* FTS Cursor handle */
  126100. Fts3Phrase *p, /* Phrase object to advance to next docid */
  126101. u8 *pbEof /* OUT: Set to 1 if EOF */
  126102. ){
  126103. int rc = SQLITE_OK;
  126104. Fts3Doclist *pDL = &p->doclist;
  126105. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  126106. u8 bEof = 0;
  126107. /* This is only called if it is guaranteed that the phrase has at least
  126108. ** one incremental token. In which case the bIncr flag is set. */
  126109. assert( p->bIncr==1 );
  126110. if( p->nToken==1 && p->bIncr ){
  126111. rc = sqlite3Fts3MsrIncrNext(pTab, p->aToken[0].pSegcsr,
  126112. &pDL->iDocid, &pDL->pList, &pDL->nList
  126113. );
  126114. if( pDL->pList==0 ) bEof = 1;
  126115. }else{
  126116. int bDescDoclist = pCsr->bDesc;
  126117. struct TokenDoclist a[MAX_INCR_PHRASE_TOKENS];
  126118. memset(a, 0, sizeof(a));
  126119. assert( p->nToken<=MAX_INCR_PHRASE_TOKENS );
  126120. assert( p->iDoclistToken<MAX_INCR_PHRASE_TOKENS );
  126121. while( bEof==0 ){
  126122. int bMaxSet = 0;
  126123. sqlite3_int64 iMax = 0; /* Largest docid for all iterators */
  126124. int i; /* Used to iterate through tokens */
  126125. /* Advance the iterator for each token in the phrase once. */
  126126. for(i=0; rc==SQLITE_OK && i<p->nToken && bEof==0; i++){
  126127. rc = incrPhraseTokenNext(pTab, p, i, &a[i], &bEof);
  126128. if( a[i].bIgnore==0 && (bMaxSet==0 || DOCID_CMP(iMax, a[i].iDocid)<0) ){
  126129. iMax = a[i].iDocid;
  126130. bMaxSet = 1;
  126131. }
  126132. }
  126133. assert( rc!=SQLITE_OK || (p->nToken>=1 && a[p->nToken-1].bIgnore==0) );
  126134. assert( rc!=SQLITE_OK || bMaxSet );
  126135. /* Keep advancing iterators until they all point to the same document */
  126136. for(i=0; i<p->nToken; i++){
  126137. while( rc==SQLITE_OK && bEof==0
  126138. && a[i].bIgnore==0 && DOCID_CMP(a[i].iDocid, iMax)<0
  126139. ){
  126140. rc = incrPhraseTokenNext(pTab, p, i, &a[i], &bEof);
  126141. if( DOCID_CMP(a[i].iDocid, iMax)>0 ){
  126142. iMax = a[i].iDocid;
  126143. i = 0;
  126144. }
  126145. }
  126146. }
  126147. /* Check if the current entries really are a phrase match */
  126148. if( bEof==0 ){
  126149. int nList = 0;
  126150. int nByte = a[p->nToken-1].nList;
  126151. char *aDoclist = sqlite3_malloc(nByte+1);
  126152. if( !aDoclist ) return SQLITE_NOMEM;
  126153. memcpy(aDoclist, a[p->nToken-1].pList, nByte+1);
  126154. for(i=0; i<(p->nToken-1); i++){
  126155. if( a[i].bIgnore==0 ){
  126156. char *pL = a[i].pList;
  126157. char *pR = aDoclist;
  126158. char *pOut = aDoclist;
  126159. int nDist = p->nToken-1-i;
  126160. int res = fts3PoslistPhraseMerge(&pOut, nDist, 0, 1, &pL, &pR);
  126161. if( res==0 ) break;
  126162. nList = (int)(pOut - aDoclist);
  126163. }
  126164. }
  126165. if( i==(p->nToken-1) ){
  126166. pDL->iDocid = iMax;
  126167. pDL->pList = aDoclist;
  126168. pDL->nList = nList;
  126169. pDL->bFreeList = 1;
  126170. break;
  126171. }
  126172. sqlite3_free(aDoclist);
  126173. }
  126174. }
  126175. }
  126176. *pbEof = bEof;
  126177. return rc;
  126178. }
  126179. /*
  126180. ** Attempt to move the phrase iterator to point to the next matching docid.
  126181. ** If an error occurs, return an SQLite error code. Otherwise, return
  126182. ** SQLITE_OK.
  126183. **
  126184. ** If there is no "next" entry and no error occurs, then *pbEof is set to
  126185. ** 1 before returning. Otherwise, if no error occurs and the iterator is
  126186. ** successfully advanced, *pbEof is set to 0.
  126187. */
  126188. static int fts3EvalPhraseNext(
  126189. Fts3Cursor *pCsr, /* FTS Cursor handle */
  126190. Fts3Phrase *p, /* Phrase object to advance to next docid */
  126191. u8 *pbEof /* OUT: Set to 1 if EOF */
  126192. ){
  126193. int rc = SQLITE_OK;
  126194. Fts3Doclist *pDL = &p->doclist;
  126195. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  126196. if( p->bIncr ){
  126197. rc = fts3EvalIncrPhraseNext(pCsr, p, pbEof);
  126198. }else if( pCsr->bDesc!=pTab->bDescIdx && pDL->nAll ){
  126199. sqlite3Fts3DoclistPrev(pTab->bDescIdx, pDL->aAll, pDL->nAll,
  126200. &pDL->pNextDocid, &pDL->iDocid, &pDL->nList, pbEof
  126201. );
  126202. pDL->pList = pDL->pNextDocid;
  126203. }else{
  126204. fts3EvalDlPhraseNext(pTab, pDL, pbEof);
  126205. }
  126206. return rc;
  126207. }
  126208. /*
  126209. **
  126210. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
  126211. ** Otherwise, fts3EvalPhraseStart() is called on all phrases within the
  126212. ** expression. Also the Fts3Expr.bDeferred variable is set to true for any
  126213. ** expressions for which all descendent tokens are deferred.
  126214. **
  126215. ** If parameter bOptOk is zero, then it is guaranteed that the
  126216. ** Fts3Phrase.doclist.aAll/nAll variables contain the entire doclist for
  126217. ** each phrase in the expression (subject to deferred token processing).
  126218. ** Or, if bOptOk is non-zero, then one or more tokens within the expression
  126219. ** may be loaded incrementally, meaning doclist.aAll/nAll is not available.
  126220. **
  126221. ** If an error occurs within this function, *pRc is set to an SQLite error
  126222. ** code before returning.
  126223. */
  126224. static void fts3EvalStartReaders(
  126225. Fts3Cursor *pCsr, /* FTS Cursor handle */
  126226. Fts3Expr *pExpr, /* Expression to initialize phrases in */
  126227. int *pRc /* IN/OUT: Error code */
  126228. ){
  126229. if( pExpr && SQLITE_OK==*pRc ){
  126230. if( pExpr->eType==FTSQUERY_PHRASE ){
  126231. int i;
  126232. int nToken = pExpr->pPhrase->nToken;
  126233. for(i=0; i<nToken; i++){
  126234. if( pExpr->pPhrase->aToken[i].pDeferred==0 ) break;
  126235. }
  126236. pExpr->bDeferred = (i==nToken);
  126237. *pRc = fts3EvalPhraseStart(pCsr, 1, pExpr->pPhrase);
  126238. }else{
  126239. fts3EvalStartReaders(pCsr, pExpr->pLeft, pRc);
  126240. fts3EvalStartReaders(pCsr, pExpr->pRight, pRc);
  126241. pExpr->bDeferred = (pExpr->pLeft->bDeferred && pExpr->pRight->bDeferred);
  126242. }
  126243. }
  126244. }
  126245. /*
  126246. ** An array of the following structures is assembled as part of the process
  126247. ** of selecting tokens to defer before the query starts executing (as part
  126248. ** of the xFilter() method). There is one element in the array for each
  126249. ** token in the FTS expression.
  126250. **
  126251. ** Tokens are divided into AND/NEAR clusters. All tokens in a cluster belong
  126252. ** to phrases that are connected only by AND and NEAR operators (not OR or
  126253. ** NOT). When determining tokens to defer, each AND/NEAR cluster is considered
  126254. ** separately. The root of a tokens AND/NEAR cluster is stored in
  126255. ** Fts3TokenAndCost.pRoot.
  126256. */
  126257. typedef struct Fts3TokenAndCost Fts3TokenAndCost;
  126258. struct Fts3TokenAndCost {
  126259. Fts3Phrase *pPhrase; /* The phrase the token belongs to */
  126260. int iToken; /* Position of token in phrase */
  126261. Fts3PhraseToken *pToken; /* The token itself */
  126262. Fts3Expr *pRoot; /* Root of NEAR/AND cluster */
  126263. int nOvfl; /* Number of overflow pages to load doclist */
  126264. int iCol; /* The column the token must match */
  126265. };
  126266. /*
  126267. ** This function is used to populate an allocated Fts3TokenAndCost array.
  126268. **
  126269. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
  126270. ** Otherwise, if an error occurs during execution, *pRc is set to an
  126271. ** SQLite error code.
  126272. */
  126273. static void fts3EvalTokenCosts(
  126274. Fts3Cursor *pCsr, /* FTS Cursor handle */
  126275. Fts3Expr *pRoot, /* Root of current AND/NEAR cluster */
  126276. Fts3Expr *pExpr, /* Expression to consider */
  126277. Fts3TokenAndCost **ppTC, /* Write new entries to *(*ppTC)++ */
  126278. Fts3Expr ***ppOr, /* Write new OR root to *(*ppOr)++ */
  126279. int *pRc /* IN/OUT: Error code */
  126280. ){
  126281. if( *pRc==SQLITE_OK ){
  126282. if( pExpr->eType==FTSQUERY_PHRASE ){
  126283. Fts3Phrase *pPhrase = pExpr->pPhrase;
  126284. int i;
  126285. for(i=0; *pRc==SQLITE_OK && i<pPhrase->nToken; i++){
  126286. Fts3TokenAndCost *pTC = (*ppTC)++;
  126287. pTC->pPhrase = pPhrase;
  126288. pTC->iToken = i;
  126289. pTC->pRoot = pRoot;
  126290. pTC->pToken = &pPhrase->aToken[i];
  126291. pTC->iCol = pPhrase->iColumn;
  126292. *pRc = sqlite3Fts3MsrOvfl(pCsr, pTC->pToken->pSegcsr, &pTC->nOvfl);
  126293. }
  126294. }else if( pExpr->eType!=FTSQUERY_NOT ){
  126295. assert( pExpr->eType==FTSQUERY_OR
  126296. || pExpr->eType==FTSQUERY_AND
  126297. || pExpr->eType==FTSQUERY_NEAR
  126298. );
  126299. assert( pExpr->pLeft && pExpr->pRight );
  126300. if( pExpr->eType==FTSQUERY_OR ){
  126301. pRoot = pExpr->pLeft;
  126302. **ppOr = pRoot;
  126303. (*ppOr)++;
  126304. }
  126305. fts3EvalTokenCosts(pCsr, pRoot, pExpr->pLeft, ppTC, ppOr, pRc);
  126306. if( pExpr->eType==FTSQUERY_OR ){
  126307. pRoot = pExpr->pRight;
  126308. **ppOr = pRoot;
  126309. (*ppOr)++;
  126310. }
  126311. fts3EvalTokenCosts(pCsr, pRoot, pExpr->pRight, ppTC, ppOr, pRc);
  126312. }
  126313. }
  126314. }
  126315. /*
  126316. ** Determine the average document (row) size in pages. If successful,
  126317. ** write this value to *pnPage and return SQLITE_OK. Otherwise, return
  126318. ** an SQLite error code.
  126319. **
  126320. ** The average document size in pages is calculated by first calculating
  126321. ** determining the average size in bytes, B. If B is less than the amount
  126322. ** of data that will fit on a single leaf page of an intkey table in
  126323. ** this database, then the average docsize is 1. Otherwise, it is 1 plus
  126324. ** the number of overflow pages consumed by a record B bytes in size.
  126325. */
  126326. static int fts3EvalAverageDocsize(Fts3Cursor *pCsr, int *pnPage){
  126327. if( pCsr->nRowAvg==0 ){
  126328. /* The average document size, which is required to calculate the cost
  126329. ** of each doclist, has not yet been determined. Read the required
  126330. ** data from the %_stat table to calculate it.
  126331. **
  126332. ** Entry 0 of the %_stat table is a blob containing (nCol+1) FTS3
  126333. ** varints, where nCol is the number of columns in the FTS3 table.
  126334. ** The first varint is the number of documents currently stored in
  126335. ** the table. The following nCol varints contain the total amount of
  126336. ** data stored in all rows of each column of the table, from left
  126337. ** to right.
  126338. */
  126339. int rc;
  126340. Fts3Table *p = (Fts3Table*)pCsr->base.pVtab;
  126341. sqlite3_stmt *pStmt;
  126342. sqlite3_int64 nDoc = 0;
  126343. sqlite3_int64 nByte = 0;
  126344. const char *pEnd;
  126345. const char *a;
  126346. rc = sqlite3Fts3SelectDoctotal(p, &pStmt);
  126347. if( rc!=SQLITE_OK ) return rc;
  126348. a = sqlite3_column_blob(pStmt, 0);
  126349. assert( a );
  126350. pEnd = &a[sqlite3_column_bytes(pStmt, 0)];
  126351. a += sqlite3Fts3GetVarint(a, &nDoc);
  126352. while( a<pEnd ){
  126353. a += sqlite3Fts3GetVarint(a, &nByte);
  126354. }
  126355. if( nDoc==0 || nByte==0 ){
  126356. sqlite3_reset(pStmt);
  126357. return FTS_CORRUPT_VTAB;
  126358. }
  126359. pCsr->nDoc = nDoc;
  126360. pCsr->nRowAvg = (int)(((nByte / nDoc) + p->nPgsz) / p->nPgsz);
  126361. assert( pCsr->nRowAvg>0 );
  126362. rc = sqlite3_reset(pStmt);
  126363. if( rc!=SQLITE_OK ) return rc;
  126364. }
  126365. *pnPage = pCsr->nRowAvg;
  126366. return SQLITE_OK;
  126367. }
  126368. /*
  126369. ** This function is called to select the tokens (if any) that will be
  126370. ** deferred. The array aTC[] has already been populated when this is
  126371. ** called.
  126372. **
  126373. ** This function is called once for each AND/NEAR cluster in the
  126374. ** expression. Each invocation determines which tokens to defer within
  126375. ** the cluster with root node pRoot. See comments above the definition
  126376. ** of struct Fts3TokenAndCost for more details.
  126377. **
  126378. ** If no error occurs, SQLITE_OK is returned and sqlite3Fts3DeferToken()
  126379. ** called on each token to defer. Otherwise, an SQLite error code is
  126380. ** returned.
  126381. */
  126382. static int fts3EvalSelectDeferred(
  126383. Fts3Cursor *pCsr, /* FTS Cursor handle */
  126384. Fts3Expr *pRoot, /* Consider tokens with this root node */
  126385. Fts3TokenAndCost *aTC, /* Array of expression tokens and costs */
  126386. int nTC /* Number of entries in aTC[] */
  126387. ){
  126388. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  126389. int nDocSize = 0; /* Number of pages per doc loaded */
  126390. int rc = SQLITE_OK; /* Return code */
  126391. int ii; /* Iterator variable for various purposes */
  126392. int nOvfl = 0; /* Total overflow pages used by doclists */
  126393. int nToken = 0; /* Total number of tokens in cluster */
  126394. int nMinEst = 0; /* The minimum count for any phrase so far. */
  126395. int nLoad4 = 1; /* (Phrases that will be loaded)^4. */
  126396. /* Tokens are never deferred for FTS tables created using the content=xxx
  126397. ** option. The reason being that it is not guaranteed that the content
  126398. ** table actually contains the same data as the index. To prevent this from
  126399. ** causing any problems, the deferred token optimization is completely
  126400. ** disabled for content=xxx tables. */
  126401. if( pTab->zContentTbl ){
  126402. return SQLITE_OK;
  126403. }
  126404. /* Count the tokens in this AND/NEAR cluster. If none of the doclists
  126405. ** associated with the tokens spill onto overflow pages, or if there is
  126406. ** only 1 token, exit early. No tokens to defer in this case. */
  126407. for(ii=0; ii<nTC; ii++){
  126408. if( aTC[ii].pRoot==pRoot ){
  126409. nOvfl += aTC[ii].nOvfl;
  126410. nToken++;
  126411. }
  126412. }
  126413. if( nOvfl==0 || nToken<2 ) return SQLITE_OK;
  126414. /* Obtain the average docsize (in pages). */
  126415. rc = fts3EvalAverageDocsize(pCsr, &nDocSize);
  126416. assert( rc!=SQLITE_OK || nDocSize>0 );
  126417. /* Iterate through all tokens in this AND/NEAR cluster, in ascending order
  126418. ** of the number of overflow pages that will be loaded by the pager layer
  126419. ** to retrieve the entire doclist for the token from the full-text index.
  126420. ** Load the doclists for tokens that are either:
  126421. **
  126422. ** a. The cheapest token in the entire query (i.e. the one visited by the
  126423. ** first iteration of this loop), or
  126424. **
  126425. ** b. Part of a multi-token phrase.
  126426. **
  126427. ** After each token doclist is loaded, merge it with the others from the
  126428. ** same phrase and count the number of documents that the merged doclist
  126429. ** contains. Set variable "nMinEst" to the smallest number of documents in
  126430. ** any phrase doclist for which 1 or more token doclists have been loaded.
  126431. ** Let nOther be the number of other phrases for which it is certain that
  126432. ** one or more tokens will not be deferred.
  126433. **
  126434. ** Then, for each token, defer it if loading the doclist would result in
  126435. ** loading N or more overflow pages into memory, where N is computed as:
  126436. **
  126437. ** (nMinEst + 4^nOther - 1) / (4^nOther)
  126438. */
  126439. for(ii=0; ii<nToken && rc==SQLITE_OK; ii++){
  126440. int iTC; /* Used to iterate through aTC[] array. */
  126441. Fts3TokenAndCost *pTC = 0; /* Set to cheapest remaining token. */
  126442. /* Set pTC to point to the cheapest remaining token. */
  126443. for(iTC=0; iTC<nTC; iTC++){
  126444. if( aTC[iTC].pToken && aTC[iTC].pRoot==pRoot
  126445. && (!pTC || aTC[iTC].nOvfl<pTC->nOvfl)
  126446. ){
  126447. pTC = &aTC[iTC];
  126448. }
  126449. }
  126450. assert( pTC );
  126451. if( ii && pTC->nOvfl>=((nMinEst+(nLoad4/4)-1)/(nLoad4/4))*nDocSize ){
  126452. /* The number of overflow pages to load for this (and therefore all
  126453. ** subsequent) tokens is greater than the estimated number of pages
  126454. ** that will be loaded if all subsequent tokens are deferred.
  126455. */
  126456. Fts3PhraseToken *pToken = pTC->pToken;
  126457. rc = sqlite3Fts3DeferToken(pCsr, pToken, pTC->iCol);
  126458. fts3SegReaderCursorFree(pToken->pSegcsr);
  126459. pToken->pSegcsr = 0;
  126460. }else{
  126461. /* Set nLoad4 to the value of (4^nOther) for the next iteration of the
  126462. ** for-loop. Except, limit the value to 2^24 to prevent it from
  126463. ** overflowing the 32-bit integer it is stored in. */
  126464. if( ii<12 ) nLoad4 = nLoad4*4;
  126465. if( ii==0 || (pTC->pPhrase->nToken>1 && ii!=nToken-1) ){
  126466. /* Either this is the cheapest token in the entire query, or it is
  126467. ** part of a multi-token phrase. Either way, the entire doclist will
  126468. ** (eventually) be loaded into memory. It may as well be now. */
  126469. Fts3PhraseToken *pToken = pTC->pToken;
  126470. int nList = 0;
  126471. char *pList = 0;
  126472. rc = fts3TermSelect(pTab, pToken, pTC->iCol, &nList, &pList);
  126473. assert( rc==SQLITE_OK || pList==0 );
  126474. if( rc==SQLITE_OK ){
  126475. int nCount;
  126476. fts3EvalPhraseMergeToken(pTab, pTC->pPhrase, pTC->iToken,pList,nList);
  126477. nCount = fts3DoclistCountDocids(
  126478. pTC->pPhrase->doclist.aAll, pTC->pPhrase->doclist.nAll
  126479. );
  126480. if( ii==0 || nCount<nMinEst ) nMinEst = nCount;
  126481. }
  126482. }
  126483. }
  126484. pTC->pToken = 0;
  126485. }
  126486. return rc;
  126487. }
  126488. /*
  126489. ** This function is called from within the xFilter method. It initializes
  126490. ** the full-text query currently stored in pCsr->pExpr. To iterate through
  126491. ** the results of a query, the caller does:
  126492. **
  126493. ** fts3EvalStart(pCsr);
  126494. ** while( 1 ){
  126495. ** fts3EvalNext(pCsr);
  126496. ** if( pCsr->bEof ) break;
  126497. ** ... return row pCsr->iPrevId to the caller ...
  126498. ** }
  126499. */
  126500. static int fts3EvalStart(Fts3Cursor *pCsr){
  126501. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  126502. int rc = SQLITE_OK;
  126503. int nToken = 0;
  126504. int nOr = 0;
  126505. /* Allocate a MultiSegReader for each token in the expression. */
  126506. fts3EvalAllocateReaders(pCsr, pCsr->pExpr, &nToken, &nOr, &rc);
  126507. /* Determine which, if any, tokens in the expression should be deferred. */
  126508. #ifndef SQLITE_DISABLE_FTS4_DEFERRED
  126509. if( rc==SQLITE_OK && nToken>1 && pTab->bFts4 ){
  126510. Fts3TokenAndCost *aTC;
  126511. Fts3Expr **apOr;
  126512. aTC = (Fts3TokenAndCost *)sqlite3_malloc(
  126513. sizeof(Fts3TokenAndCost) * nToken
  126514. + sizeof(Fts3Expr *) * nOr * 2
  126515. );
  126516. apOr = (Fts3Expr **)&aTC[nToken];
  126517. if( !aTC ){
  126518. rc = SQLITE_NOMEM;
  126519. }else{
  126520. int ii;
  126521. Fts3TokenAndCost *pTC = aTC;
  126522. Fts3Expr **ppOr = apOr;
  126523. fts3EvalTokenCosts(pCsr, 0, pCsr->pExpr, &pTC, &ppOr, &rc);
  126524. nToken = (int)(pTC-aTC);
  126525. nOr = (int)(ppOr-apOr);
  126526. if( rc==SQLITE_OK ){
  126527. rc = fts3EvalSelectDeferred(pCsr, 0, aTC, nToken);
  126528. for(ii=0; rc==SQLITE_OK && ii<nOr; ii++){
  126529. rc = fts3EvalSelectDeferred(pCsr, apOr[ii], aTC, nToken);
  126530. }
  126531. }
  126532. sqlite3_free(aTC);
  126533. }
  126534. }
  126535. #endif
  126536. fts3EvalStartReaders(pCsr, pCsr->pExpr, &rc);
  126537. return rc;
  126538. }
  126539. /*
  126540. ** Invalidate the current position list for phrase pPhrase.
  126541. */
  126542. static void fts3EvalInvalidatePoslist(Fts3Phrase *pPhrase){
  126543. if( pPhrase->doclist.bFreeList ){
  126544. sqlite3_free(pPhrase->doclist.pList);
  126545. }
  126546. pPhrase->doclist.pList = 0;
  126547. pPhrase->doclist.nList = 0;
  126548. pPhrase->doclist.bFreeList = 0;
  126549. }
  126550. /*
  126551. ** This function is called to edit the position list associated with
  126552. ** the phrase object passed as the fifth argument according to a NEAR
  126553. ** condition. For example:
  126554. **
  126555. ** abc NEAR/5 "def ghi"
  126556. **
  126557. ** Parameter nNear is passed the NEAR distance of the expression (5 in
  126558. ** the example above). When this function is called, *paPoslist points to
  126559. ** the position list, and *pnToken is the number of phrase tokens in, the
  126560. ** phrase on the other side of the NEAR operator to pPhrase. For example,
  126561. ** if pPhrase refers to the "def ghi" phrase, then *paPoslist points to
  126562. ** the position list associated with phrase "abc".
  126563. **
  126564. ** All positions in the pPhrase position list that are not sufficiently
  126565. ** close to a position in the *paPoslist position list are removed. If this
  126566. ** leaves 0 positions, zero is returned. Otherwise, non-zero.
  126567. **
  126568. ** Before returning, *paPoslist is set to point to the position lsit
  126569. ** associated with pPhrase. And *pnToken is set to the number of tokens in
  126570. ** pPhrase.
  126571. */
  126572. static int fts3EvalNearTrim(
  126573. int nNear, /* NEAR distance. As in "NEAR/nNear". */
  126574. char *aTmp, /* Temporary space to use */
  126575. char **paPoslist, /* IN/OUT: Position list */
  126576. int *pnToken, /* IN/OUT: Tokens in phrase of *paPoslist */
  126577. Fts3Phrase *pPhrase /* The phrase object to trim the doclist of */
  126578. ){
  126579. int nParam1 = nNear + pPhrase->nToken;
  126580. int nParam2 = nNear + *pnToken;
  126581. int nNew;
  126582. char *p2;
  126583. char *pOut;
  126584. int res;
  126585. assert( pPhrase->doclist.pList );
  126586. p2 = pOut = pPhrase->doclist.pList;
  126587. res = fts3PoslistNearMerge(
  126588. &pOut, aTmp, nParam1, nParam2, paPoslist, &p2
  126589. );
  126590. if( res ){
  126591. nNew = (int)(pOut - pPhrase->doclist.pList) - 1;
  126592. assert( pPhrase->doclist.pList[nNew]=='\0' );
  126593. assert( nNew<=pPhrase->doclist.nList && nNew>0 );
  126594. memset(&pPhrase->doclist.pList[nNew], 0, pPhrase->doclist.nList - nNew);
  126595. pPhrase->doclist.nList = nNew;
  126596. *paPoslist = pPhrase->doclist.pList;
  126597. *pnToken = pPhrase->nToken;
  126598. }
  126599. return res;
  126600. }
  126601. /*
  126602. ** This function is a no-op if *pRc is other than SQLITE_OK when it is called.
  126603. ** Otherwise, it advances the expression passed as the second argument to
  126604. ** point to the next matching row in the database. Expressions iterate through
  126605. ** matching rows in docid order. Ascending order if Fts3Cursor.bDesc is zero,
  126606. ** or descending if it is non-zero.
  126607. **
  126608. ** If an error occurs, *pRc is set to an SQLite error code. Otherwise, if
  126609. ** successful, the following variables in pExpr are set:
  126610. **
  126611. ** Fts3Expr.bEof (non-zero if EOF - there is no next row)
  126612. ** Fts3Expr.iDocid (valid if bEof==0. The docid of the next row)
  126613. **
  126614. ** If the expression is of type FTSQUERY_PHRASE, and the expression is not
  126615. ** at EOF, then the following variables are populated with the position list
  126616. ** for the phrase for the visited row:
  126617. **
  126618. ** FTs3Expr.pPhrase->doclist.nList (length of pList in bytes)
  126619. ** FTs3Expr.pPhrase->doclist.pList (pointer to position list)
  126620. **
  126621. ** It says above that this function advances the expression to the next
  126622. ** matching row. This is usually true, but there are the following exceptions:
  126623. **
  126624. ** 1. Deferred tokens are not taken into account. If a phrase consists
  126625. ** entirely of deferred tokens, it is assumed to match every row in
  126626. ** the db. In this case the position-list is not populated at all.
  126627. **
  126628. ** Or, if a phrase contains one or more deferred tokens and one or
  126629. ** more non-deferred tokens, then the expression is advanced to the
  126630. ** next possible match, considering only non-deferred tokens. In other
  126631. ** words, if the phrase is "A B C", and "B" is deferred, the expression
  126632. ** is advanced to the next row that contains an instance of "A * C",
  126633. ** where "*" may match any single token. The position list in this case
  126634. ** is populated as for "A * C" before returning.
  126635. **
  126636. ** 2. NEAR is treated as AND. If the expression is "x NEAR y", it is
  126637. ** advanced to point to the next row that matches "x AND y".
  126638. **
  126639. ** See fts3EvalTestDeferredAndNear() for details on testing if a row is
  126640. ** really a match, taking into account deferred tokens and NEAR operators.
  126641. */
  126642. static void fts3EvalNextRow(
  126643. Fts3Cursor *pCsr, /* FTS Cursor handle */
  126644. Fts3Expr *pExpr, /* Expr. to advance to next matching row */
  126645. int *pRc /* IN/OUT: Error code */
  126646. ){
  126647. if( *pRc==SQLITE_OK ){
  126648. int bDescDoclist = pCsr->bDesc; /* Used by DOCID_CMP() macro */
  126649. assert( pExpr->bEof==0 );
  126650. pExpr->bStart = 1;
  126651. switch( pExpr->eType ){
  126652. case FTSQUERY_NEAR:
  126653. case FTSQUERY_AND: {
  126654. Fts3Expr *pLeft = pExpr->pLeft;
  126655. Fts3Expr *pRight = pExpr->pRight;
  126656. assert( !pLeft->bDeferred || !pRight->bDeferred );
  126657. if( pLeft->bDeferred ){
  126658. /* LHS is entirely deferred. So we assume it matches every row.
  126659. ** Advance the RHS iterator to find the next row visited. */
  126660. fts3EvalNextRow(pCsr, pRight, pRc);
  126661. pExpr->iDocid = pRight->iDocid;
  126662. pExpr->bEof = pRight->bEof;
  126663. }else if( pRight->bDeferred ){
  126664. /* RHS is entirely deferred. So we assume it matches every row.
  126665. ** Advance the LHS iterator to find the next row visited. */
  126666. fts3EvalNextRow(pCsr, pLeft, pRc);
  126667. pExpr->iDocid = pLeft->iDocid;
  126668. pExpr->bEof = pLeft->bEof;
  126669. }else{
  126670. /* Neither the RHS or LHS are deferred. */
  126671. fts3EvalNextRow(pCsr, pLeft, pRc);
  126672. fts3EvalNextRow(pCsr, pRight, pRc);
  126673. while( !pLeft->bEof && !pRight->bEof && *pRc==SQLITE_OK ){
  126674. sqlite3_int64 iDiff = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
  126675. if( iDiff==0 ) break;
  126676. if( iDiff<0 ){
  126677. fts3EvalNextRow(pCsr, pLeft, pRc);
  126678. }else{
  126679. fts3EvalNextRow(pCsr, pRight, pRc);
  126680. }
  126681. }
  126682. pExpr->iDocid = pLeft->iDocid;
  126683. pExpr->bEof = (pLeft->bEof || pRight->bEof);
  126684. }
  126685. break;
  126686. }
  126687. case FTSQUERY_OR: {
  126688. Fts3Expr *pLeft = pExpr->pLeft;
  126689. Fts3Expr *pRight = pExpr->pRight;
  126690. sqlite3_int64 iCmp = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
  126691. assert( pLeft->bStart || pLeft->iDocid==pRight->iDocid );
  126692. assert( pRight->bStart || pLeft->iDocid==pRight->iDocid );
  126693. if( pRight->bEof || (pLeft->bEof==0 && iCmp<0) ){
  126694. fts3EvalNextRow(pCsr, pLeft, pRc);
  126695. }else if( pLeft->bEof || (pRight->bEof==0 && iCmp>0) ){
  126696. fts3EvalNextRow(pCsr, pRight, pRc);
  126697. }else{
  126698. fts3EvalNextRow(pCsr, pLeft, pRc);
  126699. fts3EvalNextRow(pCsr, pRight, pRc);
  126700. }
  126701. pExpr->bEof = (pLeft->bEof && pRight->bEof);
  126702. iCmp = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
  126703. if( pRight->bEof || (pLeft->bEof==0 && iCmp<0) ){
  126704. pExpr->iDocid = pLeft->iDocid;
  126705. }else{
  126706. pExpr->iDocid = pRight->iDocid;
  126707. }
  126708. break;
  126709. }
  126710. case FTSQUERY_NOT: {
  126711. Fts3Expr *pLeft = pExpr->pLeft;
  126712. Fts3Expr *pRight = pExpr->pRight;
  126713. if( pRight->bStart==0 ){
  126714. fts3EvalNextRow(pCsr, pRight, pRc);
  126715. assert( *pRc!=SQLITE_OK || pRight->bStart );
  126716. }
  126717. fts3EvalNextRow(pCsr, pLeft, pRc);
  126718. if( pLeft->bEof==0 ){
  126719. while( !*pRc
  126720. && !pRight->bEof
  126721. && DOCID_CMP(pLeft->iDocid, pRight->iDocid)>0
  126722. ){
  126723. fts3EvalNextRow(pCsr, pRight, pRc);
  126724. }
  126725. }
  126726. pExpr->iDocid = pLeft->iDocid;
  126727. pExpr->bEof = pLeft->bEof;
  126728. break;
  126729. }
  126730. default: {
  126731. Fts3Phrase *pPhrase = pExpr->pPhrase;
  126732. fts3EvalInvalidatePoslist(pPhrase);
  126733. *pRc = fts3EvalPhraseNext(pCsr, pPhrase, &pExpr->bEof);
  126734. pExpr->iDocid = pPhrase->doclist.iDocid;
  126735. break;
  126736. }
  126737. }
  126738. }
  126739. }
  126740. /*
  126741. ** If *pRc is not SQLITE_OK, or if pExpr is not the root node of a NEAR
  126742. ** cluster, then this function returns 1 immediately.
  126743. **
  126744. ** Otherwise, it checks if the current row really does match the NEAR
  126745. ** expression, using the data currently stored in the position lists
  126746. ** (Fts3Expr->pPhrase.doclist.pList/nList) for each phrase in the expression.
  126747. **
  126748. ** If the current row is a match, the position list associated with each
  126749. ** phrase in the NEAR expression is edited in place to contain only those
  126750. ** phrase instances sufficiently close to their peers to satisfy all NEAR
  126751. ** constraints. In this case it returns 1. If the NEAR expression does not
  126752. ** match the current row, 0 is returned. The position lists may or may not
  126753. ** be edited if 0 is returned.
  126754. */
  126755. static int fts3EvalNearTest(Fts3Expr *pExpr, int *pRc){
  126756. int res = 1;
  126757. /* The following block runs if pExpr is the root of a NEAR query.
  126758. ** For example, the query:
  126759. **
  126760. ** "w" NEAR "x" NEAR "y" NEAR "z"
  126761. **
  126762. ** which is represented in tree form as:
  126763. **
  126764. ** |
  126765. ** +--NEAR--+ <-- root of NEAR query
  126766. ** | |
  126767. ** +--NEAR--+ "z"
  126768. ** | |
  126769. ** +--NEAR--+ "y"
  126770. ** | |
  126771. ** "w" "x"
  126772. **
  126773. ** The right-hand child of a NEAR node is always a phrase. The
  126774. ** left-hand child may be either a phrase or a NEAR node. There are
  126775. ** no exceptions to this - it's the way the parser in fts3_expr.c works.
  126776. */
  126777. if( *pRc==SQLITE_OK
  126778. && pExpr->eType==FTSQUERY_NEAR
  126779. && pExpr->bEof==0
  126780. && (pExpr->pParent==0 || pExpr->pParent->eType!=FTSQUERY_NEAR)
  126781. ){
  126782. Fts3Expr *p;
  126783. int nTmp = 0; /* Bytes of temp space */
  126784. char *aTmp; /* Temp space for PoslistNearMerge() */
  126785. /* Allocate temporary working space. */
  126786. for(p=pExpr; p->pLeft; p=p->pLeft){
  126787. nTmp += p->pRight->pPhrase->doclist.nList;
  126788. }
  126789. nTmp += p->pPhrase->doclist.nList;
  126790. if( nTmp==0 ){
  126791. res = 0;
  126792. }else{
  126793. aTmp = sqlite3_malloc(nTmp*2);
  126794. if( !aTmp ){
  126795. *pRc = SQLITE_NOMEM;
  126796. res = 0;
  126797. }else{
  126798. char *aPoslist = p->pPhrase->doclist.pList;
  126799. int nToken = p->pPhrase->nToken;
  126800. for(p=p->pParent;res && p && p->eType==FTSQUERY_NEAR; p=p->pParent){
  126801. Fts3Phrase *pPhrase = p->pRight->pPhrase;
  126802. int nNear = p->nNear;
  126803. res = fts3EvalNearTrim(nNear, aTmp, &aPoslist, &nToken, pPhrase);
  126804. }
  126805. aPoslist = pExpr->pRight->pPhrase->doclist.pList;
  126806. nToken = pExpr->pRight->pPhrase->nToken;
  126807. for(p=pExpr->pLeft; p && res; p=p->pLeft){
  126808. int nNear;
  126809. Fts3Phrase *pPhrase;
  126810. assert( p->pParent && p->pParent->pLeft==p );
  126811. nNear = p->pParent->nNear;
  126812. pPhrase = (
  126813. p->eType==FTSQUERY_NEAR ? p->pRight->pPhrase : p->pPhrase
  126814. );
  126815. res = fts3EvalNearTrim(nNear, aTmp, &aPoslist, &nToken, pPhrase);
  126816. }
  126817. }
  126818. sqlite3_free(aTmp);
  126819. }
  126820. }
  126821. return res;
  126822. }
  126823. /*
  126824. ** This function is a helper function for fts3EvalTestDeferredAndNear().
  126825. ** Assuming no error occurs or has occurred, It returns non-zero if the
  126826. ** expression passed as the second argument matches the row that pCsr
  126827. ** currently points to, or zero if it does not.
  126828. **
  126829. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
  126830. ** If an error occurs during execution of this function, *pRc is set to
  126831. ** the appropriate SQLite error code. In this case the returned value is
  126832. ** undefined.
  126833. */
  126834. static int fts3EvalTestExpr(
  126835. Fts3Cursor *pCsr, /* FTS cursor handle */
  126836. Fts3Expr *pExpr, /* Expr to test. May or may not be root. */
  126837. int *pRc /* IN/OUT: Error code */
  126838. ){
  126839. int bHit = 1; /* Return value */
  126840. if( *pRc==SQLITE_OK ){
  126841. switch( pExpr->eType ){
  126842. case FTSQUERY_NEAR:
  126843. case FTSQUERY_AND:
  126844. bHit = (
  126845. fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc)
  126846. && fts3EvalTestExpr(pCsr, pExpr->pRight, pRc)
  126847. && fts3EvalNearTest(pExpr, pRc)
  126848. );
  126849. /* If the NEAR expression does not match any rows, zero the doclist for
  126850. ** all phrases involved in the NEAR. This is because the snippet(),
  126851. ** offsets() and matchinfo() functions are not supposed to recognize
  126852. ** any instances of phrases that are part of unmatched NEAR queries.
  126853. ** For example if this expression:
  126854. **
  126855. ** ... MATCH 'a OR (b NEAR c)'
  126856. **
  126857. ** is matched against a row containing:
  126858. **
  126859. ** 'a b d e'
  126860. **
  126861. ** then any snippet() should ony highlight the "a" term, not the "b"
  126862. ** (as "b" is part of a non-matching NEAR clause).
  126863. */
  126864. if( bHit==0
  126865. && pExpr->eType==FTSQUERY_NEAR
  126866. && (pExpr->pParent==0 || pExpr->pParent->eType!=FTSQUERY_NEAR)
  126867. ){
  126868. Fts3Expr *p;
  126869. for(p=pExpr; p->pPhrase==0; p=p->pLeft){
  126870. if( p->pRight->iDocid==pCsr->iPrevId ){
  126871. fts3EvalInvalidatePoslist(p->pRight->pPhrase);
  126872. }
  126873. }
  126874. if( p->iDocid==pCsr->iPrevId ){
  126875. fts3EvalInvalidatePoslist(p->pPhrase);
  126876. }
  126877. }
  126878. break;
  126879. case FTSQUERY_OR: {
  126880. int bHit1 = fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc);
  126881. int bHit2 = fts3EvalTestExpr(pCsr, pExpr->pRight, pRc);
  126882. bHit = bHit1 || bHit2;
  126883. break;
  126884. }
  126885. case FTSQUERY_NOT:
  126886. bHit = (
  126887. fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc)
  126888. && !fts3EvalTestExpr(pCsr, pExpr->pRight, pRc)
  126889. );
  126890. break;
  126891. default: {
  126892. #ifndef SQLITE_DISABLE_FTS4_DEFERRED
  126893. if( pCsr->pDeferred
  126894. && (pExpr->iDocid==pCsr->iPrevId || pExpr->bDeferred)
  126895. ){
  126896. Fts3Phrase *pPhrase = pExpr->pPhrase;
  126897. assert( pExpr->bDeferred || pPhrase->doclist.bFreeList==0 );
  126898. if( pExpr->bDeferred ){
  126899. fts3EvalInvalidatePoslist(pPhrase);
  126900. }
  126901. *pRc = fts3EvalDeferredPhrase(pCsr, pPhrase);
  126902. bHit = (pPhrase->doclist.pList!=0);
  126903. pExpr->iDocid = pCsr->iPrevId;
  126904. }else
  126905. #endif
  126906. {
  126907. bHit = (pExpr->bEof==0 && pExpr->iDocid==pCsr->iPrevId);
  126908. }
  126909. break;
  126910. }
  126911. }
  126912. }
  126913. return bHit;
  126914. }
  126915. /*
  126916. ** This function is called as the second part of each xNext operation when
  126917. ** iterating through the results of a full-text query. At this point the
  126918. ** cursor points to a row that matches the query expression, with the
  126919. ** following caveats:
  126920. **
  126921. ** * Up until this point, "NEAR" operators in the expression have been
  126922. ** treated as "AND".
  126923. **
  126924. ** * Deferred tokens have not yet been considered.
  126925. **
  126926. ** If *pRc is not SQLITE_OK when this function is called, it immediately
  126927. ** returns 0. Otherwise, it tests whether or not after considering NEAR
  126928. ** operators and deferred tokens the current row is still a match for the
  126929. ** expression. It returns 1 if both of the following are true:
  126930. **
  126931. ** 1. *pRc is SQLITE_OK when this function returns, and
  126932. **
  126933. ** 2. After scanning the current FTS table row for the deferred tokens,
  126934. ** it is determined that the row does *not* match the query.
  126935. **
  126936. ** Or, if no error occurs and it seems the current row does match the FTS
  126937. ** query, return 0.
  126938. */
  126939. static int fts3EvalTestDeferredAndNear(Fts3Cursor *pCsr, int *pRc){
  126940. int rc = *pRc;
  126941. int bMiss = 0;
  126942. if( rc==SQLITE_OK ){
  126943. /* If there are one or more deferred tokens, load the current row into
  126944. ** memory and scan it to determine the position list for each deferred
  126945. ** token. Then, see if this row is really a match, considering deferred
  126946. ** tokens and NEAR operators (neither of which were taken into account
  126947. ** earlier, by fts3EvalNextRow()).
  126948. */
  126949. if( pCsr->pDeferred ){
  126950. rc = fts3CursorSeek(0, pCsr);
  126951. if( rc==SQLITE_OK ){
  126952. rc = sqlite3Fts3CacheDeferredDoclists(pCsr);
  126953. }
  126954. }
  126955. bMiss = (0==fts3EvalTestExpr(pCsr, pCsr->pExpr, &rc));
  126956. /* Free the position-lists accumulated for each deferred token above. */
  126957. sqlite3Fts3FreeDeferredDoclists(pCsr);
  126958. *pRc = rc;
  126959. }
  126960. return (rc==SQLITE_OK && bMiss);
  126961. }
  126962. /*
  126963. ** Advance to the next document that matches the FTS expression in
  126964. ** Fts3Cursor.pExpr.
  126965. */
  126966. static int fts3EvalNext(Fts3Cursor *pCsr){
  126967. int rc = SQLITE_OK; /* Return Code */
  126968. Fts3Expr *pExpr = pCsr->pExpr;
  126969. assert( pCsr->isEof==0 );
  126970. if( pExpr==0 ){
  126971. pCsr->isEof = 1;
  126972. }else{
  126973. do {
  126974. if( pCsr->isRequireSeek==0 ){
  126975. sqlite3_reset(pCsr->pStmt);
  126976. }
  126977. assert( sqlite3_data_count(pCsr->pStmt)==0 );
  126978. fts3EvalNextRow(pCsr, pExpr, &rc);
  126979. pCsr->isEof = pExpr->bEof;
  126980. pCsr->isRequireSeek = 1;
  126981. pCsr->isMatchinfoNeeded = 1;
  126982. pCsr->iPrevId = pExpr->iDocid;
  126983. }while( pCsr->isEof==0 && fts3EvalTestDeferredAndNear(pCsr, &rc) );
  126984. }
  126985. /* Check if the cursor is past the end of the docid range specified
  126986. ** by Fts3Cursor.iMinDocid/iMaxDocid. If so, set the EOF flag. */
  126987. if( rc==SQLITE_OK && (
  126988. (pCsr->bDesc==0 && pCsr->iPrevId>pCsr->iMaxDocid)
  126989. || (pCsr->bDesc!=0 && pCsr->iPrevId<pCsr->iMinDocid)
  126990. )){
  126991. pCsr->isEof = 1;
  126992. }
  126993. return rc;
  126994. }
  126995. /*
  126996. ** Restart interation for expression pExpr so that the next call to
  126997. ** fts3EvalNext() visits the first row. Do not allow incremental
  126998. ** loading or merging of phrase doclists for this iteration.
  126999. **
  127000. ** If *pRc is other than SQLITE_OK when this function is called, it is
  127001. ** a no-op. If an error occurs within this function, *pRc is set to an
  127002. ** SQLite error code before returning.
  127003. */
  127004. static void fts3EvalRestart(
  127005. Fts3Cursor *pCsr,
  127006. Fts3Expr *pExpr,
  127007. int *pRc
  127008. ){
  127009. if( pExpr && *pRc==SQLITE_OK ){
  127010. Fts3Phrase *pPhrase = pExpr->pPhrase;
  127011. if( pPhrase ){
  127012. fts3EvalInvalidatePoslist(pPhrase);
  127013. if( pPhrase->bIncr ){
  127014. int i;
  127015. for(i=0; i<pPhrase->nToken; i++){
  127016. Fts3PhraseToken *pToken = &pPhrase->aToken[i];
  127017. assert( pToken->pDeferred==0 );
  127018. if( pToken->pSegcsr ){
  127019. sqlite3Fts3MsrIncrRestart(pToken->pSegcsr);
  127020. }
  127021. }
  127022. *pRc = fts3EvalPhraseStart(pCsr, 0, pPhrase);
  127023. }
  127024. pPhrase->doclist.pNextDocid = 0;
  127025. pPhrase->doclist.iDocid = 0;
  127026. }
  127027. pExpr->iDocid = 0;
  127028. pExpr->bEof = 0;
  127029. pExpr->bStart = 0;
  127030. fts3EvalRestart(pCsr, pExpr->pLeft, pRc);
  127031. fts3EvalRestart(pCsr, pExpr->pRight, pRc);
  127032. }
  127033. }
  127034. /*
  127035. ** After allocating the Fts3Expr.aMI[] array for each phrase in the
  127036. ** expression rooted at pExpr, the cursor iterates through all rows matched
  127037. ** by pExpr, calling this function for each row. This function increments
  127038. ** the values in Fts3Expr.aMI[] according to the position-list currently
  127039. ** found in Fts3Expr.pPhrase->doclist.pList for each of the phrase
  127040. ** expression nodes.
  127041. */
  127042. static void fts3EvalUpdateCounts(Fts3Expr *pExpr){
  127043. if( pExpr ){
  127044. Fts3Phrase *pPhrase = pExpr->pPhrase;
  127045. if( pPhrase && pPhrase->doclist.pList ){
  127046. int iCol = 0;
  127047. char *p = pPhrase->doclist.pList;
  127048. assert( *p );
  127049. while( 1 ){
  127050. u8 c = 0;
  127051. int iCnt = 0;
  127052. while( 0xFE & (*p | c) ){
  127053. if( (c&0x80)==0 ) iCnt++;
  127054. c = *p++ & 0x80;
  127055. }
  127056. /* aMI[iCol*3 + 1] = Number of occurrences
  127057. ** aMI[iCol*3 + 2] = Number of rows containing at least one instance
  127058. */
  127059. pExpr->aMI[iCol*3 + 1] += iCnt;
  127060. pExpr->aMI[iCol*3 + 2] += (iCnt>0);
  127061. if( *p==0x00 ) break;
  127062. p++;
  127063. p += fts3GetVarint32(p, &iCol);
  127064. }
  127065. }
  127066. fts3EvalUpdateCounts(pExpr->pLeft);
  127067. fts3EvalUpdateCounts(pExpr->pRight);
  127068. }
  127069. }
  127070. /*
  127071. ** Expression pExpr must be of type FTSQUERY_PHRASE.
  127072. **
  127073. ** If it is not already allocated and populated, this function allocates and
  127074. ** populates the Fts3Expr.aMI[] array for expression pExpr. If pExpr is part
  127075. ** of a NEAR expression, then it also allocates and populates the same array
  127076. ** for all other phrases that are part of the NEAR expression.
  127077. **
  127078. ** SQLITE_OK is returned if the aMI[] array is successfully allocated and
  127079. ** populated. Otherwise, if an error occurs, an SQLite error code is returned.
  127080. */
  127081. static int fts3EvalGatherStats(
  127082. Fts3Cursor *pCsr, /* Cursor object */
  127083. Fts3Expr *pExpr /* FTSQUERY_PHRASE expression */
  127084. ){
  127085. int rc = SQLITE_OK; /* Return code */
  127086. assert( pExpr->eType==FTSQUERY_PHRASE );
  127087. if( pExpr->aMI==0 ){
  127088. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  127089. Fts3Expr *pRoot; /* Root of NEAR expression */
  127090. Fts3Expr *p; /* Iterator used for several purposes */
  127091. sqlite3_int64 iPrevId = pCsr->iPrevId;
  127092. sqlite3_int64 iDocid;
  127093. u8 bEof;
  127094. /* Find the root of the NEAR expression */
  127095. pRoot = pExpr;
  127096. while( pRoot->pParent && pRoot->pParent->eType==FTSQUERY_NEAR ){
  127097. pRoot = pRoot->pParent;
  127098. }
  127099. iDocid = pRoot->iDocid;
  127100. bEof = pRoot->bEof;
  127101. assert( pRoot->bStart );
  127102. /* Allocate space for the aMSI[] array of each FTSQUERY_PHRASE node */
  127103. for(p=pRoot; p; p=p->pLeft){
  127104. Fts3Expr *pE = (p->eType==FTSQUERY_PHRASE?p:p->pRight);
  127105. assert( pE->aMI==0 );
  127106. pE->aMI = (u32 *)sqlite3_malloc(pTab->nColumn * 3 * sizeof(u32));
  127107. if( !pE->aMI ) return SQLITE_NOMEM;
  127108. memset(pE->aMI, 0, pTab->nColumn * 3 * sizeof(u32));
  127109. }
  127110. fts3EvalRestart(pCsr, pRoot, &rc);
  127111. while( pCsr->isEof==0 && rc==SQLITE_OK ){
  127112. do {
  127113. /* Ensure the %_content statement is reset. */
  127114. if( pCsr->isRequireSeek==0 ) sqlite3_reset(pCsr->pStmt);
  127115. assert( sqlite3_data_count(pCsr->pStmt)==0 );
  127116. /* Advance to the next document */
  127117. fts3EvalNextRow(pCsr, pRoot, &rc);
  127118. pCsr->isEof = pRoot->bEof;
  127119. pCsr->isRequireSeek = 1;
  127120. pCsr->isMatchinfoNeeded = 1;
  127121. pCsr->iPrevId = pRoot->iDocid;
  127122. }while( pCsr->isEof==0
  127123. && pRoot->eType==FTSQUERY_NEAR
  127124. && fts3EvalTestDeferredAndNear(pCsr, &rc)
  127125. );
  127126. if( rc==SQLITE_OK && pCsr->isEof==0 ){
  127127. fts3EvalUpdateCounts(pRoot);
  127128. }
  127129. }
  127130. pCsr->isEof = 0;
  127131. pCsr->iPrevId = iPrevId;
  127132. if( bEof ){
  127133. pRoot->bEof = bEof;
  127134. }else{
  127135. /* Caution: pRoot may iterate through docids in ascending or descending
  127136. ** order. For this reason, even though it seems more defensive, the
  127137. ** do loop can not be written:
  127138. **
  127139. ** do {...} while( pRoot->iDocid<iDocid && rc==SQLITE_OK );
  127140. */
  127141. fts3EvalRestart(pCsr, pRoot, &rc);
  127142. do {
  127143. fts3EvalNextRow(pCsr, pRoot, &rc);
  127144. assert( pRoot->bEof==0 );
  127145. }while( pRoot->iDocid!=iDocid && rc==SQLITE_OK );
  127146. fts3EvalTestDeferredAndNear(pCsr, &rc);
  127147. }
  127148. }
  127149. return rc;
  127150. }
  127151. /*
  127152. ** This function is used by the matchinfo() module to query a phrase
  127153. ** expression node for the following information:
  127154. **
  127155. ** 1. The total number of occurrences of the phrase in each column of
  127156. ** the FTS table (considering all rows), and
  127157. **
  127158. ** 2. For each column, the number of rows in the table for which the
  127159. ** column contains at least one instance of the phrase.
  127160. **
  127161. ** If no error occurs, SQLITE_OK is returned and the values for each column
  127162. ** written into the array aiOut as follows:
  127163. **
  127164. ** aiOut[iCol*3 + 1] = Number of occurrences
  127165. ** aiOut[iCol*3 + 2] = Number of rows containing at least one instance
  127166. **
  127167. ** Caveats:
  127168. **
  127169. ** * If a phrase consists entirely of deferred tokens, then all output
  127170. ** values are set to the number of documents in the table. In other
  127171. ** words we assume that very common tokens occur exactly once in each
  127172. ** column of each row of the table.
  127173. **
  127174. ** * If a phrase contains some deferred tokens (and some non-deferred
  127175. ** tokens), count the potential occurrence identified by considering
  127176. ** the non-deferred tokens instead of actual phrase occurrences.
  127177. **
  127178. ** * If the phrase is part of a NEAR expression, then only phrase instances
  127179. ** that meet the NEAR constraint are included in the counts.
  127180. */
  127181. SQLITE_PRIVATE int sqlite3Fts3EvalPhraseStats(
  127182. Fts3Cursor *pCsr, /* FTS cursor handle */
  127183. Fts3Expr *pExpr, /* Phrase expression */
  127184. u32 *aiOut /* Array to write results into (see above) */
  127185. ){
  127186. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  127187. int rc = SQLITE_OK;
  127188. int iCol;
  127189. if( pExpr->bDeferred && pExpr->pParent->eType!=FTSQUERY_NEAR ){
  127190. assert( pCsr->nDoc>0 );
  127191. for(iCol=0; iCol<pTab->nColumn; iCol++){
  127192. aiOut[iCol*3 + 1] = (u32)pCsr->nDoc;
  127193. aiOut[iCol*3 + 2] = (u32)pCsr->nDoc;
  127194. }
  127195. }else{
  127196. rc = fts3EvalGatherStats(pCsr, pExpr);
  127197. if( rc==SQLITE_OK ){
  127198. assert( pExpr->aMI );
  127199. for(iCol=0; iCol<pTab->nColumn; iCol++){
  127200. aiOut[iCol*3 + 1] = pExpr->aMI[iCol*3 + 1];
  127201. aiOut[iCol*3 + 2] = pExpr->aMI[iCol*3 + 2];
  127202. }
  127203. }
  127204. }
  127205. return rc;
  127206. }
  127207. /*
  127208. ** The expression pExpr passed as the second argument to this function
  127209. ** must be of type FTSQUERY_PHRASE.
  127210. **
  127211. ** The returned value is either NULL or a pointer to a buffer containing
  127212. ** a position-list indicating the occurrences of the phrase in column iCol
  127213. ** of the current row.
  127214. **
  127215. ** More specifically, the returned buffer contains 1 varint for each
  127216. ** occurrence of the phrase in the column, stored using the normal (delta+2)
  127217. ** compression and is terminated by either an 0x01 or 0x00 byte. For example,
  127218. ** if the requested column contains "a b X c d X X" and the position-list
  127219. ** for 'X' is requested, the buffer returned may contain:
  127220. **
  127221. ** 0x04 0x05 0x03 0x01 or 0x04 0x05 0x03 0x00
  127222. **
  127223. ** This function works regardless of whether or not the phrase is deferred,
  127224. ** incremental, or neither.
  127225. */
  127226. SQLITE_PRIVATE int sqlite3Fts3EvalPhrasePoslist(
  127227. Fts3Cursor *pCsr, /* FTS3 cursor object */
  127228. Fts3Expr *pExpr, /* Phrase to return doclist for */
  127229. int iCol, /* Column to return position list for */
  127230. char **ppOut /* OUT: Pointer to position list */
  127231. ){
  127232. Fts3Phrase *pPhrase = pExpr->pPhrase;
  127233. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  127234. char *pIter;
  127235. int iThis;
  127236. sqlite3_int64 iDocid;
  127237. /* If this phrase is applies specifically to some column other than
  127238. ** column iCol, return a NULL pointer. */
  127239. *ppOut = 0;
  127240. assert( iCol>=0 && iCol<pTab->nColumn );
  127241. if( (pPhrase->iColumn<pTab->nColumn && pPhrase->iColumn!=iCol) ){
  127242. return SQLITE_OK;
  127243. }
  127244. iDocid = pExpr->iDocid;
  127245. pIter = pPhrase->doclist.pList;
  127246. if( iDocid!=pCsr->iPrevId || pExpr->bEof ){
  127247. int bDescDoclist = pTab->bDescIdx; /* For DOCID_CMP macro */
  127248. int iMul; /* +1 if csr dir matches index dir, else -1 */
  127249. int bOr = 0;
  127250. u8 bEof = 0;
  127251. u8 bTreeEof = 0;
  127252. Fts3Expr *p; /* Used to iterate from pExpr to root */
  127253. Fts3Expr *pNear; /* Most senior NEAR ancestor (or pExpr) */
  127254. /* Check if this phrase descends from an OR expression node. If not,
  127255. ** return NULL. Otherwise, the entry that corresponds to docid
  127256. ** pCsr->iPrevId may lie earlier in the doclist buffer. Or, if the
  127257. ** tree that the node is part of has been marked as EOF, but the node
  127258. ** itself is not EOF, then it may point to an earlier entry. */
  127259. pNear = pExpr;
  127260. for(p=pExpr->pParent; p; p=p->pParent){
  127261. if( p->eType==FTSQUERY_OR ) bOr = 1;
  127262. if( p->eType==FTSQUERY_NEAR ) pNear = p;
  127263. if( p->bEof ) bTreeEof = 1;
  127264. }
  127265. if( bOr==0 ) return SQLITE_OK;
  127266. /* This is the descendent of an OR node. In this case we cannot use
  127267. ** an incremental phrase. Load the entire doclist for the phrase
  127268. ** into memory in this case. */
  127269. if( pPhrase->bIncr ){
  127270. int rc = SQLITE_OK;
  127271. int bEofSave = pExpr->bEof;
  127272. fts3EvalRestart(pCsr, pExpr, &rc);
  127273. while( rc==SQLITE_OK && !pExpr->bEof ){
  127274. fts3EvalNextRow(pCsr, pExpr, &rc);
  127275. if( bEofSave==0 && pExpr->iDocid==iDocid ) break;
  127276. }
  127277. pIter = pPhrase->doclist.pList;
  127278. assert( rc!=SQLITE_OK || pPhrase->bIncr==0 );
  127279. if( rc!=SQLITE_OK ) return rc;
  127280. }
  127281. iMul = ((pCsr->bDesc==bDescDoclist) ? 1 : -1);
  127282. while( bTreeEof==1
  127283. && pNear->bEof==0
  127284. && (DOCID_CMP(pNear->iDocid, pCsr->iPrevId) * iMul)<0
  127285. ){
  127286. int rc = SQLITE_OK;
  127287. fts3EvalNextRow(pCsr, pExpr, &rc);
  127288. if( rc!=SQLITE_OK ) return rc;
  127289. iDocid = pExpr->iDocid;
  127290. pIter = pPhrase->doclist.pList;
  127291. }
  127292. bEof = (pPhrase->doclist.nAll==0);
  127293. assert( bDescDoclist==0 || bDescDoclist==1 );
  127294. assert( pCsr->bDesc==0 || pCsr->bDesc==1 );
  127295. if( bEof==0 ){
  127296. if( pCsr->bDesc==bDescDoclist ){
  127297. int dummy;
  127298. if( pNear->bEof ){
  127299. /* This expression is already at EOF. So position it to point to the
  127300. ** last entry in the doclist at pPhrase->doclist.aAll[]. Variable
  127301. ** iDocid is already set for this entry, so all that is required is
  127302. ** to set pIter to point to the first byte of the last position-list
  127303. ** in the doclist.
  127304. **
  127305. ** It would also be correct to set pIter and iDocid to zero. In
  127306. ** this case, the first call to sqltie3Fts4DoclistPrev() below
  127307. ** would also move the iterator to point to the last entry in the
  127308. ** doclist. However, this is expensive, as to do so it has to
  127309. ** iterate through the entire doclist from start to finish (since
  127310. ** it does not know the docid for the last entry). */
  127311. pIter = &pPhrase->doclist.aAll[pPhrase->doclist.nAll-1];
  127312. fts3ReversePoslist(pPhrase->doclist.aAll, &pIter);
  127313. }
  127314. while( (pIter==0 || DOCID_CMP(iDocid, pCsr->iPrevId)>0 ) && bEof==0 ){
  127315. sqlite3Fts3DoclistPrev(
  127316. bDescDoclist, pPhrase->doclist.aAll, pPhrase->doclist.nAll,
  127317. &pIter, &iDocid, &dummy, &bEof
  127318. );
  127319. }
  127320. }else{
  127321. if( pNear->bEof ){
  127322. pIter = 0;
  127323. iDocid = 0;
  127324. }
  127325. while( (pIter==0 || DOCID_CMP(iDocid, pCsr->iPrevId)<0 ) && bEof==0 ){
  127326. sqlite3Fts3DoclistNext(
  127327. bDescDoclist, pPhrase->doclist.aAll, pPhrase->doclist.nAll,
  127328. &pIter, &iDocid, &bEof
  127329. );
  127330. }
  127331. }
  127332. }
  127333. if( bEof || iDocid!=pCsr->iPrevId ) pIter = 0;
  127334. }
  127335. if( pIter==0 ) return SQLITE_OK;
  127336. if( *pIter==0x01 ){
  127337. pIter++;
  127338. pIter += fts3GetVarint32(pIter, &iThis);
  127339. }else{
  127340. iThis = 0;
  127341. }
  127342. while( iThis<iCol ){
  127343. fts3ColumnlistCopy(0, &pIter);
  127344. if( *pIter==0x00 ) return 0;
  127345. pIter++;
  127346. pIter += fts3GetVarint32(pIter, &iThis);
  127347. }
  127348. *ppOut = ((iCol==iThis)?pIter:0);
  127349. return SQLITE_OK;
  127350. }
  127351. /*
  127352. ** Free all components of the Fts3Phrase structure that were allocated by
  127353. ** the eval module. Specifically, this means to free:
  127354. **
  127355. ** * the contents of pPhrase->doclist, and
  127356. ** * any Fts3MultiSegReader objects held by phrase tokens.
  127357. */
  127358. SQLITE_PRIVATE void sqlite3Fts3EvalPhraseCleanup(Fts3Phrase *pPhrase){
  127359. if( pPhrase ){
  127360. int i;
  127361. sqlite3_free(pPhrase->doclist.aAll);
  127362. fts3EvalInvalidatePoslist(pPhrase);
  127363. memset(&pPhrase->doclist, 0, sizeof(Fts3Doclist));
  127364. for(i=0; i<pPhrase->nToken; i++){
  127365. fts3SegReaderCursorFree(pPhrase->aToken[i].pSegcsr);
  127366. pPhrase->aToken[i].pSegcsr = 0;
  127367. }
  127368. }
  127369. }
  127370. /*
  127371. ** Return SQLITE_CORRUPT_VTAB.
  127372. */
  127373. #ifdef SQLITE_DEBUG
  127374. SQLITE_PRIVATE int sqlite3Fts3Corrupt(){
  127375. return SQLITE_CORRUPT_VTAB;
  127376. }
  127377. #endif
  127378. #if !SQLITE_CORE
  127379. /*
  127380. ** Initialize API pointer table, if required.
  127381. */
  127382. #ifdef _WIN32
  127383. __declspec(dllexport)
  127384. #endif
  127385. SQLITE_API int sqlite3_fts3_init(
  127386. sqlite3 *db,
  127387. char **pzErrMsg,
  127388. const sqlite3_api_routines *pApi
  127389. ){
  127390. SQLITE_EXTENSION_INIT2(pApi)
  127391. return sqlite3Fts3Init(db);
  127392. }
  127393. #endif
  127394. #endif
  127395. /************** End of fts3.c ************************************************/
  127396. /************** Begin file fts3_aux.c ****************************************/
  127397. /*
  127398. ** 2011 Jan 27
  127399. **
  127400. ** The author disclaims copyright to this source code. In place of
  127401. ** a legal notice, here is a blessing:
  127402. **
  127403. ** May you do good and not evil.
  127404. ** May you find forgiveness for yourself and forgive others.
  127405. ** May you share freely, never taking more than you give.
  127406. **
  127407. ******************************************************************************
  127408. **
  127409. */
  127410. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  127411. /* #include <string.h> */
  127412. /* #include <assert.h> */
  127413. typedef struct Fts3auxTable Fts3auxTable;
  127414. typedef struct Fts3auxCursor Fts3auxCursor;
  127415. struct Fts3auxTable {
  127416. sqlite3_vtab base; /* Base class used by SQLite core */
  127417. Fts3Table *pFts3Tab;
  127418. };
  127419. struct Fts3auxCursor {
  127420. sqlite3_vtab_cursor base; /* Base class used by SQLite core */
  127421. Fts3MultiSegReader csr; /* Must be right after "base" */
  127422. Fts3SegFilter filter;
  127423. char *zStop;
  127424. int nStop; /* Byte-length of string zStop */
  127425. int iLangid; /* Language id to query */
  127426. int isEof; /* True if cursor is at EOF */
  127427. sqlite3_int64 iRowid; /* Current rowid */
  127428. int iCol; /* Current value of 'col' column */
  127429. int nStat; /* Size of aStat[] array */
  127430. struct Fts3auxColstats {
  127431. sqlite3_int64 nDoc; /* 'documents' values for current csr row */
  127432. sqlite3_int64 nOcc; /* 'occurrences' values for current csr row */
  127433. } *aStat;
  127434. };
  127435. /*
  127436. ** Schema of the terms table.
  127437. */
  127438. #define FTS3_AUX_SCHEMA \
  127439. "CREATE TABLE x(term, col, documents, occurrences, languageid HIDDEN)"
  127440. /*
  127441. ** This function does all the work for both the xConnect and xCreate methods.
  127442. ** These tables have no persistent representation of their own, so xConnect
  127443. ** and xCreate are identical operations.
  127444. */
  127445. static int fts3auxConnectMethod(
  127446. sqlite3 *db, /* Database connection */
  127447. void *pUnused, /* Unused */
  127448. int argc, /* Number of elements in argv array */
  127449. const char * const *argv, /* xCreate/xConnect argument array */
  127450. sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
  127451. char **pzErr /* OUT: sqlite3_malloc'd error message */
  127452. ){
  127453. char const *zDb; /* Name of database (e.g. "main") */
  127454. char const *zFts3; /* Name of fts3 table */
  127455. int nDb; /* Result of strlen(zDb) */
  127456. int nFts3; /* Result of strlen(zFts3) */
  127457. int nByte; /* Bytes of space to allocate here */
  127458. int rc; /* value returned by declare_vtab() */
  127459. Fts3auxTable *p; /* Virtual table object to return */
  127460. UNUSED_PARAMETER(pUnused);
  127461. /* The user should invoke this in one of two forms:
  127462. **
  127463. ** CREATE VIRTUAL TABLE xxx USING fts4aux(fts4-table);
  127464. ** CREATE VIRTUAL TABLE xxx USING fts4aux(fts4-table-db, fts4-table);
  127465. */
  127466. if( argc!=4 && argc!=5 ) goto bad_args;
  127467. zDb = argv[1];
  127468. nDb = (int)strlen(zDb);
  127469. if( argc==5 ){
  127470. if( nDb==4 && 0==sqlite3_strnicmp("temp", zDb, 4) ){
  127471. zDb = argv[3];
  127472. nDb = (int)strlen(zDb);
  127473. zFts3 = argv[4];
  127474. }else{
  127475. goto bad_args;
  127476. }
  127477. }else{
  127478. zFts3 = argv[3];
  127479. }
  127480. nFts3 = (int)strlen(zFts3);
  127481. rc = sqlite3_declare_vtab(db, FTS3_AUX_SCHEMA);
  127482. if( rc!=SQLITE_OK ) return rc;
  127483. nByte = sizeof(Fts3auxTable) + sizeof(Fts3Table) + nDb + nFts3 + 2;
  127484. p = (Fts3auxTable *)sqlite3_malloc(nByte);
  127485. if( !p ) return SQLITE_NOMEM;
  127486. memset(p, 0, nByte);
  127487. p->pFts3Tab = (Fts3Table *)&p[1];
  127488. p->pFts3Tab->zDb = (char *)&p->pFts3Tab[1];
  127489. p->pFts3Tab->zName = &p->pFts3Tab->zDb[nDb+1];
  127490. p->pFts3Tab->db = db;
  127491. p->pFts3Tab->nIndex = 1;
  127492. memcpy((char *)p->pFts3Tab->zDb, zDb, nDb);
  127493. memcpy((char *)p->pFts3Tab->zName, zFts3, nFts3);
  127494. sqlite3Fts3Dequote((char *)p->pFts3Tab->zName);
  127495. *ppVtab = (sqlite3_vtab *)p;
  127496. return SQLITE_OK;
  127497. bad_args:
  127498. *pzErr = sqlite3_mprintf("invalid arguments to fts4aux constructor");
  127499. return SQLITE_ERROR;
  127500. }
  127501. /*
  127502. ** This function does the work for both the xDisconnect and xDestroy methods.
  127503. ** These tables have no persistent representation of their own, so xDisconnect
  127504. ** and xDestroy are identical operations.
  127505. */
  127506. static int fts3auxDisconnectMethod(sqlite3_vtab *pVtab){
  127507. Fts3auxTable *p = (Fts3auxTable *)pVtab;
  127508. Fts3Table *pFts3 = p->pFts3Tab;
  127509. int i;
  127510. /* Free any prepared statements held */
  127511. for(i=0; i<SizeofArray(pFts3->aStmt); i++){
  127512. sqlite3_finalize(pFts3->aStmt[i]);
  127513. }
  127514. sqlite3_free(pFts3->zSegmentsTbl);
  127515. sqlite3_free(p);
  127516. return SQLITE_OK;
  127517. }
  127518. #define FTS4AUX_EQ_CONSTRAINT 1
  127519. #define FTS4AUX_GE_CONSTRAINT 2
  127520. #define FTS4AUX_LE_CONSTRAINT 4
  127521. /*
  127522. ** xBestIndex - Analyze a WHERE and ORDER BY clause.
  127523. */
  127524. static int fts3auxBestIndexMethod(
  127525. sqlite3_vtab *pVTab,
  127526. sqlite3_index_info *pInfo
  127527. ){
  127528. int i;
  127529. int iEq = -1;
  127530. int iGe = -1;
  127531. int iLe = -1;
  127532. int iLangid = -1;
  127533. int iNext = 1; /* Next free argvIndex value */
  127534. UNUSED_PARAMETER(pVTab);
  127535. /* This vtab delivers always results in "ORDER BY term ASC" order. */
  127536. if( pInfo->nOrderBy==1
  127537. && pInfo->aOrderBy[0].iColumn==0
  127538. && pInfo->aOrderBy[0].desc==0
  127539. ){
  127540. pInfo->orderByConsumed = 1;
  127541. }
  127542. /* Search for equality and range constraints on the "term" column.
  127543. ** And equality constraints on the hidden "languageid" column. */
  127544. for(i=0; i<pInfo->nConstraint; i++){
  127545. if( pInfo->aConstraint[i].usable ){
  127546. int op = pInfo->aConstraint[i].op;
  127547. int iCol = pInfo->aConstraint[i].iColumn;
  127548. if( iCol==0 ){
  127549. if( op==SQLITE_INDEX_CONSTRAINT_EQ ) iEq = i;
  127550. if( op==SQLITE_INDEX_CONSTRAINT_LT ) iLe = i;
  127551. if( op==SQLITE_INDEX_CONSTRAINT_LE ) iLe = i;
  127552. if( op==SQLITE_INDEX_CONSTRAINT_GT ) iGe = i;
  127553. if( op==SQLITE_INDEX_CONSTRAINT_GE ) iGe = i;
  127554. }
  127555. if( iCol==4 ){
  127556. if( op==SQLITE_INDEX_CONSTRAINT_EQ ) iLangid = i;
  127557. }
  127558. }
  127559. }
  127560. if( iEq>=0 ){
  127561. pInfo->idxNum = FTS4AUX_EQ_CONSTRAINT;
  127562. pInfo->aConstraintUsage[iEq].argvIndex = iNext++;
  127563. pInfo->estimatedCost = 5;
  127564. }else{
  127565. pInfo->idxNum = 0;
  127566. pInfo->estimatedCost = 20000;
  127567. if( iGe>=0 ){
  127568. pInfo->idxNum += FTS4AUX_GE_CONSTRAINT;
  127569. pInfo->aConstraintUsage[iGe].argvIndex = iNext++;
  127570. pInfo->estimatedCost /= 2;
  127571. }
  127572. if( iLe>=0 ){
  127573. pInfo->idxNum += FTS4AUX_LE_CONSTRAINT;
  127574. pInfo->aConstraintUsage[iLe].argvIndex = iNext++;
  127575. pInfo->estimatedCost /= 2;
  127576. }
  127577. }
  127578. if( iLangid>=0 ){
  127579. pInfo->aConstraintUsage[iLangid].argvIndex = iNext++;
  127580. pInfo->estimatedCost--;
  127581. }
  127582. return SQLITE_OK;
  127583. }
  127584. /*
  127585. ** xOpen - Open a cursor.
  127586. */
  127587. static int fts3auxOpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
  127588. Fts3auxCursor *pCsr; /* Pointer to cursor object to return */
  127589. UNUSED_PARAMETER(pVTab);
  127590. pCsr = (Fts3auxCursor *)sqlite3_malloc(sizeof(Fts3auxCursor));
  127591. if( !pCsr ) return SQLITE_NOMEM;
  127592. memset(pCsr, 0, sizeof(Fts3auxCursor));
  127593. *ppCsr = (sqlite3_vtab_cursor *)pCsr;
  127594. return SQLITE_OK;
  127595. }
  127596. /*
  127597. ** xClose - Close a cursor.
  127598. */
  127599. static int fts3auxCloseMethod(sqlite3_vtab_cursor *pCursor){
  127600. Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
  127601. Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
  127602. sqlite3Fts3SegmentsClose(pFts3);
  127603. sqlite3Fts3SegReaderFinish(&pCsr->csr);
  127604. sqlite3_free((void *)pCsr->filter.zTerm);
  127605. sqlite3_free(pCsr->zStop);
  127606. sqlite3_free(pCsr->aStat);
  127607. sqlite3_free(pCsr);
  127608. return SQLITE_OK;
  127609. }
  127610. static int fts3auxGrowStatArray(Fts3auxCursor *pCsr, int nSize){
  127611. if( nSize>pCsr->nStat ){
  127612. struct Fts3auxColstats *aNew;
  127613. aNew = (struct Fts3auxColstats *)sqlite3_realloc(pCsr->aStat,
  127614. sizeof(struct Fts3auxColstats) * nSize
  127615. );
  127616. if( aNew==0 ) return SQLITE_NOMEM;
  127617. memset(&aNew[pCsr->nStat], 0,
  127618. sizeof(struct Fts3auxColstats) * (nSize - pCsr->nStat)
  127619. );
  127620. pCsr->aStat = aNew;
  127621. pCsr->nStat = nSize;
  127622. }
  127623. return SQLITE_OK;
  127624. }
  127625. /*
  127626. ** xNext - Advance the cursor to the next row, if any.
  127627. */
  127628. static int fts3auxNextMethod(sqlite3_vtab_cursor *pCursor){
  127629. Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
  127630. Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
  127631. int rc;
  127632. /* Increment our pretend rowid value. */
  127633. pCsr->iRowid++;
  127634. for(pCsr->iCol++; pCsr->iCol<pCsr->nStat; pCsr->iCol++){
  127635. if( pCsr->aStat[pCsr->iCol].nDoc>0 ) return SQLITE_OK;
  127636. }
  127637. rc = sqlite3Fts3SegReaderStep(pFts3, &pCsr->csr);
  127638. if( rc==SQLITE_ROW ){
  127639. int i = 0;
  127640. int nDoclist = pCsr->csr.nDoclist;
  127641. char *aDoclist = pCsr->csr.aDoclist;
  127642. int iCol;
  127643. int eState = 0;
  127644. if( pCsr->zStop ){
  127645. int n = (pCsr->nStop<pCsr->csr.nTerm) ? pCsr->nStop : pCsr->csr.nTerm;
  127646. int mc = memcmp(pCsr->zStop, pCsr->csr.zTerm, n);
  127647. if( mc<0 || (mc==0 && pCsr->csr.nTerm>pCsr->nStop) ){
  127648. pCsr->isEof = 1;
  127649. return SQLITE_OK;
  127650. }
  127651. }
  127652. if( fts3auxGrowStatArray(pCsr, 2) ) return SQLITE_NOMEM;
  127653. memset(pCsr->aStat, 0, sizeof(struct Fts3auxColstats) * pCsr->nStat);
  127654. iCol = 0;
  127655. while( i<nDoclist ){
  127656. sqlite3_int64 v = 0;
  127657. i += sqlite3Fts3GetVarint(&aDoclist[i], &v);
  127658. switch( eState ){
  127659. /* State 0. In this state the integer just read was a docid. */
  127660. case 0:
  127661. pCsr->aStat[0].nDoc++;
  127662. eState = 1;
  127663. iCol = 0;
  127664. break;
  127665. /* State 1. In this state we are expecting either a 1, indicating
  127666. ** that the following integer will be a column number, or the
  127667. ** start of a position list for column 0.
  127668. **
  127669. ** The only difference between state 1 and state 2 is that if the
  127670. ** integer encountered in state 1 is not 0 or 1, then we need to
  127671. ** increment the column 0 "nDoc" count for this term.
  127672. */
  127673. case 1:
  127674. assert( iCol==0 );
  127675. if( v>1 ){
  127676. pCsr->aStat[1].nDoc++;
  127677. }
  127678. eState = 2;
  127679. /* fall through */
  127680. case 2:
  127681. if( v==0 ){ /* 0x00. Next integer will be a docid. */
  127682. eState = 0;
  127683. }else if( v==1 ){ /* 0x01. Next integer will be a column number. */
  127684. eState = 3;
  127685. }else{ /* 2 or greater. A position. */
  127686. pCsr->aStat[iCol+1].nOcc++;
  127687. pCsr->aStat[0].nOcc++;
  127688. }
  127689. break;
  127690. /* State 3. The integer just read is a column number. */
  127691. default: assert( eState==3 );
  127692. iCol = (int)v;
  127693. if( fts3auxGrowStatArray(pCsr, iCol+2) ) return SQLITE_NOMEM;
  127694. pCsr->aStat[iCol+1].nDoc++;
  127695. eState = 2;
  127696. break;
  127697. }
  127698. }
  127699. pCsr->iCol = 0;
  127700. rc = SQLITE_OK;
  127701. }else{
  127702. pCsr->isEof = 1;
  127703. }
  127704. return rc;
  127705. }
  127706. /*
  127707. ** xFilter - Initialize a cursor to point at the start of its data.
  127708. */
  127709. static int fts3auxFilterMethod(
  127710. sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */
  127711. int idxNum, /* Strategy index */
  127712. const char *idxStr, /* Unused */
  127713. int nVal, /* Number of elements in apVal */
  127714. sqlite3_value **apVal /* Arguments for the indexing scheme */
  127715. ){
  127716. Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
  127717. Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
  127718. int rc;
  127719. int isScan = 0;
  127720. int iLangVal = 0; /* Language id to query */
  127721. int iEq = -1; /* Index of term=? value in apVal */
  127722. int iGe = -1; /* Index of term>=? value in apVal */
  127723. int iLe = -1; /* Index of term<=? value in apVal */
  127724. int iLangid = -1; /* Index of languageid=? value in apVal */
  127725. int iNext = 0;
  127726. UNUSED_PARAMETER(nVal);
  127727. UNUSED_PARAMETER(idxStr);
  127728. assert( idxStr==0 );
  127729. assert( idxNum==FTS4AUX_EQ_CONSTRAINT || idxNum==0
  127730. || idxNum==FTS4AUX_LE_CONSTRAINT || idxNum==FTS4AUX_GE_CONSTRAINT
  127731. || idxNum==(FTS4AUX_LE_CONSTRAINT|FTS4AUX_GE_CONSTRAINT)
  127732. );
  127733. if( idxNum==FTS4AUX_EQ_CONSTRAINT ){
  127734. iEq = iNext++;
  127735. }else{
  127736. isScan = 1;
  127737. if( idxNum & FTS4AUX_GE_CONSTRAINT ){
  127738. iGe = iNext++;
  127739. }
  127740. if( idxNum & FTS4AUX_LE_CONSTRAINT ){
  127741. iLe = iNext++;
  127742. }
  127743. }
  127744. if( iNext<nVal ){
  127745. iLangid = iNext++;
  127746. }
  127747. /* In case this cursor is being reused, close and zero it. */
  127748. testcase(pCsr->filter.zTerm);
  127749. sqlite3Fts3SegReaderFinish(&pCsr->csr);
  127750. sqlite3_free((void *)pCsr->filter.zTerm);
  127751. sqlite3_free(pCsr->aStat);
  127752. memset(&pCsr->csr, 0, ((u8*)&pCsr[1]) - (u8*)&pCsr->csr);
  127753. pCsr->filter.flags = FTS3_SEGMENT_REQUIRE_POS|FTS3_SEGMENT_IGNORE_EMPTY;
  127754. if( isScan ) pCsr->filter.flags |= FTS3_SEGMENT_SCAN;
  127755. if( iEq>=0 || iGe>=0 ){
  127756. const unsigned char *zStr = sqlite3_value_text(apVal[0]);
  127757. assert( (iEq==0 && iGe==-1) || (iEq==-1 && iGe==0) );
  127758. if( zStr ){
  127759. pCsr->filter.zTerm = sqlite3_mprintf("%s", zStr);
  127760. pCsr->filter.nTerm = sqlite3_value_bytes(apVal[0]);
  127761. if( pCsr->filter.zTerm==0 ) return SQLITE_NOMEM;
  127762. }
  127763. }
  127764. if( iLe>=0 ){
  127765. pCsr->zStop = sqlite3_mprintf("%s", sqlite3_value_text(apVal[iLe]));
  127766. pCsr->nStop = sqlite3_value_bytes(apVal[iLe]);
  127767. if( pCsr->zStop==0 ) return SQLITE_NOMEM;
  127768. }
  127769. if( iLangid>=0 ){
  127770. iLangVal = sqlite3_value_int(apVal[iLangid]);
  127771. /* If the user specified a negative value for the languageid, use zero
  127772. ** instead. This works, as the "languageid=?" constraint will also
  127773. ** be tested by the VDBE layer. The test will always be false (since
  127774. ** this module will not return a row with a negative languageid), and
  127775. ** so the overall query will return zero rows. */
  127776. if( iLangVal<0 ) iLangVal = 0;
  127777. }
  127778. pCsr->iLangid = iLangVal;
  127779. rc = sqlite3Fts3SegReaderCursor(pFts3, iLangVal, 0, FTS3_SEGCURSOR_ALL,
  127780. pCsr->filter.zTerm, pCsr->filter.nTerm, 0, isScan, &pCsr->csr
  127781. );
  127782. if( rc==SQLITE_OK ){
  127783. rc = sqlite3Fts3SegReaderStart(pFts3, &pCsr->csr, &pCsr->filter);
  127784. }
  127785. if( rc==SQLITE_OK ) rc = fts3auxNextMethod(pCursor);
  127786. return rc;
  127787. }
  127788. /*
  127789. ** xEof - Return true if the cursor is at EOF, or false otherwise.
  127790. */
  127791. static int fts3auxEofMethod(sqlite3_vtab_cursor *pCursor){
  127792. Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
  127793. return pCsr->isEof;
  127794. }
  127795. /*
  127796. ** xColumn - Return a column value.
  127797. */
  127798. static int fts3auxColumnMethod(
  127799. sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
  127800. sqlite3_context *pCtx, /* Context for sqlite3_result_xxx() calls */
  127801. int iCol /* Index of column to read value from */
  127802. ){
  127803. Fts3auxCursor *p = (Fts3auxCursor *)pCursor;
  127804. assert( p->isEof==0 );
  127805. switch( iCol ){
  127806. case 0: /* term */
  127807. sqlite3_result_text(pCtx, p->csr.zTerm, p->csr.nTerm, SQLITE_TRANSIENT);
  127808. break;
  127809. case 1: /* col */
  127810. if( p->iCol ){
  127811. sqlite3_result_int(pCtx, p->iCol-1);
  127812. }else{
  127813. sqlite3_result_text(pCtx, "*", -1, SQLITE_STATIC);
  127814. }
  127815. break;
  127816. case 2: /* documents */
  127817. sqlite3_result_int64(pCtx, p->aStat[p->iCol].nDoc);
  127818. break;
  127819. case 3: /* occurrences */
  127820. sqlite3_result_int64(pCtx, p->aStat[p->iCol].nOcc);
  127821. break;
  127822. default: /* languageid */
  127823. assert( iCol==4 );
  127824. sqlite3_result_int(pCtx, p->iLangid);
  127825. break;
  127826. }
  127827. return SQLITE_OK;
  127828. }
  127829. /*
  127830. ** xRowid - Return the current rowid for the cursor.
  127831. */
  127832. static int fts3auxRowidMethod(
  127833. sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
  127834. sqlite_int64 *pRowid /* OUT: Rowid value */
  127835. ){
  127836. Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
  127837. *pRowid = pCsr->iRowid;
  127838. return SQLITE_OK;
  127839. }
  127840. /*
  127841. ** Register the fts3aux module with database connection db. Return SQLITE_OK
  127842. ** if successful or an error code if sqlite3_create_module() fails.
  127843. */
  127844. SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db){
  127845. static const sqlite3_module fts3aux_module = {
  127846. 0, /* iVersion */
  127847. fts3auxConnectMethod, /* xCreate */
  127848. fts3auxConnectMethod, /* xConnect */
  127849. fts3auxBestIndexMethod, /* xBestIndex */
  127850. fts3auxDisconnectMethod, /* xDisconnect */
  127851. fts3auxDisconnectMethod, /* xDestroy */
  127852. fts3auxOpenMethod, /* xOpen */
  127853. fts3auxCloseMethod, /* xClose */
  127854. fts3auxFilterMethod, /* xFilter */
  127855. fts3auxNextMethod, /* xNext */
  127856. fts3auxEofMethod, /* xEof */
  127857. fts3auxColumnMethod, /* xColumn */
  127858. fts3auxRowidMethod, /* xRowid */
  127859. 0, /* xUpdate */
  127860. 0, /* xBegin */
  127861. 0, /* xSync */
  127862. 0, /* xCommit */
  127863. 0, /* xRollback */
  127864. 0, /* xFindFunction */
  127865. 0, /* xRename */
  127866. 0, /* xSavepoint */
  127867. 0, /* xRelease */
  127868. 0 /* xRollbackTo */
  127869. };
  127870. int rc; /* Return code */
  127871. rc = sqlite3_create_module(db, "fts4aux", &fts3aux_module, 0);
  127872. return rc;
  127873. }
  127874. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  127875. /************** End of fts3_aux.c ********************************************/
  127876. /************** Begin file fts3_expr.c ***************************************/
  127877. /*
  127878. ** 2008 Nov 28
  127879. **
  127880. ** The author disclaims copyright to this source code. In place of
  127881. ** a legal notice, here is a blessing:
  127882. **
  127883. ** May you do good and not evil.
  127884. ** May you find forgiveness for yourself and forgive others.
  127885. ** May you share freely, never taking more than you give.
  127886. **
  127887. ******************************************************************************
  127888. **
  127889. ** This module contains code that implements a parser for fts3 query strings
  127890. ** (the right-hand argument to the MATCH operator). Because the supported
  127891. ** syntax is relatively simple, the whole tokenizer/parser system is
  127892. ** hand-coded.
  127893. */
  127894. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  127895. /*
  127896. ** By default, this module parses the legacy syntax that has been
  127897. ** traditionally used by fts3. Or, if SQLITE_ENABLE_FTS3_PARENTHESIS
  127898. ** is defined, then it uses the new syntax. The differences between
  127899. ** the new and the old syntaxes are:
  127900. **
  127901. ** a) The new syntax supports parenthesis. The old does not.
  127902. **
  127903. ** b) The new syntax supports the AND and NOT operators. The old does not.
  127904. **
  127905. ** c) The old syntax supports the "-" token qualifier. This is not
  127906. ** supported by the new syntax (it is replaced by the NOT operator).
  127907. **
  127908. ** d) When using the old syntax, the OR operator has a greater precedence
  127909. ** than an implicit AND. When using the new, both implicity and explicit
  127910. ** AND operators have a higher precedence than OR.
  127911. **
  127912. ** If compiled with SQLITE_TEST defined, then this module exports the
  127913. ** symbol "int sqlite3_fts3_enable_parentheses". Setting this variable
  127914. ** to zero causes the module to use the old syntax. If it is set to
  127915. ** non-zero the new syntax is activated. This is so both syntaxes can
  127916. ** be tested using a single build of testfixture.
  127917. **
  127918. ** The following describes the syntax supported by the fts3 MATCH
  127919. ** operator in a similar format to that used by the lemon parser
  127920. ** generator. This module does not use actually lemon, it uses a
  127921. ** custom parser.
  127922. **
  127923. ** query ::= andexpr (OR andexpr)*.
  127924. **
  127925. ** andexpr ::= notexpr (AND? notexpr)*.
  127926. **
  127927. ** notexpr ::= nearexpr (NOT nearexpr|-TOKEN)*.
  127928. ** notexpr ::= LP query RP.
  127929. **
  127930. ** nearexpr ::= phrase (NEAR distance_opt nearexpr)*.
  127931. **
  127932. ** distance_opt ::= .
  127933. ** distance_opt ::= / INTEGER.
  127934. **
  127935. ** phrase ::= TOKEN.
  127936. ** phrase ::= COLUMN:TOKEN.
  127937. ** phrase ::= "TOKEN TOKEN TOKEN...".
  127938. */
  127939. #ifdef SQLITE_TEST
  127940. SQLITE_API int sqlite3_fts3_enable_parentheses = 0;
  127941. #else
  127942. # ifdef SQLITE_ENABLE_FTS3_PARENTHESIS
  127943. # define sqlite3_fts3_enable_parentheses 1
  127944. # else
  127945. # define sqlite3_fts3_enable_parentheses 0
  127946. # endif
  127947. #endif
  127948. /*
  127949. ** Default span for NEAR operators.
  127950. */
  127951. #define SQLITE_FTS3_DEFAULT_NEAR_PARAM 10
  127952. /* #include <string.h> */
  127953. /* #include <assert.h> */
  127954. /*
  127955. ** isNot:
  127956. ** This variable is used by function getNextNode(). When getNextNode() is
  127957. ** called, it sets ParseContext.isNot to true if the 'next node' is a
  127958. ** FTSQUERY_PHRASE with a unary "-" attached to it. i.e. "mysql" in the
  127959. ** FTS3 query "sqlite -mysql". Otherwise, ParseContext.isNot is set to
  127960. ** zero.
  127961. */
  127962. typedef struct ParseContext ParseContext;
  127963. struct ParseContext {
  127964. sqlite3_tokenizer *pTokenizer; /* Tokenizer module */
  127965. int iLangid; /* Language id used with tokenizer */
  127966. const char **azCol; /* Array of column names for fts3 table */
  127967. int bFts4; /* True to allow FTS4-only syntax */
  127968. int nCol; /* Number of entries in azCol[] */
  127969. int iDefaultCol; /* Default column to query */
  127970. int isNot; /* True if getNextNode() sees a unary - */
  127971. sqlite3_context *pCtx; /* Write error message here */
  127972. int nNest; /* Number of nested brackets */
  127973. };
  127974. /*
  127975. ** This function is equivalent to the standard isspace() function.
  127976. **
  127977. ** The standard isspace() can be awkward to use safely, because although it
  127978. ** is defined to accept an argument of type int, its behavior when passed
  127979. ** an integer that falls outside of the range of the unsigned char type
  127980. ** is undefined (and sometimes, "undefined" means segfault). This wrapper
  127981. ** is defined to accept an argument of type char, and always returns 0 for
  127982. ** any values that fall outside of the range of the unsigned char type (i.e.
  127983. ** negative values).
  127984. */
  127985. static int fts3isspace(char c){
  127986. return c==' ' || c=='\t' || c=='\n' || c=='\r' || c=='\v' || c=='\f';
  127987. }
  127988. /*
  127989. ** Allocate nByte bytes of memory using sqlite3_malloc(). If successful,
  127990. ** zero the memory before returning a pointer to it. If unsuccessful,
  127991. ** return NULL.
  127992. */
  127993. static void *fts3MallocZero(int nByte){
  127994. void *pRet = sqlite3_malloc(nByte);
  127995. if( pRet ) memset(pRet, 0, nByte);
  127996. return pRet;
  127997. }
  127998. SQLITE_PRIVATE int sqlite3Fts3OpenTokenizer(
  127999. sqlite3_tokenizer *pTokenizer,
  128000. int iLangid,
  128001. const char *z,
  128002. int n,
  128003. sqlite3_tokenizer_cursor **ppCsr
  128004. ){
  128005. sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
  128006. sqlite3_tokenizer_cursor *pCsr = 0;
  128007. int rc;
  128008. rc = pModule->xOpen(pTokenizer, z, n, &pCsr);
  128009. assert( rc==SQLITE_OK || pCsr==0 );
  128010. if( rc==SQLITE_OK ){
  128011. pCsr->pTokenizer = pTokenizer;
  128012. if( pModule->iVersion>=1 ){
  128013. rc = pModule->xLanguageid(pCsr, iLangid);
  128014. if( rc!=SQLITE_OK ){
  128015. pModule->xClose(pCsr);
  128016. pCsr = 0;
  128017. }
  128018. }
  128019. }
  128020. *ppCsr = pCsr;
  128021. return rc;
  128022. }
  128023. /*
  128024. ** Function getNextNode(), which is called by fts3ExprParse(), may itself
  128025. ** call fts3ExprParse(). So this forward declaration is required.
  128026. */
  128027. static int fts3ExprParse(ParseContext *, const char *, int, Fts3Expr **, int *);
  128028. /*
  128029. ** Extract the next token from buffer z (length n) using the tokenizer
  128030. ** and other information (column names etc.) in pParse. Create an Fts3Expr
  128031. ** structure of type FTSQUERY_PHRASE containing a phrase consisting of this
  128032. ** single token and set *ppExpr to point to it. If the end of the buffer is
  128033. ** reached before a token is found, set *ppExpr to zero. It is the
  128034. ** responsibility of the caller to eventually deallocate the allocated
  128035. ** Fts3Expr structure (if any) by passing it to sqlite3_free().
  128036. **
  128037. ** Return SQLITE_OK if successful, or SQLITE_NOMEM if a memory allocation
  128038. ** fails.
  128039. */
  128040. static int getNextToken(
  128041. ParseContext *pParse, /* fts3 query parse context */
  128042. int iCol, /* Value for Fts3Phrase.iColumn */
  128043. const char *z, int n, /* Input string */
  128044. Fts3Expr **ppExpr, /* OUT: expression */
  128045. int *pnConsumed /* OUT: Number of bytes consumed */
  128046. ){
  128047. sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
  128048. sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
  128049. int rc;
  128050. sqlite3_tokenizer_cursor *pCursor;
  128051. Fts3Expr *pRet = 0;
  128052. int i = 0;
  128053. /* Set variable i to the maximum number of bytes of input to tokenize. */
  128054. for(i=0; i<n; i++){
  128055. if( sqlite3_fts3_enable_parentheses && (z[i]=='(' || z[i]==')') ) break;
  128056. if( z[i]=='"' ) break;
  128057. }
  128058. *pnConsumed = i;
  128059. rc = sqlite3Fts3OpenTokenizer(pTokenizer, pParse->iLangid, z, i, &pCursor);
  128060. if( rc==SQLITE_OK ){
  128061. const char *zToken;
  128062. int nToken = 0, iStart = 0, iEnd = 0, iPosition = 0;
  128063. int nByte; /* total space to allocate */
  128064. rc = pModule->xNext(pCursor, &zToken, &nToken, &iStart, &iEnd, &iPosition);
  128065. if( rc==SQLITE_OK ){
  128066. nByte = sizeof(Fts3Expr) + sizeof(Fts3Phrase) + nToken;
  128067. pRet = (Fts3Expr *)fts3MallocZero(nByte);
  128068. if( !pRet ){
  128069. rc = SQLITE_NOMEM;
  128070. }else{
  128071. pRet->eType = FTSQUERY_PHRASE;
  128072. pRet->pPhrase = (Fts3Phrase *)&pRet[1];
  128073. pRet->pPhrase->nToken = 1;
  128074. pRet->pPhrase->iColumn = iCol;
  128075. pRet->pPhrase->aToken[0].n = nToken;
  128076. pRet->pPhrase->aToken[0].z = (char *)&pRet->pPhrase[1];
  128077. memcpy(pRet->pPhrase->aToken[0].z, zToken, nToken);
  128078. if( iEnd<n && z[iEnd]=='*' ){
  128079. pRet->pPhrase->aToken[0].isPrefix = 1;
  128080. iEnd++;
  128081. }
  128082. while( 1 ){
  128083. if( !sqlite3_fts3_enable_parentheses
  128084. && iStart>0 && z[iStart-1]=='-'
  128085. ){
  128086. pParse->isNot = 1;
  128087. iStart--;
  128088. }else if( pParse->bFts4 && iStart>0 && z[iStart-1]=='^' ){
  128089. pRet->pPhrase->aToken[0].bFirst = 1;
  128090. iStart--;
  128091. }else{
  128092. break;
  128093. }
  128094. }
  128095. }
  128096. *pnConsumed = iEnd;
  128097. }else if( i && rc==SQLITE_DONE ){
  128098. rc = SQLITE_OK;
  128099. }
  128100. pModule->xClose(pCursor);
  128101. }
  128102. *ppExpr = pRet;
  128103. return rc;
  128104. }
  128105. /*
  128106. ** Enlarge a memory allocation. If an out-of-memory allocation occurs,
  128107. ** then free the old allocation.
  128108. */
  128109. static void *fts3ReallocOrFree(void *pOrig, int nNew){
  128110. void *pRet = sqlite3_realloc(pOrig, nNew);
  128111. if( !pRet ){
  128112. sqlite3_free(pOrig);
  128113. }
  128114. return pRet;
  128115. }
  128116. /*
  128117. ** Buffer zInput, length nInput, contains the contents of a quoted string
  128118. ** that appeared as part of an fts3 query expression. Neither quote character
  128119. ** is included in the buffer. This function attempts to tokenize the entire
  128120. ** input buffer and create an Fts3Expr structure of type FTSQUERY_PHRASE
  128121. ** containing the results.
  128122. **
  128123. ** If successful, SQLITE_OK is returned and *ppExpr set to point at the
  128124. ** allocated Fts3Expr structure. Otherwise, either SQLITE_NOMEM (out of memory
  128125. ** error) or SQLITE_ERROR (tokenization error) is returned and *ppExpr set
  128126. ** to 0.
  128127. */
  128128. static int getNextString(
  128129. ParseContext *pParse, /* fts3 query parse context */
  128130. const char *zInput, int nInput, /* Input string */
  128131. Fts3Expr **ppExpr /* OUT: expression */
  128132. ){
  128133. sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
  128134. sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
  128135. int rc;
  128136. Fts3Expr *p = 0;
  128137. sqlite3_tokenizer_cursor *pCursor = 0;
  128138. char *zTemp = 0;
  128139. int nTemp = 0;
  128140. const int nSpace = sizeof(Fts3Expr) + sizeof(Fts3Phrase);
  128141. int nToken = 0;
  128142. /* The final Fts3Expr data structure, including the Fts3Phrase,
  128143. ** Fts3PhraseToken structures token buffers are all stored as a single
  128144. ** allocation so that the expression can be freed with a single call to
  128145. ** sqlite3_free(). Setting this up requires a two pass approach.
  128146. **
  128147. ** The first pass, in the block below, uses a tokenizer cursor to iterate
  128148. ** through the tokens in the expression. This pass uses fts3ReallocOrFree()
  128149. ** to assemble data in two dynamic buffers:
  128150. **
  128151. ** Buffer p: Points to the Fts3Expr structure, followed by the Fts3Phrase
  128152. ** structure, followed by the array of Fts3PhraseToken
  128153. ** structures. This pass only populates the Fts3PhraseToken array.
  128154. **
  128155. ** Buffer zTemp: Contains copies of all tokens.
  128156. **
  128157. ** The second pass, in the block that begins "if( rc==SQLITE_DONE )" below,
  128158. ** appends buffer zTemp to buffer p, and fills in the Fts3Expr and Fts3Phrase
  128159. ** structures.
  128160. */
  128161. rc = sqlite3Fts3OpenTokenizer(
  128162. pTokenizer, pParse->iLangid, zInput, nInput, &pCursor);
  128163. if( rc==SQLITE_OK ){
  128164. int ii;
  128165. for(ii=0; rc==SQLITE_OK; ii++){
  128166. const char *zByte;
  128167. int nByte = 0, iBegin = 0, iEnd = 0, iPos = 0;
  128168. rc = pModule->xNext(pCursor, &zByte, &nByte, &iBegin, &iEnd, &iPos);
  128169. if( rc==SQLITE_OK ){
  128170. Fts3PhraseToken *pToken;
  128171. p = fts3ReallocOrFree(p, nSpace + ii*sizeof(Fts3PhraseToken));
  128172. if( !p ) goto no_mem;
  128173. zTemp = fts3ReallocOrFree(zTemp, nTemp + nByte);
  128174. if( !zTemp ) goto no_mem;
  128175. assert( nToken==ii );
  128176. pToken = &((Fts3Phrase *)(&p[1]))->aToken[ii];
  128177. memset(pToken, 0, sizeof(Fts3PhraseToken));
  128178. memcpy(&zTemp[nTemp], zByte, nByte);
  128179. nTemp += nByte;
  128180. pToken->n = nByte;
  128181. pToken->isPrefix = (iEnd<nInput && zInput[iEnd]=='*');
  128182. pToken->bFirst = (iBegin>0 && zInput[iBegin-1]=='^');
  128183. nToken = ii+1;
  128184. }
  128185. }
  128186. pModule->xClose(pCursor);
  128187. pCursor = 0;
  128188. }
  128189. if( rc==SQLITE_DONE ){
  128190. int jj;
  128191. char *zBuf = 0;
  128192. p = fts3ReallocOrFree(p, nSpace + nToken*sizeof(Fts3PhraseToken) + nTemp);
  128193. if( !p ) goto no_mem;
  128194. memset(p, 0, (char *)&(((Fts3Phrase *)&p[1])->aToken[0])-(char *)p);
  128195. p->eType = FTSQUERY_PHRASE;
  128196. p->pPhrase = (Fts3Phrase *)&p[1];
  128197. p->pPhrase->iColumn = pParse->iDefaultCol;
  128198. p->pPhrase->nToken = nToken;
  128199. zBuf = (char *)&p->pPhrase->aToken[nToken];
  128200. if( zTemp ){
  128201. memcpy(zBuf, zTemp, nTemp);
  128202. sqlite3_free(zTemp);
  128203. }else{
  128204. assert( nTemp==0 );
  128205. }
  128206. for(jj=0; jj<p->pPhrase->nToken; jj++){
  128207. p->pPhrase->aToken[jj].z = zBuf;
  128208. zBuf += p->pPhrase->aToken[jj].n;
  128209. }
  128210. rc = SQLITE_OK;
  128211. }
  128212. *ppExpr = p;
  128213. return rc;
  128214. no_mem:
  128215. if( pCursor ){
  128216. pModule->xClose(pCursor);
  128217. }
  128218. sqlite3_free(zTemp);
  128219. sqlite3_free(p);
  128220. *ppExpr = 0;
  128221. return SQLITE_NOMEM;
  128222. }
  128223. /*
  128224. ** The output variable *ppExpr is populated with an allocated Fts3Expr
  128225. ** structure, or set to 0 if the end of the input buffer is reached.
  128226. **
  128227. ** Returns an SQLite error code. SQLITE_OK if everything works, SQLITE_NOMEM
  128228. ** if a malloc failure occurs, or SQLITE_ERROR if a parse error is encountered.
  128229. ** If SQLITE_ERROR is returned, pContext is populated with an error message.
  128230. */
  128231. static int getNextNode(
  128232. ParseContext *pParse, /* fts3 query parse context */
  128233. const char *z, int n, /* Input string */
  128234. Fts3Expr **ppExpr, /* OUT: expression */
  128235. int *pnConsumed /* OUT: Number of bytes consumed */
  128236. ){
  128237. static const struct Fts3Keyword {
  128238. char *z; /* Keyword text */
  128239. unsigned char n; /* Length of the keyword */
  128240. unsigned char parenOnly; /* Only valid in paren mode */
  128241. unsigned char eType; /* Keyword code */
  128242. } aKeyword[] = {
  128243. { "OR" , 2, 0, FTSQUERY_OR },
  128244. { "AND", 3, 1, FTSQUERY_AND },
  128245. { "NOT", 3, 1, FTSQUERY_NOT },
  128246. { "NEAR", 4, 0, FTSQUERY_NEAR }
  128247. };
  128248. int ii;
  128249. int iCol;
  128250. int iColLen;
  128251. int rc;
  128252. Fts3Expr *pRet = 0;
  128253. const char *zInput = z;
  128254. int nInput = n;
  128255. pParse->isNot = 0;
  128256. /* Skip over any whitespace before checking for a keyword, an open or
  128257. ** close bracket, or a quoted string.
  128258. */
  128259. while( nInput>0 && fts3isspace(*zInput) ){
  128260. nInput--;
  128261. zInput++;
  128262. }
  128263. if( nInput==0 ){
  128264. return SQLITE_DONE;
  128265. }
  128266. /* See if we are dealing with a keyword. */
  128267. for(ii=0; ii<(int)(sizeof(aKeyword)/sizeof(struct Fts3Keyword)); ii++){
  128268. const struct Fts3Keyword *pKey = &aKeyword[ii];
  128269. if( (pKey->parenOnly & ~sqlite3_fts3_enable_parentheses)!=0 ){
  128270. continue;
  128271. }
  128272. if( nInput>=pKey->n && 0==memcmp(zInput, pKey->z, pKey->n) ){
  128273. int nNear = SQLITE_FTS3_DEFAULT_NEAR_PARAM;
  128274. int nKey = pKey->n;
  128275. char cNext;
  128276. /* If this is a "NEAR" keyword, check for an explicit nearness. */
  128277. if( pKey->eType==FTSQUERY_NEAR ){
  128278. assert( nKey==4 );
  128279. if( zInput[4]=='/' && zInput[5]>='0' && zInput[5]<='9' ){
  128280. nNear = 0;
  128281. for(nKey=5; zInput[nKey]>='0' && zInput[nKey]<='9'; nKey++){
  128282. nNear = nNear * 10 + (zInput[nKey] - '0');
  128283. }
  128284. }
  128285. }
  128286. /* At this point this is probably a keyword. But for that to be true,
  128287. ** the next byte must contain either whitespace, an open or close
  128288. ** parenthesis, a quote character, or EOF.
  128289. */
  128290. cNext = zInput[nKey];
  128291. if( fts3isspace(cNext)
  128292. || cNext=='"' || cNext=='(' || cNext==')' || cNext==0
  128293. ){
  128294. pRet = (Fts3Expr *)fts3MallocZero(sizeof(Fts3Expr));
  128295. if( !pRet ){
  128296. return SQLITE_NOMEM;
  128297. }
  128298. pRet->eType = pKey->eType;
  128299. pRet->nNear = nNear;
  128300. *ppExpr = pRet;
  128301. *pnConsumed = (int)((zInput - z) + nKey);
  128302. return SQLITE_OK;
  128303. }
  128304. /* Turns out that wasn't a keyword after all. This happens if the
  128305. ** user has supplied a token such as "ORacle". Continue.
  128306. */
  128307. }
  128308. }
  128309. /* See if we are dealing with a quoted phrase. If this is the case, then
  128310. ** search for the closing quote and pass the whole string to getNextString()
  128311. ** for processing. This is easy to do, as fts3 has no syntax for escaping
  128312. ** a quote character embedded in a string.
  128313. */
  128314. if( *zInput=='"' ){
  128315. for(ii=1; ii<nInput && zInput[ii]!='"'; ii++);
  128316. *pnConsumed = (int)((zInput - z) + ii + 1);
  128317. if( ii==nInput ){
  128318. return SQLITE_ERROR;
  128319. }
  128320. return getNextString(pParse, &zInput[1], ii-1, ppExpr);
  128321. }
  128322. if( sqlite3_fts3_enable_parentheses ){
  128323. if( *zInput=='(' ){
  128324. int nConsumed = 0;
  128325. pParse->nNest++;
  128326. rc = fts3ExprParse(pParse, zInput+1, nInput-1, ppExpr, &nConsumed);
  128327. if( rc==SQLITE_OK && !*ppExpr ){ rc = SQLITE_DONE; }
  128328. *pnConsumed = (int)(zInput - z) + 1 + nConsumed;
  128329. return rc;
  128330. }else if( *zInput==')' ){
  128331. pParse->nNest--;
  128332. *pnConsumed = (int)((zInput - z) + 1);
  128333. *ppExpr = 0;
  128334. return SQLITE_DONE;
  128335. }
  128336. }
  128337. /* If control flows to this point, this must be a regular token, or
  128338. ** the end of the input. Read a regular token using the sqlite3_tokenizer
  128339. ** interface. Before doing so, figure out if there is an explicit
  128340. ** column specifier for the token.
  128341. **
  128342. ** TODO: Strangely, it is not possible to associate a column specifier
  128343. ** with a quoted phrase, only with a single token. Not sure if this was
  128344. ** an implementation artifact or an intentional decision when fts3 was
  128345. ** first implemented. Whichever it was, this module duplicates the
  128346. ** limitation.
  128347. */
  128348. iCol = pParse->iDefaultCol;
  128349. iColLen = 0;
  128350. for(ii=0; ii<pParse->nCol; ii++){
  128351. const char *zStr = pParse->azCol[ii];
  128352. int nStr = (int)strlen(zStr);
  128353. if( nInput>nStr && zInput[nStr]==':'
  128354. && sqlite3_strnicmp(zStr, zInput, nStr)==0
  128355. ){
  128356. iCol = ii;
  128357. iColLen = (int)((zInput - z) + nStr + 1);
  128358. break;
  128359. }
  128360. }
  128361. rc = getNextToken(pParse, iCol, &z[iColLen], n-iColLen, ppExpr, pnConsumed);
  128362. *pnConsumed += iColLen;
  128363. return rc;
  128364. }
  128365. /*
  128366. ** The argument is an Fts3Expr structure for a binary operator (any type
  128367. ** except an FTSQUERY_PHRASE). Return an integer value representing the
  128368. ** precedence of the operator. Lower values have a higher precedence (i.e.
  128369. ** group more tightly). For example, in the C language, the == operator
  128370. ** groups more tightly than ||, and would therefore have a higher precedence.
  128371. **
  128372. ** When using the new fts3 query syntax (when SQLITE_ENABLE_FTS3_PARENTHESIS
  128373. ** is defined), the order of the operators in precedence from highest to
  128374. ** lowest is:
  128375. **
  128376. ** NEAR
  128377. ** NOT
  128378. ** AND (including implicit ANDs)
  128379. ** OR
  128380. **
  128381. ** Note that when using the old query syntax, the OR operator has a higher
  128382. ** precedence than the AND operator.
  128383. */
  128384. static int opPrecedence(Fts3Expr *p){
  128385. assert( p->eType!=FTSQUERY_PHRASE );
  128386. if( sqlite3_fts3_enable_parentheses ){
  128387. return p->eType;
  128388. }else if( p->eType==FTSQUERY_NEAR ){
  128389. return 1;
  128390. }else if( p->eType==FTSQUERY_OR ){
  128391. return 2;
  128392. }
  128393. assert( p->eType==FTSQUERY_AND );
  128394. return 3;
  128395. }
  128396. /*
  128397. ** Argument ppHead contains a pointer to the current head of a query
  128398. ** expression tree being parsed. pPrev is the expression node most recently
  128399. ** inserted into the tree. This function adds pNew, which is always a binary
  128400. ** operator node, into the expression tree based on the relative precedence
  128401. ** of pNew and the existing nodes of the tree. This may result in the head
  128402. ** of the tree changing, in which case *ppHead is set to the new root node.
  128403. */
  128404. static void insertBinaryOperator(
  128405. Fts3Expr **ppHead, /* Pointer to the root node of a tree */
  128406. Fts3Expr *pPrev, /* Node most recently inserted into the tree */
  128407. Fts3Expr *pNew /* New binary node to insert into expression tree */
  128408. ){
  128409. Fts3Expr *pSplit = pPrev;
  128410. while( pSplit->pParent && opPrecedence(pSplit->pParent)<=opPrecedence(pNew) ){
  128411. pSplit = pSplit->pParent;
  128412. }
  128413. if( pSplit->pParent ){
  128414. assert( pSplit->pParent->pRight==pSplit );
  128415. pSplit->pParent->pRight = pNew;
  128416. pNew->pParent = pSplit->pParent;
  128417. }else{
  128418. *ppHead = pNew;
  128419. }
  128420. pNew->pLeft = pSplit;
  128421. pSplit->pParent = pNew;
  128422. }
  128423. /*
  128424. ** Parse the fts3 query expression found in buffer z, length n. This function
  128425. ** returns either when the end of the buffer is reached or an unmatched
  128426. ** closing bracket - ')' - is encountered.
  128427. **
  128428. ** If successful, SQLITE_OK is returned, *ppExpr is set to point to the
  128429. ** parsed form of the expression and *pnConsumed is set to the number of
  128430. ** bytes read from buffer z. Otherwise, *ppExpr is set to 0 and SQLITE_NOMEM
  128431. ** (out of memory error) or SQLITE_ERROR (parse error) is returned.
  128432. */
  128433. static int fts3ExprParse(
  128434. ParseContext *pParse, /* fts3 query parse context */
  128435. const char *z, int n, /* Text of MATCH query */
  128436. Fts3Expr **ppExpr, /* OUT: Parsed query structure */
  128437. int *pnConsumed /* OUT: Number of bytes consumed */
  128438. ){
  128439. Fts3Expr *pRet = 0;
  128440. Fts3Expr *pPrev = 0;
  128441. Fts3Expr *pNotBranch = 0; /* Only used in legacy parse mode */
  128442. int nIn = n;
  128443. const char *zIn = z;
  128444. int rc = SQLITE_OK;
  128445. int isRequirePhrase = 1;
  128446. while( rc==SQLITE_OK ){
  128447. Fts3Expr *p = 0;
  128448. int nByte = 0;
  128449. rc = getNextNode(pParse, zIn, nIn, &p, &nByte);
  128450. assert( nByte>0 || (rc!=SQLITE_OK && p==0) );
  128451. if( rc==SQLITE_OK ){
  128452. if( p ){
  128453. int isPhrase;
  128454. if( !sqlite3_fts3_enable_parentheses
  128455. && p->eType==FTSQUERY_PHRASE && pParse->isNot
  128456. ){
  128457. /* Create an implicit NOT operator. */
  128458. Fts3Expr *pNot = fts3MallocZero(sizeof(Fts3Expr));
  128459. if( !pNot ){
  128460. sqlite3Fts3ExprFree(p);
  128461. rc = SQLITE_NOMEM;
  128462. goto exprparse_out;
  128463. }
  128464. pNot->eType = FTSQUERY_NOT;
  128465. pNot->pRight = p;
  128466. p->pParent = pNot;
  128467. if( pNotBranch ){
  128468. pNot->pLeft = pNotBranch;
  128469. pNotBranch->pParent = pNot;
  128470. }
  128471. pNotBranch = pNot;
  128472. p = pPrev;
  128473. }else{
  128474. int eType = p->eType;
  128475. isPhrase = (eType==FTSQUERY_PHRASE || p->pLeft);
  128476. /* The isRequirePhrase variable is set to true if a phrase or
  128477. ** an expression contained in parenthesis is required. If a
  128478. ** binary operator (AND, OR, NOT or NEAR) is encounted when
  128479. ** isRequirePhrase is set, this is a syntax error.
  128480. */
  128481. if( !isPhrase && isRequirePhrase ){
  128482. sqlite3Fts3ExprFree(p);
  128483. rc = SQLITE_ERROR;
  128484. goto exprparse_out;
  128485. }
  128486. if( isPhrase && !isRequirePhrase ){
  128487. /* Insert an implicit AND operator. */
  128488. Fts3Expr *pAnd;
  128489. assert( pRet && pPrev );
  128490. pAnd = fts3MallocZero(sizeof(Fts3Expr));
  128491. if( !pAnd ){
  128492. sqlite3Fts3ExprFree(p);
  128493. rc = SQLITE_NOMEM;
  128494. goto exprparse_out;
  128495. }
  128496. pAnd->eType = FTSQUERY_AND;
  128497. insertBinaryOperator(&pRet, pPrev, pAnd);
  128498. pPrev = pAnd;
  128499. }
  128500. /* This test catches attempts to make either operand of a NEAR
  128501. ** operator something other than a phrase. For example, either of
  128502. ** the following:
  128503. **
  128504. ** (bracketed expression) NEAR phrase
  128505. ** phrase NEAR (bracketed expression)
  128506. **
  128507. ** Return an error in either case.
  128508. */
  128509. if( pPrev && (
  128510. (eType==FTSQUERY_NEAR && !isPhrase && pPrev->eType!=FTSQUERY_PHRASE)
  128511. || (eType!=FTSQUERY_PHRASE && isPhrase && pPrev->eType==FTSQUERY_NEAR)
  128512. )){
  128513. sqlite3Fts3ExprFree(p);
  128514. rc = SQLITE_ERROR;
  128515. goto exprparse_out;
  128516. }
  128517. if( isPhrase ){
  128518. if( pRet ){
  128519. assert( pPrev && pPrev->pLeft && pPrev->pRight==0 );
  128520. pPrev->pRight = p;
  128521. p->pParent = pPrev;
  128522. }else{
  128523. pRet = p;
  128524. }
  128525. }else{
  128526. insertBinaryOperator(&pRet, pPrev, p);
  128527. }
  128528. isRequirePhrase = !isPhrase;
  128529. }
  128530. pPrev = p;
  128531. }
  128532. assert( nByte>0 );
  128533. }
  128534. assert( rc!=SQLITE_OK || (nByte>0 && nByte<=nIn) );
  128535. nIn -= nByte;
  128536. zIn += nByte;
  128537. }
  128538. if( rc==SQLITE_DONE && pRet && isRequirePhrase ){
  128539. rc = SQLITE_ERROR;
  128540. }
  128541. if( rc==SQLITE_DONE ){
  128542. rc = SQLITE_OK;
  128543. if( !sqlite3_fts3_enable_parentheses && pNotBranch ){
  128544. if( !pRet ){
  128545. rc = SQLITE_ERROR;
  128546. }else{
  128547. Fts3Expr *pIter = pNotBranch;
  128548. while( pIter->pLeft ){
  128549. pIter = pIter->pLeft;
  128550. }
  128551. pIter->pLeft = pRet;
  128552. pRet->pParent = pIter;
  128553. pRet = pNotBranch;
  128554. }
  128555. }
  128556. }
  128557. *pnConsumed = n - nIn;
  128558. exprparse_out:
  128559. if( rc!=SQLITE_OK ){
  128560. sqlite3Fts3ExprFree(pRet);
  128561. sqlite3Fts3ExprFree(pNotBranch);
  128562. pRet = 0;
  128563. }
  128564. *ppExpr = pRet;
  128565. return rc;
  128566. }
  128567. /*
  128568. ** Return SQLITE_ERROR if the maximum depth of the expression tree passed
  128569. ** as the only argument is more than nMaxDepth.
  128570. */
  128571. static int fts3ExprCheckDepth(Fts3Expr *p, int nMaxDepth){
  128572. int rc = SQLITE_OK;
  128573. if( p ){
  128574. if( nMaxDepth<0 ){
  128575. rc = SQLITE_TOOBIG;
  128576. }else{
  128577. rc = fts3ExprCheckDepth(p->pLeft, nMaxDepth-1);
  128578. if( rc==SQLITE_OK ){
  128579. rc = fts3ExprCheckDepth(p->pRight, nMaxDepth-1);
  128580. }
  128581. }
  128582. }
  128583. return rc;
  128584. }
  128585. /*
  128586. ** This function attempts to transform the expression tree at (*pp) to
  128587. ** an equivalent but more balanced form. The tree is modified in place.
  128588. ** If successful, SQLITE_OK is returned and (*pp) set to point to the
  128589. ** new root expression node.
  128590. **
  128591. ** nMaxDepth is the maximum allowable depth of the balanced sub-tree.
  128592. **
  128593. ** Otherwise, if an error occurs, an SQLite error code is returned and
  128594. ** expression (*pp) freed.
  128595. */
  128596. static int fts3ExprBalance(Fts3Expr **pp, int nMaxDepth){
  128597. int rc = SQLITE_OK; /* Return code */
  128598. Fts3Expr *pRoot = *pp; /* Initial root node */
  128599. Fts3Expr *pFree = 0; /* List of free nodes. Linked by pParent. */
  128600. int eType = pRoot->eType; /* Type of node in this tree */
  128601. if( nMaxDepth==0 ){
  128602. rc = SQLITE_ERROR;
  128603. }
  128604. if( rc==SQLITE_OK && (eType==FTSQUERY_AND || eType==FTSQUERY_OR) ){
  128605. Fts3Expr **apLeaf;
  128606. apLeaf = (Fts3Expr **)sqlite3_malloc(sizeof(Fts3Expr *) * nMaxDepth);
  128607. if( 0==apLeaf ){
  128608. rc = SQLITE_NOMEM;
  128609. }else{
  128610. memset(apLeaf, 0, sizeof(Fts3Expr *) * nMaxDepth);
  128611. }
  128612. if( rc==SQLITE_OK ){
  128613. int i;
  128614. Fts3Expr *p;
  128615. /* Set $p to point to the left-most leaf in the tree of eType nodes. */
  128616. for(p=pRoot; p->eType==eType; p=p->pLeft){
  128617. assert( p->pParent==0 || p->pParent->pLeft==p );
  128618. assert( p->pLeft && p->pRight );
  128619. }
  128620. /* This loop runs once for each leaf in the tree of eType nodes. */
  128621. while( 1 ){
  128622. int iLvl;
  128623. Fts3Expr *pParent = p->pParent; /* Current parent of p */
  128624. assert( pParent==0 || pParent->pLeft==p );
  128625. p->pParent = 0;
  128626. if( pParent ){
  128627. pParent->pLeft = 0;
  128628. }else{
  128629. pRoot = 0;
  128630. }
  128631. rc = fts3ExprBalance(&p, nMaxDepth-1);
  128632. if( rc!=SQLITE_OK ) break;
  128633. for(iLvl=0; p && iLvl<nMaxDepth; iLvl++){
  128634. if( apLeaf[iLvl]==0 ){
  128635. apLeaf[iLvl] = p;
  128636. p = 0;
  128637. }else{
  128638. assert( pFree );
  128639. pFree->pLeft = apLeaf[iLvl];
  128640. pFree->pRight = p;
  128641. pFree->pLeft->pParent = pFree;
  128642. pFree->pRight->pParent = pFree;
  128643. p = pFree;
  128644. pFree = pFree->pParent;
  128645. p->pParent = 0;
  128646. apLeaf[iLvl] = 0;
  128647. }
  128648. }
  128649. if( p ){
  128650. sqlite3Fts3ExprFree(p);
  128651. rc = SQLITE_TOOBIG;
  128652. break;
  128653. }
  128654. /* If that was the last leaf node, break out of the loop */
  128655. if( pParent==0 ) break;
  128656. /* Set $p to point to the next leaf in the tree of eType nodes */
  128657. for(p=pParent->pRight; p->eType==eType; p=p->pLeft);
  128658. /* Remove pParent from the original tree. */
  128659. assert( pParent->pParent==0 || pParent->pParent->pLeft==pParent );
  128660. pParent->pRight->pParent = pParent->pParent;
  128661. if( pParent->pParent ){
  128662. pParent->pParent->pLeft = pParent->pRight;
  128663. }else{
  128664. assert( pParent==pRoot );
  128665. pRoot = pParent->pRight;
  128666. }
  128667. /* Link pParent into the free node list. It will be used as an
  128668. ** internal node of the new tree. */
  128669. pParent->pParent = pFree;
  128670. pFree = pParent;
  128671. }
  128672. if( rc==SQLITE_OK ){
  128673. p = 0;
  128674. for(i=0; i<nMaxDepth; i++){
  128675. if( apLeaf[i] ){
  128676. if( p==0 ){
  128677. p = apLeaf[i];
  128678. p->pParent = 0;
  128679. }else{
  128680. assert( pFree!=0 );
  128681. pFree->pRight = p;
  128682. pFree->pLeft = apLeaf[i];
  128683. pFree->pLeft->pParent = pFree;
  128684. pFree->pRight->pParent = pFree;
  128685. p = pFree;
  128686. pFree = pFree->pParent;
  128687. p->pParent = 0;
  128688. }
  128689. }
  128690. }
  128691. pRoot = p;
  128692. }else{
  128693. /* An error occurred. Delete the contents of the apLeaf[] array
  128694. ** and pFree list. Everything else is cleaned up by the call to
  128695. ** sqlite3Fts3ExprFree(pRoot) below. */
  128696. Fts3Expr *pDel;
  128697. for(i=0; i<nMaxDepth; i++){
  128698. sqlite3Fts3ExprFree(apLeaf[i]);
  128699. }
  128700. while( (pDel=pFree)!=0 ){
  128701. pFree = pDel->pParent;
  128702. sqlite3_free(pDel);
  128703. }
  128704. }
  128705. assert( pFree==0 );
  128706. sqlite3_free( apLeaf );
  128707. }
  128708. }
  128709. if( rc!=SQLITE_OK ){
  128710. sqlite3Fts3ExprFree(pRoot);
  128711. pRoot = 0;
  128712. }
  128713. *pp = pRoot;
  128714. return rc;
  128715. }
  128716. /*
  128717. ** This function is similar to sqlite3Fts3ExprParse(), with the following
  128718. ** differences:
  128719. **
  128720. ** 1. It does not do expression rebalancing.
  128721. ** 2. It does not check that the expression does not exceed the
  128722. ** maximum allowable depth.
  128723. ** 3. Even if it fails, *ppExpr may still be set to point to an
  128724. ** expression tree. It should be deleted using sqlite3Fts3ExprFree()
  128725. ** in this case.
  128726. */
  128727. static int fts3ExprParseUnbalanced(
  128728. sqlite3_tokenizer *pTokenizer, /* Tokenizer module */
  128729. int iLangid, /* Language id for tokenizer */
  128730. char **azCol, /* Array of column names for fts3 table */
  128731. int bFts4, /* True to allow FTS4-only syntax */
  128732. int nCol, /* Number of entries in azCol[] */
  128733. int iDefaultCol, /* Default column to query */
  128734. const char *z, int n, /* Text of MATCH query */
  128735. Fts3Expr **ppExpr /* OUT: Parsed query structure */
  128736. ){
  128737. int nParsed;
  128738. int rc;
  128739. ParseContext sParse;
  128740. memset(&sParse, 0, sizeof(ParseContext));
  128741. sParse.pTokenizer = pTokenizer;
  128742. sParse.iLangid = iLangid;
  128743. sParse.azCol = (const char **)azCol;
  128744. sParse.nCol = nCol;
  128745. sParse.iDefaultCol = iDefaultCol;
  128746. sParse.bFts4 = bFts4;
  128747. if( z==0 ){
  128748. *ppExpr = 0;
  128749. return SQLITE_OK;
  128750. }
  128751. if( n<0 ){
  128752. n = (int)strlen(z);
  128753. }
  128754. rc = fts3ExprParse(&sParse, z, n, ppExpr, &nParsed);
  128755. assert( rc==SQLITE_OK || *ppExpr==0 );
  128756. /* Check for mismatched parenthesis */
  128757. if( rc==SQLITE_OK && sParse.nNest ){
  128758. rc = SQLITE_ERROR;
  128759. }
  128760. return rc;
  128761. }
  128762. /*
  128763. ** Parameters z and n contain a pointer to and length of a buffer containing
  128764. ** an fts3 query expression, respectively. This function attempts to parse the
  128765. ** query expression and create a tree of Fts3Expr structures representing the
  128766. ** parsed expression. If successful, *ppExpr is set to point to the head
  128767. ** of the parsed expression tree and SQLITE_OK is returned. If an error
  128768. ** occurs, either SQLITE_NOMEM (out-of-memory error) or SQLITE_ERROR (parse
  128769. ** error) is returned and *ppExpr is set to 0.
  128770. **
  128771. ** If parameter n is a negative number, then z is assumed to point to a
  128772. ** nul-terminated string and the length is determined using strlen().
  128773. **
  128774. ** The first parameter, pTokenizer, is passed the fts3 tokenizer module to
  128775. ** use to normalize query tokens while parsing the expression. The azCol[]
  128776. ** array, which is assumed to contain nCol entries, should contain the names
  128777. ** of each column in the target fts3 table, in order from left to right.
  128778. ** Column names must be nul-terminated strings.
  128779. **
  128780. ** The iDefaultCol parameter should be passed the index of the table column
  128781. ** that appears on the left-hand-side of the MATCH operator (the default
  128782. ** column to match against for tokens for which a column name is not explicitly
  128783. ** specified as part of the query string), or -1 if tokens may by default
  128784. ** match any table column.
  128785. */
  128786. SQLITE_PRIVATE int sqlite3Fts3ExprParse(
  128787. sqlite3_tokenizer *pTokenizer, /* Tokenizer module */
  128788. int iLangid, /* Language id for tokenizer */
  128789. char **azCol, /* Array of column names for fts3 table */
  128790. int bFts4, /* True to allow FTS4-only syntax */
  128791. int nCol, /* Number of entries in azCol[] */
  128792. int iDefaultCol, /* Default column to query */
  128793. const char *z, int n, /* Text of MATCH query */
  128794. Fts3Expr **ppExpr, /* OUT: Parsed query structure */
  128795. char **pzErr /* OUT: Error message (sqlite3_malloc) */
  128796. ){
  128797. int rc = fts3ExprParseUnbalanced(
  128798. pTokenizer, iLangid, azCol, bFts4, nCol, iDefaultCol, z, n, ppExpr
  128799. );
  128800. /* Rebalance the expression. And check that its depth does not exceed
  128801. ** SQLITE_FTS3_MAX_EXPR_DEPTH. */
  128802. if( rc==SQLITE_OK && *ppExpr ){
  128803. rc = fts3ExprBalance(ppExpr, SQLITE_FTS3_MAX_EXPR_DEPTH);
  128804. if( rc==SQLITE_OK ){
  128805. rc = fts3ExprCheckDepth(*ppExpr, SQLITE_FTS3_MAX_EXPR_DEPTH);
  128806. }
  128807. }
  128808. if( rc!=SQLITE_OK ){
  128809. sqlite3Fts3ExprFree(*ppExpr);
  128810. *ppExpr = 0;
  128811. if( rc==SQLITE_TOOBIG ){
  128812. *pzErr = sqlite3_mprintf(
  128813. "FTS expression tree is too large (maximum depth %d)",
  128814. SQLITE_FTS3_MAX_EXPR_DEPTH
  128815. );
  128816. rc = SQLITE_ERROR;
  128817. }else if( rc==SQLITE_ERROR ){
  128818. *pzErr = sqlite3_mprintf("malformed MATCH expression: [%s]", z);
  128819. }
  128820. }
  128821. return rc;
  128822. }
  128823. /*
  128824. ** Free a single node of an expression tree.
  128825. */
  128826. static void fts3FreeExprNode(Fts3Expr *p){
  128827. assert( p->eType==FTSQUERY_PHRASE || p->pPhrase==0 );
  128828. sqlite3Fts3EvalPhraseCleanup(p->pPhrase);
  128829. sqlite3_free(p->aMI);
  128830. sqlite3_free(p);
  128831. }
  128832. /*
  128833. ** Free a parsed fts3 query expression allocated by sqlite3Fts3ExprParse().
  128834. **
  128835. ** This function would be simpler if it recursively called itself. But
  128836. ** that would mean passing a sufficiently large expression to ExprParse()
  128837. ** could cause a stack overflow.
  128838. */
  128839. SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *pDel){
  128840. Fts3Expr *p;
  128841. assert( pDel==0 || pDel->pParent==0 );
  128842. for(p=pDel; p && (p->pLeft||p->pRight); p=(p->pLeft ? p->pLeft : p->pRight)){
  128843. assert( p->pParent==0 || p==p->pParent->pRight || p==p->pParent->pLeft );
  128844. }
  128845. while( p ){
  128846. Fts3Expr *pParent = p->pParent;
  128847. fts3FreeExprNode(p);
  128848. if( pParent && p==pParent->pLeft && pParent->pRight ){
  128849. p = pParent->pRight;
  128850. while( p && (p->pLeft || p->pRight) ){
  128851. assert( p==p->pParent->pRight || p==p->pParent->pLeft );
  128852. p = (p->pLeft ? p->pLeft : p->pRight);
  128853. }
  128854. }else{
  128855. p = pParent;
  128856. }
  128857. }
  128858. }
  128859. /****************************************************************************
  128860. *****************************************************************************
  128861. ** Everything after this point is just test code.
  128862. */
  128863. #ifdef SQLITE_TEST
  128864. /* #include <stdio.h> */
  128865. /*
  128866. ** Function to query the hash-table of tokenizers (see README.tokenizers).
  128867. */
  128868. static int queryTestTokenizer(
  128869. sqlite3 *db,
  128870. const char *zName,
  128871. const sqlite3_tokenizer_module **pp
  128872. ){
  128873. int rc;
  128874. sqlite3_stmt *pStmt;
  128875. const char zSql[] = "SELECT fts3_tokenizer(?)";
  128876. *pp = 0;
  128877. rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
  128878. if( rc!=SQLITE_OK ){
  128879. return rc;
  128880. }
  128881. sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
  128882. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  128883. if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
  128884. memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
  128885. }
  128886. }
  128887. return sqlite3_finalize(pStmt);
  128888. }
  128889. /*
  128890. ** Return a pointer to a buffer containing a text representation of the
  128891. ** expression passed as the first argument. The buffer is obtained from
  128892. ** sqlite3_malloc(). It is the responsibility of the caller to use
  128893. ** sqlite3_free() to release the memory. If an OOM condition is encountered,
  128894. ** NULL is returned.
  128895. **
  128896. ** If the second argument is not NULL, then its contents are prepended to
  128897. ** the returned expression text and then freed using sqlite3_free().
  128898. */
  128899. static char *exprToString(Fts3Expr *pExpr, char *zBuf){
  128900. if( pExpr==0 ){
  128901. return sqlite3_mprintf("");
  128902. }
  128903. switch( pExpr->eType ){
  128904. case FTSQUERY_PHRASE: {
  128905. Fts3Phrase *pPhrase = pExpr->pPhrase;
  128906. int i;
  128907. zBuf = sqlite3_mprintf(
  128908. "%zPHRASE %d 0", zBuf, pPhrase->iColumn);
  128909. for(i=0; zBuf && i<pPhrase->nToken; i++){
  128910. zBuf = sqlite3_mprintf("%z %.*s%s", zBuf,
  128911. pPhrase->aToken[i].n, pPhrase->aToken[i].z,
  128912. (pPhrase->aToken[i].isPrefix?"+":"")
  128913. );
  128914. }
  128915. return zBuf;
  128916. }
  128917. case FTSQUERY_NEAR:
  128918. zBuf = sqlite3_mprintf("%zNEAR/%d ", zBuf, pExpr->nNear);
  128919. break;
  128920. case FTSQUERY_NOT:
  128921. zBuf = sqlite3_mprintf("%zNOT ", zBuf);
  128922. break;
  128923. case FTSQUERY_AND:
  128924. zBuf = sqlite3_mprintf("%zAND ", zBuf);
  128925. break;
  128926. case FTSQUERY_OR:
  128927. zBuf = sqlite3_mprintf("%zOR ", zBuf);
  128928. break;
  128929. }
  128930. if( zBuf ) zBuf = sqlite3_mprintf("%z{", zBuf);
  128931. if( zBuf ) zBuf = exprToString(pExpr->pLeft, zBuf);
  128932. if( zBuf ) zBuf = sqlite3_mprintf("%z} {", zBuf);
  128933. if( zBuf ) zBuf = exprToString(pExpr->pRight, zBuf);
  128934. if( zBuf ) zBuf = sqlite3_mprintf("%z}", zBuf);
  128935. return zBuf;
  128936. }
  128937. /*
  128938. ** This is the implementation of a scalar SQL function used to test the
  128939. ** expression parser. It should be called as follows:
  128940. **
  128941. ** fts3_exprtest(<tokenizer>, <expr>, <column 1>, ...);
  128942. **
  128943. ** The first argument, <tokenizer>, is the name of the fts3 tokenizer used
  128944. ** to parse the query expression (see README.tokenizers). The second argument
  128945. ** is the query expression to parse. Each subsequent argument is the name
  128946. ** of a column of the fts3 table that the query expression may refer to.
  128947. ** For example:
  128948. **
  128949. ** SELECT fts3_exprtest('simple', 'Bill col2:Bloggs', 'col1', 'col2');
  128950. */
  128951. static void fts3ExprTest(
  128952. sqlite3_context *context,
  128953. int argc,
  128954. sqlite3_value **argv
  128955. ){
  128956. sqlite3_tokenizer_module const *pModule = 0;
  128957. sqlite3_tokenizer *pTokenizer = 0;
  128958. int rc;
  128959. char **azCol = 0;
  128960. const char *zExpr;
  128961. int nExpr;
  128962. int nCol;
  128963. int ii;
  128964. Fts3Expr *pExpr;
  128965. char *zBuf = 0;
  128966. sqlite3 *db = sqlite3_context_db_handle(context);
  128967. if( argc<3 ){
  128968. sqlite3_result_error(context,
  128969. "Usage: fts3_exprtest(tokenizer, expr, col1, ...", -1
  128970. );
  128971. return;
  128972. }
  128973. rc = queryTestTokenizer(db,
  128974. (const char *)sqlite3_value_text(argv[0]), &pModule);
  128975. if( rc==SQLITE_NOMEM ){
  128976. sqlite3_result_error_nomem(context);
  128977. goto exprtest_out;
  128978. }else if( !pModule ){
  128979. sqlite3_result_error(context, "No such tokenizer module", -1);
  128980. goto exprtest_out;
  128981. }
  128982. rc = pModule->xCreate(0, 0, &pTokenizer);
  128983. assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
  128984. if( rc==SQLITE_NOMEM ){
  128985. sqlite3_result_error_nomem(context);
  128986. goto exprtest_out;
  128987. }
  128988. pTokenizer->pModule = pModule;
  128989. zExpr = (const char *)sqlite3_value_text(argv[1]);
  128990. nExpr = sqlite3_value_bytes(argv[1]);
  128991. nCol = argc-2;
  128992. azCol = (char **)sqlite3_malloc(nCol*sizeof(char *));
  128993. if( !azCol ){
  128994. sqlite3_result_error_nomem(context);
  128995. goto exprtest_out;
  128996. }
  128997. for(ii=0; ii<nCol; ii++){
  128998. azCol[ii] = (char *)sqlite3_value_text(argv[ii+2]);
  128999. }
  129000. if( sqlite3_user_data(context) ){
  129001. char *zDummy = 0;
  129002. rc = sqlite3Fts3ExprParse(
  129003. pTokenizer, 0, azCol, 0, nCol, nCol, zExpr, nExpr, &pExpr, &zDummy
  129004. );
  129005. assert( rc==SQLITE_OK || pExpr==0 );
  129006. sqlite3_free(zDummy);
  129007. }else{
  129008. rc = fts3ExprParseUnbalanced(
  129009. pTokenizer, 0, azCol, 0, nCol, nCol, zExpr, nExpr, &pExpr
  129010. );
  129011. }
  129012. if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM ){
  129013. sqlite3Fts3ExprFree(pExpr);
  129014. sqlite3_result_error(context, "Error parsing expression", -1);
  129015. }else if( rc==SQLITE_NOMEM || !(zBuf = exprToString(pExpr, 0)) ){
  129016. sqlite3_result_error_nomem(context);
  129017. }else{
  129018. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  129019. sqlite3_free(zBuf);
  129020. }
  129021. sqlite3Fts3ExprFree(pExpr);
  129022. exprtest_out:
  129023. if( pModule && pTokenizer ){
  129024. rc = pModule->xDestroy(pTokenizer);
  129025. }
  129026. sqlite3_free(azCol);
  129027. }
  129028. /*
  129029. ** Register the query expression parser test function fts3_exprtest()
  129030. ** with database connection db.
  129031. */
  129032. SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3* db){
  129033. int rc = sqlite3_create_function(
  129034. db, "fts3_exprtest", -1, SQLITE_UTF8, 0, fts3ExprTest, 0, 0
  129035. );
  129036. if( rc==SQLITE_OK ){
  129037. rc = sqlite3_create_function(db, "fts3_exprtest_rebalance",
  129038. -1, SQLITE_UTF8, (void *)1, fts3ExprTest, 0, 0
  129039. );
  129040. }
  129041. return rc;
  129042. }
  129043. #endif
  129044. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  129045. /************** End of fts3_expr.c *******************************************/
  129046. /************** Begin file fts3_hash.c ***************************************/
  129047. /*
  129048. ** 2001 September 22
  129049. **
  129050. ** The author disclaims copyright to this source code. In place of
  129051. ** a legal notice, here is a blessing:
  129052. **
  129053. ** May you do good and not evil.
  129054. ** May you find forgiveness for yourself and forgive others.
  129055. ** May you share freely, never taking more than you give.
  129056. **
  129057. *************************************************************************
  129058. ** This is the implementation of generic hash-tables used in SQLite.
  129059. ** We've modified it slightly to serve as a standalone hash table
  129060. ** implementation for the full-text indexing module.
  129061. */
  129062. /*
  129063. ** The code in this file is only compiled if:
  129064. **
  129065. ** * The FTS3 module is being built as an extension
  129066. ** (in which case SQLITE_CORE is not defined), or
  129067. **
  129068. ** * The FTS3 module is being built into the core of
  129069. ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
  129070. */
  129071. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  129072. /* #include <assert.h> */
  129073. /* #include <stdlib.h> */
  129074. /* #include <string.h> */
  129075. /*
  129076. ** Malloc and Free functions
  129077. */
  129078. static void *fts3HashMalloc(int n){
  129079. void *p = sqlite3_malloc(n);
  129080. if( p ){
  129081. memset(p, 0, n);
  129082. }
  129083. return p;
  129084. }
  129085. static void fts3HashFree(void *p){
  129086. sqlite3_free(p);
  129087. }
  129088. /* Turn bulk memory into a hash table object by initializing the
  129089. ** fields of the Hash structure.
  129090. **
  129091. ** "pNew" is a pointer to the hash table that is to be initialized.
  129092. ** keyClass is one of the constants
  129093. ** FTS3_HASH_BINARY or FTS3_HASH_STRING. The value of keyClass
  129094. ** determines what kind of key the hash table will use. "copyKey" is
  129095. ** true if the hash table should make its own private copy of keys and
  129096. ** false if it should just use the supplied pointer.
  129097. */
  129098. SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey){
  129099. assert( pNew!=0 );
  129100. assert( keyClass>=FTS3_HASH_STRING && keyClass<=FTS3_HASH_BINARY );
  129101. pNew->keyClass = keyClass;
  129102. pNew->copyKey = copyKey;
  129103. pNew->first = 0;
  129104. pNew->count = 0;
  129105. pNew->htsize = 0;
  129106. pNew->ht = 0;
  129107. }
  129108. /* Remove all entries from a hash table. Reclaim all memory.
  129109. ** Call this routine to delete a hash table or to reset a hash table
  129110. ** to the empty state.
  129111. */
  129112. SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash *pH){
  129113. Fts3HashElem *elem; /* For looping over all elements of the table */
  129114. assert( pH!=0 );
  129115. elem = pH->first;
  129116. pH->first = 0;
  129117. fts3HashFree(pH->ht);
  129118. pH->ht = 0;
  129119. pH->htsize = 0;
  129120. while( elem ){
  129121. Fts3HashElem *next_elem = elem->next;
  129122. if( pH->copyKey && elem->pKey ){
  129123. fts3HashFree(elem->pKey);
  129124. }
  129125. fts3HashFree(elem);
  129126. elem = next_elem;
  129127. }
  129128. pH->count = 0;
  129129. }
  129130. /*
  129131. ** Hash and comparison functions when the mode is FTS3_HASH_STRING
  129132. */
  129133. static int fts3StrHash(const void *pKey, int nKey){
  129134. const char *z = (const char *)pKey;
  129135. unsigned h = 0;
  129136. if( nKey<=0 ) nKey = (int) strlen(z);
  129137. while( nKey > 0 ){
  129138. h = (h<<3) ^ h ^ *z++;
  129139. nKey--;
  129140. }
  129141. return (int)(h & 0x7fffffff);
  129142. }
  129143. static int fts3StrCompare(const void *pKey1, int n1, const void *pKey2, int n2){
  129144. if( n1!=n2 ) return 1;
  129145. return strncmp((const char*)pKey1,(const char*)pKey2,n1);
  129146. }
  129147. /*
  129148. ** Hash and comparison functions when the mode is FTS3_HASH_BINARY
  129149. */
  129150. static int fts3BinHash(const void *pKey, int nKey){
  129151. int h = 0;
  129152. const char *z = (const char *)pKey;
  129153. while( nKey-- > 0 ){
  129154. h = (h<<3) ^ h ^ *(z++);
  129155. }
  129156. return h & 0x7fffffff;
  129157. }
  129158. static int fts3BinCompare(const void *pKey1, int n1, const void *pKey2, int n2){
  129159. if( n1!=n2 ) return 1;
  129160. return memcmp(pKey1,pKey2,n1);
  129161. }
  129162. /*
  129163. ** Return a pointer to the appropriate hash function given the key class.
  129164. **
  129165. ** The C syntax in this function definition may be unfamilar to some
  129166. ** programmers, so we provide the following additional explanation:
  129167. **
  129168. ** The name of the function is "ftsHashFunction". The function takes a
  129169. ** single parameter "keyClass". The return value of ftsHashFunction()
  129170. ** is a pointer to another function. Specifically, the return value
  129171. ** of ftsHashFunction() is a pointer to a function that takes two parameters
  129172. ** with types "const void*" and "int" and returns an "int".
  129173. */
  129174. static int (*ftsHashFunction(int keyClass))(const void*,int){
  129175. if( keyClass==FTS3_HASH_STRING ){
  129176. return &fts3StrHash;
  129177. }else{
  129178. assert( keyClass==FTS3_HASH_BINARY );
  129179. return &fts3BinHash;
  129180. }
  129181. }
  129182. /*
  129183. ** Return a pointer to the appropriate hash function given the key class.
  129184. **
  129185. ** For help in interpreted the obscure C code in the function definition,
  129186. ** see the header comment on the previous function.
  129187. */
  129188. static int (*ftsCompareFunction(int keyClass))(const void*,int,const void*,int){
  129189. if( keyClass==FTS3_HASH_STRING ){
  129190. return &fts3StrCompare;
  129191. }else{
  129192. assert( keyClass==FTS3_HASH_BINARY );
  129193. return &fts3BinCompare;
  129194. }
  129195. }
  129196. /* Link an element into the hash table
  129197. */
  129198. static void fts3HashInsertElement(
  129199. Fts3Hash *pH, /* The complete hash table */
  129200. struct _fts3ht *pEntry, /* The entry into which pNew is inserted */
  129201. Fts3HashElem *pNew /* The element to be inserted */
  129202. ){
  129203. Fts3HashElem *pHead; /* First element already in pEntry */
  129204. pHead = pEntry->chain;
  129205. if( pHead ){
  129206. pNew->next = pHead;
  129207. pNew->prev = pHead->prev;
  129208. if( pHead->prev ){ pHead->prev->next = pNew; }
  129209. else { pH->first = pNew; }
  129210. pHead->prev = pNew;
  129211. }else{
  129212. pNew->next = pH->first;
  129213. if( pH->first ){ pH->first->prev = pNew; }
  129214. pNew->prev = 0;
  129215. pH->first = pNew;
  129216. }
  129217. pEntry->count++;
  129218. pEntry->chain = pNew;
  129219. }
  129220. /* Resize the hash table so that it cantains "new_size" buckets.
  129221. ** "new_size" must be a power of 2. The hash table might fail
  129222. ** to resize if sqliteMalloc() fails.
  129223. **
  129224. ** Return non-zero if a memory allocation error occurs.
  129225. */
  129226. static int fts3Rehash(Fts3Hash *pH, int new_size){
  129227. struct _fts3ht *new_ht; /* The new hash table */
  129228. Fts3HashElem *elem, *next_elem; /* For looping over existing elements */
  129229. int (*xHash)(const void*,int); /* The hash function */
  129230. assert( (new_size & (new_size-1))==0 );
  129231. new_ht = (struct _fts3ht *)fts3HashMalloc( new_size*sizeof(struct _fts3ht) );
  129232. if( new_ht==0 ) return 1;
  129233. fts3HashFree(pH->ht);
  129234. pH->ht = new_ht;
  129235. pH->htsize = new_size;
  129236. xHash = ftsHashFunction(pH->keyClass);
  129237. for(elem=pH->first, pH->first=0; elem; elem = next_elem){
  129238. int h = (*xHash)(elem->pKey, elem->nKey) & (new_size-1);
  129239. next_elem = elem->next;
  129240. fts3HashInsertElement(pH, &new_ht[h], elem);
  129241. }
  129242. return 0;
  129243. }
  129244. /* This function (for internal use only) locates an element in an
  129245. ** hash table that matches the given key. The hash for this key has
  129246. ** already been computed and is passed as the 4th parameter.
  129247. */
  129248. static Fts3HashElem *fts3FindElementByHash(
  129249. const Fts3Hash *pH, /* The pH to be searched */
  129250. const void *pKey, /* The key we are searching for */
  129251. int nKey,
  129252. int h /* The hash for this key. */
  129253. ){
  129254. Fts3HashElem *elem; /* Used to loop thru the element list */
  129255. int count; /* Number of elements left to test */
  129256. int (*xCompare)(const void*,int,const void*,int); /* comparison function */
  129257. if( pH->ht ){
  129258. struct _fts3ht *pEntry = &pH->ht[h];
  129259. elem = pEntry->chain;
  129260. count = pEntry->count;
  129261. xCompare = ftsCompareFunction(pH->keyClass);
  129262. while( count-- && elem ){
  129263. if( (*xCompare)(elem->pKey,elem->nKey,pKey,nKey)==0 ){
  129264. return elem;
  129265. }
  129266. elem = elem->next;
  129267. }
  129268. }
  129269. return 0;
  129270. }
  129271. /* Remove a single entry from the hash table given a pointer to that
  129272. ** element and a hash on the element's key.
  129273. */
  129274. static void fts3RemoveElementByHash(
  129275. Fts3Hash *pH, /* The pH containing "elem" */
  129276. Fts3HashElem* elem, /* The element to be removed from the pH */
  129277. int h /* Hash value for the element */
  129278. ){
  129279. struct _fts3ht *pEntry;
  129280. if( elem->prev ){
  129281. elem->prev->next = elem->next;
  129282. }else{
  129283. pH->first = elem->next;
  129284. }
  129285. if( elem->next ){
  129286. elem->next->prev = elem->prev;
  129287. }
  129288. pEntry = &pH->ht[h];
  129289. if( pEntry->chain==elem ){
  129290. pEntry->chain = elem->next;
  129291. }
  129292. pEntry->count--;
  129293. if( pEntry->count<=0 ){
  129294. pEntry->chain = 0;
  129295. }
  129296. if( pH->copyKey && elem->pKey ){
  129297. fts3HashFree(elem->pKey);
  129298. }
  129299. fts3HashFree( elem );
  129300. pH->count--;
  129301. if( pH->count<=0 ){
  129302. assert( pH->first==0 );
  129303. assert( pH->count==0 );
  129304. fts3HashClear(pH);
  129305. }
  129306. }
  129307. SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(
  129308. const Fts3Hash *pH,
  129309. const void *pKey,
  129310. int nKey
  129311. ){
  129312. int h; /* A hash on key */
  129313. int (*xHash)(const void*,int); /* The hash function */
  129314. if( pH==0 || pH->ht==0 ) return 0;
  129315. xHash = ftsHashFunction(pH->keyClass);
  129316. assert( xHash!=0 );
  129317. h = (*xHash)(pKey,nKey);
  129318. assert( (pH->htsize & (pH->htsize-1))==0 );
  129319. return fts3FindElementByHash(pH,pKey,nKey, h & (pH->htsize-1));
  129320. }
  129321. /*
  129322. ** Attempt to locate an element of the hash table pH with a key
  129323. ** that matches pKey,nKey. Return the data for this element if it is
  129324. ** found, or NULL if there is no match.
  129325. */
  129326. SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash *pH, const void *pKey, int nKey){
  129327. Fts3HashElem *pElem; /* The element that matches key (if any) */
  129328. pElem = sqlite3Fts3HashFindElem(pH, pKey, nKey);
  129329. return pElem ? pElem->data : 0;
  129330. }
  129331. /* Insert an element into the hash table pH. The key is pKey,nKey
  129332. ** and the data is "data".
  129333. **
  129334. ** If no element exists with a matching key, then a new
  129335. ** element is created. A copy of the key is made if the copyKey
  129336. ** flag is set. NULL is returned.
  129337. **
  129338. ** If another element already exists with the same key, then the
  129339. ** new data replaces the old data and the old data is returned.
  129340. ** The key is not copied in this instance. If a malloc fails, then
  129341. ** the new data is returned and the hash table is unchanged.
  129342. **
  129343. ** If the "data" parameter to this function is NULL, then the
  129344. ** element corresponding to "key" is removed from the hash table.
  129345. */
  129346. SQLITE_PRIVATE void *sqlite3Fts3HashInsert(
  129347. Fts3Hash *pH, /* The hash table to insert into */
  129348. const void *pKey, /* The key */
  129349. int nKey, /* Number of bytes in the key */
  129350. void *data /* The data */
  129351. ){
  129352. int hraw; /* Raw hash value of the key */
  129353. int h; /* the hash of the key modulo hash table size */
  129354. Fts3HashElem *elem; /* Used to loop thru the element list */
  129355. Fts3HashElem *new_elem; /* New element added to the pH */
  129356. int (*xHash)(const void*,int); /* The hash function */
  129357. assert( pH!=0 );
  129358. xHash = ftsHashFunction(pH->keyClass);
  129359. assert( xHash!=0 );
  129360. hraw = (*xHash)(pKey, nKey);
  129361. assert( (pH->htsize & (pH->htsize-1))==0 );
  129362. h = hraw & (pH->htsize-1);
  129363. elem = fts3FindElementByHash(pH,pKey,nKey,h);
  129364. if( elem ){
  129365. void *old_data = elem->data;
  129366. if( data==0 ){
  129367. fts3RemoveElementByHash(pH,elem,h);
  129368. }else{
  129369. elem->data = data;
  129370. }
  129371. return old_data;
  129372. }
  129373. if( data==0 ) return 0;
  129374. if( (pH->htsize==0 && fts3Rehash(pH,8))
  129375. || (pH->count>=pH->htsize && fts3Rehash(pH, pH->htsize*2))
  129376. ){
  129377. pH->count = 0;
  129378. return data;
  129379. }
  129380. assert( pH->htsize>0 );
  129381. new_elem = (Fts3HashElem*)fts3HashMalloc( sizeof(Fts3HashElem) );
  129382. if( new_elem==0 ) return data;
  129383. if( pH->copyKey && pKey!=0 ){
  129384. new_elem->pKey = fts3HashMalloc( nKey );
  129385. if( new_elem->pKey==0 ){
  129386. fts3HashFree(new_elem);
  129387. return data;
  129388. }
  129389. memcpy((void*)new_elem->pKey, pKey, nKey);
  129390. }else{
  129391. new_elem->pKey = (void*)pKey;
  129392. }
  129393. new_elem->nKey = nKey;
  129394. pH->count++;
  129395. assert( pH->htsize>0 );
  129396. assert( (pH->htsize & (pH->htsize-1))==0 );
  129397. h = hraw & (pH->htsize-1);
  129398. fts3HashInsertElement(pH, &pH->ht[h], new_elem);
  129399. new_elem->data = data;
  129400. return 0;
  129401. }
  129402. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  129403. /************** End of fts3_hash.c *******************************************/
  129404. /************** Begin file fts3_porter.c *************************************/
  129405. /*
  129406. ** 2006 September 30
  129407. **
  129408. ** The author disclaims copyright to this source code. In place of
  129409. ** a legal notice, here is a blessing:
  129410. **
  129411. ** May you do good and not evil.
  129412. ** May you find forgiveness for yourself and forgive others.
  129413. ** May you share freely, never taking more than you give.
  129414. **
  129415. *************************************************************************
  129416. ** Implementation of the full-text-search tokenizer that implements
  129417. ** a Porter stemmer.
  129418. */
  129419. /*
  129420. ** The code in this file is only compiled if:
  129421. **
  129422. ** * The FTS3 module is being built as an extension
  129423. ** (in which case SQLITE_CORE is not defined), or
  129424. **
  129425. ** * The FTS3 module is being built into the core of
  129426. ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
  129427. */
  129428. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  129429. /* #include <assert.h> */
  129430. /* #include <stdlib.h> */
  129431. /* #include <stdio.h> */
  129432. /* #include <string.h> */
  129433. /*
  129434. ** Class derived from sqlite3_tokenizer
  129435. */
  129436. typedef struct porter_tokenizer {
  129437. sqlite3_tokenizer base; /* Base class */
  129438. } porter_tokenizer;
  129439. /*
  129440. ** Class derived from sqlite3_tokenizer_cursor
  129441. */
  129442. typedef struct porter_tokenizer_cursor {
  129443. sqlite3_tokenizer_cursor base;
  129444. const char *zInput; /* input we are tokenizing */
  129445. int nInput; /* size of the input */
  129446. int iOffset; /* current position in zInput */
  129447. int iToken; /* index of next token to be returned */
  129448. char *zToken; /* storage for current token */
  129449. int nAllocated; /* space allocated to zToken buffer */
  129450. } porter_tokenizer_cursor;
  129451. /*
  129452. ** Create a new tokenizer instance.
  129453. */
  129454. static int porterCreate(
  129455. int argc, const char * const *argv,
  129456. sqlite3_tokenizer **ppTokenizer
  129457. ){
  129458. porter_tokenizer *t;
  129459. UNUSED_PARAMETER(argc);
  129460. UNUSED_PARAMETER(argv);
  129461. t = (porter_tokenizer *) sqlite3_malloc(sizeof(*t));
  129462. if( t==NULL ) return SQLITE_NOMEM;
  129463. memset(t, 0, sizeof(*t));
  129464. *ppTokenizer = &t->base;
  129465. return SQLITE_OK;
  129466. }
  129467. /*
  129468. ** Destroy a tokenizer
  129469. */
  129470. static int porterDestroy(sqlite3_tokenizer *pTokenizer){
  129471. sqlite3_free(pTokenizer);
  129472. return SQLITE_OK;
  129473. }
  129474. /*
  129475. ** Prepare to begin tokenizing a particular string. The input
  129476. ** string to be tokenized is zInput[0..nInput-1]. A cursor
  129477. ** used to incrementally tokenize this string is returned in
  129478. ** *ppCursor.
  129479. */
  129480. static int porterOpen(
  129481. sqlite3_tokenizer *pTokenizer, /* The tokenizer */
  129482. const char *zInput, int nInput, /* String to be tokenized */
  129483. sqlite3_tokenizer_cursor **ppCursor /* OUT: Tokenization cursor */
  129484. ){
  129485. porter_tokenizer_cursor *c;
  129486. UNUSED_PARAMETER(pTokenizer);
  129487. c = (porter_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
  129488. if( c==NULL ) return SQLITE_NOMEM;
  129489. c->zInput = zInput;
  129490. if( zInput==0 ){
  129491. c->nInput = 0;
  129492. }else if( nInput<0 ){
  129493. c->nInput = (int)strlen(zInput);
  129494. }else{
  129495. c->nInput = nInput;
  129496. }
  129497. c->iOffset = 0; /* start tokenizing at the beginning */
  129498. c->iToken = 0;
  129499. c->zToken = NULL; /* no space allocated, yet. */
  129500. c->nAllocated = 0;
  129501. *ppCursor = &c->base;
  129502. return SQLITE_OK;
  129503. }
  129504. /*
  129505. ** Close a tokenization cursor previously opened by a call to
  129506. ** porterOpen() above.
  129507. */
  129508. static int porterClose(sqlite3_tokenizer_cursor *pCursor){
  129509. porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
  129510. sqlite3_free(c->zToken);
  129511. sqlite3_free(c);
  129512. return SQLITE_OK;
  129513. }
  129514. /*
  129515. ** Vowel or consonant
  129516. */
  129517. static const char cType[] = {
  129518. 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0,
  129519. 1, 1, 1, 2, 1
  129520. };
  129521. /*
  129522. ** isConsonant() and isVowel() determine if their first character in
  129523. ** the string they point to is a consonant or a vowel, according
  129524. ** to Porter ruls.
  129525. **
  129526. ** A consonate is any letter other than 'a', 'e', 'i', 'o', or 'u'.
  129527. ** 'Y' is a consonant unless it follows another consonant,
  129528. ** in which case it is a vowel.
  129529. **
  129530. ** In these routine, the letters are in reverse order. So the 'y' rule
  129531. ** is that 'y' is a consonant unless it is followed by another
  129532. ** consonent.
  129533. */
  129534. static int isVowel(const char*);
  129535. static int isConsonant(const char *z){
  129536. int j;
  129537. char x = *z;
  129538. if( x==0 ) return 0;
  129539. assert( x>='a' && x<='z' );
  129540. j = cType[x-'a'];
  129541. if( j<2 ) return j;
  129542. return z[1]==0 || isVowel(z + 1);
  129543. }
  129544. static int isVowel(const char *z){
  129545. int j;
  129546. char x = *z;
  129547. if( x==0 ) return 0;
  129548. assert( x>='a' && x<='z' );
  129549. j = cType[x-'a'];
  129550. if( j<2 ) return 1-j;
  129551. return isConsonant(z + 1);
  129552. }
  129553. /*
  129554. ** Let any sequence of one or more vowels be represented by V and let
  129555. ** C be sequence of one or more consonants. Then every word can be
  129556. ** represented as:
  129557. **
  129558. ** [C] (VC){m} [V]
  129559. **
  129560. ** In prose: A word is an optional consonant followed by zero or
  129561. ** vowel-consonant pairs followed by an optional vowel. "m" is the
  129562. ** number of vowel consonant pairs. This routine computes the value
  129563. ** of m for the first i bytes of a word.
  129564. **
  129565. ** Return true if the m-value for z is 1 or more. In other words,
  129566. ** return true if z contains at least one vowel that is followed
  129567. ** by a consonant.
  129568. **
  129569. ** In this routine z[] is in reverse order. So we are really looking
  129570. ** for an instance of of a consonant followed by a vowel.
  129571. */
  129572. static int m_gt_0(const char *z){
  129573. while( isVowel(z) ){ z++; }
  129574. if( *z==0 ) return 0;
  129575. while( isConsonant(z) ){ z++; }
  129576. return *z!=0;
  129577. }
  129578. /* Like mgt0 above except we are looking for a value of m which is
  129579. ** exactly 1
  129580. */
  129581. static int m_eq_1(const char *z){
  129582. while( isVowel(z) ){ z++; }
  129583. if( *z==0 ) return 0;
  129584. while( isConsonant(z) ){ z++; }
  129585. if( *z==0 ) return 0;
  129586. while( isVowel(z) ){ z++; }
  129587. if( *z==0 ) return 1;
  129588. while( isConsonant(z) ){ z++; }
  129589. return *z==0;
  129590. }
  129591. /* Like mgt0 above except we are looking for a value of m>1 instead
  129592. ** or m>0
  129593. */
  129594. static int m_gt_1(const char *z){
  129595. while( isVowel(z) ){ z++; }
  129596. if( *z==0 ) return 0;
  129597. while( isConsonant(z) ){ z++; }
  129598. if( *z==0 ) return 0;
  129599. while( isVowel(z) ){ z++; }
  129600. if( *z==0 ) return 0;
  129601. while( isConsonant(z) ){ z++; }
  129602. return *z!=0;
  129603. }
  129604. /*
  129605. ** Return TRUE if there is a vowel anywhere within z[0..n-1]
  129606. */
  129607. static int hasVowel(const char *z){
  129608. while( isConsonant(z) ){ z++; }
  129609. return *z!=0;
  129610. }
  129611. /*
  129612. ** Return TRUE if the word ends in a double consonant.
  129613. **
  129614. ** The text is reversed here. So we are really looking at
  129615. ** the first two characters of z[].
  129616. */
  129617. static int doubleConsonant(const char *z){
  129618. return isConsonant(z) && z[0]==z[1];
  129619. }
  129620. /*
  129621. ** Return TRUE if the word ends with three letters which
  129622. ** are consonant-vowel-consonent and where the final consonant
  129623. ** is not 'w', 'x', or 'y'.
  129624. **
  129625. ** The word is reversed here. So we are really checking the
  129626. ** first three letters and the first one cannot be in [wxy].
  129627. */
  129628. static int star_oh(const char *z){
  129629. return
  129630. isConsonant(z) &&
  129631. z[0]!='w' && z[0]!='x' && z[0]!='y' &&
  129632. isVowel(z+1) &&
  129633. isConsonant(z+2);
  129634. }
  129635. /*
  129636. ** If the word ends with zFrom and xCond() is true for the stem
  129637. ** of the word that preceeds the zFrom ending, then change the
  129638. ** ending to zTo.
  129639. **
  129640. ** The input word *pz and zFrom are both in reverse order. zTo
  129641. ** is in normal order.
  129642. **
  129643. ** Return TRUE if zFrom matches. Return FALSE if zFrom does not
  129644. ** match. Not that TRUE is returned even if xCond() fails and
  129645. ** no substitution occurs.
  129646. */
  129647. static int stem(
  129648. char **pz, /* The word being stemmed (Reversed) */
  129649. const char *zFrom, /* If the ending matches this... (Reversed) */
  129650. const char *zTo, /* ... change the ending to this (not reversed) */
  129651. int (*xCond)(const char*) /* Condition that must be true */
  129652. ){
  129653. char *z = *pz;
  129654. while( *zFrom && *zFrom==*z ){ z++; zFrom++; }
  129655. if( *zFrom!=0 ) return 0;
  129656. if( xCond && !xCond(z) ) return 1;
  129657. while( *zTo ){
  129658. *(--z) = *(zTo++);
  129659. }
  129660. *pz = z;
  129661. return 1;
  129662. }
  129663. /*
  129664. ** This is the fallback stemmer used when the porter stemmer is
  129665. ** inappropriate. The input word is copied into the output with
  129666. ** US-ASCII case folding. If the input word is too long (more
  129667. ** than 20 bytes if it contains no digits or more than 6 bytes if
  129668. ** it contains digits) then word is truncated to 20 or 6 bytes
  129669. ** by taking 10 or 3 bytes from the beginning and end.
  129670. */
  129671. static void copy_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
  129672. int i, mx, j;
  129673. int hasDigit = 0;
  129674. for(i=0; i<nIn; i++){
  129675. char c = zIn[i];
  129676. if( c>='A' && c<='Z' ){
  129677. zOut[i] = c - 'A' + 'a';
  129678. }else{
  129679. if( c>='0' && c<='9' ) hasDigit = 1;
  129680. zOut[i] = c;
  129681. }
  129682. }
  129683. mx = hasDigit ? 3 : 10;
  129684. if( nIn>mx*2 ){
  129685. for(j=mx, i=nIn-mx; i<nIn; i++, j++){
  129686. zOut[j] = zOut[i];
  129687. }
  129688. i = j;
  129689. }
  129690. zOut[i] = 0;
  129691. *pnOut = i;
  129692. }
  129693. /*
  129694. ** Stem the input word zIn[0..nIn-1]. Store the output in zOut.
  129695. ** zOut is at least big enough to hold nIn bytes. Write the actual
  129696. ** size of the output word (exclusive of the '\0' terminator) into *pnOut.
  129697. **
  129698. ** Any upper-case characters in the US-ASCII character set ([A-Z])
  129699. ** are converted to lower case. Upper-case UTF characters are
  129700. ** unchanged.
  129701. **
  129702. ** Words that are longer than about 20 bytes are stemmed by retaining
  129703. ** a few bytes from the beginning and the end of the word. If the
  129704. ** word contains digits, 3 bytes are taken from the beginning and
  129705. ** 3 bytes from the end. For long words without digits, 10 bytes
  129706. ** are taken from each end. US-ASCII case folding still applies.
  129707. **
  129708. ** If the input word contains not digits but does characters not
  129709. ** in [a-zA-Z] then no stemming is attempted and this routine just
  129710. ** copies the input into the input into the output with US-ASCII
  129711. ** case folding.
  129712. **
  129713. ** Stemming never increases the length of the word. So there is
  129714. ** no chance of overflowing the zOut buffer.
  129715. */
  129716. static void porter_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
  129717. int i, j;
  129718. char zReverse[28];
  129719. char *z, *z2;
  129720. if( nIn<3 || nIn>=(int)sizeof(zReverse)-7 ){
  129721. /* The word is too big or too small for the porter stemmer.
  129722. ** Fallback to the copy stemmer */
  129723. copy_stemmer(zIn, nIn, zOut, pnOut);
  129724. return;
  129725. }
  129726. for(i=0, j=sizeof(zReverse)-6; i<nIn; i++, j--){
  129727. char c = zIn[i];
  129728. if( c>='A' && c<='Z' ){
  129729. zReverse[j] = c + 'a' - 'A';
  129730. }else if( c>='a' && c<='z' ){
  129731. zReverse[j] = c;
  129732. }else{
  129733. /* The use of a character not in [a-zA-Z] means that we fallback
  129734. ** to the copy stemmer */
  129735. copy_stemmer(zIn, nIn, zOut, pnOut);
  129736. return;
  129737. }
  129738. }
  129739. memset(&zReverse[sizeof(zReverse)-5], 0, 5);
  129740. z = &zReverse[j+1];
  129741. /* Step 1a */
  129742. if( z[0]=='s' ){
  129743. if(
  129744. !stem(&z, "sess", "ss", 0) &&
  129745. !stem(&z, "sei", "i", 0) &&
  129746. !stem(&z, "ss", "ss", 0)
  129747. ){
  129748. z++;
  129749. }
  129750. }
  129751. /* Step 1b */
  129752. z2 = z;
  129753. if( stem(&z, "dee", "ee", m_gt_0) ){
  129754. /* Do nothing. The work was all in the test */
  129755. }else if(
  129756. (stem(&z, "gni", "", hasVowel) || stem(&z, "de", "", hasVowel))
  129757. && z!=z2
  129758. ){
  129759. if( stem(&z, "ta", "ate", 0) ||
  129760. stem(&z, "lb", "ble", 0) ||
  129761. stem(&z, "zi", "ize", 0) ){
  129762. /* Do nothing. The work was all in the test */
  129763. }else if( doubleConsonant(z) && (*z!='l' && *z!='s' && *z!='z') ){
  129764. z++;
  129765. }else if( m_eq_1(z) && star_oh(z) ){
  129766. *(--z) = 'e';
  129767. }
  129768. }
  129769. /* Step 1c */
  129770. if( z[0]=='y' && hasVowel(z+1) ){
  129771. z[0] = 'i';
  129772. }
  129773. /* Step 2 */
  129774. switch( z[1] ){
  129775. case 'a':
  129776. if( !stem(&z, "lanoita", "ate", m_gt_0) ){
  129777. stem(&z, "lanoit", "tion", m_gt_0);
  129778. }
  129779. break;
  129780. case 'c':
  129781. if( !stem(&z, "icne", "ence", m_gt_0) ){
  129782. stem(&z, "icna", "ance", m_gt_0);
  129783. }
  129784. break;
  129785. case 'e':
  129786. stem(&z, "rezi", "ize", m_gt_0);
  129787. break;
  129788. case 'g':
  129789. stem(&z, "igol", "log", m_gt_0);
  129790. break;
  129791. case 'l':
  129792. if( !stem(&z, "ilb", "ble", m_gt_0)
  129793. && !stem(&z, "illa", "al", m_gt_0)
  129794. && !stem(&z, "iltne", "ent", m_gt_0)
  129795. && !stem(&z, "ile", "e", m_gt_0)
  129796. ){
  129797. stem(&z, "ilsuo", "ous", m_gt_0);
  129798. }
  129799. break;
  129800. case 'o':
  129801. if( !stem(&z, "noitazi", "ize", m_gt_0)
  129802. && !stem(&z, "noita", "ate", m_gt_0)
  129803. ){
  129804. stem(&z, "rota", "ate", m_gt_0);
  129805. }
  129806. break;
  129807. case 's':
  129808. if( !stem(&z, "msila", "al", m_gt_0)
  129809. && !stem(&z, "ssenevi", "ive", m_gt_0)
  129810. && !stem(&z, "ssenluf", "ful", m_gt_0)
  129811. ){
  129812. stem(&z, "ssensuo", "ous", m_gt_0);
  129813. }
  129814. break;
  129815. case 't':
  129816. if( !stem(&z, "itila", "al", m_gt_0)
  129817. && !stem(&z, "itivi", "ive", m_gt_0)
  129818. ){
  129819. stem(&z, "itilib", "ble", m_gt_0);
  129820. }
  129821. break;
  129822. }
  129823. /* Step 3 */
  129824. switch( z[0] ){
  129825. case 'e':
  129826. if( !stem(&z, "etaci", "ic", m_gt_0)
  129827. && !stem(&z, "evita", "", m_gt_0)
  129828. ){
  129829. stem(&z, "ezila", "al", m_gt_0);
  129830. }
  129831. break;
  129832. case 'i':
  129833. stem(&z, "itici", "ic", m_gt_0);
  129834. break;
  129835. case 'l':
  129836. if( !stem(&z, "laci", "ic", m_gt_0) ){
  129837. stem(&z, "luf", "", m_gt_0);
  129838. }
  129839. break;
  129840. case 's':
  129841. stem(&z, "ssen", "", m_gt_0);
  129842. break;
  129843. }
  129844. /* Step 4 */
  129845. switch( z[1] ){
  129846. case 'a':
  129847. if( z[0]=='l' && m_gt_1(z+2) ){
  129848. z += 2;
  129849. }
  129850. break;
  129851. case 'c':
  129852. if( z[0]=='e' && z[2]=='n' && (z[3]=='a' || z[3]=='e') && m_gt_1(z+4) ){
  129853. z += 4;
  129854. }
  129855. break;
  129856. case 'e':
  129857. if( z[0]=='r' && m_gt_1(z+2) ){
  129858. z += 2;
  129859. }
  129860. break;
  129861. case 'i':
  129862. if( z[0]=='c' && m_gt_1(z+2) ){
  129863. z += 2;
  129864. }
  129865. break;
  129866. case 'l':
  129867. if( z[0]=='e' && z[2]=='b' && (z[3]=='a' || z[3]=='i') && m_gt_1(z+4) ){
  129868. z += 4;
  129869. }
  129870. break;
  129871. case 'n':
  129872. if( z[0]=='t' ){
  129873. if( z[2]=='a' ){
  129874. if( m_gt_1(z+3) ){
  129875. z += 3;
  129876. }
  129877. }else if( z[2]=='e' ){
  129878. if( !stem(&z, "tneme", "", m_gt_1)
  129879. && !stem(&z, "tnem", "", m_gt_1)
  129880. ){
  129881. stem(&z, "tne", "", m_gt_1);
  129882. }
  129883. }
  129884. }
  129885. break;
  129886. case 'o':
  129887. if( z[0]=='u' ){
  129888. if( m_gt_1(z+2) ){
  129889. z += 2;
  129890. }
  129891. }else if( z[3]=='s' || z[3]=='t' ){
  129892. stem(&z, "noi", "", m_gt_1);
  129893. }
  129894. break;
  129895. case 's':
  129896. if( z[0]=='m' && z[2]=='i' && m_gt_1(z+3) ){
  129897. z += 3;
  129898. }
  129899. break;
  129900. case 't':
  129901. if( !stem(&z, "eta", "", m_gt_1) ){
  129902. stem(&z, "iti", "", m_gt_1);
  129903. }
  129904. break;
  129905. case 'u':
  129906. if( z[0]=='s' && z[2]=='o' && m_gt_1(z+3) ){
  129907. z += 3;
  129908. }
  129909. break;
  129910. case 'v':
  129911. case 'z':
  129912. if( z[0]=='e' && z[2]=='i' && m_gt_1(z+3) ){
  129913. z += 3;
  129914. }
  129915. break;
  129916. }
  129917. /* Step 5a */
  129918. if( z[0]=='e' ){
  129919. if( m_gt_1(z+1) ){
  129920. z++;
  129921. }else if( m_eq_1(z+1) && !star_oh(z+1) ){
  129922. z++;
  129923. }
  129924. }
  129925. /* Step 5b */
  129926. if( m_gt_1(z) && z[0]=='l' && z[1]=='l' ){
  129927. z++;
  129928. }
  129929. /* z[] is now the stemmed word in reverse order. Flip it back
  129930. ** around into forward order and return.
  129931. */
  129932. *pnOut = i = (int)strlen(z);
  129933. zOut[i] = 0;
  129934. while( *z ){
  129935. zOut[--i] = *(z++);
  129936. }
  129937. }
  129938. /*
  129939. ** Characters that can be part of a token. We assume any character
  129940. ** whose value is greater than 0x80 (any UTF character) can be
  129941. ** part of a token. In other words, delimiters all must have
  129942. ** values of 0x7f or lower.
  129943. */
  129944. static const char porterIdChar[] = {
  129945. /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
  129946. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 3x */
  129947. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 4x */
  129948. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, /* 5x */
  129949. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 6x */
  129950. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, /* 7x */
  129951. };
  129952. #define isDelim(C) (((ch=C)&0x80)==0 && (ch<0x30 || !porterIdChar[ch-0x30]))
  129953. /*
  129954. ** Extract the next token from a tokenization cursor. The cursor must
  129955. ** have been opened by a prior call to porterOpen().
  129956. */
  129957. static int porterNext(
  129958. sqlite3_tokenizer_cursor *pCursor, /* Cursor returned by porterOpen */
  129959. const char **pzToken, /* OUT: *pzToken is the token text */
  129960. int *pnBytes, /* OUT: Number of bytes in token */
  129961. int *piStartOffset, /* OUT: Starting offset of token */
  129962. int *piEndOffset, /* OUT: Ending offset of token */
  129963. int *piPosition /* OUT: Position integer of token */
  129964. ){
  129965. porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
  129966. const char *z = c->zInput;
  129967. while( c->iOffset<c->nInput ){
  129968. int iStartOffset, ch;
  129969. /* Scan past delimiter characters */
  129970. while( c->iOffset<c->nInput && isDelim(z[c->iOffset]) ){
  129971. c->iOffset++;
  129972. }
  129973. /* Count non-delimiter characters. */
  129974. iStartOffset = c->iOffset;
  129975. while( c->iOffset<c->nInput && !isDelim(z[c->iOffset]) ){
  129976. c->iOffset++;
  129977. }
  129978. if( c->iOffset>iStartOffset ){
  129979. int n = c->iOffset-iStartOffset;
  129980. if( n>c->nAllocated ){
  129981. char *pNew;
  129982. c->nAllocated = n+20;
  129983. pNew = sqlite3_realloc(c->zToken, c->nAllocated);
  129984. if( !pNew ) return SQLITE_NOMEM;
  129985. c->zToken = pNew;
  129986. }
  129987. porter_stemmer(&z[iStartOffset], n, c->zToken, pnBytes);
  129988. *pzToken = c->zToken;
  129989. *piStartOffset = iStartOffset;
  129990. *piEndOffset = c->iOffset;
  129991. *piPosition = c->iToken++;
  129992. return SQLITE_OK;
  129993. }
  129994. }
  129995. return SQLITE_DONE;
  129996. }
  129997. /*
  129998. ** The set of routines that implement the porter-stemmer tokenizer
  129999. */
  130000. static const sqlite3_tokenizer_module porterTokenizerModule = {
  130001. 0,
  130002. porterCreate,
  130003. porterDestroy,
  130004. porterOpen,
  130005. porterClose,
  130006. porterNext,
  130007. 0
  130008. };
  130009. /*
  130010. ** Allocate a new porter tokenizer. Return a pointer to the new
  130011. ** tokenizer in *ppModule
  130012. */
  130013. SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(
  130014. sqlite3_tokenizer_module const**ppModule
  130015. ){
  130016. *ppModule = &porterTokenizerModule;
  130017. }
  130018. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  130019. /************** End of fts3_porter.c *****************************************/
  130020. /************** Begin file fts3_tokenizer.c **********************************/
  130021. /*
  130022. ** 2007 June 22
  130023. **
  130024. ** The author disclaims copyright to this source code. In place of
  130025. ** a legal notice, here is a blessing:
  130026. **
  130027. ** May you do good and not evil.
  130028. ** May you find forgiveness for yourself and forgive others.
  130029. ** May you share freely, never taking more than you give.
  130030. **
  130031. ******************************************************************************
  130032. **
  130033. ** This is part of an SQLite module implementing full-text search.
  130034. ** This particular file implements the generic tokenizer interface.
  130035. */
  130036. /*
  130037. ** The code in this file is only compiled if:
  130038. **
  130039. ** * The FTS3 module is being built as an extension
  130040. ** (in which case SQLITE_CORE is not defined), or
  130041. **
  130042. ** * The FTS3 module is being built into the core of
  130043. ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
  130044. */
  130045. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  130046. /* #include <assert.h> */
  130047. /* #include <string.h> */
  130048. /*
  130049. ** Implementation of the SQL scalar function for accessing the underlying
  130050. ** hash table. This function may be called as follows:
  130051. **
  130052. ** SELECT <function-name>(<key-name>);
  130053. ** SELECT <function-name>(<key-name>, <pointer>);
  130054. **
  130055. ** where <function-name> is the name passed as the second argument
  130056. ** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer').
  130057. **
  130058. ** If the <pointer> argument is specified, it must be a blob value
  130059. ** containing a pointer to be stored as the hash data corresponding
  130060. ** to the string <key-name>. If <pointer> is not specified, then
  130061. ** the string <key-name> must already exist in the has table. Otherwise,
  130062. ** an error is returned.
  130063. **
  130064. ** Whether or not the <pointer> argument is specified, the value returned
  130065. ** is a blob containing the pointer stored as the hash data corresponding
  130066. ** to string <key-name> (after the hash-table is updated, if applicable).
  130067. */
  130068. static void scalarFunc(
  130069. sqlite3_context *context,
  130070. int argc,
  130071. sqlite3_value **argv
  130072. ){
  130073. Fts3Hash *pHash;
  130074. void *pPtr = 0;
  130075. const unsigned char *zName;
  130076. int nName;
  130077. assert( argc==1 || argc==2 );
  130078. pHash = (Fts3Hash *)sqlite3_user_data(context);
  130079. zName = sqlite3_value_text(argv[0]);
  130080. nName = sqlite3_value_bytes(argv[0])+1;
  130081. if( argc==2 ){
  130082. void *pOld;
  130083. int n = sqlite3_value_bytes(argv[1]);
  130084. if( n!=sizeof(pPtr) ){
  130085. sqlite3_result_error(context, "argument type mismatch", -1);
  130086. return;
  130087. }
  130088. pPtr = *(void **)sqlite3_value_blob(argv[1]);
  130089. pOld = sqlite3Fts3HashInsert(pHash, (void *)zName, nName, pPtr);
  130090. if( pOld==pPtr ){
  130091. sqlite3_result_error(context, "out of memory", -1);
  130092. return;
  130093. }
  130094. }else{
  130095. pPtr = sqlite3Fts3HashFind(pHash, zName, nName);
  130096. if( !pPtr ){
  130097. char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
  130098. sqlite3_result_error(context, zErr, -1);
  130099. sqlite3_free(zErr);
  130100. return;
  130101. }
  130102. }
  130103. sqlite3_result_blob(context, (void *)&pPtr, sizeof(pPtr), SQLITE_TRANSIENT);
  130104. }
  130105. SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char c){
  130106. static const char isFtsIdChar[] = {
  130107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x */
  130108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 1x */
  130109. 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 2x */
  130110. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 3x */
  130111. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 4x */
  130112. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, /* 5x */
  130113. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 6x */
  130114. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, /* 7x */
  130115. };
  130116. return (c&0x80 || isFtsIdChar[(int)(c)]);
  130117. }
  130118. SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *zStr, int *pn){
  130119. const char *z1;
  130120. const char *z2 = 0;
  130121. /* Find the start of the next token. */
  130122. z1 = zStr;
  130123. while( z2==0 ){
  130124. char c = *z1;
  130125. switch( c ){
  130126. case '\0': return 0; /* No more tokens here */
  130127. case '\'':
  130128. case '"':
  130129. case '`': {
  130130. z2 = z1;
  130131. while( *++z2 && (*z2!=c || *++z2==c) );
  130132. break;
  130133. }
  130134. case '[':
  130135. z2 = &z1[1];
  130136. while( *z2 && z2[0]!=']' ) z2++;
  130137. if( *z2 ) z2++;
  130138. break;
  130139. default:
  130140. if( sqlite3Fts3IsIdChar(*z1) ){
  130141. z2 = &z1[1];
  130142. while( sqlite3Fts3IsIdChar(*z2) ) z2++;
  130143. }else{
  130144. z1++;
  130145. }
  130146. }
  130147. }
  130148. *pn = (int)(z2-z1);
  130149. return z1;
  130150. }
  130151. SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(
  130152. Fts3Hash *pHash, /* Tokenizer hash table */
  130153. const char *zArg, /* Tokenizer name */
  130154. sqlite3_tokenizer **ppTok, /* OUT: Tokenizer (if applicable) */
  130155. char **pzErr /* OUT: Set to malloced error message */
  130156. ){
  130157. int rc;
  130158. char *z = (char *)zArg;
  130159. int n = 0;
  130160. char *zCopy;
  130161. char *zEnd; /* Pointer to nul-term of zCopy */
  130162. sqlite3_tokenizer_module *m;
  130163. zCopy = sqlite3_mprintf("%s", zArg);
  130164. if( !zCopy ) return SQLITE_NOMEM;
  130165. zEnd = &zCopy[strlen(zCopy)];
  130166. z = (char *)sqlite3Fts3NextToken(zCopy, &n);
  130167. z[n] = '\0';
  130168. sqlite3Fts3Dequote(z);
  130169. m = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash,z,(int)strlen(z)+1);
  130170. if( !m ){
  130171. *pzErr = sqlite3_mprintf("unknown tokenizer: %s", z);
  130172. rc = SQLITE_ERROR;
  130173. }else{
  130174. char const **aArg = 0;
  130175. int iArg = 0;
  130176. z = &z[n+1];
  130177. while( z<zEnd && (NULL!=(z = (char *)sqlite3Fts3NextToken(z, &n))) ){
  130178. int nNew = sizeof(char *)*(iArg+1);
  130179. char const **aNew = (const char **)sqlite3_realloc((void *)aArg, nNew);
  130180. if( !aNew ){
  130181. sqlite3_free(zCopy);
  130182. sqlite3_free((void *)aArg);
  130183. return SQLITE_NOMEM;
  130184. }
  130185. aArg = aNew;
  130186. aArg[iArg++] = z;
  130187. z[n] = '\0';
  130188. sqlite3Fts3Dequote(z);
  130189. z = &z[n+1];
  130190. }
  130191. rc = m->xCreate(iArg, aArg, ppTok);
  130192. assert( rc!=SQLITE_OK || *ppTok );
  130193. if( rc!=SQLITE_OK ){
  130194. *pzErr = sqlite3_mprintf("unknown tokenizer");
  130195. }else{
  130196. (*ppTok)->pModule = m;
  130197. }
  130198. sqlite3_free((void *)aArg);
  130199. }
  130200. sqlite3_free(zCopy);
  130201. return rc;
  130202. }
  130203. #ifdef SQLITE_TEST
  130204. #include <tcl.h>
  130205. /* #include <string.h> */
  130206. /*
  130207. ** Implementation of a special SQL scalar function for testing tokenizers
  130208. ** designed to be used in concert with the Tcl testing framework. This
  130209. ** function must be called with two or more arguments:
  130210. **
  130211. ** SELECT <function-name>(<key-name>, ..., <input-string>);
  130212. **
  130213. ** where <function-name> is the name passed as the second argument
  130214. ** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer')
  130215. ** concatenated with the string '_test' (e.g. 'fts3_tokenizer_test').
  130216. **
  130217. ** The return value is a string that may be interpreted as a Tcl
  130218. ** list. For each token in the <input-string>, three elements are
  130219. ** added to the returned list. The first is the token position, the
  130220. ** second is the token text (folded, stemmed, etc.) and the third is the
  130221. ** substring of <input-string> associated with the token. For example,
  130222. ** using the built-in "simple" tokenizer:
  130223. **
  130224. ** SELECT fts_tokenizer_test('simple', 'I don't see how');
  130225. **
  130226. ** will return the string:
  130227. **
  130228. ** "{0 i I 1 dont don't 2 see see 3 how how}"
  130229. **
  130230. */
  130231. static void testFunc(
  130232. sqlite3_context *context,
  130233. int argc,
  130234. sqlite3_value **argv
  130235. ){
  130236. Fts3Hash *pHash;
  130237. sqlite3_tokenizer_module *p;
  130238. sqlite3_tokenizer *pTokenizer = 0;
  130239. sqlite3_tokenizer_cursor *pCsr = 0;
  130240. const char *zErr = 0;
  130241. const char *zName;
  130242. int nName;
  130243. const char *zInput;
  130244. int nInput;
  130245. const char *azArg[64];
  130246. const char *zToken;
  130247. int nToken = 0;
  130248. int iStart = 0;
  130249. int iEnd = 0;
  130250. int iPos = 0;
  130251. int i;
  130252. Tcl_Obj *pRet;
  130253. if( argc<2 ){
  130254. sqlite3_result_error(context, "insufficient arguments", -1);
  130255. return;
  130256. }
  130257. nName = sqlite3_value_bytes(argv[0]);
  130258. zName = (const char *)sqlite3_value_text(argv[0]);
  130259. nInput = sqlite3_value_bytes(argv[argc-1]);
  130260. zInput = (const char *)sqlite3_value_text(argv[argc-1]);
  130261. pHash = (Fts3Hash *)sqlite3_user_data(context);
  130262. p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1);
  130263. if( !p ){
  130264. char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
  130265. sqlite3_result_error(context, zErr, -1);
  130266. sqlite3_free(zErr);
  130267. return;
  130268. }
  130269. pRet = Tcl_NewObj();
  130270. Tcl_IncrRefCount(pRet);
  130271. for(i=1; i<argc-1; i++){
  130272. azArg[i-1] = (const char *)sqlite3_value_text(argv[i]);
  130273. }
  130274. if( SQLITE_OK!=p->xCreate(argc-2, azArg, &pTokenizer) ){
  130275. zErr = "error in xCreate()";
  130276. goto finish;
  130277. }
  130278. pTokenizer->pModule = p;
  130279. if( sqlite3Fts3OpenTokenizer(pTokenizer, 0, zInput, nInput, &pCsr) ){
  130280. zErr = "error in xOpen()";
  130281. goto finish;
  130282. }
  130283. while( SQLITE_OK==p->xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos) ){
  130284. Tcl_ListObjAppendElement(0, pRet, Tcl_NewIntObj(iPos));
  130285. Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
  130286. zToken = &zInput[iStart];
  130287. nToken = iEnd-iStart;
  130288. Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
  130289. }
  130290. if( SQLITE_OK!=p->xClose(pCsr) ){
  130291. zErr = "error in xClose()";
  130292. goto finish;
  130293. }
  130294. if( SQLITE_OK!=p->xDestroy(pTokenizer) ){
  130295. zErr = "error in xDestroy()";
  130296. goto finish;
  130297. }
  130298. finish:
  130299. if( zErr ){
  130300. sqlite3_result_error(context, zErr, -1);
  130301. }else{
  130302. sqlite3_result_text(context, Tcl_GetString(pRet), -1, SQLITE_TRANSIENT);
  130303. }
  130304. Tcl_DecrRefCount(pRet);
  130305. }
  130306. static
  130307. int registerTokenizer(
  130308. sqlite3 *db,
  130309. char *zName,
  130310. const sqlite3_tokenizer_module *p
  130311. ){
  130312. int rc;
  130313. sqlite3_stmt *pStmt;
  130314. const char zSql[] = "SELECT fts3_tokenizer(?, ?)";
  130315. rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
  130316. if( rc!=SQLITE_OK ){
  130317. return rc;
  130318. }
  130319. sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
  130320. sqlite3_bind_blob(pStmt, 2, &p, sizeof(p), SQLITE_STATIC);
  130321. sqlite3_step(pStmt);
  130322. return sqlite3_finalize(pStmt);
  130323. }
  130324. static
  130325. int queryTokenizer(
  130326. sqlite3 *db,
  130327. char *zName,
  130328. const sqlite3_tokenizer_module **pp
  130329. ){
  130330. int rc;
  130331. sqlite3_stmt *pStmt;
  130332. const char zSql[] = "SELECT fts3_tokenizer(?)";
  130333. *pp = 0;
  130334. rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
  130335. if( rc!=SQLITE_OK ){
  130336. return rc;
  130337. }
  130338. sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
  130339. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  130340. if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
  130341. memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
  130342. }
  130343. }
  130344. return sqlite3_finalize(pStmt);
  130345. }
  130346. SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
  130347. /*
  130348. ** Implementation of the scalar function fts3_tokenizer_internal_test().
  130349. ** This function is used for testing only, it is not included in the
  130350. ** build unless SQLITE_TEST is defined.
  130351. **
  130352. ** The purpose of this is to test that the fts3_tokenizer() function
  130353. ** can be used as designed by the C-code in the queryTokenizer and
  130354. ** registerTokenizer() functions above. These two functions are repeated
  130355. ** in the README.tokenizer file as an example, so it is important to
  130356. ** test them.
  130357. **
  130358. ** To run the tests, evaluate the fts3_tokenizer_internal_test() scalar
  130359. ** function with no arguments. An assert() will fail if a problem is
  130360. ** detected. i.e.:
  130361. **
  130362. ** SELECT fts3_tokenizer_internal_test();
  130363. **
  130364. */
  130365. static void intTestFunc(
  130366. sqlite3_context *context,
  130367. int argc,
  130368. sqlite3_value **argv
  130369. ){
  130370. int rc;
  130371. const sqlite3_tokenizer_module *p1;
  130372. const sqlite3_tokenizer_module *p2;
  130373. sqlite3 *db = (sqlite3 *)sqlite3_user_data(context);
  130374. UNUSED_PARAMETER(argc);
  130375. UNUSED_PARAMETER(argv);
  130376. /* Test the query function */
  130377. sqlite3Fts3SimpleTokenizerModule(&p1);
  130378. rc = queryTokenizer(db, "simple", &p2);
  130379. assert( rc==SQLITE_OK );
  130380. assert( p1==p2 );
  130381. rc = queryTokenizer(db, "nosuchtokenizer", &p2);
  130382. assert( rc==SQLITE_ERROR );
  130383. assert( p2==0 );
  130384. assert( 0==strcmp(sqlite3_errmsg(db), "unknown tokenizer: nosuchtokenizer") );
  130385. /* Test the storage function */
  130386. rc = registerTokenizer(db, "nosuchtokenizer", p1);
  130387. assert( rc==SQLITE_OK );
  130388. rc = queryTokenizer(db, "nosuchtokenizer", &p2);
  130389. assert( rc==SQLITE_OK );
  130390. assert( p2==p1 );
  130391. sqlite3_result_text(context, "ok", -1, SQLITE_STATIC);
  130392. }
  130393. #endif
  130394. /*
  130395. ** Set up SQL objects in database db used to access the contents of
  130396. ** the hash table pointed to by argument pHash. The hash table must
  130397. ** been initialized to use string keys, and to take a private copy
  130398. ** of the key when a value is inserted. i.e. by a call similar to:
  130399. **
  130400. ** sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
  130401. **
  130402. ** This function adds a scalar function (see header comment above
  130403. ** scalarFunc() in this file for details) and, if ENABLE_TABLE is
  130404. ** defined at compilation time, a temporary virtual table (see header
  130405. ** comment above struct HashTableVtab) to the database schema. Both
  130406. ** provide read/write access to the contents of *pHash.
  130407. **
  130408. ** The third argument to this function, zName, is used as the name
  130409. ** of both the scalar and, if created, the virtual table.
  130410. */
  130411. SQLITE_PRIVATE int sqlite3Fts3InitHashTable(
  130412. sqlite3 *db,
  130413. Fts3Hash *pHash,
  130414. const char *zName
  130415. ){
  130416. int rc = SQLITE_OK;
  130417. void *p = (void *)pHash;
  130418. const int any = SQLITE_ANY;
  130419. #ifdef SQLITE_TEST
  130420. char *zTest = 0;
  130421. char *zTest2 = 0;
  130422. void *pdb = (void *)db;
  130423. zTest = sqlite3_mprintf("%s_test", zName);
  130424. zTest2 = sqlite3_mprintf("%s_internal_test", zName);
  130425. if( !zTest || !zTest2 ){
  130426. rc = SQLITE_NOMEM;
  130427. }
  130428. #endif
  130429. if( SQLITE_OK==rc ){
  130430. rc = sqlite3_create_function(db, zName, 1, any, p, scalarFunc, 0, 0);
  130431. }
  130432. if( SQLITE_OK==rc ){
  130433. rc = sqlite3_create_function(db, zName, 2, any, p, scalarFunc, 0, 0);
  130434. }
  130435. #ifdef SQLITE_TEST
  130436. if( SQLITE_OK==rc ){
  130437. rc = sqlite3_create_function(db, zTest, -1, any, p, testFunc, 0, 0);
  130438. }
  130439. if( SQLITE_OK==rc ){
  130440. rc = sqlite3_create_function(db, zTest2, 0, any, pdb, intTestFunc, 0, 0);
  130441. }
  130442. #endif
  130443. #ifdef SQLITE_TEST
  130444. sqlite3_free(zTest);
  130445. sqlite3_free(zTest2);
  130446. #endif
  130447. return rc;
  130448. }
  130449. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  130450. /************** End of fts3_tokenizer.c **************************************/
  130451. /************** Begin file fts3_tokenizer1.c *********************************/
  130452. /*
  130453. ** 2006 Oct 10
  130454. **
  130455. ** The author disclaims copyright to this source code. In place of
  130456. ** a legal notice, here is a blessing:
  130457. **
  130458. ** May you do good and not evil.
  130459. ** May you find forgiveness for yourself and forgive others.
  130460. ** May you share freely, never taking more than you give.
  130461. **
  130462. ******************************************************************************
  130463. **
  130464. ** Implementation of the "simple" full-text-search tokenizer.
  130465. */
  130466. /*
  130467. ** The code in this file is only compiled if:
  130468. **
  130469. ** * The FTS3 module is being built as an extension
  130470. ** (in which case SQLITE_CORE is not defined), or
  130471. **
  130472. ** * The FTS3 module is being built into the core of
  130473. ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
  130474. */
  130475. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  130476. /* #include <assert.h> */
  130477. /* #include <stdlib.h> */
  130478. /* #include <stdio.h> */
  130479. /* #include <string.h> */
  130480. typedef struct simple_tokenizer {
  130481. sqlite3_tokenizer base;
  130482. char delim[128]; /* flag ASCII delimiters */
  130483. } simple_tokenizer;
  130484. typedef struct simple_tokenizer_cursor {
  130485. sqlite3_tokenizer_cursor base;
  130486. const char *pInput; /* input we are tokenizing */
  130487. int nBytes; /* size of the input */
  130488. int iOffset; /* current position in pInput */
  130489. int iToken; /* index of next token to be returned */
  130490. char *pToken; /* storage for current token */
  130491. int nTokenAllocated; /* space allocated to zToken buffer */
  130492. } simple_tokenizer_cursor;
  130493. static int simpleDelim(simple_tokenizer *t, unsigned char c){
  130494. return c<0x80 && t->delim[c];
  130495. }
  130496. static int fts3_isalnum(int x){
  130497. return (x>='0' && x<='9') || (x>='A' && x<='Z') || (x>='a' && x<='z');
  130498. }
  130499. /*
  130500. ** Create a new tokenizer instance.
  130501. */
  130502. static int simpleCreate(
  130503. int argc, const char * const *argv,
  130504. sqlite3_tokenizer **ppTokenizer
  130505. ){
  130506. simple_tokenizer *t;
  130507. t = (simple_tokenizer *) sqlite3_malloc(sizeof(*t));
  130508. if( t==NULL ) return SQLITE_NOMEM;
  130509. memset(t, 0, sizeof(*t));
  130510. /* TODO(shess) Delimiters need to remain the same from run to run,
  130511. ** else we need to reindex. One solution would be a meta-table to
  130512. ** track such information in the database, then we'd only want this
  130513. ** information on the initial create.
  130514. */
  130515. if( argc>1 ){
  130516. int i, n = (int)strlen(argv[1]);
  130517. for(i=0; i<n; i++){
  130518. unsigned char ch = argv[1][i];
  130519. /* We explicitly don't support UTF-8 delimiters for now. */
  130520. if( ch>=0x80 ){
  130521. sqlite3_free(t);
  130522. return SQLITE_ERROR;
  130523. }
  130524. t->delim[ch] = 1;
  130525. }
  130526. } else {
  130527. /* Mark non-alphanumeric ASCII characters as delimiters */
  130528. int i;
  130529. for(i=1; i<0x80; i++){
  130530. t->delim[i] = !fts3_isalnum(i) ? -1 : 0;
  130531. }
  130532. }
  130533. *ppTokenizer = &t->base;
  130534. return SQLITE_OK;
  130535. }
  130536. /*
  130537. ** Destroy a tokenizer
  130538. */
  130539. static int simpleDestroy(sqlite3_tokenizer *pTokenizer){
  130540. sqlite3_free(pTokenizer);
  130541. return SQLITE_OK;
  130542. }
  130543. /*
  130544. ** Prepare to begin tokenizing a particular string. The input
  130545. ** string to be tokenized is pInput[0..nBytes-1]. A cursor
  130546. ** used to incrementally tokenize this string is returned in
  130547. ** *ppCursor.
  130548. */
  130549. static int simpleOpen(
  130550. sqlite3_tokenizer *pTokenizer, /* The tokenizer */
  130551. const char *pInput, int nBytes, /* String to be tokenized */
  130552. sqlite3_tokenizer_cursor **ppCursor /* OUT: Tokenization cursor */
  130553. ){
  130554. simple_tokenizer_cursor *c;
  130555. UNUSED_PARAMETER(pTokenizer);
  130556. c = (simple_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
  130557. if( c==NULL ) return SQLITE_NOMEM;
  130558. c->pInput = pInput;
  130559. if( pInput==0 ){
  130560. c->nBytes = 0;
  130561. }else if( nBytes<0 ){
  130562. c->nBytes = (int)strlen(pInput);
  130563. }else{
  130564. c->nBytes = nBytes;
  130565. }
  130566. c->iOffset = 0; /* start tokenizing at the beginning */
  130567. c->iToken = 0;
  130568. c->pToken = NULL; /* no space allocated, yet. */
  130569. c->nTokenAllocated = 0;
  130570. *ppCursor = &c->base;
  130571. return SQLITE_OK;
  130572. }
  130573. /*
  130574. ** Close a tokenization cursor previously opened by a call to
  130575. ** simpleOpen() above.
  130576. */
  130577. static int simpleClose(sqlite3_tokenizer_cursor *pCursor){
  130578. simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
  130579. sqlite3_free(c->pToken);
  130580. sqlite3_free(c);
  130581. return SQLITE_OK;
  130582. }
  130583. /*
  130584. ** Extract the next token from a tokenization cursor. The cursor must
  130585. ** have been opened by a prior call to simpleOpen().
  130586. */
  130587. static int simpleNext(
  130588. sqlite3_tokenizer_cursor *pCursor, /* Cursor returned by simpleOpen */
  130589. const char **ppToken, /* OUT: *ppToken is the token text */
  130590. int *pnBytes, /* OUT: Number of bytes in token */
  130591. int *piStartOffset, /* OUT: Starting offset of token */
  130592. int *piEndOffset, /* OUT: Ending offset of token */
  130593. int *piPosition /* OUT: Position integer of token */
  130594. ){
  130595. simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
  130596. simple_tokenizer *t = (simple_tokenizer *) pCursor->pTokenizer;
  130597. unsigned char *p = (unsigned char *)c->pInput;
  130598. while( c->iOffset<c->nBytes ){
  130599. int iStartOffset;
  130600. /* Scan past delimiter characters */
  130601. while( c->iOffset<c->nBytes && simpleDelim(t, p[c->iOffset]) ){
  130602. c->iOffset++;
  130603. }
  130604. /* Count non-delimiter characters. */
  130605. iStartOffset = c->iOffset;
  130606. while( c->iOffset<c->nBytes && !simpleDelim(t, p[c->iOffset]) ){
  130607. c->iOffset++;
  130608. }
  130609. if( c->iOffset>iStartOffset ){
  130610. int i, n = c->iOffset-iStartOffset;
  130611. if( n>c->nTokenAllocated ){
  130612. char *pNew;
  130613. c->nTokenAllocated = n+20;
  130614. pNew = sqlite3_realloc(c->pToken, c->nTokenAllocated);
  130615. if( !pNew ) return SQLITE_NOMEM;
  130616. c->pToken = pNew;
  130617. }
  130618. for(i=0; i<n; i++){
  130619. /* TODO(shess) This needs expansion to handle UTF-8
  130620. ** case-insensitivity.
  130621. */
  130622. unsigned char ch = p[iStartOffset+i];
  130623. c->pToken[i] = (char)((ch>='A' && ch<='Z') ? ch-'A'+'a' : ch);
  130624. }
  130625. *ppToken = c->pToken;
  130626. *pnBytes = n;
  130627. *piStartOffset = iStartOffset;
  130628. *piEndOffset = c->iOffset;
  130629. *piPosition = c->iToken++;
  130630. return SQLITE_OK;
  130631. }
  130632. }
  130633. return SQLITE_DONE;
  130634. }
  130635. /*
  130636. ** The set of routines that implement the simple tokenizer
  130637. */
  130638. static const sqlite3_tokenizer_module simpleTokenizerModule = {
  130639. 0,
  130640. simpleCreate,
  130641. simpleDestroy,
  130642. simpleOpen,
  130643. simpleClose,
  130644. simpleNext,
  130645. 0,
  130646. };
  130647. /*
  130648. ** Allocate a new simple tokenizer. Return a pointer to the new
  130649. ** tokenizer in *ppModule
  130650. */
  130651. SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(
  130652. sqlite3_tokenizer_module const**ppModule
  130653. ){
  130654. *ppModule = &simpleTokenizerModule;
  130655. }
  130656. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  130657. /************** End of fts3_tokenizer1.c *************************************/
  130658. /************** Begin file fts3_tokenize_vtab.c ******************************/
  130659. /*
  130660. ** 2013 Apr 22
  130661. **
  130662. ** The author disclaims copyright to this source code. In place of
  130663. ** a legal notice, here is a blessing:
  130664. **
  130665. ** May you do good and not evil.
  130666. ** May you find forgiveness for yourself and forgive others.
  130667. ** May you share freely, never taking more than you give.
  130668. **
  130669. ******************************************************************************
  130670. **
  130671. ** This file contains code for the "fts3tokenize" virtual table module.
  130672. ** An fts3tokenize virtual table is created as follows:
  130673. **
  130674. ** CREATE VIRTUAL TABLE <tbl> USING fts3tokenize(
  130675. ** <tokenizer-name>, <arg-1>, ...
  130676. ** );
  130677. **
  130678. ** The table created has the following schema:
  130679. **
  130680. ** CREATE TABLE <tbl>(input, token, start, end, position)
  130681. **
  130682. ** When queried, the query must include a WHERE clause of type:
  130683. **
  130684. ** input = <string>
  130685. **
  130686. ** The virtual table module tokenizes this <string>, using the FTS3
  130687. ** tokenizer specified by the arguments to the CREATE VIRTUAL TABLE
  130688. ** statement and returns one row for each token in the result. With
  130689. ** fields set as follows:
  130690. **
  130691. ** input: Always set to a copy of <string>
  130692. ** token: A token from the input.
  130693. ** start: Byte offset of the token within the input <string>.
  130694. ** end: Byte offset of the byte immediately following the end of the
  130695. ** token within the input string.
  130696. ** pos: Token offset of token within input.
  130697. **
  130698. */
  130699. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  130700. /* #include <string.h> */
  130701. /* #include <assert.h> */
  130702. typedef struct Fts3tokTable Fts3tokTable;
  130703. typedef struct Fts3tokCursor Fts3tokCursor;
  130704. /*
  130705. ** Virtual table structure.
  130706. */
  130707. struct Fts3tokTable {
  130708. sqlite3_vtab base; /* Base class used by SQLite core */
  130709. const sqlite3_tokenizer_module *pMod;
  130710. sqlite3_tokenizer *pTok;
  130711. };
  130712. /*
  130713. ** Virtual table cursor structure.
  130714. */
  130715. struct Fts3tokCursor {
  130716. sqlite3_vtab_cursor base; /* Base class used by SQLite core */
  130717. char *zInput; /* Input string */
  130718. sqlite3_tokenizer_cursor *pCsr; /* Cursor to iterate through zInput */
  130719. int iRowid; /* Current 'rowid' value */
  130720. const char *zToken; /* Current 'token' value */
  130721. int nToken; /* Size of zToken in bytes */
  130722. int iStart; /* Current 'start' value */
  130723. int iEnd; /* Current 'end' value */
  130724. int iPos; /* Current 'pos' value */
  130725. };
  130726. /*
  130727. ** Query FTS for the tokenizer implementation named zName.
  130728. */
  130729. static int fts3tokQueryTokenizer(
  130730. Fts3Hash *pHash,
  130731. const char *zName,
  130732. const sqlite3_tokenizer_module **pp,
  130733. char **pzErr
  130734. ){
  130735. sqlite3_tokenizer_module *p;
  130736. int nName = (int)strlen(zName);
  130737. p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1);
  130738. if( !p ){
  130739. *pzErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
  130740. return SQLITE_ERROR;
  130741. }
  130742. *pp = p;
  130743. return SQLITE_OK;
  130744. }
  130745. /*
  130746. ** The second argument, argv[], is an array of pointers to nul-terminated
  130747. ** strings. This function makes a copy of the array and strings into a
  130748. ** single block of memory. It then dequotes any of the strings that appear
  130749. ** to be quoted.
  130750. **
  130751. ** If successful, output parameter *pazDequote is set to point at the
  130752. ** array of dequoted strings and SQLITE_OK is returned. The caller is
  130753. ** responsible for eventually calling sqlite3_free() to free the array
  130754. ** in this case. Or, if an error occurs, an SQLite error code is returned.
  130755. ** The final value of *pazDequote is undefined in this case.
  130756. */
  130757. static int fts3tokDequoteArray(
  130758. int argc, /* Number of elements in argv[] */
  130759. const char * const *argv, /* Input array */
  130760. char ***pazDequote /* Output array */
  130761. ){
  130762. int rc = SQLITE_OK; /* Return code */
  130763. if( argc==0 ){
  130764. *pazDequote = 0;
  130765. }else{
  130766. int i;
  130767. int nByte = 0;
  130768. char **azDequote;
  130769. for(i=0; i<argc; i++){
  130770. nByte += (int)(strlen(argv[i]) + 1);
  130771. }
  130772. *pazDequote = azDequote = sqlite3_malloc(sizeof(char *)*argc + nByte);
  130773. if( azDequote==0 ){
  130774. rc = SQLITE_NOMEM;
  130775. }else{
  130776. char *pSpace = (char *)&azDequote[argc];
  130777. for(i=0; i<argc; i++){
  130778. int n = (int)strlen(argv[i]);
  130779. azDequote[i] = pSpace;
  130780. memcpy(pSpace, argv[i], n+1);
  130781. sqlite3Fts3Dequote(pSpace);
  130782. pSpace += (n+1);
  130783. }
  130784. }
  130785. }
  130786. return rc;
  130787. }
  130788. /*
  130789. ** Schema of the tokenizer table.
  130790. */
  130791. #define FTS3_TOK_SCHEMA "CREATE TABLE x(input, token, start, end, position)"
  130792. /*
  130793. ** This function does all the work for both the xConnect and xCreate methods.
  130794. ** These tables have no persistent representation of their own, so xConnect
  130795. ** and xCreate are identical operations.
  130796. **
  130797. ** argv[0]: module name
  130798. ** argv[1]: database name
  130799. ** argv[2]: table name
  130800. ** argv[3]: first argument (tokenizer name)
  130801. */
  130802. static int fts3tokConnectMethod(
  130803. sqlite3 *db, /* Database connection */
  130804. void *pHash, /* Hash table of tokenizers */
  130805. int argc, /* Number of elements in argv array */
  130806. const char * const *argv, /* xCreate/xConnect argument array */
  130807. sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
  130808. char **pzErr /* OUT: sqlite3_malloc'd error message */
  130809. ){
  130810. Fts3tokTable *pTab;
  130811. const sqlite3_tokenizer_module *pMod = 0;
  130812. sqlite3_tokenizer *pTok = 0;
  130813. int rc;
  130814. char **azDequote = 0;
  130815. int nDequote;
  130816. rc = sqlite3_declare_vtab(db, FTS3_TOK_SCHEMA);
  130817. if( rc!=SQLITE_OK ) return rc;
  130818. nDequote = argc-3;
  130819. rc = fts3tokDequoteArray(nDequote, &argv[3], &azDequote);
  130820. if( rc==SQLITE_OK ){
  130821. const char *zModule;
  130822. if( nDequote<1 ){
  130823. zModule = "simple";
  130824. }else{
  130825. zModule = azDequote[0];
  130826. }
  130827. rc = fts3tokQueryTokenizer((Fts3Hash*)pHash, zModule, &pMod, pzErr);
  130828. }
  130829. assert( (rc==SQLITE_OK)==(pMod!=0) );
  130830. if( rc==SQLITE_OK ){
  130831. const char * const *azArg = (const char * const *)&azDequote[1];
  130832. rc = pMod->xCreate((nDequote>1 ? nDequote-1 : 0), azArg, &pTok);
  130833. }
  130834. if( rc==SQLITE_OK ){
  130835. pTab = (Fts3tokTable *)sqlite3_malloc(sizeof(Fts3tokTable));
  130836. if( pTab==0 ){
  130837. rc = SQLITE_NOMEM;
  130838. }
  130839. }
  130840. if( rc==SQLITE_OK ){
  130841. memset(pTab, 0, sizeof(Fts3tokTable));
  130842. pTab->pMod = pMod;
  130843. pTab->pTok = pTok;
  130844. *ppVtab = &pTab->base;
  130845. }else{
  130846. if( pTok ){
  130847. pMod->xDestroy(pTok);
  130848. }
  130849. }
  130850. sqlite3_free(azDequote);
  130851. return rc;
  130852. }
  130853. /*
  130854. ** This function does the work for both the xDisconnect and xDestroy methods.
  130855. ** These tables have no persistent representation of their own, so xDisconnect
  130856. ** and xDestroy are identical operations.
  130857. */
  130858. static int fts3tokDisconnectMethod(sqlite3_vtab *pVtab){
  130859. Fts3tokTable *pTab = (Fts3tokTable *)pVtab;
  130860. pTab->pMod->xDestroy(pTab->pTok);
  130861. sqlite3_free(pTab);
  130862. return SQLITE_OK;
  130863. }
  130864. /*
  130865. ** xBestIndex - Analyze a WHERE and ORDER BY clause.
  130866. */
  130867. static int fts3tokBestIndexMethod(
  130868. sqlite3_vtab *pVTab,
  130869. sqlite3_index_info *pInfo
  130870. ){
  130871. int i;
  130872. UNUSED_PARAMETER(pVTab);
  130873. for(i=0; i<pInfo->nConstraint; i++){
  130874. if( pInfo->aConstraint[i].usable
  130875. && pInfo->aConstraint[i].iColumn==0
  130876. && pInfo->aConstraint[i].op==SQLITE_INDEX_CONSTRAINT_EQ
  130877. ){
  130878. pInfo->idxNum = 1;
  130879. pInfo->aConstraintUsage[i].argvIndex = 1;
  130880. pInfo->aConstraintUsage[i].omit = 1;
  130881. pInfo->estimatedCost = 1;
  130882. return SQLITE_OK;
  130883. }
  130884. }
  130885. pInfo->idxNum = 0;
  130886. assert( pInfo->estimatedCost>1000000.0 );
  130887. return SQLITE_OK;
  130888. }
  130889. /*
  130890. ** xOpen - Open a cursor.
  130891. */
  130892. static int fts3tokOpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
  130893. Fts3tokCursor *pCsr;
  130894. UNUSED_PARAMETER(pVTab);
  130895. pCsr = (Fts3tokCursor *)sqlite3_malloc(sizeof(Fts3tokCursor));
  130896. if( pCsr==0 ){
  130897. return SQLITE_NOMEM;
  130898. }
  130899. memset(pCsr, 0, sizeof(Fts3tokCursor));
  130900. *ppCsr = (sqlite3_vtab_cursor *)pCsr;
  130901. return SQLITE_OK;
  130902. }
  130903. /*
  130904. ** Reset the tokenizer cursor passed as the only argument. As if it had
  130905. ** just been returned by fts3tokOpenMethod().
  130906. */
  130907. static void fts3tokResetCursor(Fts3tokCursor *pCsr){
  130908. if( pCsr->pCsr ){
  130909. Fts3tokTable *pTab = (Fts3tokTable *)(pCsr->base.pVtab);
  130910. pTab->pMod->xClose(pCsr->pCsr);
  130911. pCsr->pCsr = 0;
  130912. }
  130913. sqlite3_free(pCsr->zInput);
  130914. pCsr->zInput = 0;
  130915. pCsr->zToken = 0;
  130916. pCsr->nToken = 0;
  130917. pCsr->iStart = 0;
  130918. pCsr->iEnd = 0;
  130919. pCsr->iPos = 0;
  130920. pCsr->iRowid = 0;
  130921. }
  130922. /*
  130923. ** xClose - Close a cursor.
  130924. */
  130925. static int fts3tokCloseMethod(sqlite3_vtab_cursor *pCursor){
  130926. Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
  130927. fts3tokResetCursor(pCsr);
  130928. sqlite3_free(pCsr);
  130929. return SQLITE_OK;
  130930. }
  130931. /*
  130932. ** xNext - Advance the cursor to the next row, if any.
  130933. */
  130934. static int fts3tokNextMethod(sqlite3_vtab_cursor *pCursor){
  130935. Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
  130936. Fts3tokTable *pTab = (Fts3tokTable *)(pCursor->pVtab);
  130937. int rc; /* Return code */
  130938. pCsr->iRowid++;
  130939. rc = pTab->pMod->xNext(pCsr->pCsr,
  130940. &pCsr->zToken, &pCsr->nToken,
  130941. &pCsr->iStart, &pCsr->iEnd, &pCsr->iPos
  130942. );
  130943. if( rc!=SQLITE_OK ){
  130944. fts3tokResetCursor(pCsr);
  130945. if( rc==SQLITE_DONE ) rc = SQLITE_OK;
  130946. }
  130947. return rc;
  130948. }
  130949. /*
  130950. ** xFilter - Initialize a cursor to point at the start of its data.
  130951. */
  130952. static int fts3tokFilterMethod(
  130953. sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */
  130954. int idxNum, /* Strategy index */
  130955. const char *idxStr, /* Unused */
  130956. int nVal, /* Number of elements in apVal */
  130957. sqlite3_value **apVal /* Arguments for the indexing scheme */
  130958. ){
  130959. int rc = SQLITE_ERROR;
  130960. Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
  130961. Fts3tokTable *pTab = (Fts3tokTable *)(pCursor->pVtab);
  130962. UNUSED_PARAMETER(idxStr);
  130963. UNUSED_PARAMETER(nVal);
  130964. fts3tokResetCursor(pCsr);
  130965. if( idxNum==1 ){
  130966. const char *zByte = (const char *)sqlite3_value_text(apVal[0]);
  130967. int nByte = sqlite3_value_bytes(apVal[0]);
  130968. pCsr->zInput = sqlite3_malloc(nByte+1);
  130969. if( pCsr->zInput==0 ){
  130970. rc = SQLITE_NOMEM;
  130971. }else{
  130972. memcpy(pCsr->zInput, zByte, nByte);
  130973. pCsr->zInput[nByte] = 0;
  130974. rc = pTab->pMod->xOpen(pTab->pTok, pCsr->zInput, nByte, &pCsr->pCsr);
  130975. if( rc==SQLITE_OK ){
  130976. pCsr->pCsr->pTokenizer = pTab->pTok;
  130977. }
  130978. }
  130979. }
  130980. if( rc!=SQLITE_OK ) return rc;
  130981. return fts3tokNextMethod(pCursor);
  130982. }
  130983. /*
  130984. ** xEof - Return true if the cursor is at EOF, or false otherwise.
  130985. */
  130986. static int fts3tokEofMethod(sqlite3_vtab_cursor *pCursor){
  130987. Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
  130988. return (pCsr->zToken==0);
  130989. }
  130990. /*
  130991. ** xColumn - Return a column value.
  130992. */
  130993. static int fts3tokColumnMethod(
  130994. sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
  130995. sqlite3_context *pCtx, /* Context for sqlite3_result_xxx() calls */
  130996. int iCol /* Index of column to read value from */
  130997. ){
  130998. Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
  130999. /* CREATE TABLE x(input, token, start, end, position) */
  131000. switch( iCol ){
  131001. case 0:
  131002. sqlite3_result_text(pCtx, pCsr->zInput, -1, SQLITE_TRANSIENT);
  131003. break;
  131004. case 1:
  131005. sqlite3_result_text(pCtx, pCsr->zToken, pCsr->nToken, SQLITE_TRANSIENT);
  131006. break;
  131007. case 2:
  131008. sqlite3_result_int(pCtx, pCsr->iStart);
  131009. break;
  131010. case 3:
  131011. sqlite3_result_int(pCtx, pCsr->iEnd);
  131012. break;
  131013. default:
  131014. assert( iCol==4 );
  131015. sqlite3_result_int(pCtx, pCsr->iPos);
  131016. break;
  131017. }
  131018. return SQLITE_OK;
  131019. }
  131020. /*
  131021. ** xRowid - Return the current rowid for the cursor.
  131022. */
  131023. static int fts3tokRowidMethod(
  131024. sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
  131025. sqlite_int64 *pRowid /* OUT: Rowid value */
  131026. ){
  131027. Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
  131028. *pRowid = (sqlite3_int64)pCsr->iRowid;
  131029. return SQLITE_OK;
  131030. }
  131031. /*
  131032. ** Register the fts3tok module with database connection db. Return SQLITE_OK
  131033. ** if successful or an error code if sqlite3_create_module() fails.
  131034. */
  131035. SQLITE_PRIVATE int sqlite3Fts3InitTok(sqlite3 *db, Fts3Hash *pHash){
  131036. static const sqlite3_module fts3tok_module = {
  131037. 0, /* iVersion */
  131038. fts3tokConnectMethod, /* xCreate */
  131039. fts3tokConnectMethod, /* xConnect */
  131040. fts3tokBestIndexMethod, /* xBestIndex */
  131041. fts3tokDisconnectMethod, /* xDisconnect */
  131042. fts3tokDisconnectMethod, /* xDestroy */
  131043. fts3tokOpenMethod, /* xOpen */
  131044. fts3tokCloseMethod, /* xClose */
  131045. fts3tokFilterMethod, /* xFilter */
  131046. fts3tokNextMethod, /* xNext */
  131047. fts3tokEofMethod, /* xEof */
  131048. fts3tokColumnMethod, /* xColumn */
  131049. fts3tokRowidMethod, /* xRowid */
  131050. 0, /* xUpdate */
  131051. 0, /* xBegin */
  131052. 0, /* xSync */
  131053. 0, /* xCommit */
  131054. 0, /* xRollback */
  131055. 0, /* xFindFunction */
  131056. 0, /* xRename */
  131057. 0, /* xSavepoint */
  131058. 0, /* xRelease */
  131059. 0 /* xRollbackTo */
  131060. };
  131061. int rc; /* Return code */
  131062. rc = sqlite3_create_module(db, "fts3tokenize", &fts3tok_module, (void*)pHash);
  131063. return rc;
  131064. }
  131065. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  131066. /************** End of fts3_tokenize_vtab.c **********************************/
  131067. /************** Begin file fts3_write.c **************************************/
  131068. /*
  131069. ** 2009 Oct 23
  131070. **
  131071. ** The author disclaims copyright to this source code. In place of
  131072. ** a legal notice, here is a blessing:
  131073. **
  131074. ** May you do good and not evil.
  131075. ** May you find forgiveness for yourself and forgive others.
  131076. ** May you share freely, never taking more than you give.
  131077. **
  131078. ******************************************************************************
  131079. **
  131080. ** This file is part of the SQLite FTS3 extension module. Specifically,
  131081. ** this file contains code to insert, update and delete rows from FTS3
  131082. ** tables. It also contains code to merge FTS3 b-tree segments. Some
  131083. ** of the sub-routines used to merge segments are also used by the query
  131084. ** code in fts3.c.
  131085. */
  131086. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  131087. /* #include <string.h> */
  131088. /* #include <assert.h> */
  131089. /* #include <stdlib.h> */
  131090. #define FTS_MAX_APPENDABLE_HEIGHT 16
  131091. /*
  131092. ** When full-text index nodes are loaded from disk, the buffer that they
  131093. ** are loaded into has the following number of bytes of padding at the end
  131094. ** of it. i.e. if a full-text index node is 900 bytes in size, then a buffer
  131095. ** of 920 bytes is allocated for it.
  131096. **
  131097. ** This means that if we have a pointer into a buffer containing node data,
  131098. ** it is always safe to read up to two varints from it without risking an
  131099. ** overread, even if the node data is corrupted.
  131100. */
  131101. #define FTS3_NODE_PADDING (FTS3_VARINT_MAX*2)
  131102. /*
  131103. ** Under certain circumstances, b-tree nodes (doclists) can be loaded into
  131104. ** memory incrementally instead of all at once. This can be a big performance
  131105. ** win (reduced IO and CPU) if SQLite stops calling the virtual table xNext()
  131106. ** method before retrieving all query results (as may happen, for example,
  131107. ** if a query has a LIMIT clause).
  131108. **
  131109. ** Incremental loading is used for b-tree nodes FTS3_NODE_CHUNK_THRESHOLD
  131110. ** bytes and larger. Nodes are loaded in chunks of FTS3_NODE_CHUNKSIZE bytes.
  131111. ** The code is written so that the hard lower-limit for each of these values
  131112. ** is 1. Clearly such small values would be inefficient, but can be useful
  131113. ** for testing purposes.
  131114. **
  131115. ** If this module is built with SQLITE_TEST defined, these constants may
  131116. ** be overridden at runtime for testing purposes. File fts3_test.c contains
  131117. ** a Tcl interface to read and write the values.
  131118. */
  131119. #ifdef SQLITE_TEST
  131120. int test_fts3_node_chunksize = (4*1024);
  131121. int test_fts3_node_chunk_threshold = (4*1024)*4;
  131122. # define FTS3_NODE_CHUNKSIZE test_fts3_node_chunksize
  131123. # define FTS3_NODE_CHUNK_THRESHOLD test_fts3_node_chunk_threshold
  131124. #else
  131125. # define FTS3_NODE_CHUNKSIZE (4*1024)
  131126. # define FTS3_NODE_CHUNK_THRESHOLD (FTS3_NODE_CHUNKSIZE*4)
  131127. #endif
  131128. /*
  131129. ** The two values that may be meaningfully bound to the :1 parameter in
  131130. ** statements SQL_REPLACE_STAT and SQL_SELECT_STAT.
  131131. */
  131132. #define FTS_STAT_DOCTOTAL 0
  131133. #define FTS_STAT_INCRMERGEHINT 1
  131134. #define FTS_STAT_AUTOINCRMERGE 2
  131135. /*
  131136. ** If FTS_LOG_MERGES is defined, call sqlite3_log() to report each automatic
  131137. ** and incremental merge operation that takes place. This is used for
  131138. ** debugging FTS only, it should not usually be turned on in production
  131139. ** systems.
  131140. */
  131141. #ifdef FTS3_LOG_MERGES
  131142. static void fts3LogMerge(int nMerge, sqlite3_int64 iAbsLevel){
  131143. sqlite3_log(SQLITE_OK, "%d-way merge from level %d", nMerge, (int)iAbsLevel);
  131144. }
  131145. #else
  131146. #define fts3LogMerge(x, y)
  131147. #endif
  131148. typedef struct PendingList PendingList;
  131149. typedef struct SegmentNode SegmentNode;
  131150. typedef struct SegmentWriter SegmentWriter;
  131151. /*
  131152. ** An instance of the following data structure is used to build doclists
  131153. ** incrementally. See function fts3PendingListAppend() for details.
  131154. */
  131155. struct PendingList {
  131156. int nData;
  131157. char *aData;
  131158. int nSpace;
  131159. sqlite3_int64 iLastDocid;
  131160. sqlite3_int64 iLastCol;
  131161. sqlite3_int64 iLastPos;
  131162. };
  131163. /*
  131164. ** Each cursor has a (possibly empty) linked list of the following objects.
  131165. */
  131166. struct Fts3DeferredToken {
  131167. Fts3PhraseToken *pToken; /* Pointer to corresponding expr token */
  131168. int iCol; /* Column token must occur in */
  131169. Fts3DeferredToken *pNext; /* Next in list of deferred tokens */
  131170. PendingList *pList; /* Doclist is assembled here */
  131171. };
  131172. /*
  131173. ** An instance of this structure is used to iterate through the terms on
  131174. ** a contiguous set of segment b-tree leaf nodes. Although the details of
  131175. ** this structure are only manipulated by code in this file, opaque handles
  131176. ** of type Fts3SegReader* are also used by code in fts3.c to iterate through
  131177. ** terms when querying the full-text index. See functions:
  131178. **
  131179. ** sqlite3Fts3SegReaderNew()
  131180. ** sqlite3Fts3SegReaderFree()
  131181. ** sqlite3Fts3SegReaderIterate()
  131182. **
  131183. ** Methods used to manipulate Fts3SegReader structures:
  131184. **
  131185. ** fts3SegReaderNext()
  131186. ** fts3SegReaderFirstDocid()
  131187. ** fts3SegReaderNextDocid()
  131188. */
  131189. struct Fts3SegReader {
  131190. int iIdx; /* Index within level, or 0x7FFFFFFF for PT */
  131191. u8 bLookup; /* True for a lookup only */
  131192. u8 rootOnly; /* True for a root-only reader */
  131193. sqlite3_int64 iStartBlock; /* Rowid of first leaf block to traverse */
  131194. sqlite3_int64 iLeafEndBlock; /* Rowid of final leaf block to traverse */
  131195. sqlite3_int64 iEndBlock; /* Rowid of final block in segment (or 0) */
  131196. sqlite3_int64 iCurrentBlock; /* Current leaf block (or 0) */
  131197. char *aNode; /* Pointer to node data (or NULL) */
  131198. int nNode; /* Size of buffer at aNode (or 0) */
  131199. int nPopulate; /* If >0, bytes of buffer aNode[] loaded */
  131200. sqlite3_blob *pBlob; /* If not NULL, blob handle to read node */
  131201. Fts3HashElem **ppNextElem;
  131202. /* Variables set by fts3SegReaderNext(). These may be read directly
  131203. ** by the caller. They are valid from the time SegmentReaderNew() returns
  131204. ** until SegmentReaderNext() returns something other than SQLITE_OK
  131205. ** (i.e. SQLITE_DONE).
  131206. */
  131207. int nTerm; /* Number of bytes in current term */
  131208. char *zTerm; /* Pointer to current term */
  131209. int nTermAlloc; /* Allocated size of zTerm buffer */
  131210. char *aDoclist; /* Pointer to doclist of current entry */
  131211. int nDoclist; /* Size of doclist in current entry */
  131212. /* The following variables are used by fts3SegReaderNextDocid() to iterate
  131213. ** through the current doclist (aDoclist/nDoclist).
  131214. */
  131215. char *pOffsetList;
  131216. int nOffsetList; /* For descending pending seg-readers only */
  131217. sqlite3_int64 iDocid;
  131218. };
  131219. #define fts3SegReaderIsPending(p) ((p)->ppNextElem!=0)
  131220. #define fts3SegReaderIsRootOnly(p) ((p)->rootOnly!=0)
  131221. /*
  131222. ** An instance of this structure is used to create a segment b-tree in the
  131223. ** database. The internal details of this type are only accessed by the
  131224. ** following functions:
  131225. **
  131226. ** fts3SegWriterAdd()
  131227. ** fts3SegWriterFlush()
  131228. ** fts3SegWriterFree()
  131229. */
  131230. struct SegmentWriter {
  131231. SegmentNode *pTree; /* Pointer to interior tree structure */
  131232. sqlite3_int64 iFirst; /* First slot in %_segments written */
  131233. sqlite3_int64 iFree; /* Next free slot in %_segments */
  131234. char *zTerm; /* Pointer to previous term buffer */
  131235. int nTerm; /* Number of bytes in zTerm */
  131236. int nMalloc; /* Size of malloc'd buffer at zMalloc */
  131237. char *zMalloc; /* Malloc'd space (possibly) used for zTerm */
  131238. int nSize; /* Size of allocation at aData */
  131239. int nData; /* Bytes of data in aData */
  131240. char *aData; /* Pointer to block from malloc() */
  131241. i64 nLeafData; /* Number of bytes of leaf data written */
  131242. };
  131243. /*
  131244. ** Type SegmentNode is used by the following three functions to create
  131245. ** the interior part of the segment b+-tree structures (everything except
  131246. ** the leaf nodes). These functions and type are only ever used by code
  131247. ** within the fts3SegWriterXXX() family of functions described above.
  131248. **
  131249. ** fts3NodeAddTerm()
  131250. ** fts3NodeWrite()
  131251. ** fts3NodeFree()
  131252. **
  131253. ** When a b+tree is written to the database (either as a result of a merge
  131254. ** or the pending-terms table being flushed), leaves are written into the
  131255. ** database file as soon as they are completely populated. The interior of
  131256. ** the tree is assembled in memory and written out only once all leaves have
  131257. ** been populated and stored. This is Ok, as the b+-tree fanout is usually
  131258. ** very large, meaning that the interior of the tree consumes relatively
  131259. ** little memory.
  131260. */
  131261. struct SegmentNode {
  131262. SegmentNode *pParent; /* Parent node (or NULL for root node) */
  131263. SegmentNode *pRight; /* Pointer to right-sibling */
  131264. SegmentNode *pLeftmost; /* Pointer to left-most node of this depth */
  131265. int nEntry; /* Number of terms written to node so far */
  131266. char *zTerm; /* Pointer to previous term buffer */
  131267. int nTerm; /* Number of bytes in zTerm */
  131268. int nMalloc; /* Size of malloc'd buffer at zMalloc */
  131269. char *zMalloc; /* Malloc'd space (possibly) used for zTerm */
  131270. int nData; /* Bytes of valid data so far */
  131271. char *aData; /* Node data */
  131272. };
  131273. /*
  131274. ** Valid values for the second argument to fts3SqlStmt().
  131275. */
  131276. #define SQL_DELETE_CONTENT 0
  131277. #define SQL_IS_EMPTY 1
  131278. #define SQL_DELETE_ALL_CONTENT 2
  131279. #define SQL_DELETE_ALL_SEGMENTS 3
  131280. #define SQL_DELETE_ALL_SEGDIR 4
  131281. #define SQL_DELETE_ALL_DOCSIZE 5
  131282. #define SQL_DELETE_ALL_STAT 6
  131283. #define SQL_SELECT_CONTENT_BY_ROWID 7
  131284. #define SQL_NEXT_SEGMENT_INDEX 8
  131285. #define SQL_INSERT_SEGMENTS 9
  131286. #define SQL_NEXT_SEGMENTS_ID 10
  131287. #define SQL_INSERT_SEGDIR 11
  131288. #define SQL_SELECT_LEVEL 12
  131289. #define SQL_SELECT_LEVEL_RANGE 13
  131290. #define SQL_SELECT_LEVEL_COUNT 14
  131291. #define SQL_SELECT_SEGDIR_MAX_LEVEL 15
  131292. #define SQL_DELETE_SEGDIR_LEVEL 16
  131293. #define SQL_DELETE_SEGMENTS_RANGE 17
  131294. #define SQL_CONTENT_INSERT 18
  131295. #define SQL_DELETE_DOCSIZE 19
  131296. #define SQL_REPLACE_DOCSIZE 20
  131297. #define SQL_SELECT_DOCSIZE 21
  131298. #define SQL_SELECT_STAT 22
  131299. #define SQL_REPLACE_STAT 23
  131300. #define SQL_SELECT_ALL_PREFIX_LEVEL 24
  131301. #define SQL_DELETE_ALL_TERMS_SEGDIR 25
  131302. #define SQL_DELETE_SEGDIR_RANGE 26
  131303. #define SQL_SELECT_ALL_LANGID 27
  131304. #define SQL_FIND_MERGE_LEVEL 28
  131305. #define SQL_MAX_LEAF_NODE_ESTIMATE 29
  131306. #define SQL_DELETE_SEGDIR_ENTRY 30
  131307. #define SQL_SHIFT_SEGDIR_ENTRY 31
  131308. #define SQL_SELECT_SEGDIR 32
  131309. #define SQL_CHOMP_SEGDIR 33
  131310. #define SQL_SEGMENT_IS_APPENDABLE 34
  131311. #define SQL_SELECT_INDEXES 35
  131312. #define SQL_SELECT_MXLEVEL 36
  131313. #define SQL_SELECT_LEVEL_RANGE2 37
  131314. #define SQL_UPDATE_LEVEL_IDX 38
  131315. #define SQL_UPDATE_LEVEL 39
  131316. /*
  131317. ** This function is used to obtain an SQLite prepared statement handle
  131318. ** for the statement identified by the second argument. If successful,
  131319. ** *pp is set to the requested statement handle and SQLITE_OK returned.
  131320. ** Otherwise, an SQLite error code is returned and *pp is set to 0.
  131321. **
  131322. ** If argument apVal is not NULL, then it must point to an array with
  131323. ** at least as many entries as the requested statement has bound
  131324. ** parameters. The values are bound to the statements parameters before
  131325. ** returning.
  131326. */
  131327. static int fts3SqlStmt(
  131328. Fts3Table *p, /* Virtual table handle */
  131329. int eStmt, /* One of the SQL_XXX constants above */
  131330. sqlite3_stmt **pp, /* OUT: Statement handle */
  131331. sqlite3_value **apVal /* Values to bind to statement */
  131332. ){
  131333. const char *azSql[] = {
  131334. /* 0 */ "DELETE FROM %Q.'%q_content' WHERE rowid = ?",
  131335. /* 1 */ "SELECT NOT EXISTS(SELECT docid FROM %Q.'%q_content' WHERE rowid!=?)",
  131336. /* 2 */ "DELETE FROM %Q.'%q_content'",
  131337. /* 3 */ "DELETE FROM %Q.'%q_segments'",
  131338. /* 4 */ "DELETE FROM %Q.'%q_segdir'",
  131339. /* 5 */ "DELETE FROM %Q.'%q_docsize'",
  131340. /* 6 */ "DELETE FROM %Q.'%q_stat'",
  131341. /* 7 */ "SELECT %s WHERE rowid=?",
  131342. /* 8 */ "SELECT (SELECT max(idx) FROM %Q.'%q_segdir' WHERE level = ?) + 1",
  131343. /* 9 */ "REPLACE INTO %Q.'%q_segments'(blockid, block) VALUES(?, ?)",
  131344. /* 10 */ "SELECT coalesce((SELECT max(blockid) FROM %Q.'%q_segments') + 1, 1)",
  131345. /* 11 */ "REPLACE INTO %Q.'%q_segdir' VALUES(?,?,?,?,?,?)",
  131346. /* Return segments in order from oldest to newest.*/
  131347. /* 12 */ "SELECT idx, start_block, leaves_end_block, end_block, root "
  131348. "FROM %Q.'%q_segdir' WHERE level = ? ORDER BY idx ASC",
  131349. /* 13 */ "SELECT idx, start_block, leaves_end_block, end_block, root "
  131350. "FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?"
  131351. "ORDER BY level DESC, idx ASC",
  131352. /* 14 */ "SELECT count(*) FROM %Q.'%q_segdir' WHERE level = ?",
  131353. /* 15 */ "SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?",
  131354. /* 16 */ "DELETE FROM %Q.'%q_segdir' WHERE level = ?",
  131355. /* 17 */ "DELETE FROM %Q.'%q_segments' WHERE blockid BETWEEN ? AND ?",
  131356. /* 18 */ "INSERT INTO %Q.'%q_content' VALUES(%s)",
  131357. /* 19 */ "DELETE FROM %Q.'%q_docsize' WHERE docid = ?",
  131358. /* 20 */ "REPLACE INTO %Q.'%q_docsize' VALUES(?,?)",
  131359. /* 21 */ "SELECT size FROM %Q.'%q_docsize' WHERE docid=?",
  131360. /* 22 */ "SELECT value FROM %Q.'%q_stat' WHERE id=?",
  131361. /* 23 */ "REPLACE INTO %Q.'%q_stat' VALUES(?,?)",
  131362. /* 24 */ "",
  131363. /* 25 */ "",
  131364. /* 26 */ "DELETE FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?",
  131365. /* 27 */ "SELECT DISTINCT level / (1024 * ?) FROM %Q.'%q_segdir'",
  131366. /* This statement is used to determine which level to read the input from
  131367. ** when performing an incremental merge. It returns the absolute level number
  131368. ** of the oldest level in the db that contains at least ? segments. Or,
  131369. ** if no level in the FTS index contains more than ? segments, the statement
  131370. ** returns zero rows. */
  131371. /* 28 */ "SELECT level FROM %Q.'%q_segdir' GROUP BY level HAVING count(*)>=?"
  131372. " ORDER BY (level %% 1024) ASC LIMIT 1",
  131373. /* Estimate the upper limit on the number of leaf nodes in a new segment
  131374. ** created by merging the oldest :2 segments from absolute level :1. See
  131375. ** function sqlite3Fts3Incrmerge() for details. */
  131376. /* 29 */ "SELECT 2 * total(1 + leaves_end_block - start_block) "
  131377. " FROM %Q.'%q_segdir' WHERE level = ? AND idx < ?",
  131378. /* SQL_DELETE_SEGDIR_ENTRY
  131379. ** Delete the %_segdir entry on absolute level :1 with index :2. */
  131380. /* 30 */ "DELETE FROM %Q.'%q_segdir' WHERE level = ? AND idx = ?",
  131381. /* SQL_SHIFT_SEGDIR_ENTRY
  131382. ** Modify the idx value for the segment with idx=:3 on absolute level :2
  131383. ** to :1. */
  131384. /* 31 */ "UPDATE %Q.'%q_segdir' SET idx = ? WHERE level=? AND idx=?",
  131385. /* SQL_SELECT_SEGDIR
  131386. ** Read a single entry from the %_segdir table. The entry from absolute
  131387. ** level :1 with index value :2. */
  131388. /* 32 */ "SELECT idx, start_block, leaves_end_block, end_block, root "
  131389. "FROM %Q.'%q_segdir' WHERE level = ? AND idx = ?",
  131390. /* SQL_CHOMP_SEGDIR
  131391. ** Update the start_block (:1) and root (:2) fields of the %_segdir
  131392. ** entry located on absolute level :3 with index :4. */
  131393. /* 33 */ "UPDATE %Q.'%q_segdir' SET start_block = ?, root = ?"
  131394. "WHERE level = ? AND idx = ?",
  131395. /* SQL_SEGMENT_IS_APPENDABLE
  131396. ** Return a single row if the segment with end_block=? is appendable. Or
  131397. ** no rows otherwise. */
  131398. /* 34 */ "SELECT 1 FROM %Q.'%q_segments' WHERE blockid=? AND block IS NULL",
  131399. /* SQL_SELECT_INDEXES
  131400. ** Return the list of valid segment indexes for absolute level ? */
  131401. /* 35 */ "SELECT idx FROM %Q.'%q_segdir' WHERE level=? ORDER BY 1 ASC",
  131402. /* SQL_SELECT_MXLEVEL
  131403. ** Return the largest relative level in the FTS index or indexes. */
  131404. /* 36 */ "SELECT max( level %% 1024 ) FROM %Q.'%q_segdir'",
  131405. /* Return segments in order from oldest to newest.*/
  131406. /* 37 */ "SELECT level, idx, end_block "
  131407. "FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ? "
  131408. "ORDER BY level DESC, idx ASC",
  131409. /* Update statements used while promoting segments */
  131410. /* 38 */ "UPDATE OR FAIL %Q.'%q_segdir' SET level=-1,idx=? "
  131411. "WHERE level=? AND idx=?",
  131412. /* 39 */ "UPDATE OR FAIL %Q.'%q_segdir' SET level=? WHERE level=-1"
  131413. };
  131414. int rc = SQLITE_OK;
  131415. sqlite3_stmt *pStmt;
  131416. assert( SizeofArray(azSql)==SizeofArray(p->aStmt) );
  131417. assert( eStmt<SizeofArray(azSql) && eStmt>=0 );
  131418. pStmt = p->aStmt[eStmt];
  131419. if( !pStmt ){
  131420. char *zSql;
  131421. if( eStmt==SQL_CONTENT_INSERT ){
  131422. zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName, p->zWriteExprlist);
  131423. }else if( eStmt==SQL_SELECT_CONTENT_BY_ROWID ){
  131424. zSql = sqlite3_mprintf(azSql[eStmt], p->zReadExprlist);
  131425. }else{
  131426. zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName);
  131427. }
  131428. if( !zSql ){
  131429. rc = SQLITE_NOMEM;
  131430. }else{
  131431. rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, NULL);
  131432. sqlite3_free(zSql);
  131433. assert( rc==SQLITE_OK || pStmt==0 );
  131434. p->aStmt[eStmt] = pStmt;
  131435. }
  131436. }
  131437. if( apVal ){
  131438. int i;
  131439. int nParam = sqlite3_bind_parameter_count(pStmt);
  131440. for(i=0; rc==SQLITE_OK && i<nParam; i++){
  131441. rc = sqlite3_bind_value(pStmt, i+1, apVal[i]);
  131442. }
  131443. }
  131444. *pp = pStmt;
  131445. return rc;
  131446. }
  131447. static int fts3SelectDocsize(
  131448. Fts3Table *pTab, /* FTS3 table handle */
  131449. sqlite3_int64 iDocid, /* Docid to bind for SQL_SELECT_DOCSIZE */
  131450. sqlite3_stmt **ppStmt /* OUT: Statement handle */
  131451. ){
  131452. sqlite3_stmt *pStmt = 0; /* Statement requested from fts3SqlStmt() */
  131453. int rc; /* Return code */
  131454. rc = fts3SqlStmt(pTab, SQL_SELECT_DOCSIZE, &pStmt, 0);
  131455. if( rc==SQLITE_OK ){
  131456. sqlite3_bind_int64(pStmt, 1, iDocid);
  131457. rc = sqlite3_step(pStmt);
  131458. if( rc!=SQLITE_ROW || sqlite3_column_type(pStmt, 0)!=SQLITE_BLOB ){
  131459. rc = sqlite3_reset(pStmt);
  131460. if( rc==SQLITE_OK ) rc = FTS_CORRUPT_VTAB;
  131461. pStmt = 0;
  131462. }else{
  131463. rc = SQLITE_OK;
  131464. }
  131465. }
  131466. *ppStmt = pStmt;
  131467. return rc;
  131468. }
  131469. SQLITE_PRIVATE int sqlite3Fts3SelectDoctotal(
  131470. Fts3Table *pTab, /* Fts3 table handle */
  131471. sqlite3_stmt **ppStmt /* OUT: Statement handle */
  131472. ){
  131473. sqlite3_stmt *pStmt = 0;
  131474. int rc;
  131475. rc = fts3SqlStmt(pTab, SQL_SELECT_STAT, &pStmt, 0);
  131476. if( rc==SQLITE_OK ){
  131477. sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
  131478. if( sqlite3_step(pStmt)!=SQLITE_ROW
  131479. || sqlite3_column_type(pStmt, 0)!=SQLITE_BLOB
  131480. ){
  131481. rc = sqlite3_reset(pStmt);
  131482. if( rc==SQLITE_OK ) rc = FTS_CORRUPT_VTAB;
  131483. pStmt = 0;
  131484. }
  131485. }
  131486. *ppStmt = pStmt;
  131487. return rc;
  131488. }
  131489. SQLITE_PRIVATE int sqlite3Fts3SelectDocsize(
  131490. Fts3Table *pTab, /* Fts3 table handle */
  131491. sqlite3_int64 iDocid, /* Docid to read size data for */
  131492. sqlite3_stmt **ppStmt /* OUT: Statement handle */
  131493. ){
  131494. return fts3SelectDocsize(pTab, iDocid, ppStmt);
  131495. }
  131496. /*
  131497. ** Similar to fts3SqlStmt(). Except, after binding the parameters in
  131498. ** array apVal[] to the SQL statement identified by eStmt, the statement
  131499. ** is executed.
  131500. **
  131501. ** Returns SQLITE_OK if the statement is successfully executed, or an
  131502. ** SQLite error code otherwise.
  131503. */
  131504. static void fts3SqlExec(
  131505. int *pRC, /* Result code */
  131506. Fts3Table *p, /* The FTS3 table */
  131507. int eStmt, /* Index of statement to evaluate */
  131508. sqlite3_value **apVal /* Parameters to bind */
  131509. ){
  131510. sqlite3_stmt *pStmt;
  131511. int rc;
  131512. if( *pRC ) return;
  131513. rc = fts3SqlStmt(p, eStmt, &pStmt, apVal);
  131514. if( rc==SQLITE_OK ){
  131515. sqlite3_step(pStmt);
  131516. rc = sqlite3_reset(pStmt);
  131517. }
  131518. *pRC = rc;
  131519. }
  131520. /*
  131521. ** This function ensures that the caller has obtained an exclusive
  131522. ** shared-cache table-lock on the %_segdir table. This is required before
  131523. ** writing data to the fts3 table. If this lock is not acquired first, then
  131524. ** the caller may end up attempting to take this lock as part of committing
  131525. ** a transaction, causing SQLite to return SQLITE_LOCKED or
  131526. ** LOCKED_SHAREDCACHEto a COMMIT command.
  131527. **
  131528. ** It is best to avoid this because if FTS3 returns any error when
  131529. ** committing a transaction, the whole transaction will be rolled back.
  131530. ** And this is not what users expect when they get SQLITE_LOCKED_SHAREDCACHE.
  131531. ** It can still happen if the user locks the underlying tables directly
  131532. ** instead of accessing them via FTS.
  131533. */
  131534. static int fts3Writelock(Fts3Table *p){
  131535. int rc = SQLITE_OK;
  131536. if( p->nPendingData==0 ){
  131537. sqlite3_stmt *pStmt;
  131538. rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_LEVEL, &pStmt, 0);
  131539. if( rc==SQLITE_OK ){
  131540. sqlite3_bind_null(pStmt, 1);
  131541. sqlite3_step(pStmt);
  131542. rc = sqlite3_reset(pStmt);
  131543. }
  131544. }
  131545. return rc;
  131546. }
  131547. /*
  131548. ** FTS maintains a separate indexes for each language-id (a 32-bit integer).
  131549. ** Within each language id, a separate index is maintained to store the
  131550. ** document terms, and each configured prefix size (configured the FTS
  131551. ** "prefix=" option). And each index consists of multiple levels ("relative
  131552. ** levels").
  131553. **
  131554. ** All three of these values (the language id, the specific index and the
  131555. ** level within the index) are encoded in 64-bit integer values stored
  131556. ** in the %_segdir table on disk. This function is used to convert three
  131557. ** separate component values into the single 64-bit integer value that
  131558. ** can be used to query the %_segdir table.
  131559. **
  131560. ** Specifically, each language-id/index combination is allocated 1024
  131561. ** 64-bit integer level values ("absolute levels"). The main terms index
  131562. ** for language-id 0 is allocate values 0-1023. The first prefix index
  131563. ** (if any) for language-id 0 is allocated values 1024-2047. And so on.
  131564. ** Language 1 indexes are allocated immediately following language 0.
  131565. **
  131566. ** So, for a system with nPrefix prefix indexes configured, the block of
  131567. ** absolute levels that corresponds to language-id iLangid and index
  131568. ** iIndex starts at absolute level ((iLangid * (nPrefix+1) + iIndex) * 1024).
  131569. */
  131570. static sqlite3_int64 getAbsoluteLevel(
  131571. Fts3Table *p, /* FTS3 table handle */
  131572. int iLangid, /* Language id */
  131573. int iIndex, /* Index in p->aIndex[] */
  131574. int iLevel /* Level of segments */
  131575. ){
  131576. sqlite3_int64 iBase; /* First absolute level for iLangid/iIndex */
  131577. assert( iLangid>=0 );
  131578. assert( p->nIndex>0 );
  131579. assert( iIndex>=0 && iIndex<p->nIndex );
  131580. iBase = ((sqlite3_int64)iLangid * p->nIndex + iIndex) * FTS3_SEGDIR_MAXLEVEL;
  131581. return iBase + iLevel;
  131582. }
  131583. /*
  131584. ** Set *ppStmt to a statement handle that may be used to iterate through
  131585. ** all rows in the %_segdir table, from oldest to newest. If successful,
  131586. ** return SQLITE_OK. If an error occurs while preparing the statement,
  131587. ** return an SQLite error code.
  131588. **
  131589. ** There is only ever one instance of this SQL statement compiled for
  131590. ** each FTS3 table.
  131591. **
  131592. ** The statement returns the following columns from the %_segdir table:
  131593. **
  131594. ** 0: idx
  131595. ** 1: start_block
  131596. ** 2: leaves_end_block
  131597. ** 3: end_block
  131598. ** 4: root
  131599. */
  131600. SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(
  131601. Fts3Table *p, /* FTS3 table */
  131602. int iLangid, /* Language being queried */
  131603. int iIndex, /* Index for p->aIndex[] */
  131604. int iLevel, /* Level to select (relative level) */
  131605. sqlite3_stmt **ppStmt /* OUT: Compiled statement */
  131606. ){
  131607. int rc;
  131608. sqlite3_stmt *pStmt = 0;
  131609. assert( iLevel==FTS3_SEGCURSOR_ALL || iLevel>=0 );
  131610. assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
  131611. assert( iIndex>=0 && iIndex<p->nIndex );
  131612. if( iLevel<0 ){
  131613. /* "SELECT * FROM %_segdir WHERE level BETWEEN ? AND ? ORDER BY ..." */
  131614. rc = fts3SqlStmt(p, SQL_SELECT_LEVEL_RANGE, &pStmt, 0);
  131615. if( rc==SQLITE_OK ){
  131616. sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
  131617. sqlite3_bind_int64(pStmt, 2,
  131618. getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
  131619. );
  131620. }
  131621. }else{
  131622. /* "SELECT * FROM %_segdir WHERE level = ? ORDER BY ..." */
  131623. rc = fts3SqlStmt(p, SQL_SELECT_LEVEL, &pStmt, 0);
  131624. if( rc==SQLITE_OK ){
  131625. sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex,iLevel));
  131626. }
  131627. }
  131628. *ppStmt = pStmt;
  131629. return rc;
  131630. }
  131631. /*
  131632. ** Append a single varint to a PendingList buffer. SQLITE_OK is returned
  131633. ** if successful, or an SQLite error code otherwise.
  131634. **
  131635. ** This function also serves to allocate the PendingList structure itself.
  131636. ** For example, to create a new PendingList structure containing two
  131637. ** varints:
  131638. **
  131639. ** PendingList *p = 0;
  131640. ** fts3PendingListAppendVarint(&p, 1);
  131641. ** fts3PendingListAppendVarint(&p, 2);
  131642. */
  131643. static int fts3PendingListAppendVarint(
  131644. PendingList **pp, /* IN/OUT: Pointer to PendingList struct */
  131645. sqlite3_int64 i /* Value to append to data */
  131646. ){
  131647. PendingList *p = *pp;
  131648. /* Allocate or grow the PendingList as required. */
  131649. if( !p ){
  131650. p = sqlite3_malloc(sizeof(*p) + 100);
  131651. if( !p ){
  131652. return SQLITE_NOMEM;
  131653. }
  131654. p->nSpace = 100;
  131655. p->aData = (char *)&p[1];
  131656. p->nData = 0;
  131657. }
  131658. else if( p->nData+FTS3_VARINT_MAX+1>p->nSpace ){
  131659. int nNew = p->nSpace * 2;
  131660. p = sqlite3_realloc(p, sizeof(*p) + nNew);
  131661. if( !p ){
  131662. sqlite3_free(*pp);
  131663. *pp = 0;
  131664. return SQLITE_NOMEM;
  131665. }
  131666. p->nSpace = nNew;
  131667. p->aData = (char *)&p[1];
  131668. }
  131669. /* Append the new serialized varint to the end of the list. */
  131670. p->nData += sqlite3Fts3PutVarint(&p->aData[p->nData], i);
  131671. p->aData[p->nData] = '\0';
  131672. *pp = p;
  131673. return SQLITE_OK;
  131674. }
  131675. /*
  131676. ** Add a docid/column/position entry to a PendingList structure. Non-zero
  131677. ** is returned if the structure is sqlite3_realloced as part of adding
  131678. ** the entry. Otherwise, zero.
  131679. **
  131680. ** If an OOM error occurs, *pRc is set to SQLITE_NOMEM before returning.
  131681. ** Zero is always returned in this case. Otherwise, if no OOM error occurs,
  131682. ** it is set to SQLITE_OK.
  131683. */
  131684. static int fts3PendingListAppend(
  131685. PendingList **pp, /* IN/OUT: PendingList structure */
  131686. sqlite3_int64 iDocid, /* Docid for entry to add */
  131687. sqlite3_int64 iCol, /* Column for entry to add */
  131688. sqlite3_int64 iPos, /* Position of term for entry to add */
  131689. int *pRc /* OUT: Return code */
  131690. ){
  131691. PendingList *p = *pp;
  131692. int rc = SQLITE_OK;
  131693. assert( !p || p->iLastDocid<=iDocid );
  131694. if( !p || p->iLastDocid!=iDocid ){
  131695. sqlite3_int64 iDelta = iDocid - (p ? p->iLastDocid : 0);
  131696. if( p ){
  131697. assert( p->nData<p->nSpace );
  131698. assert( p->aData[p->nData]==0 );
  131699. p->nData++;
  131700. }
  131701. if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iDelta)) ){
  131702. goto pendinglistappend_out;
  131703. }
  131704. p->iLastCol = -1;
  131705. p->iLastPos = 0;
  131706. p->iLastDocid = iDocid;
  131707. }
  131708. if( iCol>0 && p->iLastCol!=iCol ){
  131709. if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, 1))
  131710. || SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iCol))
  131711. ){
  131712. goto pendinglistappend_out;
  131713. }
  131714. p->iLastCol = iCol;
  131715. p->iLastPos = 0;
  131716. }
  131717. if( iCol>=0 ){
  131718. assert( iPos>p->iLastPos || (iPos==0 && p->iLastPos==0) );
  131719. rc = fts3PendingListAppendVarint(&p, 2+iPos-p->iLastPos);
  131720. if( rc==SQLITE_OK ){
  131721. p->iLastPos = iPos;
  131722. }
  131723. }
  131724. pendinglistappend_out:
  131725. *pRc = rc;
  131726. if( p!=*pp ){
  131727. *pp = p;
  131728. return 1;
  131729. }
  131730. return 0;
  131731. }
  131732. /*
  131733. ** Free a PendingList object allocated by fts3PendingListAppend().
  131734. */
  131735. static void fts3PendingListDelete(PendingList *pList){
  131736. sqlite3_free(pList);
  131737. }
  131738. /*
  131739. ** Add an entry to one of the pending-terms hash tables.
  131740. */
  131741. static int fts3PendingTermsAddOne(
  131742. Fts3Table *p,
  131743. int iCol,
  131744. int iPos,
  131745. Fts3Hash *pHash, /* Pending terms hash table to add entry to */
  131746. const char *zToken,
  131747. int nToken
  131748. ){
  131749. PendingList *pList;
  131750. int rc = SQLITE_OK;
  131751. pList = (PendingList *)fts3HashFind(pHash, zToken, nToken);
  131752. if( pList ){
  131753. p->nPendingData -= (pList->nData + nToken + sizeof(Fts3HashElem));
  131754. }
  131755. if( fts3PendingListAppend(&pList, p->iPrevDocid, iCol, iPos, &rc) ){
  131756. if( pList==fts3HashInsert(pHash, zToken, nToken, pList) ){
  131757. /* Malloc failed while inserting the new entry. This can only
  131758. ** happen if there was no previous entry for this token.
  131759. */
  131760. assert( 0==fts3HashFind(pHash, zToken, nToken) );
  131761. sqlite3_free(pList);
  131762. rc = SQLITE_NOMEM;
  131763. }
  131764. }
  131765. if( rc==SQLITE_OK ){
  131766. p->nPendingData += (pList->nData + nToken + sizeof(Fts3HashElem));
  131767. }
  131768. return rc;
  131769. }
  131770. /*
  131771. ** Tokenize the nul-terminated string zText and add all tokens to the
  131772. ** pending-terms hash-table. The docid used is that currently stored in
  131773. ** p->iPrevDocid, and the column is specified by argument iCol.
  131774. **
  131775. ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
  131776. */
  131777. static int fts3PendingTermsAdd(
  131778. Fts3Table *p, /* Table into which text will be inserted */
  131779. int iLangid, /* Language id to use */
  131780. const char *zText, /* Text of document to be inserted */
  131781. int iCol, /* Column into which text is being inserted */
  131782. u32 *pnWord /* IN/OUT: Incr. by number tokens inserted */
  131783. ){
  131784. int rc;
  131785. int iStart = 0;
  131786. int iEnd = 0;
  131787. int iPos = 0;
  131788. int nWord = 0;
  131789. char const *zToken;
  131790. int nToken = 0;
  131791. sqlite3_tokenizer *pTokenizer = p->pTokenizer;
  131792. sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
  131793. sqlite3_tokenizer_cursor *pCsr;
  131794. int (*xNext)(sqlite3_tokenizer_cursor *pCursor,
  131795. const char**,int*,int*,int*,int*);
  131796. assert( pTokenizer && pModule );
  131797. /* If the user has inserted a NULL value, this function may be called with
  131798. ** zText==0. In this case, add zero token entries to the hash table and
  131799. ** return early. */
  131800. if( zText==0 ){
  131801. *pnWord = 0;
  131802. return SQLITE_OK;
  131803. }
  131804. rc = sqlite3Fts3OpenTokenizer(pTokenizer, iLangid, zText, -1, &pCsr);
  131805. if( rc!=SQLITE_OK ){
  131806. return rc;
  131807. }
  131808. xNext = pModule->xNext;
  131809. while( SQLITE_OK==rc
  131810. && SQLITE_OK==(rc = xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos))
  131811. ){
  131812. int i;
  131813. if( iPos>=nWord ) nWord = iPos+1;
  131814. /* Positions cannot be negative; we use -1 as a terminator internally.
  131815. ** Tokens must have a non-zero length.
  131816. */
  131817. if( iPos<0 || !zToken || nToken<=0 ){
  131818. rc = SQLITE_ERROR;
  131819. break;
  131820. }
  131821. /* Add the term to the terms index */
  131822. rc = fts3PendingTermsAddOne(
  131823. p, iCol, iPos, &p->aIndex[0].hPending, zToken, nToken
  131824. );
  131825. /* Add the term to each of the prefix indexes that it is not too
  131826. ** short for. */
  131827. for(i=1; rc==SQLITE_OK && i<p->nIndex; i++){
  131828. struct Fts3Index *pIndex = &p->aIndex[i];
  131829. if( nToken<pIndex->nPrefix ) continue;
  131830. rc = fts3PendingTermsAddOne(
  131831. p, iCol, iPos, &pIndex->hPending, zToken, pIndex->nPrefix
  131832. );
  131833. }
  131834. }
  131835. pModule->xClose(pCsr);
  131836. *pnWord += nWord;
  131837. return (rc==SQLITE_DONE ? SQLITE_OK : rc);
  131838. }
  131839. /*
  131840. ** Calling this function indicates that subsequent calls to
  131841. ** fts3PendingTermsAdd() are to add term/position-list pairs for the
  131842. ** contents of the document with docid iDocid.
  131843. */
  131844. static int fts3PendingTermsDocid(
  131845. Fts3Table *p, /* Full-text table handle */
  131846. int iLangid, /* Language id of row being written */
  131847. sqlite_int64 iDocid /* Docid of row being written */
  131848. ){
  131849. assert( iLangid>=0 );
  131850. /* TODO(shess) Explore whether partially flushing the buffer on
  131851. ** forced-flush would provide better performance. I suspect that if
  131852. ** we ordered the doclists by size and flushed the largest until the
  131853. ** buffer was half empty, that would let the less frequent terms
  131854. ** generate longer doclists.
  131855. */
  131856. if( iDocid<=p->iPrevDocid
  131857. || p->iPrevLangid!=iLangid
  131858. || p->nPendingData>p->nMaxPendingData
  131859. ){
  131860. int rc = sqlite3Fts3PendingTermsFlush(p);
  131861. if( rc!=SQLITE_OK ) return rc;
  131862. }
  131863. p->iPrevDocid = iDocid;
  131864. p->iPrevLangid = iLangid;
  131865. return SQLITE_OK;
  131866. }
  131867. /*
  131868. ** Discard the contents of the pending-terms hash tables.
  131869. */
  131870. SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *p){
  131871. int i;
  131872. for(i=0; i<p->nIndex; i++){
  131873. Fts3HashElem *pElem;
  131874. Fts3Hash *pHash = &p->aIndex[i].hPending;
  131875. for(pElem=fts3HashFirst(pHash); pElem; pElem=fts3HashNext(pElem)){
  131876. PendingList *pList = (PendingList *)fts3HashData(pElem);
  131877. fts3PendingListDelete(pList);
  131878. }
  131879. fts3HashClear(pHash);
  131880. }
  131881. p->nPendingData = 0;
  131882. }
  131883. /*
  131884. ** This function is called by the xUpdate() method as part of an INSERT
  131885. ** operation. It adds entries for each term in the new record to the
  131886. ** pendingTerms hash table.
  131887. **
  131888. ** Argument apVal is the same as the similarly named argument passed to
  131889. ** fts3InsertData(). Parameter iDocid is the docid of the new row.
  131890. */
  131891. static int fts3InsertTerms(
  131892. Fts3Table *p,
  131893. int iLangid,
  131894. sqlite3_value **apVal,
  131895. u32 *aSz
  131896. ){
  131897. int i; /* Iterator variable */
  131898. for(i=2; i<p->nColumn+2; i++){
  131899. int iCol = i-2;
  131900. if( p->abNotindexed[iCol]==0 ){
  131901. const char *zText = (const char *)sqlite3_value_text(apVal[i]);
  131902. int rc = fts3PendingTermsAdd(p, iLangid, zText, iCol, &aSz[iCol]);
  131903. if( rc!=SQLITE_OK ){
  131904. return rc;
  131905. }
  131906. aSz[p->nColumn] += sqlite3_value_bytes(apVal[i]);
  131907. }
  131908. }
  131909. return SQLITE_OK;
  131910. }
  131911. /*
  131912. ** This function is called by the xUpdate() method for an INSERT operation.
  131913. ** The apVal parameter is passed a copy of the apVal argument passed by
  131914. ** SQLite to the xUpdate() method. i.e:
  131915. **
  131916. ** apVal[0] Not used for INSERT.
  131917. ** apVal[1] rowid
  131918. ** apVal[2] Left-most user-defined column
  131919. ** ...
  131920. ** apVal[p->nColumn+1] Right-most user-defined column
  131921. ** apVal[p->nColumn+2] Hidden column with same name as table
  131922. ** apVal[p->nColumn+3] Hidden "docid" column (alias for rowid)
  131923. ** apVal[p->nColumn+4] Hidden languageid column
  131924. */
  131925. static int fts3InsertData(
  131926. Fts3Table *p, /* Full-text table */
  131927. sqlite3_value **apVal, /* Array of values to insert */
  131928. sqlite3_int64 *piDocid /* OUT: Docid for row just inserted */
  131929. ){
  131930. int rc; /* Return code */
  131931. sqlite3_stmt *pContentInsert; /* INSERT INTO %_content VALUES(...) */
  131932. if( p->zContentTbl ){
  131933. sqlite3_value *pRowid = apVal[p->nColumn+3];
  131934. if( sqlite3_value_type(pRowid)==SQLITE_NULL ){
  131935. pRowid = apVal[1];
  131936. }
  131937. if( sqlite3_value_type(pRowid)!=SQLITE_INTEGER ){
  131938. return SQLITE_CONSTRAINT;
  131939. }
  131940. *piDocid = sqlite3_value_int64(pRowid);
  131941. return SQLITE_OK;
  131942. }
  131943. /* Locate the statement handle used to insert data into the %_content
  131944. ** table. The SQL for this statement is:
  131945. **
  131946. ** INSERT INTO %_content VALUES(?, ?, ?, ...)
  131947. **
  131948. ** The statement features N '?' variables, where N is the number of user
  131949. ** defined columns in the FTS3 table, plus one for the docid field.
  131950. */
  131951. rc = fts3SqlStmt(p, SQL_CONTENT_INSERT, &pContentInsert, &apVal[1]);
  131952. if( rc==SQLITE_OK && p->zLanguageid ){
  131953. rc = sqlite3_bind_int(
  131954. pContentInsert, p->nColumn+2,
  131955. sqlite3_value_int(apVal[p->nColumn+4])
  131956. );
  131957. }
  131958. if( rc!=SQLITE_OK ) return rc;
  131959. /* There is a quirk here. The users INSERT statement may have specified
  131960. ** a value for the "rowid" field, for the "docid" field, or for both.
  131961. ** Which is a problem, since "rowid" and "docid" are aliases for the
  131962. ** same value. For example:
  131963. **
  131964. ** INSERT INTO fts3tbl(rowid, docid) VALUES(1, 2);
  131965. **
  131966. ** In FTS3, this is an error. It is an error to specify non-NULL values
  131967. ** for both docid and some other rowid alias.
  131968. */
  131969. if( SQLITE_NULL!=sqlite3_value_type(apVal[3+p->nColumn]) ){
  131970. if( SQLITE_NULL==sqlite3_value_type(apVal[0])
  131971. && SQLITE_NULL!=sqlite3_value_type(apVal[1])
  131972. ){
  131973. /* A rowid/docid conflict. */
  131974. return SQLITE_ERROR;
  131975. }
  131976. rc = sqlite3_bind_value(pContentInsert, 1, apVal[3+p->nColumn]);
  131977. if( rc!=SQLITE_OK ) return rc;
  131978. }
  131979. /* Execute the statement to insert the record. Set *piDocid to the
  131980. ** new docid value.
  131981. */
  131982. sqlite3_step(pContentInsert);
  131983. rc = sqlite3_reset(pContentInsert);
  131984. *piDocid = sqlite3_last_insert_rowid(p->db);
  131985. return rc;
  131986. }
  131987. /*
  131988. ** Remove all data from the FTS3 table. Clear the hash table containing
  131989. ** pending terms.
  131990. */
  131991. static int fts3DeleteAll(Fts3Table *p, int bContent){
  131992. int rc = SQLITE_OK; /* Return code */
  131993. /* Discard the contents of the pending-terms hash table. */
  131994. sqlite3Fts3PendingTermsClear(p);
  131995. /* Delete everything from the shadow tables. Except, leave %_content as
  131996. ** is if bContent is false. */
  131997. assert( p->zContentTbl==0 || bContent==0 );
  131998. if( bContent ) fts3SqlExec(&rc, p, SQL_DELETE_ALL_CONTENT, 0);
  131999. fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGMENTS, 0);
  132000. fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGDIR, 0);
  132001. if( p->bHasDocsize ){
  132002. fts3SqlExec(&rc, p, SQL_DELETE_ALL_DOCSIZE, 0);
  132003. }
  132004. if( p->bHasStat ){
  132005. fts3SqlExec(&rc, p, SQL_DELETE_ALL_STAT, 0);
  132006. }
  132007. return rc;
  132008. }
  132009. /*
  132010. **
  132011. */
  132012. static int langidFromSelect(Fts3Table *p, sqlite3_stmt *pSelect){
  132013. int iLangid = 0;
  132014. if( p->zLanguageid ) iLangid = sqlite3_column_int(pSelect, p->nColumn+1);
  132015. return iLangid;
  132016. }
  132017. /*
  132018. ** The first element in the apVal[] array is assumed to contain the docid
  132019. ** (an integer) of a row about to be deleted. Remove all terms from the
  132020. ** full-text index.
  132021. */
  132022. static void fts3DeleteTerms(
  132023. int *pRC, /* Result code */
  132024. Fts3Table *p, /* The FTS table to delete from */
  132025. sqlite3_value *pRowid, /* The docid to be deleted */
  132026. u32 *aSz, /* Sizes of deleted document written here */
  132027. int *pbFound /* OUT: Set to true if row really does exist */
  132028. ){
  132029. int rc;
  132030. sqlite3_stmt *pSelect;
  132031. assert( *pbFound==0 );
  132032. if( *pRC ) return;
  132033. rc = fts3SqlStmt(p, SQL_SELECT_CONTENT_BY_ROWID, &pSelect, &pRowid);
  132034. if( rc==SQLITE_OK ){
  132035. if( SQLITE_ROW==sqlite3_step(pSelect) ){
  132036. int i;
  132037. int iLangid = langidFromSelect(p, pSelect);
  132038. rc = fts3PendingTermsDocid(p, iLangid, sqlite3_column_int64(pSelect, 0));
  132039. for(i=1; rc==SQLITE_OK && i<=p->nColumn; i++){
  132040. int iCol = i-1;
  132041. if( p->abNotindexed[iCol]==0 ){
  132042. const char *zText = (const char *)sqlite3_column_text(pSelect, i);
  132043. rc = fts3PendingTermsAdd(p, iLangid, zText, -1, &aSz[iCol]);
  132044. aSz[p->nColumn] += sqlite3_column_bytes(pSelect, i);
  132045. }
  132046. }
  132047. if( rc!=SQLITE_OK ){
  132048. sqlite3_reset(pSelect);
  132049. *pRC = rc;
  132050. return;
  132051. }
  132052. *pbFound = 1;
  132053. }
  132054. rc = sqlite3_reset(pSelect);
  132055. }else{
  132056. sqlite3_reset(pSelect);
  132057. }
  132058. *pRC = rc;
  132059. }
  132060. /*
  132061. ** Forward declaration to account for the circular dependency between
  132062. ** functions fts3SegmentMerge() and fts3AllocateSegdirIdx().
  132063. */
  132064. static int fts3SegmentMerge(Fts3Table *, int, int, int);
  132065. /*
  132066. ** This function allocates a new level iLevel index in the segdir table.
  132067. ** Usually, indexes are allocated within a level sequentially starting
  132068. ** with 0, so the allocated index is one greater than the value returned
  132069. ** by:
  132070. **
  132071. ** SELECT max(idx) FROM %_segdir WHERE level = :iLevel
  132072. **
  132073. ** However, if there are already FTS3_MERGE_COUNT indexes at the requested
  132074. ** level, they are merged into a single level (iLevel+1) segment and the
  132075. ** allocated index is 0.
  132076. **
  132077. ** If successful, *piIdx is set to the allocated index slot and SQLITE_OK
  132078. ** returned. Otherwise, an SQLite error code is returned.
  132079. */
  132080. static int fts3AllocateSegdirIdx(
  132081. Fts3Table *p,
  132082. int iLangid, /* Language id */
  132083. int iIndex, /* Index for p->aIndex */
  132084. int iLevel,
  132085. int *piIdx
  132086. ){
  132087. int rc; /* Return Code */
  132088. sqlite3_stmt *pNextIdx; /* Query for next idx at level iLevel */
  132089. int iNext = 0; /* Result of query pNextIdx */
  132090. assert( iLangid>=0 );
  132091. assert( p->nIndex>=1 );
  132092. /* Set variable iNext to the next available segdir index at level iLevel. */
  132093. rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pNextIdx, 0);
  132094. if( rc==SQLITE_OK ){
  132095. sqlite3_bind_int64(
  132096. pNextIdx, 1, getAbsoluteLevel(p, iLangid, iIndex, iLevel)
  132097. );
  132098. if( SQLITE_ROW==sqlite3_step(pNextIdx) ){
  132099. iNext = sqlite3_column_int(pNextIdx, 0);
  132100. }
  132101. rc = sqlite3_reset(pNextIdx);
  132102. }
  132103. if( rc==SQLITE_OK ){
  132104. /* If iNext is FTS3_MERGE_COUNT, indicating that level iLevel is already
  132105. ** full, merge all segments in level iLevel into a single iLevel+1
  132106. ** segment and allocate (newly freed) index 0 at level iLevel. Otherwise,
  132107. ** if iNext is less than FTS3_MERGE_COUNT, allocate index iNext.
  132108. */
  132109. if( iNext>=FTS3_MERGE_COUNT ){
  132110. fts3LogMerge(16, getAbsoluteLevel(p, iLangid, iIndex, iLevel));
  132111. rc = fts3SegmentMerge(p, iLangid, iIndex, iLevel);
  132112. *piIdx = 0;
  132113. }else{
  132114. *piIdx = iNext;
  132115. }
  132116. }
  132117. return rc;
  132118. }
  132119. /*
  132120. ** The %_segments table is declared as follows:
  132121. **
  132122. ** CREATE TABLE %_segments(blockid INTEGER PRIMARY KEY, block BLOB)
  132123. **
  132124. ** This function reads data from a single row of the %_segments table. The
  132125. ** specific row is identified by the iBlockid parameter. If paBlob is not
  132126. ** NULL, then a buffer is allocated using sqlite3_malloc() and populated
  132127. ** with the contents of the blob stored in the "block" column of the
  132128. ** identified table row is. Whether or not paBlob is NULL, *pnBlob is set
  132129. ** to the size of the blob in bytes before returning.
  132130. **
  132131. ** If an error occurs, or the table does not contain the specified row,
  132132. ** an SQLite error code is returned. Otherwise, SQLITE_OK is returned. If
  132133. ** paBlob is non-NULL, then it is the responsibility of the caller to
  132134. ** eventually free the returned buffer.
  132135. **
  132136. ** This function may leave an open sqlite3_blob* handle in the
  132137. ** Fts3Table.pSegments variable. This handle is reused by subsequent calls
  132138. ** to this function. The handle may be closed by calling the
  132139. ** sqlite3Fts3SegmentsClose() function. Reusing a blob handle is a handy
  132140. ** performance improvement, but the blob handle should always be closed
  132141. ** before control is returned to the user (to prevent a lock being held
  132142. ** on the database file for longer than necessary). Thus, any virtual table
  132143. ** method (xFilter etc.) that may directly or indirectly call this function
  132144. ** must call sqlite3Fts3SegmentsClose() before returning.
  132145. */
  132146. SQLITE_PRIVATE int sqlite3Fts3ReadBlock(
  132147. Fts3Table *p, /* FTS3 table handle */
  132148. sqlite3_int64 iBlockid, /* Access the row with blockid=$iBlockid */
  132149. char **paBlob, /* OUT: Blob data in malloc'd buffer */
  132150. int *pnBlob, /* OUT: Size of blob data */
  132151. int *pnLoad /* OUT: Bytes actually loaded */
  132152. ){
  132153. int rc; /* Return code */
  132154. /* pnBlob must be non-NULL. paBlob may be NULL or non-NULL. */
  132155. assert( pnBlob );
  132156. if( p->pSegments ){
  132157. rc = sqlite3_blob_reopen(p->pSegments, iBlockid);
  132158. }else{
  132159. if( 0==p->zSegmentsTbl ){
  132160. p->zSegmentsTbl = sqlite3_mprintf("%s_segments", p->zName);
  132161. if( 0==p->zSegmentsTbl ) return SQLITE_NOMEM;
  132162. }
  132163. rc = sqlite3_blob_open(
  132164. p->db, p->zDb, p->zSegmentsTbl, "block", iBlockid, 0, &p->pSegments
  132165. );
  132166. }
  132167. if( rc==SQLITE_OK ){
  132168. int nByte = sqlite3_blob_bytes(p->pSegments);
  132169. *pnBlob = nByte;
  132170. if( paBlob ){
  132171. char *aByte = sqlite3_malloc(nByte + FTS3_NODE_PADDING);
  132172. if( !aByte ){
  132173. rc = SQLITE_NOMEM;
  132174. }else{
  132175. if( pnLoad && nByte>(FTS3_NODE_CHUNK_THRESHOLD) ){
  132176. nByte = FTS3_NODE_CHUNKSIZE;
  132177. *pnLoad = nByte;
  132178. }
  132179. rc = sqlite3_blob_read(p->pSegments, aByte, nByte, 0);
  132180. memset(&aByte[nByte], 0, FTS3_NODE_PADDING);
  132181. if( rc!=SQLITE_OK ){
  132182. sqlite3_free(aByte);
  132183. aByte = 0;
  132184. }
  132185. }
  132186. *paBlob = aByte;
  132187. }
  132188. }
  132189. return rc;
  132190. }
  132191. /*
  132192. ** Close the blob handle at p->pSegments, if it is open. See comments above
  132193. ** the sqlite3Fts3ReadBlock() function for details.
  132194. */
  132195. SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *p){
  132196. sqlite3_blob_close(p->pSegments);
  132197. p->pSegments = 0;
  132198. }
  132199. static int fts3SegReaderIncrRead(Fts3SegReader *pReader){
  132200. int nRead; /* Number of bytes to read */
  132201. int rc; /* Return code */
  132202. nRead = MIN(pReader->nNode - pReader->nPopulate, FTS3_NODE_CHUNKSIZE);
  132203. rc = sqlite3_blob_read(
  132204. pReader->pBlob,
  132205. &pReader->aNode[pReader->nPopulate],
  132206. nRead,
  132207. pReader->nPopulate
  132208. );
  132209. if( rc==SQLITE_OK ){
  132210. pReader->nPopulate += nRead;
  132211. memset(&pReader->aNode[pReader->nPopulate], 0, FTS3_NODE_PADDING);
  132212. if( pReader->nPopulate==pReader->nNode ){
  132213. sqlite3_blob_close(pReader->pBlob);
  132214. pReader->pBlob = 0;
  132215. pReader->nPopulate = 0;
  132216. }
  132217. }
  132218. return rc;
  132219. }
  132220. static int fts3SegReaderRequire(Fts3SegReader *pReader, char *pFrom, int nByte){
  132221. int rc = SQLITE_OK;
  132222. assert( !pReader->pBlob
  132223. || (pFrom>=pReader->aNode && pFrom<&pReader->aNode[pReader->nNode])
  132224. );
  132225. while( pReader->pBlob && rc==SQLITE_OK
  132226. && (pFrom - pReader->aNode + nByte)>pReader->nPopulate
  132227. ){
  132228. rc = fts3SegReaderIncrRead(pReader);
  132229. }
  132230. return rc;
  132231. }
  132232. /*
  132233. ** Set an Fts3SegReader cursor to point at EOF.
  132234. */
  132235. static void fts3SegReaderSetEof(Fts3SegReader *pSeg){
  132236. if( !fts3SegReaderIsRootOnly(pSeg) ){
  132237. sqlite3_free(pSeg->aNode);
  132238. sqlite3_blob_close(pSeg->pBlob);
  132239. pSeg->pBlob = 0;
  132240. }
  132241. pSeg->aNode = 0;
  132242. }
  132243. /*
  132244. ** Move the iterator passed as the first argument to the next term in the
  132245. ** segment. If successful, SQLITE_OK is returned. If there is no next term,
  132246. ** SQLITE_DONE. Otherwise, an SQLite error code.
  132247. */
  132248. static int fts3SegReaderNext(
  132249. Fts3Table *p,
  132250. Fts3SegReader *pReader,
  132251. int bIncr
  132252. ){
  132253. int rc; /* Return code of various sub-routines */
  132254. char *pNext; /* Cursor variable */
  132255. int nPrefix; /* Number of bytes in term prefix */
  132256. int nSuffix; /* Number of bytes in term suffix */
  132257. if( !pReader->aDoclist ){
  132258. pNext = pReader->aNode;
  132259. }else{
  132260. pNext = &pReader->aDoclist[pReader->nDoclist];
  132261. }
  132262. if( !pNext || pNext>=&pReader->aNode[pReader->nNode] ){
  132263. if( fts3SegReaderIsPending(pReader) ){
  132264. Fts3HashElem *pElem = *(pReader->ppNextElem);
  132265. if( pElem==0 ){
  132266. pReader->aNode = 0;
  132267. }else{
  132268. PendingList *pList = (PendingList *)fts3HashData(pElem);
  132269. pReader->zTerm = (char *)fts3HashKey(pElem);
  132270. pReader->nTerm = fts3HashKeysize(pElem);
  132271. pReader->nNode = pReader->nDoclist = pList->nData + 1;
  132272. pReader->aNode = pReader->aDoclist = pList->aData;
  132273. pReader->ppNextElem++;
  132274. assert( pReader->aNode );
  132275. }
  132276. return SQLITE_OK;
  132277. }
  132278. fts3SegReaderSetEof(pReader);
  132279. /* If iCurrentBlock>=iLeafEndBlock, this is an EOF condition. All leaf
  132280. ** blocks have already been traversed. */
  132281. assert( pReader->iCurrentBlock<=pReader->iLeafEndBlock );
  132282. if( pReader->iCurrentBlock>=pReader->iLeafEndBlock ){
  132283. return SQLITE_OK;
  132284. }
  132285. rc = sqlite3Fts3ReadBlock(
  132286. p, ++pReader->iCurrentBlock, &pReader->aNode, &pReader->nNode,
  132287. (bIncr ? &pReader->nPopulate : 0)
  132288. );
  132289. if( rc!=SQLITE_OK ) return rc;
  132290. assert( pReader->pBlob==0 );
  132291. if( bIncr && pReader->nPopulate<pReader->nNode ){
  132292. pReader->pBlob = p->pSegments;
  132293. p->pSegments = 0;
  132294. }
  132295. pNext = pReader->aNode;
  132296. }
  132297. assert( !fts3SegReaderIsPending(pReader) );
  132298. rc = fts3SegReaderRequire(pReader, pNext, FTS3_VARINT_MAX*2);
  132299. if( rc!=SQLITE_OK ) return rc;
  132300. /* Because of the FTS3_NODE_PADDING bytes of padding, the following is
  132301. ** safe (no risk of overread) even if the node data is corrupted. */
  132302. pNext += fts3GetVarint32(pNext, &nPrefix);
  132303. pNext += fts3GetVarint32(pNext, &nSuffix);
  132304. if( nPrefix<0 || nSuffix<=0
  132305. || &pNext[nSuffix]>&pReader->aNode[pReader->nNode]
  132306. ){
  132307. return FTS_CORRUPT_VTAB;
  132308. }
  132309. if( nPrefix+nSuffix>pReader->nTermAlloc ){
  132310. int nNew = (nPrefix+nSuffix)*2;
  132311. char *zNew = sqlite3_realloc(pReader->zTerm, nNew);
  132312. if( !zNew ){
  132313. return SQLITE_NOMEM;
  132314. }
  132315. pReader->zTerm = zNew;
  132316. pReader->nTermAlloc = nNew;
  132317. }
  132318. rc = fts3SegReaderRequire(pReader, pNext, nSuffix+FTS3_VARINT_MAX);
  132319. if( rc!=SQLITE_OK ) return rc;
  132320. memcpy(&pReader->zTerm[nPrefix], pNext, nSuffix);
  132321. pReader->nTerm = nPrefix+nSuffix;
  132322. pNext += nSuffix;
  132323. pNext += fts3GetVarint32(pNext, &pReader->nDoclist);
  132324. pReader->aDoclist = pNext;
  132325. pReader->pOffsetList = 0;
  132326. /* Check that the doclist does not appear to extend past the end of the
  132327. ** b-tree node. And that the final byte of the doclist is 0x00. If either
  132328. ** of these statements is untrue, then the data structure is corrupt.
  132329. */
  132330. if( &pReader->aDoclist[pReader->nDoclist]>&pReader->aNode[pReader->nNode]
  132331. || (pReader->nPopulate==0 && pReader->aDoclist[pReader->nDoclist-1])
  132332. ){
  132333. return FTS_CORRUPT_VTAB;
  132334. }
  132335. return SQLITE_OK;
  132336. }
  132337. /*
  132338. ** Set the SegReader to point to the first docid in the doclist associated
  132339. ** with the current term.
  132340. */
  132341. static int fts3SegReaderFirstDocid(Fts3Table *pTab, Fts3SegReader *pReader){
  132342. int rc = SQLITE_OK;
  132343. assert( pReader->aDoclist );
  132344. assert( !pReader->pOffsetList );
  132345. if( pTab->bDescIdx && fts3SegReaderIsPending(pReader) ){
  132346. u8 bEof = 0;
  132347. pReader->iDocid = 0;
  132348. pReader->nOffsetList = 0;
  132349. sqlite3Fts3DoclistPrev(0,
  132350. pReader->aDoclist, pReader->nDoclist, &pReader->pOffsetList,
  132351. &pReader->iDocid, &pReader->nOffsetList, &bEof
  132352. );
  132353. }else{
  132354. rc = fts3SegReaderRequire(pReader, pReader->aDoclist, FTS3_VARINT_MAX);
  132355. if( rc==SQLITE_OK ){
  132356. int n = sqlite3Fts3GetVarint(pReader->aDoclist, &pReader->iDocid);
  132357. pReader->pOffsetList = &pReader->aDoclist[n];
  132358. }
  132359. }
  132360. return rc;
  132361. }
  132362. /*
  132363. ** Advance the SegReader to point to the next docid in the doclist
  132364. ** associated with the current term.
  132365. **
  132366. ** If arguments ppOffsetList and pnOffsetList are not NULL, then
  132367. ** *ppOffsetList is set to point to the first column-offset list
  132368. ** in the doclist entry (i.e. immediately past the docid varint).
  132369. ** *pnOffsetList is set to the length of the set of column-offset
  132370. ** lists, not including the nul-terminator byte. For example:
  132371. */
  132372. static int fts3SegReaderNextDocid(
  132373. Fts3Table *pTab,
  132374. Fts3SegReader *pReader, /* Reader to advance to next docid */
  132375. char **ppOffsetList, /* OUT: Pointer to current position-list */
  132376. int *pnOffsetList /* OUT: Length of *ppOffsetList in bytes */
  132377. ){
  132378. int rc = SQLITE_OK;
  132379. char *p = pReader->pOffsetList;
  132380. char c = 0;
  132381. assert( p );
  132382. if( pTab->bDescIdx && fts3SegReaderIsPending(pReader) ){
  132383. /* A pending-terms seg-reader for an FTS4 table that uses order=desc.
  132384. ** Pending-terms doclists are always built up in ascending order, so
  132385. ** we have to iterate through them backwards here. */
  132386. u8 bEof = 0;
  132387. if( ppOffsetList ){
  132388. *ppOffsetList = pReader->pOffsetList;
  132389. *pnOffsetList = pReader->nOffsetList - 1;
  132390. }
  132391. sqlite3Fts3DoclistPrev(0,
  132392. pReader->aDoclist, pReader->nDoclist, &p, &pReader->iDocid,
  132393. &pReader->nOffsetList, &bEof
  132394. );
  132395. if( bEof ){
  132396. pReader->pOffsetList = 0;
  132397. }else{
  132398. pReader->pOffsetList = p;
  132399. }
  132400. }else{
  132401. char *pEnd = &pReader->aDoclist[pReader->nDoclist];
  132402. /* Pointer p currently points at the first byte of an offset list. The
  132403. ** following block advances it to point one byte past the end of
  132404. ** the same offset list. */
  132405. while( 1 ){
  132406. /* The following line of code (and the "p++" below the while() loop) is
  132407. ** normally all that is required to move pointer p to the desired
  132408. ** position. The exception is if this node is being loaded from disk
  132409. ** incrementally and pointer "p" now points to the first byte past
  132410. ** the populated part of pReader->aNode[].
  132411. */
  132412. while( *p | c ) c = *p++ & 0x80;
  132413. assert( *p==0 );
  132414. if( pReader->pBlob==0 || p<&pReader->aNode[pReader->nPopulate] ) break;
  132415. rc = fts3SegReaderIncrRead(pReader);
  132416. if( rc!=SQLITE_OK ) return rc;
  132417. }
  132418. p++;
  132419. /* If required, populate the output variables with a pointer to and the
  132420. ** size of the previous offset-list.
  132421. */
  132422. if( ppOffsetList ){
  132423. *ppOffsetList = pReader->pOffsetList;
  132424. *pnOffsetList = (int)(p - pReader->pOffsetList - 1);
  132425. }
  132426. /* List may have been edited in place by fts3EvalNearTrim() */
  132427. while( p<pEnd && *p==0 ) p++;
  132428. /* If there are no more entries in the doclist, set pOffsetList to
  132429. ** NULL. Otherwise, set Fts3SegReader.iDocid to the next docid and
  132430. ** Fts3SegReader.pOffsetList to point to the next offset list before
  132431. ** returning.
  132432. */
  132433. if( p>=pEnd ){
  132434. pReader->pOffsetList = 0;
  132435. }else{
  132436. rc = fts3SegReaderRequire(pReader, p, FTS3_VARINT_MAX);
  132437. if( rc==SQLITE_OK ){
  132438. sqlite3_int64 iDelta;
  132439. pReader->pOffsetList = p + sqlite3Fts3GetVarint(p, &iDelta);
  132440. if( pTab->bDescIdx ){
  132441. pReader->iDocid -= iDelta;
  132442. }else{
  132443. pReader->iDocid += iDelta;
  132444. }
  132445. }
  132446. }
  132447. }
  132448. return SQLITE_OK;
  132449. }
  132450. SQLITE_PRIVATE int sqlite3Fts3MsrOvfl(
  132451. Fts3Cursor *pCsr,
  132452. Fts3MultiSegReader *pMsr,
  132453. int *pnOvfl
  132454. ){
  132455. Fts3Table *p = (Fts3Table*)pCsr->base.pVtab;
  132456. int nOvfl = 0;
  132457. int ii;
  132458. int rc = SQLITE_OK;
  132459. int pgsz = p->nPgsz;
  132460. assert( p->bFts4 );
  132461. assert( pgsz>0 );
  132462. for(ii=0; rc==SQLITE_OK && ii<pMsr->nSegment; ii++){
  132463. Fts3SegReader *pReader = pMsr->apSegment[ii];
  132464. if( !fts3SegReaderIsPending(pReader)
  132465. && !fts3SegReaderIsRootOnly(pReader)
  132466. ){
  132467. sqlite3_int64 jj;
  132468. for(jj=pReader->iStartBlock; jj<=pReader->iLeafEndBlock; jj++){
  132469. int nBlob;
  132470. rc = sqlite3Fts3ReadBlock(p, jj, 0, &nBlob, 0);
  132471. if( rc!=SQLITE_OK ) break;
  132472. if( (nBlob+35)>pgsz ){
  132473. nOvfl += (nBlob + 34)/pgsz;
  132474. }
  132475. }
  132476. }
  132477. }
  132478. *pnOvfl = nOvfl;
  132479. return rc;
  132480. }
  132481. /*
  132482. ** Free all allocations associated with the iterator passed as the
  132483. ** second argument.
  132484. */
  132485. SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *pReader){
  132486. if( pReader && !fts3SegReaderIsPending(pReader) ){
  132487. sqlite3_free(pReader->zTerm);
  132488. if( !fts3SegReaderIsRootOnly(pReader) ){
  132489. sqlite3_free(pReader->aNode);
  132490. sqlite3_blob_close(pReader->pBlob);
  132491. }
  132492. }
  132493. sqlite3_free(pReader);
  132494. }
  132495. /*
  132496. ** Allocate a new SegReader object.
  132497. */
  132498. SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(
  132499. int iAge, /* Segment "age". */
  132500. int bLookup, /* True for a lookup only */
  132501. sqlite3_int64 iStartLeaf, /* First leaf to traverse */
  132502. sqlite3_int64 iEndLeaf, /* Final leaf to traverse */
  132503. sqlite3_int64 iEndBlock, /* Final block of segment */
  132504. const char *zRoot, /* Buffer containing root node */
  132505. int nRoot, /* Size of buffer containing root node */
  132506. Fts3SegReader **ppReader /* OUT: Allocated Fts3SegReader */
  132507. ){
  132508. Fts3SegReader *pReader; /* Newly allocated SegReader object */
  132509. int nExtra = 0; /* Bytes to allocate segment root node */
  132510. assert( iStartLeaf<=iEndLeaf );
  132511. if( iStartLeaf==0 ){
  132512. nExtra = nRoot + FTS3_NODE_PADDING;
  132513. }
  132514. pReader = (Fts3SegReader *)sqlite3_malloc(sizeof(Fts3SegReader) + nExtra);
  132515. if( !pReader ){
  132516. return SQLITE_NOMEM;
  132517. }
  132518. memset(pReader, 0, sizeof(Fts3SegReader));
  132519. pReader->iIdx = iAge;
  132520. pReader->bLookup = bLookup!=0;
  132521. pReader->iStartBlock = iStartLeaf;
  132522. pReader->iLeafEndBlock = iEndLeaf;
  132523. pReader->iEndBlock = iEndBlock;
  132524. if( nExtra ){
  132525. /* The entire segment is stored in the root node. */
  132526. pReader->aNode = (char *)&pReader[1];
  132527. pReader->rootOnly = 1;
  132528. pReader->nNode = nRoot;
  132529. memcpy(pReader->aNode, zRoot, nRoot);
  132530. memset(&pReader->aNode[nRoot], 0, FTS3_NODE_PADDING);
  132531. }else{
  132532. pReader->iCurrentBlock = iStartLeaf-1;
  132533. }
  132534. *ppReader = pReader;
  132535. return SQLITE_OK;
  132536. }
  132537. /*
  132538. ** This is a comparison function used as a qsort() callback when sorting
  132539. ** an array of pending terms by term. This occurs as part of flushing
  132540. ** the contents of the pending-terms hash table to the database.
  132541. */
  132542. static int fts3CompareElemByTerm(const void *lhs, const void *rhs){
  132543. char *z1 = fts3HashKey(*(Fts3HashElem **)lhs);
  132544. char *z2 = fts3HashKey(*(Fts3HashElem **)rhs);
  132545. int n1 = fts3HashKeysize(*(Fts3HashElem **)lhs);
  132546. int n2 = fts3HashKeysize(*(Fts3HashElem **)rhs);
  132547. int n = (n1<n2 ? n1 : n2);
  132548. int c = memcmp(z1, z2, n);
  132549. if( c==0 ){
  132550. c = n1 - n2;
  132551. }
  132552. return c;
  132553. }
  132554. /*
  132555. ** This function is used to allocate an Fts3SegReader that iterates through
  132556. ** a subset of the terms stored in the Fts3Table.pendingTerms array.
  132557. **
  132558. ** If the isPrefixIter parameter is zero, then the returned SegReader iterates
  132559. ** through each term in the pending-terms table. Or, if isPrefixIter is
  132560. ** non-zero, it iterates through each term and its prefixes. For example, if
  132561. ** the pending terms hash table contains the terms "sqlite", "mysql" and
  132562. ** "firebird", then the iterator visits the following 'terms' (in the order
  132563. ** shown):
  132564. **
  132565. ** f fi fir fire fireb firebi firebir firebird
  132566. ** m my mys mysq mysql
  132567. ** s sq sql sqli sqlit sqlite
  132568. **
  132569. ** Whereas if isPrefixIter is zero, the terms visited are:
  132570. **
  132571. ** firebird mysql sqlite
  132572. */
  132573. SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(
  132574. Fts3Table *p, /* Virtual table handle */
  132575. int iIndex, /* Index for p->aIndex */
  132576. const char *zTerm, /* Term to search for */
  132577. int nTerm, /* Size of buffer zTerm */
  132578. int bPrefix, /* True for a prefix iterator */
  132579. Fts3SegReader **ppReader /* OUT: SegReader for pending-terms */
  132580. ){
  132581. Fts3SegReader *pReader = 0; /* Fts3SegReader object to return */
  132582. Fts3HashElem *pE; /* Iterator variable */
  132583. Fts3HashElem **aElem = 0; /* Array of term hash entries to scan */
  132584. int nElem = 0; /* Size of array at aElem */
  132585. int rc = SQLITE_OK; /* Return Code */
  132586. Fts3Hash *pHash;
  132587. pHash = &p->aIndex[iIndex].hPending;
  132588. if( bPrefix ){
  132589. int nAlloc = 0; /* Size of allocated array at aElem */
  132590. for(pE=fts3HashFirst(pHash); pE; pE=fts3HashNext(pE)){
  132591. char *zKey = (char *)fts3HashKey(pE);
  132592. int nKey = fts3HashKeysize(pE);
  132593. if( nTerm==0 || (nKey>=nTerm && 0==memcmp(zKey, zTerm, nTerm)) ){
  132594. if( nElem==nAlloc ){
  132595. Fts3HashElem **aElem2;
  132596. nAlloc += 16;
  132597. aElem2 = (Fts3HashElem **)sqlite3_realloc(
  132598. aElem, nAlloc*sizeof(Fts3HashElem *)
  132599. );
  132600. if( !aElem2 ){
  132601. rc = SQLITE_NOMEM;
  132602. nElem = 0;
  132603. break;
  132604. }
  132605. aElem = aElem2;
  132606. }
  132607. aElem[nElem++] = pE;
  132608. }
  132609. }
  132610. /* If more than one term matches the prefix, sort the Fts3HashElem
  132611. ** objects in term order using qsort(). This uses the same comparison
  132612. ** callback as is used when flushing terms to disk.
  132613. */
  132614. if( nElem>1 ){
  132615. qsort(aElem, nElem, sizeof(Fts3HashElem *), fts3CompareElemByTerm);
  132616. }
  132617. }else{
  132618. /* The query is a simple term lookup that matches at most one term in
  132619. ** the index. All that is required is a straight hash-lookup.
  132620. **
  132621. ** Because the stack address of pE may be accessed via the aElem pointer
  132622. ** below, the "Fts3HashElem *pE" must be declared so that it is valid
  132623. ** within this entire function, not just this "else{...}" block.
  132624. */
  132625. pE = fts3HashFindElem(pHash, zTerm, nTerm);
  132626. if( pE ){
  132627. aElem = &pE;
  132628. nElem = 1;
  132629. }
  132630. }
  132631. if( nElem>0 ){
  132632. int nByte = sizeof(Fts3SegReader) + (nElem+1)*sizeof(Fts3HashElem *);
  132633. pReader = (Fts3SegReader *)sqlite3_malloc(nByte);
  132634. if( !pReader ){
  132635. rc = SQLITE_NOMEM;
  132636. }else{
  132637. memset(pReader, 0, nByte);
  132638. pReader->iIdx = 0x7FFFFFFF;
  132639. pReader->ppNextElem = (Fts3HashElem **)&pReader[1];
  132640. memcpy(pReader->ppNextElem, aElem, nElem*sizeof(Fts3HashElem *));
  132641. }
  132642. }
  132643. if( bPrefix ){
  132644. sqlite3_free(aElem);
  132645. }
  132646. *ppReader = pReader;
  132647. return rc;
  132648. }
  132649. /*
  132650. ** Compare the entries pointed to by two Fts3SegReader structures.
  132651. ** Comparison is as follows:
  132652. **
  132653. ** 1) EOF is greater than not EOF.
  132654. **
  132655. ** 2) The current terms (if any) are compared using memcmp(). If one
  132656. ** term is a prefix of another, the longer term is considered the
  132657. ** larger.
  132658. **
  132659. ** 3) By segment age. An older segment is considered larger.
  132660. */
  132661. static int fts3SegReaderCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
  132662. int rc;
  132663. if( pLhs->aNode && pRhs->aNode ){
  132664. int rc2 = pLhs->nTerm - pRhs->nTerm;
  132665. if( rc2<0 ){
  132666. rc = memcmp(pLhs->zTerm, pRhs->zTerm, pLhs->nTerm);
  132667. }else{
  132668. rc = memcmp(pLhs->zTerm, pRhs->zTerm, pRhs->nTerm);
  132669. }
  132670. if( rc==0 ){
  132671. rc = rc2;
  132672. }
  132673. }else{
  132674. rc = (pLhs->aNode==0) - (pRhs->aNode==0);
  132675. }
  132676. if( rc==0 ){
  132677. rc = pRhs->iIdx - pLhs->iIdx;
  132678. }
  132679. assert( rc!=0 );
  132680. return rc;
  132681. }
  132682. /*
  132683. ** A different comparison function for SegReader structures. In this
  132684. ** version, it is assumed that each SegReader points to an entry in
  132685. ** a doclist for identical terms. Comparison is made as follows:
  132686. **
  132687. ** 1) EOF (end of doclist in this case) is greater than not EOF.
  132688. **
  132689. ** 2) By current docid.
  132690. **
  132691. ** 3) By segment age. An older segment is considered larger.
  132692. */
  132693. static int fts3SegReaderDoclistCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
  132694. int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
  132695. if( rc==0 ){
  132696. if( pLhs->iDocid==pRhs->iDocid ){
  132697. rc = pRhs->iIdx - pLhs->iIdx;
  132698. }else{
  132699. rc = (pLhs->iDocid > pRhs->iDocid) ? 1 : -1;
  132700. }
  132701. }
  132702. assert( pLhs->aNode && pRhs->aNode );
  132703. return rc;
  132704. }
  132705. static int fts3SegReaderDoclistCmpRev(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
  132706. int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
  132707. if( rc==0 ){
  132708. if( pLhs->iDocid==pRhs->iDocid ){
  132709. rc = pRhs->iIdx - pLhs->iIdx;
  132710. }else{
  132711. rc = (pLhs->iDocid < pRhs->iDocid) ? 1 : -1;
  132712. }
  132713. }
  132714. assert( pLhs->aNode && pRhs->aNode );
  132715. return rc;
  132716. }
  132717. /*
  132718. ** Compare the term that the Fts3SegReader object passed as the first argument
  132719. ** points to with the term specified by arguments zTerm and nTerm.
  132720. **
  132721. ** If the pSeg iterator is already at EOF, return 0. Otherwise, return
  132722. ** -ve if the pSeg term is less than zTerm/nTerm, 0 if the two terms are
  132723. ** equal, or +ve if the pSeg term is greater than zTerm/nTerm.
  132724. */
  132725. static int fts3SegReaderTermCmp(
  132726. Fts3SegReader *pSeg, /* Segment reader object */
  132727. const char *zTerm, /* Term to compare to */
  132728. int nTerm /* Size of term zTerm in bytes */
  132729. ){
  132730. int res = 0;
  132731. if( pSeg->aNode ){
  132732. if( pSeg->nTerm>nTerm ){
  132733. res = memcmp(pSeg->zTerm, zTerm, nTerm);
  132734. }else{
  132735. res = memcmp(pSeg->zTerm, zTerm, pSeg->nTerm);
  132736. }
  132737. if( res==0 ){
  132738. res = pSeg->nTerm-nTerm;
  132739. }
  132740. }
  132741. return res;
  132742. }
  132743. /*
  132744. ** Argument apSegment is an array of nSegment elements. It is known that
  132745. ** the final (nSegment-nSuspect) members are already in sorted order
  132746. ** (according to the comparison function provided). This function shuffles
  132747. ** the array around until all entries are in sorted order.
  132748. */
  132749. static void fts3SegReaderSort(
  132750. Fts3SegReader **apSegment, /* Array to sort entries of */
  132751. int nSegment, /* Size of apSegment array */
  132752. int nSuspect, /* Unsorted entry count */
  132753. int (*xCmp)(Fts3SegReader *, Fts3SegReader *) /* Comparison function */
  132754. ){
  132755. int i; /* Iterator variable */
  132756. assert( nSuspect<=nSegment );
  132757. if( nSuspect==nSegment ) nSuspect--;
  132758. for(i=nSuspect-1; i>=0; i--){
  132759. int j;
  132760. for(j=i; j<(nSegment-1); j++){
  132761. Fts3SegReader *pTmp;
  132762. if( xCmp(apSegment[j], apSegment[j+1])<0 ) break;
  132763. pTmp = apSegment[j+1];
  132764. apSegment[j+1] = apSegment[j];
  132765. apSegment[j] = pTmp;
  132766. }
  132767. }
  132768. #ifndef NDEBUG
  132769. /* Check that the list really is sorted now. */
  132770. for(i=0; i<(nSuspect-1); i++){
  132771. assert( xCmp(apSegment[i], apSegment[i+1])<0 );
  132772. }
  132773. #endif
  132774. }
  132775. /*
  132776. ** Insert a record into the %_segments table.
  132777. */
  132778. static int fts3WriteSegment(
  132779. Fts3Table *p, /* Virtual table handle */
  132780. sqlite3_int64 iBlock, /* Block id for new block */
  132781. char *z, /* Pointer to buffer containing block data */
  132782. int n /* Size of buffer z in bytes */
  132783. ){
  132784. sqlite3_stmt *pStmt;
  132785. int rc = fts3SqlStmt(p, SQL_INSERT_SEGMENTS, &pStmt, 0);
  132786. if( rc==SQLITE_OK ){
  132787. sqlite3_bind_int64(pStmt, 1, iBlock);
  132788. sqlite3_bind_blob(pStmt, 2, z, n, SQLITE_STATIC);
  132789. sqlite3_step(pStmt);
  132790. rc = sqlite3_reset(pStmt);
  132791. }
  132792. return rc;
  132793. }
  132794. /*
  132795. ** Find the largest relative level number in the table. If successful, set
  132796. ** *pnMax to this value and return SQLITE_OK. Otherwise, if an error occurs,
  132797. ** set *pnMax to zero and return an SQLite error code.
  132798. */
  132799. SQLITE_PRIVATE int sqlite3Fts3MaxLevel(Fts3Table *p, int *pnMax){
  132800. int rc;
  132801. int mxLevel = 0;
  132802. sqlite3_stmt *pStmt = 0;
  132803. rc = fts3SqlStmt(p, SQL_SELECT_MXLEVEL, &pStmt, 0);
  132804. if( rc==SQLITE_OK ){
  132805. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  132806. mxLevel = sqlite3_column_int(pStmt, 0);
  132807. }
  132808. rc = sqlite3_reset(pStmt);
  132809. }
  132810. *pnMax = mxLevel;
  132811. return rc;
  132812. }
  132813. /*
  132814. ** Insert a record into the %_segdir table.
  132815. */
  132816. static int fts3WriteSegdir(
  132817. Fts3Table *p, /* Virtual table handle */
  132818. sqlite3_int64 iLevel, /* Value for "level" field (absolute level) */
  132819. int iIdx, /* Value for "idx" field */
  132820. sqlite3_int64 iStartBlock, /* Value for "start_block" field */
  132821. sqlite3_int64 iLeafEndBlock, /* Value for "leaves_end_block" field */
  132822. sqlite3_int64 iEndBlock, /* Value for "end_block" field */
  132823. sqlite3_int64 nLeafData, /* Bytes of leaf data in segment */
  132824. char *zRoot, /* Blob value for "root" field */
  132825. int nRoot /* Number of bytes in buffer zRoot */
  132826. ){
  132827. sqlite3_stmt *pStmt;
  132828. int rc = fts3SqlStmt(p, SQL_INSERT_SEGDIR, &pStmt, 0);
  132829. if( rc==SQLITE_OK ){
  132830. sqlite3_bind_int64(pStmt, 1, iLevel);
  132831. sqlite3_bind_int(pStmt, 2, iIdx);
  132832. sqlite3_bind_int64(pStmt, 3, iStartBlock);
  132833. sqlite3_bind_int64(pStmt, 4, iLeafEndBlock);
  132834. if( nLeafData==0 ){
  132835. sqlite3_bind_int64(pStmt, 5, iEndBlock);
  132836. }else{
  132837. char *zEnd = sqlite3_mprintf("%lld %lld", iEndBlock, nLeafData);
  132838. if( !zEnd ) return SQLITE_NOMEM;
  132839. sqlite3_bind_text(pStmt, 5, zEnd, -1, sqlite3_free);
  132840. }
  132841. sqlite3_bind_blob(pStmt, 6, zRoot, nRoot, SQLITE_STATIC);
  132842. sqlite3_step(pStmt);
  132843. rc = sqlite3_reset(pStmt);
  132844. }
  132845. return rc;
  132846. }
  132847. /*
  132848. ** Return the size of the common prefix (if any) shared by zPrev and
  132849. ** zNext, in bytes. For example,
  132850. **
  132851. ** fts3PrefixCompress("abc", 3, "abcdef", 6) // returns 3
  132852. ** fts3PrefixCompress("abX", 3, "abcdef", 6) // returns 2
  132853. ** fts3PrefixCompress("abX", 3, "Xbcdef", 6) // returns 0
  132854. */
  132855. static int fts3PrefixCompress(
  132856. const char *zPrev, /* Buffer containing previous term */
  132857. int nPrev, /* Size of buffer zPrev in bytes */
  132858. const char *zNext, /* Buffer containing next term */
  132859. int nNext /* Size of buffer zNext in bytes */
  132860. ){
  132861. int n;
  132862. UNUSED_PARAMETER(nNext);
  132863. for(n=0; n<nPrev && zPrev[n]==zNext[n]; n++);
  132864. return n;
  132865. }
  132866. /*
  132867. ** Add term zTerm to the SegmentNode. It is guaranteed that zTerm is larger
  132868. ** (according to memcmp) than the previous term.
  132869. */
  132870. static int fts3NodeAddTerm(
  132871. Fts3Table *p, /* Virtual table handle */
  132872. SegmentNode **ppTree, /* IN/OUT: SegmentNode handle */
  132873. int isCopyTerm, /* True if zTerm/nTerm is transient */
  132874. const char *zTerm, /* Pointer to buffer containing term */
  132875. int nTerm /* Size of term in bytes */
  132876. ){
  132877. SegmentNode *pTree = *ppTree;
  132878. int rc;
  132879. SegmentNode *pNew;
  132880. /* First try to append the term to the current node. Return early if
  132881. ** this is possible.
  132882. */
  132883. if( pTree ){
  132884. int nData = pTree->nData; /* Current size of node in bytes */
  132885. int nReq = nData; /* Required space after adding zTerm */
  132886. int nPrefix; /* Number of bytes of prefix compression */
  132887. int nSuffix; /* Suffix length */
  132888. nPrefix = fts3PrefixCompress(pTree->zTerm, pTree->nTerm, zTerm, nTerm);
  132889. nSuffix = nTerm-nPrefix;
  132890. nReq += sqlite3Fts3VarintLen(nPrefix)+sqlite3Fts3VarintLen(nSuffix)+nSuffix;
  132891. if( nReq<=p->nNodeSize || !pTree->zTerm ){
  132892. if( nReq>p->nNodeSize ){
  132893. /* An unusual case: this is the first term to be added to the node
  132894. ** and the static node buffer (p->nNodeSize bytes) is not large
  132895. ** enough. Use a separately malloced buffer instead This wastes
  132896. ** p->nNodeSize bytes, but since this scenario only comes about when
  132897. ** the database contain two terms that share a prefix of almost 2KB,
  132898. ** this is not expected to be a serious problem.
  132899. */
  132900. assert( pTree->aData==(char *)&pTree[1] );
  132901. pTree->aData = (char *)sqlite3_malloc(nReq);
  132902. if( !pTree->aData ){
  132903. return SQLITE_NOMEM;
  132904. }
  132905. }
  132906. if( pTree->zTerm ){
  132907. /* There is no prefix-length field for first term in a node */
  132908. nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nPrefix);
  132909. }
  132910. nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nSuffix);
  132911. memcpy(&pTree->aData[nData], &zTerm[nPrefix], nSuffix);
  132912. pTree->nData = nData + nSuffix;
  132913. pTree->nEntry++;
  132914. if( isCopyTerm ){
  132915. if( pTree->nMalloc<nTerm ){
  132916. char *zNew = sqlite3_realloc(pTree->zMalloc, nTerm*2);
  132917. if( !zNew ){
  132918. return SQLITE_NOMEM;
  132919. }
  132920. pTree->nMalloc = nTerm*2;
  132921. pTree->zMalloc = zNew;
  132922. }
  132923. pTree->zTerm = pTree->zMalloc;
  132924. memcpy(pTree->zTerm, zTerm, nTerm);
  132925. pTree->nTerm = nTerm;
  132926. }else{
  132927. pTree->zTerm = (char *)zTerm;
  132928. pTree->nTerm = nTerm;
  132929. }
  132930. return SQLITE_OK;
  132931. }
  132932. }
  132933. /* If control flows to here, it was not possible to append zTerm to the
  132934. ** current node. Create a new node (a right-sibling of the current node).
  132935. ** If this is the first node in the tree, the term is added to it.
  132936. **
  132937. ** Otherwise, the term is not added to the new node, it is left empty for
  132938. ** now. Instead, the term is inserted into the parent of pTree. If pTree
  132939. ** has no parent, one is created here.
  132940. */
  132941. pNew = (SegmentNode *)sqlite3_malloc(sizeof(SegmentNode) + p->nNodeSize);
  132942. if( !pNew ){
  132943. return SQLITE_NOMEM;
  132944. }
  132945. memset(pNew, 0, sizeof(SegmentNode));
  132946. pNew->nData = 1 + FTS3_VARINT_MAX;
  132947. pNew->aData = (char *)&pNew[1];
  132948. if( pTree ){
  132949. SegmentNode *pParent = pTree->pParent;
  132950. rc = fts3NodeAddTerm(p, &pParent, isCopyTerm, zTerm, nTerm);
  132951. if( pTree->pParent==0 ){
  132952. pTree->pParent = pParent;
  132953. }
  132954. pTree->pRight = pNew;
  132955. pNew->pLeftmost = pTree->pLeftmost;
  132956. pNew->pParent = pParent;
  132957. pNew->zMalloc = pTree->zMalloc;
  132958. pNew->nMalloc = pTree->nMalloc;
  132959. pTree->zMalloc = 0;
  132960. }else{
  132961. pNew->pLeftmost = pNew;
  132962. rc = fts3NodeAddTerm(p, &pNew, isCopyTerm, zTerm, nTerm);
  132963. }
  132964. *ppTree = pNew;
  132965. return rc;
  132966. }
  132967. /*
  132968. ** Helper function for fts3NodeWrite().
  132969. */
  132970. static int fts3TreeFinishNode(
  132971. SegmentNode *pTree,
  132972. int iHeight,
  132973. sqlite3_int64 iLeftChild
  132974. ){
  132975. int nStart;
  132976. assert( iHeight>=1 && iHeight<128 );
  132977. nStart = FTS3_VARINT_MAX - sqlite3Fts3VarintLen(iLeftChild);
  132978. pTree->aData[nStart] = (char)iHeight;
  132979. sqlite3Fts3PutVarint(&pTree->aData[nStart+1], iLeftChild);
  132980. return nStart;
  132981. }
  132982. /*
  132983. ** Write the buffer for the segment node pTree and all of its peers to the
  132984. ** database. Then call this function recursively to write the parent of
  132985. ** pTree and its peers to the database.
  132986. **
  132987. ** Except, if pTree is a root node, do not write it to the database. Instead,
  132988. ** set output variables *paRoot and *pnRoot to contain the root node.
  132989. **
  132990. ** If successful, SQLITE_OK is returned and output variable *piLast is
  132991. ** set to the largest blockid written to the database (or zero if no
  132992. ** blocks were written to the db). Otherwise, an SQLite error code is
  132993. ** returned.
  132994. */
  132995. static int fts3NodeWrite(
  132996. Fts3Table *p, /* Virtual table handle */
  132997. SegmentNode *pTree, /* SegmentNode handle */
  132998. int iHeight, /* Height of this node in tree */
  132999. sqlite3_int64 iLeaf, /* Block id of first leaf node */
  133000. sqlite3_int64 iFree, /* Block id of next free slot in %_segments */
  133001. sqlite3_int64 *piLast, /* OUT: Block id of last entry written */
  133002. char **paRoot, /* OUT: Data for root node */
  133003. int *pnRoot /* OUT: Size of root node in bytes */
  133004. ){
  133005. int rc = SQLITE_OK;
  133006. if( !pTree->pParent ){
  133007. /* Root node of the tree. */
  133008. int nStart = fts3TreeFinishNode(pTree, iHeight, iLeaf);
  133009. *piLast = iFree-1;
  133010. *pnRoot = pTree->nData - nStart;
  133011. *paRoot = &pTree->aData[nStart];
  133012. }else{
  133013. SegmentNode *pIter;
  133014. sqlite3_int64 iNextFree = iFree;
  133015. sqlite3_int64 iNextLeaf = iLeaf;
  133016. for(pIter=pTree->pLeftmost; pIter && rc==SQLITE_OK; pIter=pIter->pRight){
  133017. int nStart = fts3TreeFinishNode(pIter, iHeight, iNextLeaf);
  133018. int nWrite = pIter->nData - nStart;
  133019. rc = fts3WriteSegment(p, iNextFree, &pIter->aData[nStart], nWrite);
  133020. iNextFree++;
  133021. iNextLeaf += (pIter->nEntry+1);
  133022. }
  133023. if( rc==SQLITE_OK ){
  133024. assert( iNextLeaf==iFree );
  133025. rc = fts3NodeWrite(
  133026. p, pTree->pParent, iHeight+1, iFree, iNextFree, piLast, paRoot, pnRoot
  133027. );
  133028. }
  133029. }
  133030. return rc;
  133031. }
  133032. /*
  133033. ** Free all memory allocations associated with the tree pTree.
  133034. */
  133035. static void fts3NodeFree(SegmentNode *pTree){
  133036. if( pTree ){
  133037. SegmentNode *p = pTree->pLeftmost;
  133038. fts3NodeFree(p->pParent);
  133039. while( p ){
  133040. SegmentNode *pRight = p->pRight;
  133041. if( p->aData!=(char *)&p[1] ){
  133042. sqlite3_free(p->aData);
  133043. }
  133044. assert( pRight==0 || p->zMalloc==0 );
  133045. sqlite3_free(p->zMalloc);
  133046. sqlite3_free(p);
  133047. p = pRight;
  133048. }
  133049. }
  133050. }
  133051. /*
  133052. ** Add a term to the segment being constructed by the SegmentWriter object
  133053. ** *ppWriter. When adding the first term to a segment, *ppWriter should
  133054. ** be passed NULL. This function will allocate a new SegmentWriter object
  133055. ** and return it via the input/output variable *ppWriter in this case.
  133056. **
  133057. ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
  133058. */
  133059. static int fts3SegWriterAdd(
  133060. Fts3Table *p, /* Virtual table handle */
  133061. SegmentWriter **ppWriter, /* IN/OUT: SegmentWriter handle */
  133062. int isCopyTerm, /* True if buffer zTerm must be copied */
  133063. const char *zTerm, /* Pointer to buffer containing term */
  133064. int nTerm, /* Size of term in bytes */
  133065. const char *aDoclist, /* Pointer to buffer containing doclist */
  133066. int nDoclist /* Size of doclist in bytes */
  133067. ){
  133068. int nPrefix; /* Size of term prefix in bytes */
  133069. int nSuffix; /* Size of term suffix in bytes */
  133070. int nReq; /* Number of bytes required on leaf page */
  133071. int nData;
  133072. SegmentWriter *pWriter = *ppWriter;
  133073. if( !pWriter ){
  133074. int rc;
  133075. sqlite3_stmt *pStmt;
  133076. /* Allocate the SegmentWriter structure */
  133077. pWriter = (SegmentWriter *)sqlite3_malloc(sizeof(SegmentWriter));
  133078. if( !pWriter ) return SQLITE_NOMEM;
  133079. memset(pWriter, 0, sizeof(SegmentWriter));
  133080. *ppWriter = pWriter;
  133081. /* Allocate a buffer in which to accumulate data */
  133082. pWriter->aData = (char *)sqlite3_malloc(p->nNodeSize);
  133083. if( !pWriter->aData ) return SQLITE_NOMEM;
  133084. pWriter->nSize = p->nNodeSize;
  133085. /* Find the next free blockid in the %_segments table */
  133086. rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pStmt, 0);
  133087. if( rc!=SQLITE_OK ) return rc;
  133088. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  133089. pWriter->iFree = sqlite3_column_int64(pStmt, 0);
  133090. pWriter->iFirst = pWriter->iFree;
  133091. }
  133092. rc = sqlite3_reset(pStmt);
  133093. if( rc!=SQLITE_OK ) return rc;
  133094. }
  133095. nData = pWriter->nData;
  133096. nPrefix = fts3PrefixCompress(pWriter->zTerm, pWriter->nTerm, zTerm, nTerm);
  133097. nSuffix = nTerm-nPrefix;
  133098. /* Figure out how many bytes are required by this new entry */
  133099. nReq = sqlite3Fts3VarintLen(nPrefix) + /* varint containing prefix size */
  133100. sqlite3Fts3VarintLen(nSuffix) + /* varint containing suffix size */
  133101. nSuffix + /* Term suffix */
  133102. sqlite3Fts3VarintLen(nDoclist) + /* Size of doclist */
  133103. nDoclist; /* Doclist data */
  133104. if( nData>0 && nData+nReq>p->nNodeSize ){
  133105. int rc;
  133106. /* The current leaf node is full. Write it out to the database. */
  133107. rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, nData);
  133108. if( rc!=SQLITE_OK ) return rc;
  133109. p->nLeafAdd++;
  133110. /* Add the current term to the interior node tree. The term added to
  133111. ** the interior tree must:
  133112. **
  133113. ** a) be greater than the largest term on the leaf node just written
  133114. ** to the database (still available in pWriter->zTerm), and
  133115. **
  133116. ** b) be less than or equal to the term about to be added to the new
  133117. ** leaf node (zTerm/nTerm).
  133118. **
  133119. ** In other words, it must be the prefix of zTerm 1 byte longer than
  133120. ** the common prefix (if any) of zTerm and pWriter->zTerm.
  133121. */
  133122. assert( nPrefix<nTerm );
  133123. rc = fts3NodeAddTerm(p, &pWriter->pTree, isCopyTerm, zTerm, nPrefix+1);
  133124. if( rc!=SQLITE_OK ) return rc;
  133125. nData = 0;
  133126. pWriter->nTerm = 0;
  133127. nPrefix = 0;
  133128. nSuffix = nTerm;
  133129. nReq = 1 + /* varint containing prefix size */
  133130. sqlite3Fts3VarintLen(nTerm) + /* varint containing suffix size */
  133131. nTerm + /* Term suffix */
  133132. sqlite3Fts3VarintLen(nDoclist) + /* Size of doclist */
  133133. nDoclist; /* Doclist data */
  133134. }
  133135. /* Increase the total number of bytes written to account for the new entry. */
  133136. pWriter->nLeafData += nReq;
  133137. /* If the buffer currently allocated is too small for this entry, realloc
  133138. ** the buffer to make it large enough.
  133139. */
  133140. if( nReq>pWriter->nSize ){
  133141. char *aNew = sqlite3_realloc(pWriter->aData, nReq);
  133142. if( !aNew ) return SQLITE_NOMEM;
  133143. pWriter->aData = aNew;
  133144. pWriter->nSize = nReq;
  133145. }
  133146. assert( nData+nReq<=pWriter->nSize );
  133147. /* Append the prefix-compressed term and doclist to the buffer. */
  133148. nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nPrefix);
  133149. nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nSuffix);
  133150. memcpy(&pWriter->aData[nData], &zTerm[nPrefix], nSuffix);
  133151. nData += nSuffix;
  133152. nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nDoclist);
  133153. memcpy(&pWriter->aData[nData], aDoclist, nDoclist);
  133154. pWriter->nData = nData + nDoclist;
  133155. /* Save the current term so that it can be used to prefix-compress the next.
  133156. ** If the isCopyTerm parameter is true, then the buffer pointed to by
  133157. ** zTerm is transient, so take a copy of the term data. Otherwise, just
  133158. ** store a copy of the pointer.
  133159. */
  133160. if( isCopyTerm ){
  133161. if( nTerm>pWriter->nMalloc ){
  133162. char *zNew = sqlite3_realloc(pWriter->zMalloc, nTerm*2);
  133163. if( !zNew ){
  133164. return SQLITE_NOMEM;
  133165. }
  133166. pWriter->nMalloc = nTerm*2;
  133167. pWriter->zMalloc = zNew;
  133168. pWriter->zTerm = zNew;
  133169. }
  133170. assert( pWriter->zTerm==pWriter->zMalloc );
  133171. memcpy(pWriter->zTerm, zTerm, nTerm);
  133172. }else{
  133173. pWriter->zTerm = (char *)zTerm;
  133174. }
  133175. pWriter->nTerm = nTerm;
  133176. return SQLITE_OK;
  133177. }
  133178. /*
  133179. ** Flush all data associated with the SegmentWriter object pWriter to the
  133180. ** database. This function must be called after all terms have been added
  133181. ** to the segment using fts3SegWriterAdd(). If successful, SQLITE_OK is
  133182. ** returned. Otherwise, an SQLite error code.
  133183. */
  133184. static int fts3SegWriterFlush(
  133185. Fts3Table *p, /* Virtual table handle */
  133186. SegmentWriter *pWriter, /* SegmentWriter to flush to the db */
  133187. sqlite3_int64 iLevel, /* Value for 'level' column of %_segdir */
  133188. int iIdx /* Value for 'idx' column of %_segdir */
  133189. ){
  133190. int rc; /* Return code */
  133191. if( pWriter->pTree ){
  133192. sqlite3_int64 iLast = 0; /* Largest block id written to database */
  133193. sqlite3_int64 iLastLeaf; /* Largest leaf block id written to db */
  133194. char *zRoot = NULL; /* Pointer to buffer containing root node */
  133195. int nRoot = 0; /* Size of buffer zRoot */
  133196. iLastLeaf = pWriter->iFree;
  133197. rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, pWriter->nData);
  133198. if( rc==SQLITE_OK ){
  133199. rc = fts3NodeWrite(p, pWriter->pTree, 1,
  133200. pWriter->iFirst, pWriter->iFree, &iLast, &zRoot, &nRoot);
  133201. }
  133202. if( rc==SQLITE_OK ){
  133203. rc = fts3WriteSegdir(p, iLevel, iIdx,
  133204. pWriter->iFirst, iLastLeaf, iLast, pWriter->nLeafData, zRoot, nRoot);
  133205. }
  133206. }else{
  133207. /* The entire tree fits on the root node. Write it to the segdir table. */
  133208. rc = fts3WriteSegdir(p, iLevel, iIdx,
  133209. 0, 0, 0, pWriter->nLeafData, pWriter->aData, pWriter->nData);
  133210. }
  133211. p->nLeafAdd++;
  133212. return rc;
  133213. }
  133214. /*
  133215. ** Release all memory held by the SegmentWriter object passed as the
  133216. ** first argument.
  133217. */
  133218. static void fts3SegWriterFree(SegmentWriter *pWriter){
  133219. if( pWriter ){
  133220. sqlite3_free(pWriter->aData);
  133221. sqlite3_free(pWriter->zMalloc);
  133222. fts3NodeFree(pWriter->pTree);
  133223. sqlite3_free(pWriter);
  133224. }
  133225. }
  133226. /*
  133227. ** The first value in the apVal[] array is assumed to contain an integer.
  133228. ** This function tests if there exist any documents with docid values that
  133229. ** are different from that integer. i.e. if deleting the document with docid
  133230. ** pRowid would mean the FTS3 table were empty.
  133231. **
  133232. ** If successful, *pisEmpty is set to true if the table is empty except for
  133233. ** document pRowid, or false otherwise, and SQLITE_OK is returned. If an
  133234. ** error occurs, an SQLite error code is returned.
  133235. */
  133236. static int fts3IsEmpty(Fts3Table *p, sqlite3_value *pRowid, int *pisEmpty){
  133237. sqlite3_stmt *pStmt;
  133238. int rc;
  133239. if( p->zContentTbl ){
  133240. /* If using the content=xxx option, assume the table is never empty */
  133241. *pisEmpty = 0;
  133242. rc = SQLITE_OK;
  133243. }else{
  133244. rc = fts3SqlStmt(p, SQL_IS_EMPTY, &pStmt, &pRowid);
  133245. if( rc==SQLITE_OK ){
  133246. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  133247. *pisEmpty = sqlite3_column_int(pStmt, 0);
  133248. }
  133249. rc = sqlite3_reset(pStmt);
  133250. }
  133251. }
  133252. return rc;
  133253. }
  133254. /*
  133255. ** Set *pnMax to the largest segment level in the database for the index
  133256. ** iIndex.
  133257. **
  133258. ** Segment levels are stored in the 'level' column of the %_segdir table.
  133259. **
  133260. ** Return SQLITE_OK if successful, or an SQLite error code if not.
  133261. */
  133262. static int fts3SegmentMaxLevel(
  133263. Fts3Table *p,
  133264. int iLangid,
  133265. int iIndex,
  133266. sqlite3_int64 *pnMax
  133267. ){
  133268. sqlite3_stmt *pStmt;
  133269. int rc;
  133270. assert( iIndex>=0 && iIndex<p->nIndex );
  133271. /* Set pStmt to the compiled version of:
  133272. **
  133273. ** SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?
  133274. **
  133275. ** (1024 is actually the value of macro FTS3_SEGDIR_PREFIXLEVEL_STR).
  133276. */
  133277. rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR_MAX_LEVEL, &pStmt, 0);
  133278. if( rc!=SQLITE_OK ) return rc;
  133279. sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
  133280. sqlite3_bind_int64(pStmt, 2,
  133281. getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
  133282. );
  133283. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  133284. *pnMax = sqlite3_column_int64(pStmt, 0);
  133285. }
  133286. return sqlite3_reset(pStmt);
  133287. }
  133288. /*
  133289. ** iAbsLevel is an absolute level that may be assumed to exist within
  133290. ** the database. This function checks if it is the largest level number
  133291. ** within its index. Assuming no error occurs, *pbMax is set to 1 if
  133292. ** iAbsLevel is indeed the largest level, or 0 otherwise, and SQLITE_OK
  133293. ** is returned. If an error occurs, an error code is returned and the
  133294. ** final value of *pbMax is undefined.
  133295. */
  133296. static int fts3SegmentIsMaxLevel(Fts3Table *p, i64 iAbsLevel, int *pbMax){
  133297. /* Set pStmt to the compiled version of:
  133298. **
  133299. ** SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?
  133300. **
  133301. ** (1024 is actually the value of macro FTS3_SEGDIR_PREFIXLEVEL_STR).
  133302. */
  133303. sqlite3_stmt *pStmt;
  133304. int rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR_MAX_LEVEL, &pStmt, 0);
  133305. if( rc!=SQLITE_OK ) return rc;
  133306. sqlite3_bind_int64(pStmt, 1, iAbsLevel+1);
  133307. sqlite3_bind_int64(pStmt, 2,
  133308. ((iAbsLevel/FTS3_SEGDIR_MAXLEVEL)+1) * FTS3_SEGDIR_MAXLEVEL
  133309. );
  133310. *pbMax = 0;
  133311. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  133312. *pbMax = sqlite3_column_type(pStmt, 0)==SQLITE_NULL;
  133313. }
  133314. return sqlite3_reset(pStmt);
  133315. }
  133316. /*
  133317. ** Delete all entries in the %_segments table associated with the segment
  133318. ** opened with seg-reader pSeg. This function does not affect the contents
  133319. ** of the %_segdir table.
  133320. */
  133321. static int fts3DeleteSegment(
  133322. Fts3Table *p, /* FTS table handle */
  133323. Fts3SegReader *pSeg /* Segment to delete */
  133324. ){
  133325. int rc = SQLITE_OK; /* Return code */
  133326. if( pSeg->iStartBlock ){
  133327. sqlite3_stmt *pDelete; /* SQL statement to delete rows */
  133328. rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDelete, 0);
  133329. if( rc==SQLITE_OK ){
  133330. sqlite3_bind_int64(pDelete, 1, pSeg->iStartBlock);
  133331. sqlite3_bind_int64(pDelete, 2, pSeg->iEndBlock);
  133332. sqlite3_step(pDelete);
  133333. rc = sqlite3_reset(pDelete);
  133334. }
  133335. }
  133336. return rc;
  133337. }
  133338. /*
  133339. ** This function is used after merging multiple segments into a single large
  133340. ** segment to delete the old, now redundant, segment b-trees. Specifically,
  133341. ** it:
  133342. **
  133343. ** 1) Deletes all %_segments entries for the segments associated with
  133344. ** each of the SegReader objects in the array passed as the third
  133345. ** argument, and
  133346. **
  133347. ** 2) deletes all %_segdir entries with level iLevel, or all %_segdir
  133348. ** entries regardless of level if (iLevel<0).
  133349. **
  133350. ** SQLITE_OK is returned if successful, otherwise an SQLite error code.
  133351. */
  133352. static int fts3DeleteSegdir(
  133353. Fts3Table *p, /* Virtual table handle */
  133354. int iLangid, /* Language id */
  133355. int iIndex, /* Index for p->aIndex */
  133356. int iLevel, /* Level of %_segdir entries to delete */
  133357. Fts3SegReader **apSegment, /* Array of SegReader objects */
  133358. int nReader /* Size of array apSegment */
  133359. ){
  133360. int rc = SQLITE_OK; /* Return Code */
  133361. int i; /* Iterator variable */
  133362. sqlite3_stmt *pDelete = 0; /* SQL statement to delete rows */
  133363. for(i=0; rc==SQLITE_OK && i<nReader; i++){
  133364. rc = fts3DeleteSegment(p, apSegment[i]);
  133365. }
  133366. if( rc!=SQLITE_OK ){
  133367. return rc;
  133368. }
  133369. assert( iLevel>=0 || iLevel==FTS3_SEGCURSOR_ALL );
  133370. if( iLevel==FTS3_SEGCURSOR_ALL ){
  133371. rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_RANGE, &pDelete, 0);
  133372. if( rc==SQLITE_OK ){
  133373. sqlite3_bind_int64(pDelete, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
  133374. sqlite3_bind_int64(pDelete, 2,
  133375. getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
  133376. );
  133377. }
  133378. }else{
  133379. rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_LEVEL, &pDelete, 0);
  133380. if( rc==SQLITE_OK ){
  133381. sqlite3_bind_int64(
  133382. pDelete, 1, getAbsoluteLevel(p, iLangid, iIndex, iLevel)
  133383. );
  133384. }
  133385. }
  133386. if( rc==SQLITE_OK ){
  133387. sqlite3_step(pDelete);
  133388. rc = sqlite3_reset(pDelete);
  133389. }
  133390. return rc;
  133391. }
  133392. /*
  133393. ** When this function is called, buffer *ppList (size *pnList bytes) contains
  133394. ** a position list that may (or may not) feature multiple columns. This
  133395. ** function adjusts the pointer *ppList and the length *pnList so that they
  133396. ** identify the subset of the position list that corresponds to column iCol.
  133397. **
  133398. ** If there are no entries in the input position list for column iCol, then
  133399. ** *pnList is set to zero before returning.
  133400. **
  133401. ** If parameter bZero is non-zero, then any part of the input list following
  133402. ** the end of the output list is zeroed before returning.
  133403. */
  133404. static void fts3ColumnFilter(
  133405. int iCol, /* Column to filter on */
  133406. int bZero, /* Zero out anything following *ppList */
  133407. char **ppList, /* IN/OUT: Pointer to position list */
  133408. int *pnList /* IN/OUT: Size of buffer *ppList in bytes */
  133409. ){
  133410. char *pList = *ppList;
  133411. int nList = *pnList;
  133412. char *pEnd = &pList[nList];
  133413. int iCurrent = 0;
  133414. char *p = pList;
  133415. assert( iCol>=0 );
  133416. while( 1 ){
  133417. char c = 0;
  133418. while( p<pEnd && (c | *p)&0xFE ) c = *p++ & 0x80;
  133419. if( iCol==iCurrent ){
  133420. nList = (int)(p - pList);
  133421. break;
  133422. }
  133423. nList -= (int)(p - pList);
  133424. pList = p;
  133425. if( nList==0 ){
  133426. break;
  133427. }
  133428. p = &pList[1];
  133429. p += fts3GetVarint32(p, &iCurrent);
  133430. }
  133431. if( bZero && &pList[nList]!=pEnd ){
  133432. memset(&pList[nList], 0, pEnd - &pList[nList]);
  133433. }
  133434. *ppList = pList;
  133435. *pnList = nList;
  133436. }
  133437. /*
  133438. ** Cache data in the Fts3MultiSegReader.aBuffer[] buffer (overwriting any
  133439. ** existing data). Grow the buffer if required.
  133440. **
  133441. ** If successful, return SQLITE_OK. Otherwise, if an OOM error is encountered
  133442. ** trying to resize the buffer, return SQLITE_NOMEM.
  133443. */
  133444. static int fts3MsrBufferData(
  133445. Fts3MultiSegReader *pMsr, /* Multi-segment-reader handle */
  133446. char *pList,
  133447. int nList
  133448. ){
  133449. if( nList>pMsr->nBuffer ){
  133450. char *pNew;
  133451. pMsr->nBuffer = nList*2;
  133452. pNew = (char *)sqlite3_realloc(pMsr->aBuffer, pMsr->nBuffer);
  133453. if( !pNew ) return SQLITE_NOMEM;
  133454. pMsr->aBuffer = pNew;
  133455. }
  133456. memcpy(pMsr->aBuffer, pList, nList);
  133457. return SQLITE_OK;
  133458. }
  133459. SQLITE_PRIVATE int sqlite3Fts3MsrIncrNext(
  133460. Fts3Table *p, /* Virtual table handle */
  133461. Fts3MultiSegReader *pMsr, /* Multi-segment-reader handle */
  133462. sqlite3_int64 *piDocid, /* OUT: Docid value */
  133463. char **paPoslist, /* OUT: Pointer to position list */
  133464. int *pnPoslist /* OUT: Size of position list in bytes */
  133465. ){
  133466. int nMerge = pMsr->nAdvance;
  133467. Fts3SegReader **apSegment = pMsr->apSegment;
  133468. int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
  133469. p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
  133470. );
  133471. if( nMerge==0 ){
  133472. *paPoslist = 0;
  133473. return SQLITE_OK;
  133474. }
  133475. while( 1 ){
  133476. Fts3SegReader *pSeg;
  133477. pSeg = pMsr->apSegment[0];
  133478. if( pSeg->pOffsetList==0 ){
  133479. *paPoslist = 0;
  133480. break;
  133481. }else{
  133482. int rc;
  133483. char *pList;
  133484. int nList;
  133485. int j;
  133486. sqlite3_int64 iDocid = apSegment[0]->iDocid;
  133487. rc = fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList);
  133488. j = 1;
  133489. while( rc==SQLITE_OK
  133490. && j<nMerge
  133491. && apSegment[j]->pOffsetList
  133492. && apSegment[j]->iDocid==iDocid
  133493. ){
  133494. rc = fts3SegReaderNextDocid(p, apSegment[j], 0, 0);
  133495. j++;
  133496. }
  133497. if( rc!=SQLITE_OK ) return rc;
  133498. fts3SegReaderSort(pMsr->apSegment, nMerge, j, xCmp);
  133499. if( nList>0 && fts3SegReaderIsPending(apSegment[0]) ){
  133500. rc = fts3MsrBufferData(pMsr, pList, nList+1);
  133501. if( rc!=SQLITE_OK ) return rc;
  133502. assert( (pMsr->aBuffer[nList] & 0xFE)==0x00 );
  133503. pList = pMsr->aBuffer;
  133504. }
  133505. if( pMsr->iColFilter>=0 ){
  133506. fts3ColumnFilter(pMsr->iColFilter, 1, &pList, &nList);
  133507. }
  133508. if( nList>0 ){
  133509. *paPoslist = pList;
  133510. *piDocid = iDocid;
  133511. *pnPoslist = nList;
  133512. break;
  133513. }
  133514. }
  133515. }
  133516. return SQLITE_OK;
  133517. }
  133518. static int fts3SegReaderStart(
  133519. Fts3Table *p, /* Virtual table handle */
  133520. Fts3MultiSegReader *pCsr, /* Cursor object */
  133521. const char *zTerm, /* Term searched for (or NULL) */
  133522. int nTerm /* Length of zTerm in bytes */
  133523. ){
  133524. int i;
  133525. int nSeg = pCsr->nSegment;
  133526. /* If the Fts3SegFilter defines a specific term (or term prefix) to search
  133527. ** for, then advance each segment iterator until it points to a term of
  133528. ** equal or greater value than the specified term. This prevents many
  133529. ** unnecessary merge/sort operations for the case where single segment
  133530. ** b-tree leaf nodes contain more than one term.
  133531. */
  133532. for(i=0; pCsr->bRestart==0 && i<pCsr->nSegment; i++){
  133533. int res = 0;
  133534. Fts3SegReader *pSeg = pCsr->apSegment[i];
  133535. do {
  133536. int rc = fts3SegReaderNext(p, pSeg, 0);
  133537. if( rc!=SQLITE_OK ) return rc;
  133538. }while( zTerm && (res = fts3SegReaderTermCmp(pSeg, zTerm, nTerm))<0 );
  133539. if( pSeg->bLookup && res!=0 ){
  133540. fts3SegReaderSetEof(pSeg);
  133541. }
  133542. }
  133543. fts3SegReaderSort(pCsr->apSegment, nSeg, nSeg, fts3SegReaderCmp);
  133544. return SQLITE_OK;
  133545. }
  133546. SQLITE_PRIVATE int sqlite3Fts3SegReaderStart(
  133547. Fts3Table *p, /* Virtual table handle */
  133548. Fts3MultiSegReader *pCsr, /* Cursor object */
  133549. Fts3SegFilter *pFilter /* Restrictions on range of iteration */
  133550. ){
  133551. pCsr->pFilter = pFilter;
  133552. return fts3SegReaderStart(p, pCsr, pFilter->zTerm, pFilter->nTerm);
  133553. }
  133554. SQLITE_PRIVATE int sqlite3Fts3MsrIncrStart(
  133555. Fts3Table *p, /* Virtual table handle */
  133556. Fts3MultiSegReader *pCsr, /* Cursor object */
  133557. int iCol, /* Column to match on. */
  133558. const char *zTerm, /* Term to iterate through a doclist for */
  133559. int nTerm /* Number of bytes in zTerm */
  133560. ){
  133561. int i;
  133562. int rc;
  133563. int nSegment = pCsr->nSegment;
  133564. int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
  133565. p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
  133566. );
  133567. assert( pCsr->pFilter==0 );
  133568. assert( zTerm && nTerm>0 );
  133569. /* Advance each segment iterator until it points to the term zTerm/nTerm. */
  133570. rc = fts3SegReaderStart(p, pCsr, zTerm, nTerm);
  133571. if( rc!=SQLITE_OK ) return rc;
  133572. /* Determine how many of the segments actually point to zTerm/nTerm. */
  133573. for(i=0; i<nSegment; i++){
  133574. Fts3SegReader *pSeg = pCsr->apSegment[i];
  133575. if( !pSeg->aNode || fts3SegReaderTermCmp(pSeg, zTerm, nTerm) ){
  133576. break;
  133577. }
  133578. }
  133579. pCsr->nAdvance = i;
  133580. /* Advance each of the segments to point to the first docid. */
  133581. for(i=0; i<pCsr->nAdvance; i++){
  133582. rc = fts3SegReaderFirstDocid(p, pCsr->apSegment[i]);
  133583. if( rc!=SQLITE_OK ) return rc;
  133584. }
  133585. fts3SegReaderSort(pCsr->apSegment, i, i, xCmp);
  133586. assert( iCol<0 || iCol<p->nColumn );
  133587. pCsr->iColFilter = iCol;
  133588. return SQLITE_OK;
  133589. }
  133590. /*
  133591. ** This function is called on a MultiSegReader that has been started using
  133592. ** sqlite3Fts3MsrIncrStart(). One or more calls to MsrIncrNext() may also
  133593. ** have been made. Calling this function puts the MultiSegReader in such
  133594. ** a state that if the next two calls are:
  133595. **
  133596. ** sqlite3Fts3SegReaderStart()
  133597. ** sqlite3Fts3SegReaderStep()
  133598. **
  133599. ** then the entire doclist for the term is available in
  133600. ** MultiSegReader.aDoclist/nDoclist.
  133601. */
  133602. SQLITE_PRIVATE int sqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr){
  133603. int i; /* Used to iterate through segment-readers */
  133604. assert( pCsr->zTerm==0 );
  133605. assert( pCsr->nTerm==0 );
  133606. assert( pCsr->aDoclist==0 );
  133607. assert( pCsr->nDoclist==0 );
  133608. pCsr->nAdvance = 0;
  133609. pCsr->bRestart = 1;
  133610. for(i=0; i<pCsr->nSegment; i++){
  133611. pCsr->apSegment[i]->pOffsetList = 0;
  133612. pCsr->apSegment[i]->nOffsetList = 0;
  133613. pCsr->apSegment[i]->iDocid = 0;
  133614. }
  133615. return SQLITE_OK;
  133616. }
  133617. SQLITE_PRIVATE int sqlite3Fts3SegReaderStep(
  133618. Fts3Table *p, /* Virtual table handle */
  133619. Fts3MultiSegReader *pCsr /* Cursor object */
  133620. ){
  133621. int rc = SQLITE_OK;
  133622. int isIgnoreEmpty = (pCsr->pFilter->flags & FTS3_SEGMENT_IGNORE_EMPTY);
  133623. int isRequirePos = (pCsr->pFilter->flags & FTS3_SEGMENT_REQUIRE_POS);
  133624. int isColFilter = (pCsr->pFilter->flags & FTS3_SEGMENT_COLUMN_FILTER);
  133625. int isPrefix = (pCsr->pFilter->flags & FTS3_SEGMENT_PREFIX);
  133626. int isScan = (pCsr->pFilter->flags & FTS3_SEGMENT_SCAN);
  133627. int isFirst = (pCsr->pFilter->flags & FTS3_SEGMENT_FIRST);
  133628. Fts3SegReader **apSegment = pCsr->apSegment;
  133629. int nSegment = pCsr->nSegment;
  133630. Fts3SegFilter *pFilter = pCsr->pFilter;
  133631. int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
  133632. p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
  133633. );
  133634. if( pCsr->nSegment==0 ) return SQLITE_OK;
  133635. do {
  133636. int nMerge;
  133637. int i;
  133638. /* Advance the first pCsr->nAdvance entries in the apSegment[] array
  133639. ** forward. Then sort the list in order of current term again.
  133640. */
  133641. for(i=0; i<pCsr->nAdvance; i++){
  133642. Fts3SegReader *pSeg = apSegment[i];
  133643. if( pSeg->bLookup ){
  133644. fts3SegReaderSetEof(pSeg);
  133645. }else{
  133646. rc = fts3SegReaderNext(p, pSeg, 0);
  133647. }
  133648. if( rc!=SQLITE_OK ) return rc;
  133649. }
  133650. fts3SegReaderSort(apSegment, nSegment, pCsr->nAdvance, fts3SegReaderCmp);
  133651. pCsr->nAdvance = 0;
  133652. /* If all the seg-readers are at EOF, we're finished. return SQLITE_OK. */
  133653. assert( rc==SQLITE_OK );
  133654. if( apSegment[0]->aNode==0 ) break;
  133655. pCsr->nTerm = apSegment[0]->nTerm;
  133656. pCsr->zTerm = apSegment[0]->zTerm;
  133657. /* If this is a prefix-search, and if the term that apSegment[0] points
  133658. ** to does not share a suffix with pFilter->zTerm/nTerm, then all
  133659. ** required callbacks have been made. In this case exit early.
  133660. **
  133661. ** Similarly, if this is a search for an exact match, and the first term
  133662. ** of segment apSegment[0] is not a match, exit early.
  133663. */
  133664. if( pFilter->zTerm && !isScan ){
  133665. if( pCsr->nTerm<pFilter->nTerm
  133666. || (!isPrefix && pCsr->nTerm>pFilter->nTerm)
  133667. || memcmp(pCsr->zTerm, pFilter->zTerm, pFilter->nTerm)
  133668. ){
  133669. break;
  133670. }
  133671. }
  133672. nMerge = 1;
  133673. while( nMerge<nSegment
  133674. && apSegment[nMerge]->aNode
  133675. && apSegment[nMerge]->nTerm==pCsr->nTerm
  133676. && 0==memcmp(pCsr->zTerm, apSegment[nMerge]->zTerm, pCsr->nTerm)
  133677. ){
  133678. nMerge++;
  133679. }
  133680. assert( isIgnoreEmpty || (isRequirePos && !isColFilter) );
  133681. if( nMerge==1
  133682. && !isIgnoreEmpty
  133683. && !isFirst
  133684. && (p->bDescIdx==0 || fts3SegReaderIsPending(apSegment[0])==0)
  133685. ){
  133686. pCsr->nDoclist = apSegment[0]->nDoclist;
  133687. if( fts3SegReaderIsPending(apSegment[0]) ){
  133688. rc = fts3MsrBufferData(pCsr, apSegment[0]->aDoclist, pCsr->nDoclist);
  133689. pCsr->aDoclist = pCsr->aBuffer;
  133690. }else{
  133691. pCsr->aDoclist = apSegment[0]->aDoclist;
  133692. }
  133693. if( rc==SQLITE_OK ) rc = SQLITE_ROW;
  133694. }else{
  133695. int nDoclist = 0; /* Size of doclist */
  133696. sqlite3_int64 iPrev = 0; /* Previous docid stored in doclist */
  133697. /* The current term of the first nMerge entries in the array
  133698. ** of Fts3SegReader objects is the same. The doclists must be merged
  133699. ** and a single term returned with the merged doclist.
  133700. */
  133701. for(i=0; i<nMerge; i++){
  133702. fts3SegReaderFirstDocid(p, apSegment[i]);
  133703. }
  133704. fts3SegReaderSort(apSegment, nMerge, nMerge, xCmp);
  133705. while( apSegment[0]->pOffsetList ){
  133706. int j; /* Number of segments that share a docid */
  133707. char *pList = 0;
  133708. int nList = 0;
  133709. int nByte;
  133710. sqlite3_int64 iDocid = apSegment[0]->iDocid;
  133711. fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList);
  133712. j = 1;
  133713. while( j<nMerge
  133714. && apSegment[j]->pOffsetList
  133715. && apSegment[j]->iDocid==iDocid
  133716. ){
  133717. fts3SegReaderNextDocid(p, apSegment[j], 0, 0);
  133718. j++;
  133719. }
  133720. if( isColFilter ){
  133721. fts3ColumnFilter(pFilter->iCol, 0, &pList, &nList);
  133722. }
  133723. if( !isIgnoreEmpty || nList>0 ){
  133724. /* Calculate the 'docid' delta value to write into the merged
  133725. ** doclist. */
  133726. sqlite3_int64 iDelta;
  133727. if( p->bDescIdx && nDoclist>0 ){
  133728. iDelta = iPrev - iDocid;
  133729. }else{
  133730. iDelta = iDocid - iPrev;
  133731. }
  133732. assert( iDelta>0 || (nDoclist==0 && iDelta==iDocid) );
  133733. assert( nDoclist>0 || iDelta==iDocid );
  133734. nByte = sqlite3Fts3VarintLen(iDelta) + (isRequirePos?nList+1:0);
  133735. if( nDoclist+nByte>pCsr->nBuffer ){
  133736. char *aNew;
  133737. pCsr->nBuffer = (nDoclist+nByte)*2;
  133738. aNew = sqlite3_realloc(pCsr->aBuffer, pCsr->nBuffer);
  133739. if( !aNew ){
  133740. return SQLITE_NOMEM;
  133741. }
  133742. pCsr->aBuffer = aNew;
  133743. }
  133744. if( isFirst ){
  133745. char *a = &pCsr->aBuffer[nDoclist];
  133746. int nWrite;
  133747. nWrite = sqlite3Fts3FirstFilter(iDelta, pList, nList, a);
  133748. if( nWrite ){
  133749. iPrev = iDocid;
  133750. nDoclist += nWrite;
  133751. }
  133752. }else{
  133753. nDoclist += sqlite3Fts3PutVarint(&pCsr->aBuffer[nDoclist], iDelta);
  133754. iPrev = iDocid;
  133755. if( isRequirePos ){
  133756. memcpy(&pCsr->aBuffer[nDoclist], pList, nList);
  133757. nDoclist += nList;
  133758. pCsr->aBuffer[nDoclist++] = '\0';
  133759. }
  133760. }
  133761. }
  133762. fts3SegReaderSort(apSegment, nMerge, j, xCmp);
  133763. }
  133764. if( nDoclist>0 ){
  133765. pCsr->aDoclist = pCsr->aBuffer;
  133766. pCsr->nDoclist = nDoclist;
  133767. rc = SQLITE_ROW;
  133768. }
  133769. }
  133770. pCsr->nAdvance = nMerge;
  133771. }while( rc==SQLITE_OK );
  133772. return rc;
  133773. }
  133774. SQLITE_PRIVATE void sqlite3Fts3SegReaderFinish(
  133775. Fts3MultiSegReader *pCsr /* Cursor object */
  133776. ){
  133777. if( pCsr ){
  133778. int i;
  133779. for(i=0; i<pCsr->nSegment; i++){
  133780. sqlite3Fts3SegReaderFree(pCsr->apSegment[i]);
  133781. }
  133782. sqlite3_free(pCsr->apSegment);
  133783. sqlite3_free(pCsr->aBuffer);
  133784. pCsr->nSegment = 0;
  133785. pCsr->apSegment = 0;
  133786. pCsr->aBuffer = 0;
  133787. }
  133788. }
  133789. /*
  133790. ** Decode the "end_block" field, selected by column iCol of the SELECT
  133791. ** statement passed as the first argument.
  133792. **
  133793. ** The "end_block" field may contain either an integer, or a text field
  133794. ** containing the text representation of two non-negative integers separated
  133795. ** by one or more space (0x20) characters. In the first case, set *piEndBlock
  133796. ** to the integer value and *pnByte to zero before returning. In the second,
  133797. ** set *piEndBlock to the first value and *pnByte to the second.
  133798. */
  133799. static void fts3ReadEndBlockField(
  133800. sqlite3_stmt *pStmt,
  133801. int iCol,
  133802. i64 *piEndBlock,
  133803. i64 *pnByte
  133804. ){
  133805. const unsigned char *zText = sqlite3_column_text(pStmt, iCol);
  133806. if( zText ){
  133807. int i;
  133808. int iMul = 1;
  133809. i64 iVal = 0;
  133810. for(i=0; zText[i]>='0' && zText[i]<='9'; i++){
  133811. iVal = iVal*10 + (zText[i] - '0');
  133812. }
  133813. *piEndBlock = iVal;
  133814. while( zText[i]==' ' ) i++;
  133815. iVal = 0;
  133816. if( zText[i]=='-' ){
  133817. i++;
  133818. iMul = -1;
  133819. }
  133820. for(/* no-op */; zText[i]>='0' && zText[i]<='9'; i++){
  133821. iVal = iVal*10 + (zText[i] - '0');
  133822. }
  133823. *pnByte = (iVal * (i64)iMul);
  133824. }
  133825. }
  133826. /*
  133827. ** A segment of size nByte bytes has just been written to absolute level
  133828. ** iAbsLevel. Promote any segments that should be promoted as a result.
  133829. */
  133830. static int fts3PromoteSegments(
  133831. Fts3Table *p, /* FTS table handle */
  133832. sqlite3_int64 iAbsLevel, /* Absolute level just updated */
  133833. sqlite3_int64 nByte /* Size of new segment at iAbsLevel */
  133834. ){
  133835. int rc = SQLITE_OK;
  133836. sqlite3_stmt *pRange;
  133837. rc = fts3SqlStmt(p, SQL_SELECT_LEVEL_RANGE2, &pRange, 0);
  133838. if( rc==SQLITE_OK ){
  133839. int bOk = 0;
  133840. i64 iLast = (iAbsLevel/FTS3_SEGDIR_MAXLEVEL + 1) * FTS3_SEGDIR_MAXLEVEL - 1;
  133841. i64 nLimit = (nByte*3)/2;
  133842. /* Loop through all entries in the %_segdir table corresponding to
  133843. ** segments in this index on levels greater than iAbsLevel. If there is
  133844. ** at least one such segment, and it is possible to determine that all
  133845. ** such segments are smaller than nLimit bytes in size, they will be
  133846. ** promoted to level iAbsLevel. */
  133847. sqlite3_bind_int64(pRange, 1, iAbsLevel+1);
  133848. sqlite3_bind_int64(pRange, 2, iLast);
  133849. while( SQLITE_ROW==sqlite3_step(pRange) ){
  133850. i64 nSize = 0, dummy;
  133851. fts3ReadEndBlockField(pRange, 2, &dummy, &nSize);
  133852. if( nSize<=0 || nSize>nLimit ){
  133853. /* If nSize==0, then the %_segdir.end_block field does not not
  133854. ** contain a size value. This happens if it was written by an
  133855. ** old version of FTS. In this case it is not possible to determine
  133856. ** the size of the segment, and so segment promotion does not
  133857. ** take place. */
  133858. bOk = 0;
  133859. break;
  133860. }
  133861. bOk = 1;
  133862. }
  133863. rc = sqlite3_reset(pRange);
  133864. if( bOk ){
  133865. int iIdx = 0;
  133866. sqlite3_stmt *pUpdate1;
  133867. sqlite3_stmt *pUpdate2;
  133868. if( rc==SQLITE_OK ){
  133869. rc = fts3SqlStmt(p, SQL_UPDATE_LEVEL_IDX, &pUpdate1, 0);
  133870. }
  133871. if( rc==SQLITE_OK ){
  133872. rc = fts3SqlStmt(p, SQL_UPDATE_LEVEL, &pUpdate2, 0);
  133873. }
  133874. if( rc==SQLITE_OK ){
  133875. /* Loop through all %_segdir entries for segments in this index with
  133876. ** levels equal to or greater than iAbsLevel. As each entry is visited,
  133877. ** updated it to set (level = -1) and (idx = N), where N is 0 for the
  133878. ** oldest segment in the range, 1 for the next oldest, and so on.
  133879. **
  133880. ** In other words, move all segments being promoted to level -1,
  133881. ** setting the "idx" fields as appropriate to keep them in the same
  133882. ** order. The contents of level -1 (which is never used, except
  133883. ** transiently here), will be moved back to level iAbsLevel below. */
  133884. sqlite3_bind_int64(pRange, 1, iAbsLevel);
  133885. while( SQLITE_ROW==sqlite3_step(pRange) ){
  133886. sqlite3_bind_int(pUpdate1, 1, iIdx++);
  133887. sqlite3_bind_int(pUpdate1, 2, sqlite3_column_int(pRange, 0));
  133888. sqlite3_bind_int(pUpdate1, 3, sqlite3_column_int(pRange, 1));
  133889. sqlite3_step(pUpdate1);
  133890. rc = sqlite3_reset(pUpdate1);
  133891. if( rc!=SQLITE_OK ){
  133892. sqlite3_reset(pRange);
  133893. break;
  133894. }
  133895. }
  133896. }
  133897. if( rc==SQLITE_OK ){
  133898. rc = sqlite3_reset(pRange);
  133899. }
  133900. /* Move level -1 to level iAbsLevel */
  133901. if( rc==SQLITE_OK ){
  133902. sqlite3_bind_int64(pUpdate2, 1, iAbsLevel);
  133903. sqlite3_step(pUpdate2);
  133904. rc = sqlite3_reset(pUpdate2);
  133905. }
  133906. }
  133907. }
  133908. return rc;
  133909. }
  133910. /*
  133911. ** Merge all level iLevel segments in the database into a single
  133912. ** iLevel+1 segment. Or, if iLevel<0, merge all segments into a
  133913. ** single segment with a level equal to the numerically largest level
  133914. ** currently present in the database.
  133915. **
  133916. ** If this function is called with iLevel<0, but there is only one
  133917. ** segment in the database, SQLITE_DONE is returned immediately.
  133918. ** Otherwise, if successful, SQLITE_OK is returned. If an error occurs,
  133919. ** an SQLite error code is returned.
  133920. */
  133921. static int fts3SegmentMerge(
  133922. Fts3Table *p,
  133923. int iLangid, /* Language id to merge */
  133924. int iIndex, /* Index in p->aIndex[] to merge */
  133925. int iLevel /* Level to merge */
  133926. ){
  133927. int rc; /* Return code */
  133928. int iIdx = 0; /* Index of new segment */
  133929. sqlite3_int64 iNewLevel = 0; /* Level/index to create new segment at */
  133930. SegmentWriter *pWriter = 0; /* Used to write the new, merged, segment */
  133931. Fts3SegFilter filter; /* Segment term filter condition */
  133932. Fts3MultiSegReader csr; /* Cursor to iterate through level(s) */
  133933. int bIgnoreEmpty = 0; /* True to ignore empty segments */
  133934. i64 iMaxLevel = 0; /* Max level number for this index/langid */
  133935. assert( iLevel==FTS3_SEGCURSOR_ALL
  133936. || iLevel==FTS3_SEGCURSOR_PENDING
  133937. || iLevel>=0
  133938. );
  133939. assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
  133940. assert( iIndex>=0 && iIndex<p->nIndex );
  133941. rc = sqlite3Fts3SegReaderCursor(p, iLangid, iIndex, iLevel, 0, 0, 1, 0, &csr);
  133942. if( rc!=SQLITE_OK || csr.nSegment==0 ) goto finished;
  133943. if( iLevel!=FTS3_SEGCURSOR_PENDING ){
  133944. rc = fts3SegmentMaxLevel(p, iLangid, iIndex, &iMaxLevel);
  133945. if( rc!=SQLITE_OK ) goto finished;
  133946. }
  133947. if( iLevel==FTS3_SEGCURSOR_ALL ){
  133948. /* This call is to merge all segments in the database to a single
  133949. ** segment. The level of the new segment is equal to the numerically
  133950. ** greatest segment level currently present in the database for this
  133951. ** index. The idx of the new segment is always 0. */
  133952. if( csr.nSegment==1 ){
  133953. rc = SQLITE_DONE;
  133954. goto finished;
  133955. }
  133956. iNewLevel = iMaxLevel;
  133957. bIgnoreEmpty = 1;
  133958. }else{
  133959. /* This call is to merge all segments at level iLevel. find the next
  133960. ** available segment index at level iLevel+1. The call to
  133961. ** fts3AllocateSegdirIdx() will merge the segments at level iLevel+1 to
  133962. ** a single iLevel+2 segment if necessary. */
  133963. assert( FTS3_SEGCURSOR_PENDING==-1 );
  133964. iNewLevel = getAbsoluteLevel(p, iLangid, iIndex, iLevel+1);
  133965. rc = fts3AllocateSegdirIdx(p, iLangid, iIndex, iLevel+1, &iIdx);
  133966. bIgnoreEmpty = (iLevel!=FTS3_SEGCURSOR_PENDING) && (iNewLevel>iMaxLevel);
  133967. }
  133968. if( rc!=SQLITE_OK ) goto finished;
  133969. assert( csr.nSegment>0 );
  133970. assert( iNewLevel>=getAbsoluteLevel(p, iLangid, iIndex, 0) );
  133971. assert( iNewLevel<getAbsoluteLevel(p, iLangid, iIndex,FTS3_SEGDIR_MAXLEVEL) );
  133972. memset(&filter, 0, sizeof(Fts3SegFilter));
  133973. filter.flags = FTS3_SEGMENT_REQUIRE_POS;
  133974. filter.flags |= (bIgnoreEmpty ? FTS3_SEGMENT_IGNORE_EMPTY : 0);
  133975. rc = sqlite3Fts3SegReaderStart(p, &csr, &filter);
  133976. while( SQLITE_OK==rc ){
  133977. rc = sqlite3Fts3SegReaderStep(p, &csr);
  133978. if( rc!=SQLITE_ROW ) break;
  133979. rc = fts3SegWriterAdd(p, &pWriter, 1,
  133980. csr.zTerm, csr.nTerm, csr.aDoclist, csr.nDoclist);
  133981. }
  133982. if( rc!=SQLITE_OK ) goto finished;
  133983. assert( pWriter || bIgnoreEmpty );
  133984. if( iLevel!=FTS3_SEGCURSOR_PENDING ){
  133985. rc = fts3DeleteSegdir(
  133986. p, iLangid, iIndex, iLevel, csr.apSegment, csr.nSegment
  133987. );
  133988. if( rc!=SQLITE_OK ) goto finished;
  133989. }
  133990. if( pWriter ){
  133991. rc = fts3SegWriterFlush(p, pWriter, iNewLevel, iIdx);
  133992. if( rc==SQLITE_OK ){
  133993. if( iLevel==FTS3_SEGCURSOR_PENDING || iNewLevel<iMaxLevel ){
  133994. rc = fts3PromoteSegments(p, iNewLevel, pWriter->nLeafData);
  133995. }
  133996. }
  133997. }
  133998. finished:
  133999. fts3SegWriterFree(pWriter);
  134000. sqlite3Fts3SegReaderFinish(&csr);
  134001. return rc;
  134002. }
  134003. /*
  134004. ** Flush the contents of pendingTerms to level 0 segments.
  134005. */
  134006. SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *p){
  134007. int rc = SQLITE_OK;
  134008. int i;
  134009. for(i=0; rc==SQLITE_OK && i<p->nIndex; i++){
  134010. rc = fts3SegmentMerge(p, p->iPrevLangid, i, FTS3_SEGCURSOR_PENDING);
  134011. if( rc==SQLITE_DONE ) rc = SQLITE_OK;
  134012. }
  134013. sqlite3Fts3PendingTermsClear(p);
  134014. /* Determine the auto-incr-merge setting if unknown. If enabled,
  134015. ** estimate the number of leaf blocks of content to be written
  134016. */
  134017. if( rc==SQLITE_OK && p->bHasStat
  134018. && p->nAutoincrmerge==0xff && p->nLeafAdd>0
  134019. ){
  134020. sqlite3_stmt *pStmt = 0;
  134021. rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pStmt, 0);
  134022. if( rc==SQLITE_OK ){
  134023. sqlite3_bind_int(pStmt, 1, FTS_STAT_AUTOINCRMERGE);
  134024. rc = sqlite3_step(pStmt);
  134025. if( rc==SQLITE_ROW ){
  134026. p->nAutoincrmerge = sqlite3_column_int(pStmt, 0);
  134027. if( p->nAutoincrmerge==1 ) p->nAutoincrmerge = 8;
  134028. }else if( rc==SQLITE_DONE ){
  134029. p->nAutoincrmerge = 0;
  134030. }
  134031. rc = sqlite3_reset(pStmt);
  134032. }
  134033. }
  134034. return rc;
  134035. }
  134036. /*
  134037. ** Encode N integers as varints into a blob.
  134038. */
  134039. static void fts3EncodeIntArray(
  134040. int N, /* The number of integers to encode */
  134041. u32 *a, /* The integer values */
  134042. char *zBuf, /* Write the BLOB here */
  134043. int *pNBuf /* Write number of bytes if zBuf[] used here */
  134044. ){
  134045. int i, j;
  134046. for(i=j=0; i<N; i++){
  134047. j += sqlite3Fts3PutVarint(&zBuf[j], (sqlite3_int64)a[i]);
  134048. }
  134049. *pNBuf = j;
  134050. }
  134051. /*
  134052. ** Decode a blob of varints into N integers
  134053. */
  134054. static void fts3DecodeIntArray(
  134055. int N, /* The number of integers to decode */
  134056. u32 *a, /* Write the integer values */
  134057. const char *zBuf, /* The BLOB containing the varints */
  134058. int nBuf /* size of the BLOB */
  134059. ){
  134060. int i, j;
  134061. UNUSED_PARAMETER(nBuf);
  134062. for(i=j=0; i<N; i++){
  134063. sqlite3_int64 x;
  134064. j += sqlite3Fts3GetVarint(&zBuf[j], &x);
  134065. assert(j<=nBuf);
  134066. a[i] = (u32)(x & 0xffffffff);
  134067. }
  134068. }
  134069. /*
  134070. ** Insert the sizes (in tokens) for each column of the document
  134071. ** with docid equal to p->iPrevDocid. The sizes are encoded as
  134072. ** a blob of varints.
  134073. */
  134074. static void fts3InsertDocsize(
  134075. int *pRC, /* Result code */
  134076. Fts3Table *p, /* Table into which to insert */
  134077. u32 *aSz /* Sizes of each column, in tokens */
  134078. ){
  134079. char *pBlob; /* The BLOB encoding of the document size */
  134080. int nBlob; /* Number of bytes in the BLOB */
  134081. sqlite3_stmt *pStmt; /* Statement used to insert the encoding */
  134082. int rc; /* Result code from subfunctions */
  134083. if( *pRC ) return;
  134084. pBlob = sqlite3_malloc( 10*p->nColumn );
  134085. if( pBlob==0 ){
  134086. *pRC = SQLITE_NOMEM;
  134087. return;
  134088. }
  134089. fts3EncodeIntArray(p->nColumn, aSz, pBlob, &nBlob);
  134090. rc = fts3SqlStmt(p, SQL_REPLACE_DOCSIZE, &pStmt, 0);
  134091. if( rc ){
  134092. sqlite3_free(pBlob);
  134093. *pRC = rc;
  134094. return;
  134095. }
  134096. sqlite3_bind_int64(pStmt, 1, p->iPrevDocid);
  134097. sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, sqlite3_free);
  134098. sqlite3_step(pStmt);
  134099. *pRC = sqlite3_reset(pStmt);
  134100. }
  134101. /*
  134102. ** Record 0 of the %_stat table contains a blob consisting of N varints,
  134103. ** where N is the number of user defined columns in the fts3 table plus
  134104. ** two. If nCol is the number of user defined columns, then values of the
  134105. ** varints are set as follows:
  134106. **
  134107. ** Varint 0: Total number of rows in the table.
  134108. **
  134109. ** Varint 1..nCol: For each column, the total number of tokens stored in
  134110. ** the column for all rows of the table.
  134111. **
  134112. ** Varint 1+nCol: The total size, in bytes, of all text values in all
  134113. ** columns of all rows of the table.
  134114. **
  134115. */
  134116. static void fts3UpdateDocTotals(
  134117. int *pRC, /* The result code */
  134118. Fts3Table *p, /* Table being updated */
  134119. u32 *aSzIns, /* Size increases */
  134120. u32 *aSzDel, /* Size decreases */
  134121. int nChng /* Change in the number of documents */
  134122. ){
  134123. char *pBlob; /* Storage for BLOB written into %_stat */
  134124. int nBlob; /* Size of BLOB written into %_stat */
  134125. u32 *a; /* Array of integers that becomes the BLOB */
  134126. sqlite3_stmt *pStmt; /* Statement for reading and writing */
  134127. int i; /* Loop counter */
  134128. int rc; /* Result code from subfunctions */
  134129. const int nStat = p->nColumn+2;
  134130. if( *pRC ) return;
  134131. a = sqlite3_malloc( (sizeof(u32)+10)*nStat );
  134132. if( a==0 ){
  134133. *pRC = SQLITE_NOMEM;
  134134. return;
  134135. }
  134136. pBlob = (char*)&a[nStat];
  134137. rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pStmt, 0);
  134138. if( rc ){
  134139. sqlite3_free(a);
  134140. *pRC = rc;
  134141. return;
  134142. }
  134143. sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
  134144. if( sqlite3_step(pStmt)==SQLITE_ROW ){
  134145. fts3DecodeIntArray(nStat, a,
  134146. sqlite3_column_blob(pStmt, 0),
  134147. sqlite3_column_bytes(pStmt, 0));
  134148. }else{
  134149. memset(a, 0, sizeof(u32)*(nStat) );
  134150. }
  134151. rc = sqlite3_reset(pStmt);
  134152. if( rc!=SQLITE_OK ){
  134153. sqlite3_free(a);
  134154. *pRC = rc;
  134155. return;
  134156. }
  134157. if( nChng<0 && a[0]<(u32)(-nChng) ){
  134158. a[0] = 0;
  134159. }else{
  134160. a[0] += nChng;
  134161. }
  134162. for(i=0; i<p->nColumn+1; i++){
  134163. u32 x = a[i+1];
  134164. if( x+aSzIns[i] < aSzDel[i] ){
  134165. x = 0;
  134166. }else{
  134167. x = x + aSzIns[i] - aSzDel[i];
  134168. }
  134169. a[i+1] = x;
  134170. }
  134171. fts3EncodeIntArray(nStat, a, pBlob, &nBlob);
  134172. rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pStmt, 0);
  134173. if( rc ){
  134174. sqlite3_free(a);
  134175. *pRC = rc;
  134176. return;
  134177. }
  134178. sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
  134179. sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, SQLITE_STATIC);
  134180. sqlite3_step(pStmt);
  134181. *pRC = sqlite3_reset(pStmt);
  134182. sqlite3_free(a);
  134183. }
  134184. /*
  134185. ** Merge the entire database so that there is one segment for each
  134186. ** iIndex/iLangid combination.
  134187. */
  134188. static int fts3DoOptimize(Fts3Table *p, int bReturnDone){
  134189. int bSeenDone = 0;
  134190. int rc;
  134191. sqlite3_stmt *pAllLangid = 0;
  134192. rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);
  134193. if( rc==SQLITE_OK ){
  134194. int rc2;
  134195. sqlite3_bind_int(pAllLangid, 1, p->nIndex);
  134196. while( sqlite3_step(pAllLangid)==SQLITE_ROW ){
  134197. int i;
  134198. int iLangid = sqlite3_column_int(pAllLangid, 0);
  134199. for(i=0; rc==SQLITE_OK && i<p->nIndex; i++){
  134200. rc = fts3SegmentMerge(p, iLangid, i, FTS3_SEGCURSOR_ALL);
  134201. if( rc==SQLITE_DONE ){
  134202. bSeenDone = 1;
  134203. rc = SQLITE_OK;
  134204. }
  134205. }
  134206. }
  134207. rc2 = sqlite3_reset(pAllLangid);
  134208. if( rc==SQLITE_OK ) rc = rc2;
  134209. }
  134210. sqlite3Fts3SegmentsClose(p);
  134211. sqlite3Fts3PendingTermsClear(p);
  134212. return (rc==SQLITE_OK && bReturnDone && bSeenDone) ? SQLITE_DONE : rc;
  134213. }
  134214. /*
  134215. ** This function is called when the user executes the following statement:
  134216. **
  134217. ** INSERT INTO <tbl>(<tbl>) VALUES('rebuild');
  134218. **
  134219. ** The entire FTS index is discarded and rebuilt. If the table is one
  134220. ** created using the content=xxx option, then the new index is based on
  134221. ** the current contents of the xxx table. Otherwise, it is rebuilt based
  134222. ** on the contents of the %_content table.
  134223. */
  134224. static int fts3DoRebuild(Fts3Table *p){
  134225. int rc; /* Return Code */
  134226. rc = fts3DeleteAll(p, 0);
  134227. if( rc==SQLITE_OK ){
  134228. u32 *aSz = 0;
  134229. u32 *aSzIns = 0;
  134230. u32 *aSzDel = 0;
  134231. sqlite3_stmt *pStmt = 0;
  134232. int nEntry = 0;
  134233. /* Compose and prepare an SQL statement to loop through the content table */
  134234. char *zSql = sqlite3_mprintf("SELECT %s" , p->zReadExprlist);
  134235. if( !zSql ){
  134236. rc = SQLITE_NOMEM;
  134237. }else{
  134238. rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
  134239. sqlite3_free(zSql);
  134240. }
  134241. if( rc==SQLITE_OK ){
  134242. int nByte = sizeof(u32) * (p->nColumn+1)*3;
  134243. aSz = (u32 *)sqlite3_malloc(nByte);
  134244. if( aSz==0 ){
  134245. rc = SQLITE_NOMEM;
  134246. }else{
  134247. memset(aSz, 0, nByte);
  134248. aSzIns = &aSz[p->nColumn+1];
  134249. aSzDel = &aSzIns[p->nColumn+1];
  134250. }
  134251. }
  134252. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
  134253. int iCol;
  134254. int iLangid = langidFromSelect(p, pStmt);
  134255. rc = fts3PendingTermsDocid(p, iLangid, sqlite3_column_int64(pStmt, 0));
  134256. memset(aSz, 0, sizeof(aSz[0]) * (p->nColumn+1));
  134257. for(iCol=0; rc==SQLITE_OK && iCol<p->nColumn; iCol++){
  134258. if( p->abNotindexed[iCol]==0 ){
  134259. const char *z = (const char *) sqlite3_column_text(pStmt, iCol+1);
  134260. rc = fts3PendingTermsAdd(p, iLangid, z, iCol, &aSz[iCol]);
  134261. aSz[p->nColumn] += sqlite3_column_bytes(pStmt, iCol+1);
  134262. }
  134263. }
  134264. if( p->bHasDocsize ){
  134265. fts3InsertDocsize(&rc, p, aSz);
  134266. }
  134267. if( rc!=SQLITE_OK ){
  134268. sqlite3_finalize(pStmt);
  134269. pStmt = 0;
  134270. }else{
  134271. nEntry++;
  134272. for(iCol=0; iCol<=p->nColumn; iCol++){
  134273. aSzIns[iCol] += aSz[iCol];
  134274. }
  134275. }
  134276. }
  134277. if( p->bFts4 ){
  134278. fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nEntry);
  134279. }
  134280. sqlite3_free(aSz);
  134281. if( pStmt ){
  134282. int rc2 = sqlite3_finalize(pStmt);
  134283. if( rc==SQLITE_OK ){
  134284. rc = rc2;
  134285. }
  134286. }
  134287. }
  134288. return rc;
  134289. }
  134290. /*
  134291. ** This function opens a cursor used to read the input data for an
  134292. ** incremental merge operation. Specifically, it opens a cursor to scan
  134293. ** the oldest nSeg segments (idx=0 through idx=(nSeg-1)) in absolute
  134294. ** level iAbsLevel.
  134295. */
  134296. static int fts3IncrmergeCsr(
  134297. Fts3Table *p, /* FTS3 table handle */
  134298. sqlite3_int64 iAbsLevel, /* Absolute level to open */
  134299. int nSeg, /* Number of segments to merge */
  134300. Fts3MultiSegReader *pCsr /* Cursor object to populate */
  134301. ){
  134302. int rc; /* Return Code */
  134303. sqlite3_stmt *pStmt = 0; /* Statement used to read %_segdir entry */
  134304. int nByte; /* Bytes allocated at pCsr->apSegment[] */
  134305. /* Allocate space for the Fts3MultiSegReader.aCsr[] array */
  134306. memset(pCsr, 0, sizeof(*pCsr));
  134307. nByte = sizeof(Fts3SegReader *) * nSeg;
  134308. pCsr->apSegment = (Fts3SegReader **)sqlite3_malloc(nByte);
  134309. if( pCsr->apSegment==0 ){
  134310. rc = SQLITE_NOMEM;
  134311. }else{
  134312. memset(pCsr->apSegment, 0, nByte);
  134313. rc = fts3SqlStmt(p, SQL_SELECT_LEVEL, &pStmt, 0);
  134314. }
  134315. if( rc==SQLITE_OK ){
  134316. int i;
  134317. int rc2;
  134318. sqlite3_bind_int64(pStmt, 1, iAbsLevel);
  134319. assert( pCsr->nSegment==0 );
  134320. for(i=0; rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW && i<nSeg; i++){
  134321. rc = sqlite3Fts3SegReaderNew(i, 0,
  134322. sqlite3_column_int64(pStmt, 1), /* segdir.start_block */
  134323. sqlite3_column_int64(pStmt, 2), /* segdir.leaves_end_block */
  134324. sqlite3_column_int64(pStmt, 3), /* segdir.end_block */
  134325. sqlite3_column_blob(pStmt, 4), /* segdir.root */
  134326. sqlite3_column_bytes(pStmt, 4), /* segdir.root */
  134327. &pCsr->apSegment[i]
  134328. );
  134329. pCsr->nSegment++;
  134330. }
  134331. rc2 = sqlite3_reset(pStmt);
  134332. if( rc==SQLITE_OK ) rc = rc2;
  134333. }
  134334. return rc;
  134335. }
  134336. typedef struct IncrmergeWriter IncrmergeWriter;
  134337. typedef struct NodeWriter NodeWriter;
  134338. typedef struct Blob Blob;
  134339. typedef struct NodeReader NodeReader;
  134340. /*
  134341. ** An instance of the following structure is used as a dynamic buffer
  134342. ** to build up nodes or other blobs of data in.
  134343. **
  134344. ** The function blobGrowBuffer() is used to extend the allocation.
  134345. */
  134346. struct Blob {
  134347. char *a; /* Pointer to allocation */
  134348. int n; /* Number of valid bytes of data in a[] */
  134349. int nAlloc; /* Allocated size of a[] (nAlloc>=n) */
  134350. };
  134351. /*
  134352. ** This structure is used to build up buffers containing segment b-tree
  134353. ** nodes (blocks).
  134354. */
  134355. struct NodeWriter {
  134356. sqlite3_int64 iBlock; /* Current block id */
  134357. Blob key; /* Last key written to the current block */
  134358. Blob block; /* Current block image */
  134359. };
  134360. /*
  134361. ** An object of this type contains the state required to create or append
  134362. ** to an appendable b-tree segment.
  134363. */
  134364. struct IncrmergeWriter {
  134365. int nLeafEst; /* Space allocated for leaf blocks */
  134366. int nWork; /* Number of leaf pages flushed */
  134367. sqlite3_int64 iAbsLevel; /* Absolute level of input segments */
  134368. int iIdx; /* Index of *output* segment in iAbsLevel+1 */
  134369. sqlite3_int64 iStart; /* Block number of first allocated block */
  134370. sqlite3_int64 iEnd; /* Block number of last allocated block */
  134371. sqlite3_int64 nLeafData; /* Bytes of leaf page data so far */
  134372. u8 bNoLeafData; /* If true, store 0 for segment size */
  134373. NodeWriter aNodeWriter[FTS_MAX_APPENDABLE_HEIGHT];
  134374. };
  134375. /*
  134376. ** An object of the following type is used to read data from a single
  134377. ** FTS segment node. See the following functions:
  134378. **
  134379. ** nodeReaderInit()
  134380. ** nodeReaderNext()
  134381. ** nodeReaderRelease()
  134382. */
  134383. struct NodeReader {
  134384. const char *aNode;
  134385. int nNode;
  134386. int iOff; /* Current offset within aNode[] */
  134387. /* Output variables. Containing the current node entry. */
  134388. sqlite3_int64 iChild; /* Pointer to child node */
  134389. Blob term; /* Current term */
  134390. const char *aDoclist; /* Pointer to doclist */
  134391. int nDoclist; /* Size of doclist in bytes */
  134392. };
  134393. /*
  134394. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
  134395. ** Otherwise, if the allocation at pBlob->a is not already at least nMin
  134396. ** bytes in size, extend (realloc) it to be so.
  134397. **
  134398. ** If an OOM error occurs, set *pRc to SQLITE_NOMEM and leave pBlob->a
  134399. ** unmodified. Otherwise, if the allocation succeeds, update pBlob->nAlloc
  134400. ** to reflect the new size of the pBlob->a[] buffer.
  134401. */
  134402. static void blobGrowBuffer(Blob *pBlob, int nMin, int *pRc){
  134403. if( *pRc==SQLITE_OK && nMin>pBlob->nAlloc ){
  134404. int nAlloc = nMin;
  134405. char *a = (char *)sqlite3_realloc(pBlob->a, nAlloc);
  134406. if( a ){
  134407. pBlob->nAlloc = nAlloc;
  134408. pBlob->a = a;
  134409. }else{
  134410. *pRc = SQLITE_NOMEM;
  134411. }
  134412. }
  134413. }
  134414. /*
  134415. ** Attempt to advance the node-reader object passed as the first argument to
  134416. ** the next entry on the node.
  134417. **
  134418. ** Return an error code if an error occurs (SQLITE_NOMEM is possible).
  134419. ** Otherwise return SQLITE_OK. If there is no next entry on the node
  134420. ** (e.g. because the current entry is the last) set NodeReader->aNode to
  134421. ** NULL to indicate EOF. Otherwise, populate the NodeReader structure output
  134422. ** variables for the new entry.
  134423. */
  134424. static int nodeReaderNext(NodeReader *p){
  134425. int bFirst = (p->term.n==0); /* True for first term on the node */
  134426. int nPrefix = 0; /* Bytes to copy from previous term */
  134427. int nSuffix = 0; /* Bytes to append to the prefix */
  134428. int rc = SQLITE_OK; /* Return code */
  134429. assert( p->aNode );
  134430. if( p->iChild && bFirst==0 ) p->iChild++;
  134431. if( p->iOff>=p->nNode ){
  134432. /* EOF */
  134433. p->aNode = 0;
  134434. }else{
  134435. if( bFirst==0 ){
  134436. p->iOff += fts3GetVarint32(&p->aNode[p->iOff], &nPrefix);
  134437. }
  134438. p->iOff += fts3GetVarint32(&p->aNode[p->iOff], &nSuffix);
  134439. blobGrowBuffer(&p->term, nPrefix+nSuffix, &rc);
  134440. if( rc==SQLITE_OK ){
  134441. memcpy(&p->term.a[nPrefix], &p->aNode[p->iOff], nSuffix);
  134442. p->term.n = nPrefix+nSuffix;
  134443. p->iOff += nSuffix;
  134444. if( p->iChild==0 ){
  134445. p->iOff += fts3GetVarint32(&p->aNode[p->iOff], &p->nDoclist);
  134446. p->aDoclist = &p->aNode[p->iOff];
  134447. p->iOff += p->nDoclist;
  134448. }
  134449. }
  134450. }
  134451. assert( p->iOff<=p->nNode );
  134452. return rc;
  134453. }
  134454. /*
  134455. ** Release all dynamic resources held by node-reader object *p.
  134456. */
  134457. static void nodeReaderRelease(NodeReader *p){
  134458. sqlite3_free(p->term.a);
  134459. }
  134460. /*
  134461. ** Initialize a node-reader object to read the node in buffer aNode/nNode.
  134462. **
  134463. ** If successful, SQLITE_OK is returned and the NodeReader object set to
  134464. ** point to the first entry on the node (if any). Otherwise, an SQLite
  134465. ** error code is returned.
  134466. */
  134467. static int nodeReaderInit(NodeReader *p, const char *aNode, int nNode){
  134468. memset(p, 0, sizeof(NodeReader));
  134469. p->aNode = aNode;
  134470. p->nNode = nNode;
  134471. /* Figure out if this is a leaf or an internal node. */
  134472. if( p->aNode[0] ){
  134473. /* An internal node. */
  134474. p->iOff = 1 + sqlite3Fts3GetVarint(&p->aNode[1], &p->iChild);
  134475. }else{
  134476. p->iOff = 1;
  134477. }
  134478. return nodeReaderNext(p);
  134479. }
  134480. /*
  134481. ** This function is called while writing an FTS segment each time a leaf o
  134482. ** node is finished and written to disk. The key (zTerm/nTerm) is guaranteed
  134483. ** to be greater than the largest key on the node just written, but smaller
  134484. ** than or equal to the first key that will be written to the next leaf
  134485. ** node.
  134486. **
  134487. ** The block id of the leaf node just written to disk may be found in
  134488. ** (pWriter->aNodeWriter[0].iBlock) when this function is called.
  134489. */
  134490. static int fts3IncrmergePush(
  134491. Fts3Table *p, /* Fts3 table handle */
  134492. IncrmergeWriter *pWriter, /* Writer object */
  134493. const char *zTerm, /* Term to write to internal node */
  134494. int nTerm /* Bytes at zTerm */
  134495. ){
  134496. sqlite3_int64 iPtr = pWriter->aNodeWriter[0].iBlock;
  134497. int iLayer;
  134498. assert( nTerm>0 );
  134499. for(iLayer=1; ALWAYS(iLayer<FTS_MAX_APPENDABLE_HEIGHT); iLayer++){
  134500. sqlite3_int64 iNextPtr = 0;
  134501. NodeWriter *pNode = &pWriter->aNodeWriter[iLayer];
  134502. int rc = SQLITE_OK;
  134503. int nPrefix;
  134504. int nSuffix;
  134505. int nSpace;
  134506. /* Figure out how much space the key will consume if it is written to
  134507. ** the current node of layer iLayer. Due to the prefix compression,
  134508. ** the space required changes depending on which node the key is to
  134509. ** be added to. */
  134510. nPrefix = fts3PrefixCompress(pNode->key.a, pNode->key.n, zTerm, nTerm);
  134511. nSuffix = nTerm - nPrefix;
  134512. nSpace = sqlite3Fts3VarintLen(nPrefix);
  134513. nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
  134514. if( pNode->key.n==0 || (pNode->block.n + nSpace)<=p->nNodeSize ){
  134515. /* If the current node of layer iLayer contains zero keys, or if adding
  134516. ** the key to it will not cause it to grow to larger than nNodeSize
  134517. ** bytes in size, write the key here. */
  134518. Blob *pBlk = &pNode->block;
  134519. if( pBlk->n==0 ){
  134520. blobGrowBuffer(pBlk, p->nNodeSize, &rc);
  134521. if( rc==SQLITE_OK ){
  134522. pBlk->a[0] = (char)iLayer;
  134523. pBlk->n = 1 + sqlite3Fts3PutVarint(&pBlk->a[1], iPtr);
  134524. }
  134525. }
  134526. blobGrowBuffer(pBlk, pBlk->n + nSpace, &rc);
  134527. blobGrowBuffer(&pNode->key, nTerm, &rc);
  134528. if( rc==SQLITE_OK ){
  134529. if( pNode->key.n ){
  134530. pBlk->n += sqlite3Fts3PutVarint(&pBlk->a[pBlk->n], nPrefix);
  134531. }
  134532. pBlk->n += sqlite3Fts3PutVarint(&pBlk->a[pBlk->n], nSuffix);
  134533. memcpy(&pBlk->a[pBlk->n], &zTerm[nPrefix], nSuffix);
  134534. pBlk->n += nSuffix;
  134535. memcpy(pNode->key.a, zTerm, nTerm);
  134536. pNode->key.n = nTerm;
  134537. }
  134538. }else{
  134539. /* Otherwise, flush the current node of layer iLayer to disk.
  134540. ** Then allocate a new, empty sibling node. The key will be written
  134541. ** into the parent of this node. */
  134542. rc = fts3WriteSegment(p, pNode->iBlock, pNode->block.a, pNode->block.n);
  134543. assert( pNode->block.nAlloc>=p->nNodeSize );
  134544. pNode->block.a[0] = (char)iLayer;
  134545. pNode->block.n = 1 + sqlite3Fts3PutVarint(&pNode->block.a[1], iPtr+1);
  134546. iNextPtr = pNode->iBlock;
  134547. pNode->iBlock++;
  134548. pNode->key.n = 0;
  134549. }
  134550. if( rc!=SQLITE_OK || iNextPtr==0 ) return rc;
  134551. iPtr = iNextPtr;
  134552. }
  134553. assert( 0 );
  134554. return 0;
  134555. }
  134556. /*
  134557. ** Append a term and (optionally) doclist to the FTS segment node currently
  134558. ** stored in blob *pNode. The node need not contain any terms, but the
  134559. ** header must be written before this function is called.
  134560. **
  134561. ** A node header is a single 0x00 byte for a leaf node, or a height varint
  134562. ** followed by the left-hand-child varint for an internal node.
  134563. **
  134564. ** The term to be appended is passed via arguments zTerm/nTerm. For a
  134565. ** leaf node, the doclist is passed as aDoclist/nDoclist. For an internal
  134566. ** node, both aDoclist and nDoclist must be passed 0.
  134567. **
  134568. ** If the size of the value in blob pPrev is zero, then this is the first
  134569. ** term written to the node. Otherwise, pPrev contains a copy of the
  134570. ** previous term. Before this function returns, it is updated to contain a
  134571. ** copy of zTerm/nTerm.
  134572. **
  134573. ** It is assumed that the buffer associated with pNode is already large
  134574. ** enough to accommodate the new entry. The buffer associated with pPrev
  134575. ** is extended by this function if requrired.
  134576. **
  134577. ** If an error (i.e. OOM condition) occurs, an SQLite error code is
  134578. ** returned. Otherwise, SQLITE_OK.
  134579. */
  134580. static int fts3AppendToNode(
  134581. Blob *pNode, /* Current node image to append to */
  134582. Blob *pPrev, /* Buffer containing previous term written */
  134583. const char *zTerm, /* New term to write */
  134584. int nTerm, /* Size of zTerm in bytes */
  134585. const char *aDoclist, /* Doclist (or NULL) to write */
  134586. int nDoclist /* Size of aDoclist in bytes */
  134587. ){
  134588. int rc = SQLITE_OK; /* Return code */
  134589. int bFirst = (pPrev->n==0); /* True if this is the first term written */
  134590. int nPrefix; /* Size of term prefix in bytes */
  134591. int nSuffix; /* Size of term suffix in bytes */
  134592. /* Node must have already been started. There must be a doclist for a
  134593. ** leaf node, and there must not be a doclist for an internal node. */
  134594. assert( pNode->n>0 );
  134595. assert( (pNode->a[0]=='\0')==(aDoclist!=0) );
  134596. blobGrowBuffer(pPrev, nTerm, &rc);
  134597. if( rc!=SQLITE_OK ) return rc;
  134598. nPrefix = fts3PrefixCompress(pPrev->a, pPrev->n, zTerm, nTerm);
  134599. nSuffix = nTerm - nPrefix;
  134600. memcpy(pPrev->a, zTerm, nTerm);
  134601. pPrev->n = nTerm;
  134602. if( bFirst==0 ){
  134603. pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nPrefix);
  134604. }
  134605. pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nSuffix);
  134606. memcpy(&pNode->a[pNode->n], &zTerm[nPrefix], nSuffix);
  134607. pNode->n += nSuffix;
  134608. if( aDoclist ){
  134609. pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nDoclist);
  134610. memcpy(&pNode->a[pNode->n], aDoclist, nDoclist);
  134611. pNode->n += nDoclist;
  134612. }
  134613. assert( pNode->n<=pNode->nAlloc );
  134614. return SQLITE_OK;
  134615. }
  134616. /*
  134617. ** Append the current term and doclist pointed to by cursor pCsr to the
  134618. ** appendable b-tree segment opened for writing by pWriter.
  134619. **
  134620. ** Return SQLITE_OK if successful, or an SQLite error code otherwise.
  134621. */
  134622. static int fts3IncrmergeAppend(
  134623. Fts3Table *p, /* Fts3 table handle */
  134624. IncrmergeWriter *pWriter, /* Writer object */
  134625. Fts3MultiSegReader *pCsr /* Cursor containing term and doclist */
  134626. ){
  134627. const char *zTerm = pCsr->zTerm;
  134628. int nTerm = pCsr->nTerm;
  134629. const char *aDoclist = pCsr->aDoclist;
  134630. int nDoclist = pCsr->nDoclist;
  134631. int rc = SQLITE_OK; /* Return code */
  134632. int nSpace; /* Total space in bytes required on leaf */
  134633. int nPrefix; /* Size of prefix shared with previous term */
  134634. int nSuffix; /* Size of suffix (nTerm - nPrefix) */
  134635. NodeWriter *pLeaf; /* Object used to write leaf nodes */
  134636. pLeaf = &pWriter->aNodeWriter[0];
  134637. nPrefix = fts3PrefixCompress(pLeaf->key.a, pLeaf->key.n, zTerm, nTerm);
  134638. nSuffix = nTerm - nPrefix;
  134639. nSpace = sqlite3Fts3VarintLen(nPrefix);
  134640. nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
  134641. nSpace += sqlite3Fts3VarintLen(nDoclist) + nDoclist;
  134642. /* If the current block is not empty, and if adding this term/doclist
  134643. ** to the current block would make it larger than Fts3Table.nNodeSize
  134644. ** bytes, write this block out to the database. */
  134645. if( pLeaf->block.n>0 && (pLeaf->block.n + nSpace)>p->nNodeSize ){
  134646. rc = fts3WriteSegment(p, pLeaf->iBlock, pLeaf->block.a, pLeaf->block.n);
  134647. pWriter->nWork++;
  134648. /* Add the current term to the parent node. The term added to the
  134649. ** parent must:
  134650. **
  134651. ** a) be greater than the largest term on the leaf node just written
  134652. ** to the database (still available in pLeaf->key), and
  134653. **
  134654. ** b) be less than or equal to the term about to be added to the new
  134655. ** leaf node (zTerm/nTerm).
  134656. **
  134657. ** In other words, it must be the prefix of zTerm 1 byte longer than
  134658. ** the common prefix (if any) of zTerm and pWriter->zTerm.
  134659. */
  134660. if( rc==SQLITE_OK ){
  134661. rc = fts3IncrmergePush(p, pWriter, zTerm, nPrefix+1);
  134662. }
  134663. /* Advance to the next output block */
  134664. pLeaf->iBlock++;
  134665. pLeaf->key.n = 0;
  134666. pLeaf->block.n = 0;
  134667. nSuffix = nTerm;
  134668. nSpace = 1;
  134669. nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
  134670. nSpace += sqlite3Fts3VarintLen(nDoclist) + nDoclist;
  134671. }
  134672. pWriter->nLeafData += nSpace;
  134673. blobGrowBuffer(&pLeaf->block, pLeaf->block.n + nSpace, &rc);
  134674. if( rc==SQLITE_OK ){
  134675. if( pLeaf->block.n==0 ){
  134676. pLeaf->block.n = 1;
  134677. pLeaf->block.a[0] = '\0';
  134678. }
  134679. rc = fts3AppendToNode(
  134680. &pLeaf->block, &pLeaf->key, zTerm, nTerm, aDoclist, nDoclist
  134681. );
  134682. }
  134683. return rc;
  134684. }
  134685. /*
  134686. ** This function is called to release all dynamic resources held by the
  134687. ** merge-writer object pWriter, and if no error has occurred, to flush
  134688. ** all outstanding node buffers held by pWriter to disk.
  134689. **
  134690. ** If *pRc is not SQLITE_OK when this function is called, then no attempt
  134691. ** is made to write any data to disk. Instead, this function serves only
  134692. ** to release outstanding resources.
  134693. **
  134694. ** Otherwise, if *pRc is initially SQLITE_OK and an error occurs while
  134695. ** flushing buffers to disk, *pRc is set to an SQLite error code before
  134696. ** returning.
  134697. */
  134698. static void fts3IncrmergeRelease(
  134699. Fts3Table *p, /* FTS3 table handle */
  134700. IncrmergeWriter *pWriter, /* Merge-writer object */
  134701. int *pRc /* IN/OUT: Error code */
  134702. ){
  134703. int i; /* Used to iterate through non-root layers */
  134704. int iRoot; /* Index of root in pWriter->aNodeWriter */
  134705. NodeWriter *pRoot; /* NodeWriter for root node */
  134706. int rc = *pRc; /* Error code */
  134707. /* Set iRoot to the index in pWriter->aNodeWriter[] of the output segment
  134708. ** root node. If the segment fits entirely on a single leaf node, iRoot
  134709. ** will be set to 0. If the root node is the parent of the leaves, iRoot
  134710. ** will be 1. And so on. */
  134711. for(iRoot=FTS_MAX_APPENDABLE_HEIGHT-1; iRoot>=0; iRoot--){
  134712. NodeWriter *pNode = &pWriter->aNodeWriter[iRoot];
  134713. if( pNode->block.n>0 ) break;
  134714. assert( *pRc || pNode->block.nAlloc==0 );
  134715. assert( *pRc || pNode->key.nAlloc==0 );
  134716. sqlite3_free(pNode->block.a);
  134717. sqlite3_free(pNode->key.a);
  134718. }
  134719. /* Empty output segment. This is a no-op. */
  134720. if( iRoot<0 ) return;
  134721. /* The entire output segment fits on a single node. Normally, this means
  134722. ** the node would be stored as a blob in the "root" column of the %_segdir
  134723. ** table. However, this is not permitted in this case. The problem is that
  134724. ** space has already been reserved in the %_segments table, and so the
  134725. ** start_block and end_block fields of the %_segdir table must be populated.
  134726. ** And, by design or by accident, released versions of FTS cannot handle
  134727. ** segments that fit entirely on the root node with start_block!=0.
  134728. **
  134729. ** Instead, create a synthetic root node that contains nothing but a
  134730. ** pointer to the single content node. So that the segment consists of a
  134731. ** single leaf and a single interior (root) node.
  134732. **
  134733. ** Todo: Better might be to defer allocating space in the %_segments
  134734. ** table until we are sure it is needed.
  134735. */
  134736. if( iRoot==0 ){
  134737. Blob *pBlock = &pWriter->aNodeWriter[1].block;
  134738. blobGrowBuffer(pBlock, 1 + FTS3_VARINT_MAX, &rc);
  134739. if( rc==SQLITE_OK ){
  134740. pBlock->a[0] = 0x01;
  134741. pBlock->n = 1 + sqlite3Fts3PutVarint(
  134742. &pBlock->a[1], pWriter->aNodeWriter[0].iBlock
  134743. );
  134744. }
  134745. iRoot = 1;
  134746. }
  134747. pRoot = &pWriter->aNodeWriter[iRoot];
  134748. /* Flush all currently outstanding nodes to disk. */
  134749. for(i=0; i<iRoot; i++){
  134750. NodeWriter *pNode = &pWriter->aNodeWriter[i];
  134751. if( pNode->block.n>0 && rc==SQLITE_OK ){
  134752. rc = fts3WriteSegment(p, pNode->iBlock, pNode->block.a, pNode->block.n);
  134753. }
  134754. sqlite3_free(pNode->block.a);
  134755. sqlite3_free(pNode->key.a);
  134756. }
  134757. /* Write the %_segdir record. */
  134758. if( rc==SQLITE_OK ){
  134759. rc = fts3WriteSegdir(p,
  134760. pWriter->iAbsLevel+1, /* level */
  134761. pWriter->iIdx, /* idx */
  134762. pWriter->iStart, /* start_block */
  134763. pWriter->aNodeWriter[0].iBlock, /* leaves_end_block */
  134764. pWriter->iEnd, /* end_block */
  134765. (pWriter->bNoLeafData==0 ? pWriter->nLeafData : 0), /* end_block */
  134766. pRoot->block.a, pRoot->block.n /* root */
  134767. );
  134768. }
  134769. sqlite3_free(pRoot->block.a);
  134770. sqlite3_free(pRoot->key.a);
  134771. *pRc = rc;
  134772. }
  134773. /*
  134774. ** Compare the term in buffer zLhs (size in bytes nLhs) with that in
  134775. ** zRhs (size in bytes nRhs) using memcmp. If one term is a prefix of
  134776. ** the other, it is considered to be smaller than the other.
  134777. **
  134778. ** Return -ve if zLhs is smaller than zRhs, 0 if it is equal, or +ve
  134779. ** if it is greater.
  134780. */
  134781. static int fts3TermCmp(
  134782. const char *zLhs, int nLhs, /* LHS of comparison */
  134783. const char *zRhs, int nRhs /* RHS of comparison */
  134784. ){
  134785. int nCmp = MIN(nLhs, nRhs);
  134786. int res;
  134787. res = memcmp(zLhs, zRhs, nCmp);
  134788. if( res==0 ) res = nLhs - nRhs;
  134789. return res;
  134790. }
  134791. /*
  134792. ** Query to see if the entry in the %_segments table with blockid iEnd is
  134793. ** NULL. If no error occurs and the entry is NULL, set *pbRes 1 before
  134794. ** returning. Otherwise, set *pbRes to 0.
  134795. **
  134796. ** Or, if an error occurs while querying the database, return an SQLite
  134797. ** error code. The final value of *pbRes is undefined in this case.
  134798. **
  134799. ** This is used to test if a segment is an "appendable" segment. If it
  134800. ** is, then a NULL entry has been inserted into the %_segments table
  134801. ** with blockid %_segdir.end_block.
  134802. */
  134803. static int fts3IsAppendable(Fts3Table *p, sqlite3_int64 iEnd, int *pbRes){
  134804. int bRes = 0; /* Result to set *pbRes to */
  134805. sqlite3_stmt *pCheck = 0; /* Statement to query database with */
  134806. int rc; /* Return code */
  134807. rc = fts3SqlStmt(p, SQL_SEGMENT_IS_APPENDABLE, &pCheck, 0);
  134808. if( rc==SQLITE_OK ){
  134809. sqlite3_bind_int64(pCheck, 1, iEnd);
  134810. if( SQLITE_ROW==sqlite3_step(pCheck) ) bRes = 1;
  134811. rc = sqlite3_reset(pCheck);
  134812. }
  134813. *pbRes = bRes;
  134814. return rc;
  134815. }
  134816. /*
  134817. ** This function is called when initializing an incremental-merge operation.
  134818. ** It checks if the existing segment with index value iIdx at absolute level
  134819. ** (iAbsLevel+1) can be appended to by the incremental merge. If it can, the
  134820. ** merge-writer object *pWriter is initialized to write to it.
  134821. **
  134822. ** An existing segment can be appended to by an incremental merge if:
  134823. **
  134824. ** * It was initially created as an appendable segment (with all required
  134825. ** space pre-allocated), and
  134826. **
  134827. ** * The first key read from the input (arguments zKey and nKey) is
  134828. ** greater than the largest key currently stored in the potential
  134829. ** output segment.
  134830. */
  134831. static int fts3IncrmergeLoad(
  134832. Fts3Table *p, /* Fts3 table handle */
  134833. sqlite3_int64 iAbsLevel, /* Absolute level of input segments */
  134834. int iIdx, /* Index of candidate output segment */
  134835. const char *zKey, /* First key to write */
  134836. int nKey, /* Number of bytes in nKey */
  134837. IncrmergeWriter *pWriter /* Populate this object */
  134838. ){
  134839. int rc; /* Return code */
  134840. sqlite3_stmt *pSelect = 0; /* SELECT to read %_segdir entry */
  134841. rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR, &pSelect, 0);
  134842. if( rc==SQLITE_OK ){
  134843. sqlite3_int64 iStart = 0; /* Value of %_segdir.start_block */
  134844. sqlite3_int64 iLeafEnd = 0; /* Value of %_segdir.leaves_end_block */
  134845. sqlite3_int64 iEnd = 0; /* Value of %_segdir.end_block */
  134846. const char *aRoot = 0; /* Pointer to %_segdir.root buffer */
  134847. int nRoot = 0; /* Size of aRoot[] in bytes */
  134848. int rc2; /* Return code from sqlite3_reset() */
  134849. int bAppendable = 0; /* Set to true if segment is appendable */
  134850. /* Read the %_segdir entry for index iIdx absolute level (iAbsLevel+1) */
  134851. sqlite3_bind_int64(pSelect, 1, iAbsLevel+1);
  134852. sqlite3_bind_int(pSelect, 2, iIdx);
  134853. if( sqlite3_step(pSelect)==SQLITE_ROW ){
  134854. iStart = sqlite3_column_int64(pSelect, 1);
  134855. iLeafEnd = sqlite3_column_int64(pSelect, 2);
  134856. fts3ReadEndBlockField(pSelect, 3, &iEnd, &pWriter->nLeafData);
  134857. if( pWriter->nLeafData<0 ){
  134858. pWriter->nLeafData = pWriter->nLeafData * -1;
  134859. }
  134860. pWriter->bNoLeafData = (pWriter->nLeafData==0);
  134861. nRoot = sqlite3_column_bytes(pSelect, 4);
  134862. aRoot = sqlite3_column_blob(pSelect, 4);
  134863. }else{
  134864. return sqlite3_reset(pSelect);
  134865. }
  134866. /* Check for the zero-length marker in the %_segments table */
  134867. rc = fts3IsAppendable(p, iEnd, &bAppendable);
  134868. /* Check that zKey/nKey is larger than the largest key the candidate */
  134869. if( rc==SQLITE_OK && bAppendable ){
  134870. char *aLeaf = 0;
  134871. int nLeaf = 0;
  134872. rc = sqlite3Fts3ReadBlock(p, iLeafEnd, &aLeaf, &nLeaf, 0);
  134873. if( rc==SQLITE_OK ){
  134874. NodeReader reader;
  134875. for(rc = nodeReaderInit(&reader, aLeaf, nLeaf);
  134876. rc==SQLITE_OK && reader.aNode;
  134877. rc = nodeReaderNext(&reader)
  134878. ){
  134879. assert( reader.aNode );
  134880. }
  134881. if( fts3TermCmp(zKey, nKey, reader.term.a, reader.term.n)<=0 ){
  134882. bAppendable = 0;
  134883. }
  134884. nodeReaderRelease(&reader);
  134885. }
  134886. sqlite3_free(aLeaf);
  134887. }
  134888. if( rc==SQLITE_OK && bAppendable ){
  134889. /* It is possible to append to this segment. Set up the IncrmergeWriter
  134890. ** object to do so. */
  134891. int i;
  134892. int nHeight = (int)aRoot[0];
  134893. NodeWriter *pNode;
  134894. pWriter->nLeafEst = (int)((iEnd - iStart) + 1)/FTS_MAX_APPENDABLE_HEIGHT;
  134895. pWriter->iStart = iStart;
  134896. pWriter->iEnd = iEnd;
  134897. pWriter->iAbsLevel = iAbsLevel;
  134898. pWriter->iIdx = iIdx;
  134899. for(i=nHeight+1; i<FTS_MAX_APPENDABLE_HEIGHT; i++){
  134900. pWriter->aNodeWriter[i].iBlock = pWriter->iStart + i*pWriter->nLeafEst;
  134901. }
  134902. pNode = &pWriter->aNodeWriter[nHeight];
  134903. pNode->iBlock = pWriter->iStart + pWriter->nLeafEst*nHeight;
  134904. blobGrowBuffer(&pNode->block, MAX(nRoot, p->nNodeSize), &rc);
  134905. if( rc==SQLITE_OK ){
  134906. memcpy(pNode->block.a, aRoot, nRoot);
  134907. pNode->block.n = nRoot;
  134908. }
  134909. for(i=nHeight; i>=0 && rc==SQLITE_OK; i--){
  134910. NodeReader reader;
  134911. pNode = &pWriter->aNodeWriter[i];
  134912. rc = nodeReaderInit(&reader, pNode->block.a, pNode->block.n);
  134913. while( reader.aNode && rc==SQLITE_OK ) rc = nodeReaderNext(&reader);
  134914. blobGrowBuffer(&pNode->key, reader.term.n, &rc);
  134915. if( rc==SQLITE_OK ){
  134916. memcpy(pNode->key.a, reader.term.a, reader.term.n);
  134917. pNode->key.n = reader.term.n;
  134918. if( i>0 ){
  134919. char *aBlock = 0;
  134920. int nBlock = 0;
  134921. pNode = &pWriter->aNodeWriter[i-1];
  134922. pNode->iBlock = reader.iChild;
  134923. rc = sqlite3Fts3ReadBlock(p, reader.iChild, &aBlock, &nBlock, 0);
  134924. blobGrowBuffer(&pNode->block, MAX(nBlock, p->nNodeSize), &rc);
  134925. if( rc==SQLITE_OK ){
  134926. memcpy(pNode->block.a, aBlock, nBlock);
  134927. pNode->block.n = nBlock;
  134928. }
  134929. sqlite3_free(aBlock);
  134930. }
  134931. }
  134932. nodeReaderRelease(&reader);
  134933. }
  134934. }
  134935. rc2 = sqlite3_reset(pSelect);
  134936. if( rc==SQLITE_OK ) rc = rc2;
  134937. }
  134938. return rc;
  134939. }
  134940. /*
  134941. ** Determine the largest segment index value that exists within absolute
  134942. ** level iAbsLevel+1. If no error occurs, set *piIdx to this value plus
  134943. ** one before returning SQLITE_OK. Or, if there are no segments at all
  134944. ** within level iAbsLevel, set *piIdx to zero.
  134945. **
  134946. ** If an error occurs, return an SQLite error code. The final value of
  134947. ** *piIdx is undefined in this case.
  134948. */
  134949. static int fts3IncrmergeOutputIdx(
  134950. Fts3Table *p, /* FTS Table handle */
  134951. sqlite3_int64 iAbsLevel, /* Absolute index of input segments */
  134952. int *piIdx /* OUT: Next free index at iAbsLevel+1 */
  134953. ){
  134954. int rc;
  134955. sqlite3_stmt *pOutputIdx = 0; /* SQL used to find output index */
  134956. rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pOutputIdx, 0);
  134957. if( rc==SQLITE_OK ){
  134958. sqlite3_bind_int64(pOutputIdx, 1, iAbsLevel+1);
  134959. sqlite3_step(pOutputIdx);
  134960. *piIdx = sqlite3_column_int(pOutputIdx, 0);
  134961. rc = sqlite3_reset(pOutputIdx);
  134962. }
  134963. return rc;
  134964. }
  134965. /*
  134966. ** Allocate an appendable output segment on absolute level iAbsLevel+1
  134967. ** with idx value iIdx.
  134968. **
  134969. ** In the %_segdir table, a segment is defined by the values in three
  134970. ** columns:
  134971. **
  134972. ** start_block
  134973. ** leaves_end_block
  134974. ** end_block
  134975. **
  134976. ** When an appendable segment is allocated, it is estimated that the
  134977. ** maximum number of leaf blocks that may be required is the sum of the
  134978. ** number of leaf blocks consumed by the input segments, plus the number
  134979. ** of input segments, multiplied by two. This value is stored in stack
  134980. ** variable nLeafEst.
  134981. **
  134982. ** A total of 16*nLeafEst blocks are allocated when an appendable segment
  134983. ** is created ((1 + end_block - start_block)==16*nLeafEst). The contiguous
  134984. ** array of leaf nodes starts at the first block allocated. The array
  134985. ** of interior nodes that are parents of the leaf nodes start at block
  134986. ** (start_block + (1 + end_block - start_block) / 16). And so on.
  134987. **
  134988. ** In the actual code below, the value "16" is replaced with the
  134989. ** pre-processor macro FTS_MAX_APPENDABLE_HEIGHT.
  134990. */
  134991. static int fts3IncrmergeWriter(
  134992. Fts3Table *p, /* Fts3 table handle */
  134993. sqlite3_int64 iAbsLevel, /* Absolute level of input segments */
  134994. int iIdx, /* Index of new output segment */
  134995. Fts3MultiSegReader *pCsr, /* Cursor that data will be read from */
  134996. IncrmergeWriter *pWriter /* Populate this object */
  134997. ){
  134998. int rc; /* Return Code */
  134999. int i; /* Iterator variable */
  135000. int nLeafEst = 0; /* Blocks allocated for leaf nodes */
  135001. sqlite3_stmt *pLeafEst = 0; /* SQL used to determine nLeafEst */
  135002. sqlite3_stmt *pFirstBlock = 0; /* SQL used to determine first block */
  135003. /* Calculate nLeafEst. */
  135004. rc = fts3SqlStmt(p, SQL_MAX_LEAF_NODE_ESTIMATE, &pLeafEst, 0);
  135005. if( rc==SQLITE_OK ){
  135006. sqlite3_bind_int64(pLeafEst, 1, iAbsLevel);
  135007. sqlite3_bind_int64(pLeafEst, 2, pCsr->nSegment);
  135008. if( SQLITE_ROW==sqlite3_step(pLeafEst) ){
  135009. nLeafEst = sqlite3_column_int(pLeafEst, 0);
  135010. }
  135011. rc = sqlite3_reset(pLeafEst);
  135012. }
  135013. if( rc!=SQLITE_OK ) return rc;
  135014. /* Calculate the first block to use in the output segment */
  135015. rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pFirstBlock, 0);
  135016. if( rc==SQLITE_OK ){
  135017. if( SQLITE_ROW==sqlite3_step(pFirstBlock) ){
  135018. pWriter->iStart = sqlite3_column_int64(pFirstBlock, 0);
  135019. pWriter->iEnd = pWriter->iStart - 1;
  135020. pWriter->iEnd += nLeafEst * FTS_MAX_APPENDABLE_HEIGHT;
  135021. }
  135022. rc = sqlite3_reset(pFirstBlock);
  135023. }
  135024. if( rc!=SQLITE_OK ) return rc;
  135025. /* Insert the marker in the %_segments table to make sure nobody tries
  135026. ** to steal the space just allocated. This is also used to identify
  135027. ** appendable segments. */
  135028. rc = fts3WriteSegment(p, pWriter->iEnd, 0, 0);
  135029. if( rc!=SQLITE_OK ) return rc;
  135030. pWriter->iAbsLevel = iAbsLevel;
  135031. pWriter->nLeafEst = nLeafEst;
  135032. pWriter->iIdx = iIdx;
  135033. /* Set up the array of NodeWriter objects */
  135034. for(i=0; i<FTS_MAX_APPENDABLE_HEIGHT; i++){
  135035. pWriter->aNodeWriter[i].iBlock = pWriter->iStart + i*pWriter->nLeafEst;
  135036. }
  135037. return SQLITE_OK;
  135038. }
  135039. /*
  135040. ** Remove an entry from the %_segdir table. This involves running the
  135041. ** following two statements:
  135042. **
  135043. ** DELETE FROM %_segdir WHERE level = :iAbsLevel AND idx = :iIdx
  135044. ** UPDATE %_segdir SET idx = idx - 1 WHERE level = :iAbsLevel AND idx > :iIdx
  135045. **
  135046. ** The DELETE statement removes the specific %_segdir level. The UPDATE
  135047. ** statement ensures that the remaining segments have contiguously allocated
  135048. ** idx values.
  135049. */
  135050. static int fts3RemoveSegdirEntry(
  135051. Fts3Table *p, /* FTS3 table handle */
  135052. sqlite3_int64 iAbsLevel, /* Absolute level to delete from */
  135053. int iIdx /* Index of %_segdir entry to delete */
  135054. ){
  135055. int rc; /* Return code */
  135056. sqlite3_stmt *pDelete = 0; /* DELETE statement */
  135057. rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_ENTRY, &pDelete, 0);
  135058. if( rc==SQLITE_OK ){
  135059. sqlite3_bind_int64(pDelete, 1, iAbsLevel);
  135060. sqlite3_bind_int(pDelete, 2, iIdx);
  135061. sqlite3_step(pDelete);
  135062. rc = sqlite3_reset(pDelete);
  135063. }
  135064. return rc;
  135065. }
  135066. /*
  135067. ** One or more segments have just been removed from absolute level iAbsLevel.
  135068. ** Update the 'idx' values of the remaining segments in the level so that
  135069. ** the idx values are a contiguous sequence starting from 0.
  135070. */
  135071. static int fts3RepackSegdirLevel(
  135072. Fts3Table *p, /* FTS3 table handle */
  135073. sqlite3_int64 iAbsLevel /* Absolute level to repack */
  135074. ){
  135075. int rc; /* Return code */
  135076. int *aIdx = 0; /* Array of remaining idx values */
  135077. int nIdx = 0; /* Valid entries in aIdx[] */
  135078. int nAlloc = 0; /* Allocated size of aIdx[] */
  135079. int i; /* Iterator variable */
  135080. sqlite3_stmt *pSelect = 0; /* Select statement to read idx values */
  135081. sqlite3_stmt *pUpdate = 0; /* Update statement to modify idx values */
  135082. rc = fts3SqlStmt(p, SQL_SELECT_INDEXES, &pSelect, 0);
  135083. if( rc==SQLITE_OK ){
  135084. int rc2;
  135085. sqlite3_bind_int64(pSelect, 1, iAbsLevel);
  135086. while( SQLITE_ROW==sqlite3_step(pSelect) ){
  135087. if( nIdx>=nAlloc ){
  135088. int *aNew;
  135089. nAlloc += 16;
  135090. aNew = sqlite3_realloc(aIdx, nAlloc*sizeof(int));
  135091. if( !aNew ){
  135092. rc = SQLITE_NOMEM;
  135093. break;
  135094. }
  135095. aIdx = aNew;
  135096. }
  135097. aIdx[nIdx++] = sqlite3_column_int(pSelect, 0);
  135098. }
  135099. rc2 = sqlite3_reset(pSelect);
  135100. if( rc==SQLITE_OK ) rc = rc2;
  135101. }
  135102. if( rc==SQLITE_OK ){
  135103. rc = fts3SqlStmt(p, SQL_SHIFT_SEGDIR_ENTRY, &pUpdate, 0);
  135104. }
  135105. if( rc==SQLITE_OK ){
  135106. sqlite3_bind_int64(pUpdate, 2, iAbsLevel);
  135107. }
  135108. assert( p->bIgnoreSavepoint==0 );
  135109. p->bIgnoreSavepoint = 1;
  135110. for(i=0; rc==SQLITE_OK && i<nIdx; i++){
  135111. if( aIdx[i]!=i ){
  135112. sqlite3_bind_int(pUpdate, 3, aIdx[i]);
  135113. sqlite3_bind_int(pUpdate, 1, i);
  135114. sqlite3_step(pUpdate);
  135115. rc = sqlite3_reset(pUpdate);
  135116. }
  135117. }
  135118. p->bIgnoreSavepoint = 0;
  135119. sqlite3_free(aIdx);
  135120. return rc;
  135121. }
  135122. static void fts3StartNode(Blob *pNode, int iHeight, sqlite3_int64 iChild){
  135123. pNode->a[0] = (char)iHeight;
  135124. if( iChild ){
  135125. assert( pNode->nAlloc>=1+sqlite3Fts3VarintLen(iChild) );
  135126. pNode->n = 1 + sqlite3Fts3PutVarint(&pNode->a[1], iChild);
  135127. }else{
  135128. assert( pNode->nAlloc>=1 );
  135129. pNode->n = 1;
  135130. }
  135131. }
  135132. /*
  135133. ** The first two arguments are a pointer to and the size of a segment b-tree
  135134. ** node. The node may be a leaf or an internal node.
  135135. **
  135136. ** This function creates a new node image in blob object *pNew by copying
  135137. ** all terms that are greater than or equal to zTerm/nTerm (for leaf nodes)
  135138. ** or greater than zTerm/nTerm (for internal nodes) from aNode/nNode.
  135139. */
  135140. static int fts3TruncateNode(
  135141. const char *aNode, /* Current node image */
  135142. int nNode, /* Size of aNode in bytes */
  135143. Blob *pNew, /* OUT: Write new node image here */
  135144. const char *zTerm, /* Omit all terms smaller than this */
  135145. int nTerm, /* Size of zTerm in bytes */
  135146. sqlite3_int64 *piBlock /* OUT: Block number in next layer down */
  135147. ){
  135148. NodeReader reader; /* Reader object */
  135149. Blob prev = {0, 0, 0}; /* Previous term written to new node */
  135150. int rc = SQLITE_OK; /* Return code */
  135151. int bLeaf = aNode[0]=='\0'; /* True for a leaf node */
  135152. /* Allocate required output space */
  135153. blobGrowBuffer(pNew, nNode, &rc);
  135154. if( rc!=SQLITE_OK ) return rc;
  135155. pNew->n = 0;
  135156. /* Populate new node buffer */
  135157. for(rc = nodeReaderInit(&reader, aNode, nNode);
  135158. rc==SQLITE_OK && reader.aNode;
  135159. rc = nodeReaderNext(&reader)
  135160. ){
  135161. if( pNew->n==0 ){
  135162. int res = fts3TermCmp(reader.term.a, reader.term.n, zTerm, nTerm);
  135163. if( res<0 || (bLeaf==0 && res==0) ) continue;
  135164. fts3StartNode(pNew, (int)aNode[0], reader.iChild);
  135165. *piBlock = reader.iChild;
  135166. }
  135167. rc = fts3AppendToNode(
  135168. pNew, &prev, reader.term.a, reader.term.n,
  135169. reader.aDoclist, reader.nDoclist
  135170. );
  135171. if( rc!=SQLITE_OK ) break;
  135172. }
  135173. if( pNew->n==0 ){
  135174. fts3StartNode(pNew, (int)aNode[0], reader.iChild);
  135175. *piBlock = reader.iChild;
  135176. }
  135177. assert( pNew->n<=pNew->nAlloc );
  135178. nodeReaderRelease(&reader);
  135179. sqlite3_free(prev.a);
  135180. return rc;
  135181. }
  135182. /*
  135183. ** Remove all terms smaller than zTerm/nTerm from segment iIdx in absolute
  135184. ** level iAbsLevel. This may involve deleting entries from the %_segments
  135185. ** table, and modifying existing entries in both the %_segments and %_segdir
  135186. ** tables.
  135187. **
  135188. ** SQLITE_OK is returned if the segment is updated successfully. Or an
  135189. ** SQLite error code otherwise.
  135190. */
  135191. static int fts3TruncateSegment(
  135192. Fts3Table *p, /* FTS3 table handle */
  135193. sqlite3_int64 iAbsLevel, /* Absolute level of segment to modify */
  135194. int iIdx, /* Index within level of segment to modify */
  135195. const char *zTerm, /* Remove terms smaller than this */
  135196. int nTerm /* Number of bytes in buffer zTerm */
  135197. ){
  135198. int rc = SQLITE_OK; /* Return code */
  135199. Blob root = {0,0,0}; /* New root page image */
  135200. Blob block = {0,0,0}; /* Buffer used for any other block */
  135201. sqlite3_int64 iBlock = 0; /* Block id */
  135202. sqlite3_int64 iNewStart = 0; /* New value for iStartBlock */
  135203. sqlite3_int64 iOldStart = 0; /* Old value for iStartBlock */
  135204. sqlite3_stmt *pFetch = 0; /* Statement used to fetch segdir */
  135205. rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR, &pFetch, 0);
  135206. if( rc==SQLITE_OK ){
  135207. int rc2; /* sqlite3_reset() return code */
  135208. sqlite3_bind_int64(pFetch, 1, iAbsLevel);
  135209. sqlite3_bind_int(pFetch, 2, iIdx);
  135210. if( SQLITE_ROW==sqlite3_step(pFetch) ){
  135211. const char *aRoot = sqlite3_column_blob(pFetch, 4);
  135212. int nRoot = sqlite3_column_bytes(pFetch, 4);
  135213. iOldStart = sqlite3_column_int64(pFetch, 1);
  135214. rc = fts3TruncateNode(aRoot, nRoot, &root, zTerm, nTerm, &iBlock);
  135215. }
  135216. rc2 = sqlite3_reset(pFetch);
  135217. if( rc==SQLITE_OK ) rc = rc2;
  135218. }
  135219. while( rc==SQLITE_OK && iBlock ){
  135220. char *aBlock = 0;
  135221. int nBlock = 0;
  135222. iNewStart = iBlock;
  135223. rc = sqlite3Fts3ReadBlock(p, iBlock, &aBlock, &nBlock, 0);
  135224. if( rc==SQLITE_OK ){
  135225. rc = fts3TruncateNode(aBlock, nBlock, &block, zTerm, nTerm, &iBlock);
  135226. }
  135227. if( rc==SQLITE_OK ){
  135228. rc = fts3WriteSegment(p, iNewStart, block.a, block.n);
  135229. }
  135230. sqlite3_free(aBlock);
  135231. }
  135232. /* Variable iNewStart now contains the first valid leaf node. */
  135233. if( rc==SQLITE_OK && iNewStart ){
  135234. sqlite3_stmt *pDel = 0;
  135235. rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDel, 0);
  135236. if( rc==SQLITE_OK ){
  135237. sqlite3_bind_int64(pDel, 1, iOldStart);
  135238. sqlite3_bind_int64(pDel, 2, iNewStart-1);
  135239. sqlite3_step(pDel);
  135240. rc = sqlite3_reset(pDel);
  135241. }
  135242. }
  135243. if( rc==SQLITE_OK ){
  135244. sqlite3_stmt *pChomp = 0;
  135245. rc = fts3SqlStmt(p, SQL_CHOMP_SEGDIR, &pChomp, 0);
  135246. if( rc==SQLITE_OK ){
  135247. sqlite3_bind_int64(pChomp, 1, iNewStart);
  135248. sqlite3_bind_blob(pChomp, 2, root.a, root.n, SQLITE_STATIC);
  135249. sqlite3_bind_int64(pChomp, 3, iAbsLevel);
  135250. sqlite3_bind_int(pChomp, 4, iIdx);
  135251. sqlite3_step(pChomp);
  135252. rc = sqlite3_reset(pChomp);
  135253. }
  135254. }
  135255. sqlite3_free(root.a);
  135256. sqlite3_free(block.a);
  135257. return rc;
  135258. }
  135259. /*
  135260. ** This function is called after an incrmental-merge operation has run to
  135261. ** merge (or partially merge) two or more segments from absolute level
  135262. ** iAbsLevel.
  135263. **
  135264. ** Each input segment is either removed from the db completely (if all of
  135265. ** its data was copied to the output segment by the incrmerge operation)
  135266. ** or modified in place so that it no longer contains those entries that
  135267. ** have been duplicated in the output segment.
  135268. */
  135269. static int fts3IncrmergeChomp(
  135270. Fts3Table *p, /* FTS table handle */
  135271. sqlite3_int64 iAbsLevel, /* Absolute level containing segments */
  135272. Fts3MultiSegReader *pCsr, /* Chomp all segments opened by this cursor */
  135273. int *pnRem /* Number of segments not deleted */
  135274. ){
  135275. int i;
  135276. int nRem = 0;
  135277. int rc = SQLITE_OK;
  135278. for(i=pCsr->nSegment-1; i>=0 && rc==SQLITE_OK; i--){
  135279. Fts3SegReader *pSeg = 0;
  135280. int j;
  135281. /* Find the Fts3SegReader object with Fts3SegReader.iIdx==i. It is hiding
  135282. ** somewhere in the pCsr->apSegment[] array. */
  135283. for(j=0; ALWAYS(j<pCsr->nSegment); j++){
  135284. pSeg = pCsr->apSegment[j];
  135285. if( pSeg->iIdx==i ) break;
  135286. }
  135287. assert( j<pCsr->nSegment && pSeg->iIdx==i );
  135288. if( pSeg->aNode==0 ){
  135289. /* Seg-reader is at EOF. Remove the entire input segment. */
  135290. rc = fts3DeleteSegment(p, pSeg);
  135291. if( rc==SQLITE_OK ){
  135292. rc = fts3RemoveSegdirEntry(p, iAbsLevel, pSeg->iIdx);
  135293. }
  135294. *pnRem = 0;
  135295. }else{
  135296. /* The incremental merge did not copy all the data from this
  135297. ** segment to the upper level. The segment is modified in place
  135298. ** so that it contains no keys smaller than zTerm/nTerm. */
  135299. const char *zTerm = pSeg->zTerm;
  135300. int nTerm = pSeg->nTerm;
  135301. rc = fts3TruncateSegment(p, iAbsLevel, pSeg->iIdx, zTerm, nTerm);
  135302. nRem++;
  135303. }
  135304. }
  135305. if( rc==SQLITE_OK && nRem!=pCsr->nSegment ){
  135306. rc = fts3RepackSegdirLevel(p, iAbsLevel);
  135307. }
  135308. *pnRem = nRem;
  135309. return rc;
  135310. }
  135311. /*
  135312. ** Store an incr-merge hint in the database.
  135313. */
  135314. static int fts3IncrmergeHintStore(Fts3Table *p, Blob *pHint){
  135315. sqlite3_stmt *pReplace = 0;
  135316. int rc; /* Return code */
  135317. rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pReplace, 0);
  135318. if( rc==SQLITE_OK ){
  135319. sqlite3_bind_int(pReplace, 1, FTS_STAT_INCRMERGEHINT);
  135320. sqlite3_bind_blob(pReplace, 2, pHint->a, pHint->n, SQLITE_STATIC);
  135321. sqlite3_step(pReplace);
  135322. rc = sqlite3_reset(pReplace);
  135323. }
  135324. return rc;
  135325. }
  135326. /*
  135327. ** Load an incr-merge hint from the database. The incr-merge hint, if one
  135328. ** exists, is stored in the rowid==1 row of the %_stat table.
  135329. **
  135330. ** If successful, populate blob *pHint with the value read from the %_stat
  135331. ** table and return SQLITE_OK. Otherwise, if an error occurs, return an
  135332. ** SQLite error code.
  135333. */
  135334. static int fts3IncrmergeHintLoad(Fts3Table *p, Blob *pHint){
  135335. sqlite3_stmt *pSelect = 0;
  135336. int rc;
  135337. pHint->n = 0;
  135338. rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pSelect, 0);
  135339. if( rc==SQLITE_OK ){
  135340. int rc2;
  135341. sqlite3_bind_int(pSelect, 1, FTS_STAT_INCRMERGEHINT);
  135342. if( SQLITE_ROW==sqlite3_step(pSelect) ){
  135343. const char *aHint = sqlite3_column_blob(pSelect, 0);
  135344. int nHint = sqlite3_column_bytes(pSelect, 0);
  135345. if( aHint ){
  135346. blobGrowBuffer(pHint, nHint, &rc);
  135347. if( rc==SQLITE_OK ){
  135348. memcpy(pHint->a, aHint, nHint);
  135349. pHint->n = nHint;
  135350. }
  135351. }
  135352. }
  135353. rc2 = sqlite3_reset(pSelect);
  135354. if( rc==SQLITE_OK ) rc = rc2;
  135355. }
  135356. return rc;
  135357. }
  135358. /*
  135359. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
  135360. ** Otherwise, append an entry to the hint stored in blob *pHint. Each entry
  135361. ** consists of two varints, the absolute level number of the input segments
  135362. ** and the number of input segments.
  135363. **
  135364. ** If successful, leave *pRc set to SQLITE_OK and return. If an error occurs,
  135365. ** set *pRc to an SQLite error code before returning.
  135366. */
  135367. static void fts3IncrmergeHintPush(
  135368. Blob *pHint, /* Hint blob to append to */
  135369. i64 iAbsLevel, /* First varint to store in hint */
  135370. int nInput, /* Second varint to store in hint */
  135371. int *pRc /* IN/OUT: Error code */
  135372. ){
  135373. blobGrowBuffer(pHint, pHint->n + 2*FTS3_VARINT_MAX, pRc);
  135374. if( *pRc==SQLITE_OK ){
  135375. pHint->n += sqlite3Fts3PutVarint(&pHint->a[pHint->n], iAbsLevel);
  135376. pHint->n += sqlite3Fts3PutVarint(&pHint->a[pHint->n], (i64)nInput);
  135377. }
  135378. }
  135379. /*
  135380. ** Read the last entry (most recently pushed) from the hint blob *pHint
  135381. ** and then remove the entry. Write the two values read to *piAbsLevel and
  135382. ** *pnInput before returning.
  135383. **
  135384. ** If no error occurs, return SQLITE_OK. If the hint blob in *pHint does
  135385. ** not contain at least two valid varints, return SQLITE_CORRUPT_VTAB.
  135386. */
  135387. static int fts3IncrmergeHintPop(Blob *pHint, i64 *piAbsLevel, int *pnInput){
  135388. const int nHint = pHint->n;
  135389. int i;
  135390. i = pHint->n-2;
  135391. while( i>0 && (pHint->a[i-1] & 0x80) ) i--;
  135392. while( i>0 && (pHint->a[i-1] & 0x80) ) i--;
  135393. pHint->n = i;
  135394. i += sqlite3Fts3GetVarint(&pHint->a[i], piAbsLevel);
  135395. i += fts3GetVarint32(&pHint->a[i], pnInput);
  135396. if( i!=nHint ) return SQLITE_CORRUPT_VTAB;
  135397. return SQLITE_OK;
  135398. }
  135399. /*
  135400. ** Attempt an incremental merge that writes nMerge leaf blocks.
  135401. **
  135402. ** Incremental merges happen nMin segments at a time. The segments
  135403. ** to be merged are the nMin oldest segments (the ones with the smallest
  135404. ** values for the _segdir.idx field) in the highest level that contains
  135405. ** at least nMin segments. Multiple merges might occur in an attempt to
  135406. ** write the quota of nMerge leaf blocks.
  135407. */
  135408. SQLITE_PRIVATE int sqlite3Fts3Incrmerge(Fts3Table *p, int nMerge, int nMin){
  135409. int rc; /* Return code */
  135410. int nRem = nMerge; /* Number of leaf pages yet to be written */
  135411. Fts3MultiSegReader *pCsr; /* Cursor used to read input data */
  135412. Fts3SegFilter *pFilter; /* Filter used with cursor pCsr */
  135413. IncrmergeWriter *pWriter; /* Writer object */
  135414. int nSeg = 0; /* Number of input segments */
  135415. sqlite3_int64 iAbsLevel = 0; /* Absolute level number to work on */
  135416. Blob hint = {0, 0, 0}; /* Hint read from %_stat table */
  135417. int bDirtyHint = 0; /* True if blob 'hint' has been modified */
  135418. /* Allocate space for the cursor, filter and writer objects */
  135419. const int nAlloc = sizeof(*pCsr) + sizeof(*pFilter) + sizeof(*pWriter);
  135420. pWriter = (IncrmergeWriter *)sqlite3_malloc(nAlloc);
  135421. if( !pWriter ) return SQLITE_NOMEM;
  135422. pFilter = (Fts3SegFilter *)&pWriter[1];
  135423. pCsr = (Fts3MultiSegReader *)&pFilter[1];
  135424. rc = fts3IncrmergeHintLoad(p, &hint);
  135425. while( rc==SQLITE_OK && nRem>0 ){
  135426. const i64 nMod = FTS3_SEGDIR_MAXLEVEL * p->nIndex;
  135427. sqlite3_stmt *pFindLevel = 0; /* SQL used to determine iAbsLevel */
  135428. int bUseHint = 0; /* True if attempting to append */
  135429. int iIdx = 0; /* Largest idx in level (iAbsLevel+1) */
  135430. /* Search the %_segdir table for the absolute level with the smallest
  135431. ** relative level number that contains at least nMin segments, if any.
  135432. ** If one is found, set iAbsLevel to the absolute level number and
  135433. ** nSeg to nMin. If no level with at least nMin segments can be found,
  135434. ** set nSeg to -1.
  135435. */
  135436. rc = fts3SqlStmt(p, SQL_FIND_MERGE_LEVEL, &pFindLevel, 0);
  135437. sqlite3_bind_int(pFindLevel, 1, nMin);
  135438. if( sqlite3_step(pFindLevel)==SQLITE_ROW ){
  135439. iAbsLevel = sqlite3_column_int64(pFindLevel, 0);
  135440. nSeg = nMin;
  135441. }else{
  135442. nSeg = -1;
  135443. }
  135444. rc = sqlite3_reset(pFindLevel);
  135445. /* If the hint read from the %_stat table is not empty, check if the
  135446. ** last entry in it specifies a relative level smaller than or equal
  135447. ** to the level identified by the block above (if any). If so, this
  135448. ** iteration of the loop will work on merging at the hinted level.
  135449. */
  135450. if( rc==SQLITE_OK && hint.n ){
  135451. int nHint = hint.n;
  135452. sqlite3_int64 iHintAbsLevel = 0; /* Hint level */
  135453. int nHintSeg = 0; /* Hint number of segments */
  135454. rc = fts3IncrmergeHintPop(&hint, &iHintAbsLevel, &nHintSeg);
  135455. if( nSeg<0 || (iAbsLevel % nMod) >= (iHintAbsLevel % nMod) ){
  135456. iAbsLevel = iHintAbsLevel;
  135457. nSeg = nHintSeg;
  135458. bUseHint = 1;
  135459. bDirtyHint = 1;
  135460. }else{
  135461. /* This undoes the effect of the HintPop() above - so that no entry
  135462. ** is removed from the hint blob. */
  135463. hint.n = nHint;
  135464. }
  135465. }
  135466. /* If nSeg is less that zero, then there is no level with at least
  135467. ** nMin segments and no hint in the %_stat table. No work to do.
  135468. ** Exit early in this case. */
  135469. if( nSeg<0 ) break;
  135470. /* Open a cursor to iterate through the contents of the oldest nSeg
  135471. ** indexes of absolute level iAbsLevel. If this cursor is opened using
  135472. ** the 'hint' parameters, it is possible that there are less than nSeg
  135473. ** segments available in level iAbsLevel. In this case, no work is
  135474. ** done on iAbsLevel - fall through to the next iteration of the loop
  135475. ** to start work on some other level. */
  135476. memset(pWriter, 0, nAlloc);
  135477. pFilter->flags = FTS3_SEGMENT_REQUIRE_POS;
  135478. if( rc==SQLITE_OK ){
  135479. rc = fts3IncrmergeOutputIdx(p, iAbsLevel, &iIdx);
  135480. assert( bUseHint==1 || bUseHint==0 );
  135481. if( iIdx==0 || (bUseHint && iIdx==1) ){
  135482. int bIgnore = 0;
  135483. rc = fts3SegmentIsMaxLevel(p, iAbsLevel+1, &bIgnore);
  135484. if( bIgnore ){
  135485. pFilter->flags |= FTS3_SEGMENT_IGNORE_EMPTY;
  135486. }
  135487. }
  135488. }
  135489. if( rc==SQLITE_OK ){
  135490. rc = fts3IncrmergeCsr(p, iAbsLevel, nSeg, pCsr);
  135491. }
  135492. if( SQLITE_OK==rc && pCsr->nSegment==nSeg
  135493. && SQLITE_OK==(rc = sqlite3Fts3SegReaderStart(p, pCsr, pFilter))
  135494. && SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, pCsr))
  135495. ){
  135496. if( bUseHint && iIdx>0 ){
  135497. const char *zKey = pCsr->zTerm;
  135498. int nKey = pCsr->nTerm;
  135499. rc = fts3IncrmergeLoad(p, iAbsLevel, iIdx-1, zKey, nKey, pWriter);
  135500. }else{
  135501. rc = fts3IncrmergeWriter(p, iAbsLevel, iIdx, pCsr, pWriter);
  135502. }
  135503. if( rc==SQLITE_OK && pWriter->nLeafEst ){
  135504. fts3LogMerge(nSeg, iAbsLevel);
  135505. do {
  135506. rc = fts3IncrmergeAppend(p, pWriter, pCsr);
  135507. if( rc==SQLITE_OK ) rc = sqlite3Fts3SegReaderStep(p, pCsr);
  135508. if( pWriter->nWork>=nRem && rc==SQLITE_ROW ) rc = SQLITE_OK;
  135509. }while( rc==SQLITE_ROW );
  135510. /* Update or delete the input segments */
  135511. if( rc==SQLITE_OK ){
  135512. nRem -= (1 + pWriter->nWork);
  135513. rc = fts3IncrmergeChomp(p, iAbsLevel, pCsr, &nSeg);
  135514. if( nSeg!=0 ){
  135515. bDirtyHint = 1;
  135516. fts3IncrmergeHintPush(&hint, iAbsLevel, nSeg, &rc);
  135517. }
  135518. }
  135519. }
  135520. if( nSeg!=0 ){
  135521. pWriter->nLeafData = pWriter->nLeafData * -1;
  135522. }
  135523. fts3IncrmergeRelease(p, pWriter, &rc);
  135524. if( nSeg==0 && pWriter->bNoLeafData==0 ){
  135525. fts3PromoteSegments(p, iAbsLevel+1, pWriter->nLeafData);
  135526. }
  135527. }
  135528. sqlite3Fts3SegReaderFinish(pCsr);
  135529. }
  135530. /* Write the hint values into the %_stat table for the next incr-merger */
  135531. if( bDirtyHint && rc==SQLITE_OK ){
  135532. rc = fts3IncrmergeHintStore(p, &hint);
  135533. }
  135534. sqlite3_free(pWriter);
  135535. sqlite3_free(hint.a);
  135536. return rc;
  135537. }
  135538. /*
  135539. ** Convert the text beginning at *pz into an integer and return
  135540. ** its value. Advance *pz to point to the first character past
  135541. ** the integer.
  135542. */
  135543. static int fts3Getint(const char **pz){
  135544. const char *z = *pz;
  135545. int i = 0;
  135546. while( (*z)>='0' && (*z)<='9' ) i = 10*i + *(z++) - '0';
  135547. *pz = z;
  135548. return i;
  135549. }
  135550. /*
  135551. ** Process statements of the form:
  135552. **
  135553. ** INSERT INTO table(table) VALUES('merge=A,B');
  135554. **
  135555. ** A and B are integers that decode to be the number of leaf pages
  135556. ** written for the merge, and the minimum number of segments on a level
  135557. ** before it will be selected for a merge, respectively.
  135558. */
  135559. static int fts3DoIncrmerge(
  135560. Fts3Table *p, /* FTS3 table handle */
  135561. const char *zParam /* Nul-terminated string containing "A,B" */
  135562. ){
  135563. int rc;
  135564. int nMin = (FTS3_MERGE_COUNT / 2);
  135565. int nMerge = 0;
  135566. const char *z = zParam;
  135567. /* Read the first integer value */
  135568. nMerge = fts3Getint(&z);
  135569. /* If the first integer value is followed by a ',', read the second
  135570. ** integer value. */
  135571. if( z[0]==',' && z[1]!='\0' ){
  135572. z++;
  135573. nMin = fts3Getint(&z);
  135574. }
  135575. if( z[0]!='\0' || nMin<2 ){
  135576. rc = SQLITE_ERROR;
  135577. }else{
  135578. rc = SQLITE_OK;
  135579. if( !p->bHasStat ){
  135580. assert( p->bFts4==0 );
  135581. sqlite3Fts3CreateStatTable(&rc, p);
  135582. }
  135583. if( rc==SQLITE_OK ){
  135584. rc = sqlite3Fts3Incrmerge(p, nMerge, nMin);
  135585. }
  135586. sqlite3Fts3SegmentsClose(p);
  135587. }
  135588. return rc;
  135589. }
  135590. /*
  135591. ** Process statements of the form:
  135592. **
  135593. ** INSERT INTO table(table) VALUES('automerge=X');
  135594. **
  135595. ** where X is an integer. X==0 means to turn automerge off. X!=0 means
  135596. ** turn it on. The setting is persistent.
  135597. */
  135598. static int fts3DoAutoincrmerge(
  135599. Fts3Table *p, /* FTS3 table handle */
  135600. const char *zParam /* Nul-terminated string containing boolean */
  135601. ){
  135602. int rc = SQLITE_OK;
  135603. sqlite3_stmt *pStmt = 0;
  135604. p->nAutoincrmerge = fts3Getint(&zParam);
  135605. if( p->nAutoincrmerge==1 || p->nAutoincrmerge>FTS3_MERGE_COUNT ){
  135606. p->nAutoincrmerge = 8;
  135607. }
  135608. if( !p->bHasStat ){
  135609. assert( p->bFts4==0 );
  135610. sqlite3Fts3CreateStatTable(&rc, p);
  135611. if( rc ) return rc;
  135612. }
  135613. rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pStmt, 0);
  135614. if( rc ) return rc;
  135615. sqlite3_bind_int(pStmt, 1, FTS_STAT_AUTOINCRMERGE);
  135616. sqlite3_bind_int(pStmt, 2, p->nAutoincrmerge);
  135617. sqlite3_step(pStmt);
  135618. rc = sqlite3_reset(pStmt);
  135619. return rc;
  135620. }
  135621. /*
  135622. ** Return a 64-bit checksum for the FTS index entry specified by the
  135623. ** arguments to this function.
  135624. */
  135625. static u64 fts3ChecksumEntry(
  135626. const char *zTerm, /* Pointer to buffer containing term */
  135627. int nTerm, /* Size of zTerm in bytes */
  135628. int iLangid, /* Language id for current row */
  135629. int iIndex, /* Index (0..Fts3Table.nIndex-1) */
  135630. i64 iDocid, /* Docid for current row. */
  135631. int iCol, /* Column number */
  135632. int iPos /* Position */
  135633. ){
  135634. int i;
  135635. u64 ret = (u64)iDocid;
  135636. ret += (ret<<3) + iLangid;
  135637. ret += (ret<<3) + iIndex;
  135638. ret += (ret<<3) + iCol;
  135639. ret += (ret<<3) + iPos;
  135640. for(i=0; i<nTerm; i++) ret += (ret<<3) + zTerm[i];
  135641. return ret;
  135642. }
  135643. /*
  135644. ** Return a checksum of all entries in the FTS index that correspond to
  135645. ** language id iLangid. The checksum is calculated by XORing the checksums
  135646. ** of each individual entry (see fts3ChecksumEntry()) together.
  135647. **
  135648. ** If successful, the checksum value is returned and *pRc set to SQLITE_OK.
  135649. ** Otherwise, if an error occurs, *pRc is set to an SQLite error code. The
  135650. ** return value is undefined in this case.
  135651. */
  135652. static u64 fts3ChecksumIndex(
  135653. Fts3Table *p, /* FTS3 table handle */
  135654. int iLangid, /* Language id to return cksum for */
  135655. int iIndex, /* Index to cksum (0..p->nIndex-1) */
  135656. int *pRc /* OUT: Return code */
  135657. ){
  135658. Fts3SegFilter filter;
  135659. Fts3MultiSegReader csr;
  135660. int rc;
  135661. u64 cksum = 0;
  135662. assert( *pRc==SQLITE_OK );
  135663. memset(&filter, 0, sizeof(filter));
  135664. memset(&csr, 0, sizeof(csr));
  135665. filter.flags = FTS3_SEGMENT_REQUIRE_POS|FTS3_SEGMENT_IGNORE_EMPTY;
  135666. filter.flags |= FTS3_SEGMENT_SCAN;
  135667. rc = sqlite3Fts3SegReaderCursor(
  135668. p, iLangid, iIndex, FTS3_SEGCURSOR_ALL, 0, 0, 0, 1,&csr
  135669. );
  135670. if( rc==SQLITE_OK ){
  135671. rc = sqlite3Fts3SegReaderStart(p, &csr, &filter);
  135672. }
  135673. if( rc==SQLITE_OK ){
  135674. while( SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, &csr)) ){
  135675. char *pCsr = csr.aDoclist;
  135676. char *pEnd = &pCsr[csr.nDoclist];
  135677. i64 iDocid = 0;
  135678. i64 iCol = 0;
  135679. i64 iPos = 0;
  135680. pCsr += sqlite3Fts3GetVarint(pCsr, &iDocid);
  135681. while( pCsr<pEnd ){
  135682. i64 iVal = 0;
  135683. pCsr += sqlite3Fts3GetVarint(pCsr, &iVal);
  135684. if( pCsr<pEnd ){
  135685. if( iVal==0 || iVal==1 ){
  135686. iCol = 0;
  135687. iPos = 0;
  135688. if( iVal ){
  135689. pCsr += sqlite3Fts3GetVarint(pCsr, &iCol);
  135690. }else{
  135691. pCsr += sqlite3Fts3GetVarint(pCsr, &iVal);
  135692. iDocid += iVal;
  135693. }
  135694. }else{
  135695. iPos += (iVal - 2);
  135696. cksum = cksum ^ fts3ChecksumEntry(
  135697. csr.zTerm, csr.nTerm, iLangid, iIndex, iDocid,
  135698. (int)iCol, (int)iPos
  135699. );
  135700. }
  135701. }
  135702. }
  135703. }
  135704. }
  135705. sqlite3Fts3SegReaderFinish(&csr);
  135706. *pRc = rc;
  135707. return cksum;
  135708. }
  135709. /*
  135710. ** Check if the contents of the FTS index match the current contents of the
  135711. ** content table. If no error occurs and the contents do match, set *pbOk
  135712. ** to true and return SQLITE_OK. Or if the contents do not match, set *pbOk
  135713. ** to false before returning.
  135714. **
  135715. ** If an error occurs (e.g. an OOM or IO error), return an SQLite error
  135716. ** code. The final value of *pbOk is undefined in this case.
  135717. */
  135718. static int fts3IntegrityCheck(Fts3Table *p, int *pbOk){
  135719. int rc = SQLITE_OK; /* Return code */
  135720. u64 cksum1 = 0; /* Checksum based on FTS index contents */
  135721. u64 cksum2 = 0; /* Checksum based on %_content contents */
  135722. sqlite3_stmt *pAllLangid = 0; /* Statement to return all language-ids */
  135723. /* This block calculates the checksum according to the FTS index. */
  135724. rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);
  135725. if( rc==SQLITE_OK ){
  135726. int rc2;
  135727. sqlite3_bind_int(pAllLangid, 1, p->nIndex);
  135728. while( rc==SQLITE_OK && sqlite3_step(pAllLangid)==SQLITE_ROW ){
  135729. int iLangid = sqlite3_column_int(pAllLangid, 0);
  135730. int i;
  135731. for(i=0; i<p->nIndex; i++){
  135732. cksum1 = cksum1 ^ fts3ChecksumIndex(p, iLangid, i, &rc);
  135733. }
  135734. }
  135735. rc2 = sqlite3_reset(pAllLangid);
  135736. if( rc==SQLITE_OK ) rc = rc2;
  135737. }
  135738. /* This block calculates the checksum according to the %_content table */
  135739. rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);
  135740. if( rc==SQLITE_OK ){
  135741. sqlite3_tokenizer_module const *pModule = p->pTokenizer->pModule;
  135742. sqlite3_stmt *pStmt = 0;
  135743. char *zSql;
  135744. zSql = sqlite3_mprintf("SELECT %s" , p->zReadExprlist);
  135745. if( !zSql ){
  135746. rc = SQLITE_NOMEM;
  135747. }else{
  135748. rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
  135749. sqlite3_free(zSql);
  135750. }
  135751. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
  135752. i64 iDocid = sqlite3_column_int64(pStmt, 0);
  135753. int iLang = langidFromSelect(p, pStmt);
  135754. int iCol;
  135755. for(iCol=0; rc==SQLITE_OK && iCol<p->nColumn; iCol++){
  135756. if( p->abNotindexed[iCol]==0 ){
  135757. const char *zText = (const char *)sqlite3_column_text(pStmt, iCol+1);
  135758. int nText = sqlite3_column_bytes(pStmt, iCol+1);
  135759. sqlite3_tokenizer_cursor *pT = 0;
  135760. rc = sqlite3Fts3OpenTokenizer(p->pTokenizer, iLang, zText, nText,&pT);
  135761. while( rc==SQLITE_OK ){
  135762. char const *zToken; /* Buffer containing token */
  135763. int nToken = 0; /* Number of bytes in token */
  135764. int iDum1 = 0, iDum2 = 0; /* Dummy variables */
  135765. int iPos = 0; /* Position of token in zText */
  135766. rc = pModule->xNext(pT, &zToken, &nToken, &iDum1, &iDum2, &iPos);
  135767. if( rc==SQLITE_OK ){
  135768. int i;
  135769. cksum2 = cksum2 ^ fts3ChecksumEntry(
  135770. zToken, nToken, iLang, 0, iDocid, iCol, iPos
  135771. );
  135772. for(i=1; i<p->nIndex; i++){
  135773. if( p->aIndex[i].nPrefix<=nToken ){
  135774. cksum2 = cksum2 ^ fts3ChecksumEntry(
  135775. zToken, p->aIndex[i].nPrefix, iLang, i, iDocid, iCol, iPos
  135776. );
  135777. }
  135778. }
  135779. }
  135780. }
  135781. if( pT ) pModule->xClose(pT);
  135782. if( rc==SQLITE_DONE ) rc = SQLITE_OK;
  135783. }
  135784. }
  135785. }
  135786. sqlite3_finalize(pStmt);
  135787. }
  135788. *pbOk = (cksum1==cksum2);
  135789. return rc;
  135790. }
  135791. /*
  135792. ** Run the integrity-check. If no error occurs and the current contents of
  135793. ** the FTS index are correct, return SQLITE_OK. Or, if the contents of the
  135794. ** FTS index are incorrect, return SQLITE_CORRUPT_VTAB.
  135795. **
  135796. ** Or, if an error (e.g. an OOM or IO error) occurs, return an SQLite
  135797. ** error code.
  135798. **
  135799. ** The integrity-check works as follows. For each token and indexed token
  135800. ** prefix in the document set, a 64-bit checksum is calculated (by code
  135801. ** in fts3ChecksumEntry()) based on the following:
  135802. **
  135803. ** + The index number (0 for the main index, 1 for the first prefix
  135804. ** index etc.),
  135805. ** + The token (or token prefix) text itself,
  135806. ** + The language-id of the row it appears in,
  135807. ** + The docid of the row it appears in,
  135808. ** + The column it appears in, and
  135809. ** + The tokens position within that column.
  135810. **
  135811. ** The checksums for all entries in the index are XORed together to create
  135812. ** a single checksum for the entire index.
  135813. **
  135814. ** The integrity-check code calculates the same checksum in two ways:
  135815. **
  135816. ** 1. By scanning the contents of the FTS index, and
  135817. ** 2. By scanning and tokenizing the content table.
  135818. **
  135819. ** If the two checksums are identical, the integrity-check is deemed to have
  135820. ** passed.
  135821. */
  135822. static int fts3DoIntegrityCheck(
  135823. Fts3Table *p /* FTS3 table handle */
  135824. ){
  135825. int rc;
  135826. int bOk = 0;
  135827. rc = fts3IntegrityCheck(p, &bOk);
  135828. if( rc==SQLITE_OK && bOk==0 ) rc = SQLITE_CORRUPT_VTAB;
  135829. return rc;
  135830. }
  135831. /*
  135832. ** Handle a 'special' INSERT of the form:
  135833. **
  135834. ** "INSERT INTO tbl(tbl) VALUES(<expr>)"
  135835. **
  135836. ** Argument pVal contains the result of <expr>. Currently the only
  135837. ** meaningful value to insert is the text 'optimize'.
  135838. */
  135839. static int fts3SpecialInsert(Fts3Table *p, sqlite3_value *pVal){
  135840. int rc; /* Return Code */
  135841. const char *zVal = (const char *)sqlite3_value_text(pVal);
  135842. int nVal = sqlite3_value_bytes(pVal);
  135843. if( !zVal ){
  135844. return SQLITE_NOMEM;
  135845. }else if( nVal==8 && 0==sqlite3_strnicmp(zVal, "optimize", 8) ){
  135846. rc = fts3DoOptimize(p, 0);
  135847. }else if( nVal==7 && 0==sqlite3_strnicmp(zVal, "rebuild", 7) ){
  135848. rc = fts3DoRebuild(p);
  135849. }else if( nVal==15 && 0==sqlite3_strnicmp(zVal, "integrity-check", 15) ){
  135850. rc = fts3DoIntegrityCheck(p);
  135851. }else if( nVal>6 && 0==sqlite3_strnicmp(zVal, "merge=", 6) ){
  135852. rc = fts3DoIncrmerge(p, &zVal[6]);
  135853. }else if( nVal>10 && 0==sqlite3_strnicmp(zVal, "automerge=", 10) ){
  135854. rc = fts3DoAutoincrmerge(p, &zVal[10]);
  135855. #ifdef SQLITE_TEST
  135856. }else if( nVal>9 && 0==sqlite3_strnicmp(zVal, "nodesize=", 9) ){
  135857. p->nNodeSize = atoi(&zVal[9]);
  135858. rc = SQLITE_OK;
  135859. }else if( nVal>11 && 0==sqlite3_strnicmp(zVal, "maxpending=", 9) ){
  135860. p->nMaxPendingData = atoi(&zVal[11]);
  135861. rc = SQLITE_OK;
  135862. }else if( nVal>21 && 0==sqlite3_strnicmp(zVal, "test-no-incr-doclist=", 21) ){
  135863. p->bNoIncrDoclist = atoi(&zVal[21]);
  135864. rc = SQLITE_OK;
  135865. #endif
  135866. }else{
  135867. rc = SQLITE_ERROR;
  135868. }
  135869. return rc;
  135870. }
  135871. #ifndef SQLITE_DISABLE_FTS4_DEFERRED
  135872. /*
  135873. ** Delete all cached deferred doclists. Deferred doclists are cached
  135874. ** (allocated) by the sqlite3Fts3CacheDeferredDoclists() function.
  135875. */
  135876. SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *pCsr){
  135877. Fts3DeferredToken *pDef;
  135878. for(pDef=pCsr->pDeferred; pDef; pDef=pDef->pNext){
  135879. fts3PendingListDelete(pDef->pList);
  135880. pDef->pList = 0;
  135881. }
  135882. }
  135883. /*
  135884. ** Free all entries in the pCsr->pDeffered list. Entries are added to
  135885. ** this list using sqlite3Fts3DeferToken().
  135886. */
  135887. SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *pCsr){
  135888. Fts3DeferredToken *pDef;
  135889. Fts3DeferredToken *pNext;
  135890. for(pDef=pCsr->pDeferred; pDef; pDef=pNext){
  135891. pNext = pDef->pNext;
  135892. fts3PendingListDelete(pDef->pList);
  135893. sqlite3_free(pDef);
  135894. }
  135895. pCsr->pDeferred = 0;
  135896. }
  135897. /*
  135898. ** Generate deferred-doclists for all tokens in the pCsr->pDeferred list
  135899. ** based on the row that pCsr currently points to.
  135900. **
  135901. ** A deferred-doclist is like any other doclist with position information
  135902. ** included, except that it only contains entries for a single row of the
  135903. ** table, not for all rows.
  135904. */
  135905. SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *pCsr){
  135906. int rc = SQLITE_OK; /* Return code */
  135907. if( pCsr->pDeferred ){
  135908. int i; /* Used to iterate through table columns */
  135909. sqlite3_int64 iDocid; /* Docid of the row pCsr points to */
  135910. Fts3DeferredToken *pDef; /* Used to iterate through deferred tokens */
  135911. Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
  135912. sqlite3_tokenizer *pT = p->pTokenizer;
  135913. sqlite3_tokenizer_module const *pModule = pT->pModule;
  135914. assert( pCsr->isRequireSeek==0 );
  135915. iDocid = sqlite3_column_int64(pCsr->pStmt, 0);
  135916. for(i=0; i<p->nColumn && rc==SQLITE_OK; i++){
  135917. if( p->abNotindexed[i]==0 ){
  135918. const char *zText = (const char *)sqlite3_column_text(pCsr->pStmt, i+1);
  135919. sqlite3_tokenizer_cursor *pTC = 0;
  135920. rc = sqlite3Fts3OpenTokenizer(pT, pCsr->iLangid, zText, -1, &pTC);
  135921. while( rc==SQLITE_OK ){
  135922. char const *zToken; /* Buffer containing token */
  135923. int nToken = 0; /* Number of bytes in token */
  135924. int iDum1 = 0, iDum2 = 0; /* Dummy variables */
  135925. int iPos = 0; /* Position of token in zText */
  135926. rc = pModule->xNext(pTC, &zToken, &nToken, &iDum1, &iDum2, &iPos);
  135927. for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){
  135928. Fts3PhraseToken *pPT = pDef->pToken;
  135929. if( (pDef->iCol>=p->nColumn || pDef->iCol==i)
  135930. && (pPT->bFirst==0 || iPos==0)
  135931. && (pPT->n==nToken || (pPT->isPrefix && pPT->n<nToken))
  135932. && (0==memcmp(zToken, pPT->z, pPT->n))
  135933. ){
  135934. fts3PendingListAppend(&pDef->pList, iDocid, i, iPos, &rc);
  135935. }
  135936. }
  135937. }
  135938. if( pTC ) pModule->xClose(pTC);
  135939. if( rc==SQLITE_DONE ) rc = SQLITE_OK;
  135940. }
  135941. }
  135942. for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){
  135943. if( pDef->pList ){
  135944. rc = fts3PendingListAppendVarint(&pDef->pList, 0);
  135945. }
  135946. }
  135947. }
  135948. return rc;
  135949. }
  135950. SQLITE_PRIVATE int sqlite3Fts3DeferredTokenList(
  135951. Fts3DeferredToken *p,
  135952. char **ppData,
  135953. int *pnData
  135954. ){
  135955. char *pRet;
  135956. int nSkip;
  135957. sqlite3_int64 dummy;
  135958. *ppData = 0;
  135959. *pnData = 0;
  135960. if( p->pList==0 ){
  135961. return SQLITE_OK;
  135962. }
  135963. pRet = (char *)sqlite3_malloc(p->pList->nData);
  135964. if( !pRet ) return SQLITE_NOMEM;
  135965. nSkip = sqlite3Fts3GetVarint(p->pList->aData, &dummy);
  135966. *pnData = p->pList->nData - nSkip;
  135967. *ppData = pRet;
  135968. memcpy(pRet, &p->pList->aData[nSkip], *pnData);
  135969. return SQLITE_OK;
  135970. }
  135971. /*
  135972. ** Add an entry for token pToken to the pCsr->pDeferred list.
  135973. */
  135974. SQLITE_PRIVATE int sqlite3Fts3DeferToken(
  135975. Fts3Cursor *pCsr, /* Fts3 table cursor */
  135976. Fts3PhraseToken *pToken, /* Token to defer */
  135977. int iCol /* Column that token must appear in (or -1) */
  135978. ){
  135979. Fts3DeferredToken *pDeferred;
  135980. pDeferred = sqlite3_malloc(sizeof(*pDeferred));
  135981. if( !pDeferred ){
  135982. return SQLITE_NOMEM;
  135983. }
  135984. memset(pDeferred, 0, sizeof(*pDeferred));
  135985. pDeferred->pToken = pToken;
  135986. pDeferred->pNext = pCsr->pDeferred;
  135987. pDeferred->iCol = iCol;
  135988. pCsr->pDeferred = pDeferred;
  135989. assert( pToken->pDeferred==0 );
  135990. pToken->pDeferred = pDeferred;
  135991. return SQLITE_OK;
  135992. }
  135993. #endif
  135994. /*
  135995. ** SQLite value pRowid contains the rowid of a row that may or may not be
  135996. ** present in the FTS3 table. If it is, delete it and adjust the contents
  135997. ** of subsiduary data structures accordingly.
  135998. */
  135999. static int fts3DeleteByRowid(
  136000. Fts3Table *p,
  136001. sqlite3_value *pRowid,
  136002. int *pnChng, /* IN/OUT: Decrement if row is deleted */
  136003. u32 *aSzDel
  136004. ){
  136005. int rc = SQLITE_OK; /* Return code */
  136006. int bFound = 0; /* True if *pRowid really is in the table */
  136007. fts3DeleteTerms(&rc, p, pRowid, aSzDel, &bFound);
  136008. if( bFound && rc==SQLITE_OK ){
  136009. int isEmpty = 0; /* Deleting *pRowid leaves the table empty */
  136010. rc = fts3IsEmpty(p, pRowid, &isEmpty);
  136011. if( rc==SQLITE_OK ){
  136012. if( isEmpty ){
  136013. /* Deleting this row means the whole table is empty. In this case
  136014. ** delete the contents of all three tables and throw away any
  136015. ** data in the pendingTerms hash table. */
  136016. rc = fts3DeleteAll(p, 1);
  136017. *pnChng = 0;
  136018. memset(aSzDel, 0, sizeof(u32) * (p->nColumn+1) * 2);
  136019. }else{
  136020. *pnChng = *pnChng - 1;
  136021. if( p->zContentTbl==0 ){
  136022. fts3SqlExec(&rc, p, SQL_DELETE_CONTENT, &pRowid);
  136023. }
  136024. if( p->bHasDocsize ){
  136025. fts3SqlExec(&rc, p, SQL_DELETE_DOCSIZE, &pRowid);
  136026. }
  136027. }
  136028. }
  136029. }
  136030. return rc;
  136031. }
  136032. /*
  136033. ** This function does the work for the xUpdate method of FTS3 virtual
  136034. ** tables. The schema of the virtual table being:
  136035. **
  136036. ** CREATE TABLE <table name>(
  136037. ** <user columns>,
  136038. ** <table name> HIDDEN,
  136039. ** docid HIDDEN,
  136040. ** <langid> HIDDEN
  136041. ** );
  136042. **
  136043. **
  136044. */
  136045. SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(
  136046. sqlite3_vtab *pVtab, /* FTS3 vtab object */
  136047. int nArg, /* Size of argument array */
  136048. sqlite3_value **apVal, /* Array of arguments */
  136049. sqlite_int64 *pRowid /* OUT: The affected (or effected) rowid */
  136050. ){
  136051. Fts3Table *p = (Fts3Table *)pVtab;
  136052. int rc = SQLITE_OK; /* Return Code */
  136053. int isRemove = 0; /* True for an UPDATE or DELETE */
  136054. u32 *aSzIns = 0; /* Sizes of inserted documents */
  136055. u32 *aSzDel = 0; /* Sizes of deleted documents */
  136056. int nChng = 0; /* Net change in number of documents */
  136057. int bInsertDone = 0;
  136058. /* At this point it must be known if the %_stat table exists or not.
  136059. ** So bHasStat may not be 2. */
  136060. assert( p->bHasStat==0 || p->bHasStat==1 );
  136061. assert( p->pSegments==0 );
  136062. assert(
  136063. nArg==1 /* DELETE operations */
  136064. || nArg==(2 + p->nColumn + 3) /* INSERT or UPDATE operations */
  136065. );
  136066. /* Check for a "special" INSERT operation. One of the form:
  136067. **
  136068. ** INSERT INTO xyz(xyz) VALUES('command');
  136069. */
  136070. if( nArg>1
  136071. && sqlite3_value_type(apVal[0])==SQLITE_NULL
  136072. && sqlite3_value_type(apVal[p->nColumn+2])!=SQLITE_NULL
  136073. ){
  136074. rc = fts3SpecialInsert(p, apVal[p->nColumn+2]);
  136075. goto update_out;
  136076. }
  136077. if( nArg>1 && sqlite3_value_int(apVal[2 + p->nColumn + 2])<0 ){
  136078. rc = SQLITE_CONSTRAINT;
  136079. goto update_out;
  136080. }
  136081. /* Allocate space to hold the change in document sizes */
  136082. aSzDel = sqlite3_malloc( sizeof(aSzDel[0])*(p->nColumn+1)*2 );
  136083. if( aSzDel==0 ){
  136084. rc = SQLITE_NOMEM;
  136085. goto update_out;
  136086. }
  136087. aSzIns = &aSzDel[p->nColumn+1];
  136088. memset(aSzDel, 0, sizeof(aSzDel[0])*(p->nColumn+1)*2);
  136089. rc = fts3Writelock(p);
  136090. if( rc!=SQLITE_OK ) goto update_out;
  136091. /* If this is an INSERT operation, or an UPDATE that modifies the rowid
  136092. ** value, then this operation requires constraint handling.
  136093. **
  136094. ** If the on-conflict mode is REPLACE, this means that the existing row
  136095. ** should be deleted from the database before inserting the new row. Or,
  136096. ** if the on-conflict mode is other than REPLACE, then this method must
  136097. ** detect the conflict and return SQLITE_CONSTRAINT before beginning to
  136098. ** modify the database file.
  136099. */
  136100. if( nArg>1 && p->zContentTbl==0 ){
  136101. /* Find the value object that holds the new rowid value. */
  136102. sqlite3_value *pNewRowid = apVal[3+p->nColumn];
  136103. if( sqlite3_value_type(pNewRowid)==SQLITE_NULL ){
  136104. pNewRowid = apVal[1];
  136105. }
  136106. if( sqlite3_value_type(pNewRowid)!=SQLITE_NULL && (
  136107. sqlite3_value_type(apVal[0])==SQLITE_NULL
  136108. || sqlite3_value_int64(apVal[0])!=sqlite3_value_int64(pNewRowid)
  136109. )){
  136110. /* The new rowid is not NULL (in this case the rowid will be
  136111. ** automatically assigned and there is no chance of a conflict), and
  136112. ** the statement is either an INSERT or an UPDATE that modifies the
  136113. ** rowid column. So if the conflict mode is REPLACE, then delete any
  136114. ** existing row with rowid=pNewRowid.
  136115. **
  136116. ** Or, if the conflict mode is not REPLACE, insert the new record into
  136117. ** the %_content table. If we hit the duplicate rowid constraint (or any
  136118. ** other error) while doing so, return immediately.
  136119. **
  136120. ** This branch may also run if pNewRowid contains a value that cannot
  136121. ** be losslessly converted to an integer. In this case, the eventual
  136122. ** call to fts3InsertData() (either just below or further on in this
  136123. ** function) will return SQLITE_MISMATCH. If fts3DeleteByRowid is
  136124. ** invoked, it will delete zero rows (since no row will have
  136125. ** docid=$pNewRowid if $pNewRowid is not an integer value).
  136126. */
  136127. if( sqlite3_vtab_on_conflict(p->db)==SQLITE_REPLACE ){
  136128. rc = fts3DeleteByRowid(p, pNewRowid, &nChng, aSzDel);
  136129. }else{
  136130. rc = fts3InsertData(p, apVal, pRowid);
  136131. bInsertDone = 1;
  136132. }
  136133. }
  136134. }
  136135. if( rc!=SQLITE_OK ){
  136136. goto update_out;
  136137. }
  136138. /* If this is a DELETE or UPDATE operation, remove the old record. */
  136139. if( sqlite3_value_type(apVal[0])!=SQLITE_NULL ){
  136140. assert( sqlite3_value_type(apVal[0])==SQLITE_INTEGER );
  136141. rc = fts3DeleteByRowid(p, apVal[0], &nChng, aSzDel);
  136142. isRemove = 1;
  136143. }
  136144. /* If this is an INSERT or UPDATE operation, insert the new record. */
  136145. if( nArg>1 && rc==SQLITE_OK ){
  136146. int iLangid = sqlite3_value_int(apVal[2 + p->nColumn + 2]);
  136147. if( bInsertDone==0 ){
  136148. rc = fts3InsertData(p, apVal, pRowid);
  136149. if( rc==SQLITE_CONSTRAINT && p->zContentTbl==0 ){
  136150. rc = FTS_CORRUPT_VTAB;
  136151. }
  136152. }
  136153. if( rc==SQLITE_OK && (!isRemove || *pRowid!=p->iPrevDocid ) ){
  136154. rc = fts3PendingTermsDocid(p, iLangid, *pRowid);
  136155. }
  136156. if( rc==SQLITE_OK ){
  136157. assert( p->iPrevDocid==*pRowid );
  136158. rc = fts3InsertTerms(p, iLangid, apVal, aSzIns);
  136159. }
  136160. if( p->bHasDocsize ){
  136161. fts3InsertDocsize(&rc, p, aSzIns);
  136162. }
  136163. nChng++;
  136164. }
  136165. if( p->bFts4 ){
  136166. fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nChng);
  136167. }
  136168. update_out:
  136169. sqlite3_free(aSzDel);
  136170. sqlite3Fts3SegmentsClose(p);
  136171. return rc;
  136172. }
  136173. /*
  136174. ** Flush any data in the pending-terms hash table to disk. If successful,
  136175. ** merge all segments in the database (including the new segment, if
  136176. ** there was any data to flush) into a single segment.
  136177. */
  136178. SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *p){
  136179. int rc;
  136180. rc = sqlite3_exec(p->db, "SAVEPOINT fts3", 0, 0, 0);
  136181. if( rc==SQLITE_OK ){
  136182. rc = fts3DoOptimize(p, 1);
  136183. if( rc==SQLITE_OK || rc==SQLITE_DONE ){
  136184. int rc2 = sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
  136185. if( rc2!=SQLITE_OK ) rc = rc2;
  136186. }else{
  136187. sqlite3_exec(p->db, "ROLLBACK TO fts3", 0, 0, 0);
  136188. sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
  136189. }
  136190. }
  136191. sqlite3Fts3SegmentsClose(p);
  136192. return rc;
  136193. }
  136194. #endif
  136195. /************** End of fts3_write.c ******************************************/
  136196. /************** Begin file fts3_snippet.c ************************************/
  136197. /*
  136198. ** 2009 Oct 23
  136199. **
  136200. ** The author disclaims copyright to this source code. In place of
  136201. ** a legal notice, here is a blessing:
  136202. **
  136203. ** May you do good and not evil.
  136204. ** May you find forgiveness for yourself and forgive others.
  136205. ** May you share freely, never taking more than you give.
  136206. **
  136207. ******************************************************************************
  136208. */
  136209. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  136210. /* #include <string.h> */
  136211. /* #include <assert.h> */
  136212. /*
  136213. ** Characters that may appear in the second argument to matchinfo().
  136214. */
  136215. #define FTS3_MATCHINFO_NPHRASE 'p' /* 1 value */
  136216. #define FTS3_MATCHINFO_NCOL 'c' /* 1 value */
  136217. #define FTS3_MATCHINFO_NDOC 'n' /* 1 value */
  136218. #define FTS3_MATCHINFO_AVGLENGTH 'a' /* nCol values */
  136219. #define FTS3_MATCHINFO_LENGTH 'l' /* nCol values */
  136220. #define FTS3_MATCHINFO_LCS 's' /* nCol values */
  136221. #define FTS3_MATCHINFO_HITS 'x' /* 3*nCol*nPhrase values */
  136222. /*
  136223. ** The default value for the second argument to matchinfo().
  136224. */
  136225. #define FTS3_MATCHINFO_DEFAULT "pcx"
  136226. /*
  136227. ** Used as an fts3ExprIterate() context when loading phrase doclists to
  136228. ** Fts3Expr.aDoclist[]/nDoclist.
  136229. */
  136230. typedef struct LoadDoclistCtx LoadDoclistCtx;
  136231. struct LoadDoclistCtx {
  136232. Fts3Cursor *pCsr; /* FTS3 Cursor */
  136233. int nPhrase; /* Number of phrases seen so far */
  136234. int nToken; /* Number of tokens seen so far */
  136235. };
  136236. /*
  136237. ** The following types are used as part of the implementation of the
  136238. ** fts3BestSnippet() routine.
  136239. */
  136240. typedef struct SnippetIter SnippetIter;
  136241. typedef struct SnippetPhrase SnippetPhrase;
  136242. typedef struct SnippetFragment SnippetFragment;
  136243. struct SnippetIter {
  136244. Fts3Cursor *pCsr; /* Cursor snippet is being generated from */
  136245. int iCol; /* Extract snippet from this column */
  136246. int nSnippet; /* Requested snippet length (in tokens) */
  136247. int nPhrase; /* Number of phrases in query */
  136248. SnippetPhrase *aPhrase; /* Array of size nPhrase */
  136249. int iCurrent; /* First token of current snippet */
  136250. };
  136251. struct SnippetPhrase {
  136252. int nToken; /* Number of tokens in phrase */
  136253. char *pList; /* Pointer to start of phrase position list */
  136254. int iHead; /* Next value in position list */
  136255. char *pHead; /* Position list data following iHead */
  136256. int iTail; /* Next value in trailing position list */
  136257. char *pTail; /* Position list data following iTail */
  136258. };
  136259. struct SnippetFragment {
  136260. int iCol; /* Column snippet is extracted from */
  136261. int iPos; /* Index of first token in snippet */
  136262. u64 covered; /* Mask of query phrases covered */
  136263. u64 hlmask; /* Mask of snippet terms to highlight */
  136264. };
  136265. /*
  136266. ** This type is used as an fts3ExprIterate() context object while
  136267. ** accumulating the data returned by the matchinfo() function.
  136268. */
  136269. typedef struct MatchInfo MatchInfo;
  136270. struct MatchInfo {
  136271. Fts3Cursor *pCursor; /* FTS3 Cursor */
  136272. int nCol; /* Number of columns in table */
  136273. int nPhrase; /* Number of matchable phrases in query */
  136274. sqlite3_int64 nDoc; /* Number of docs in database */
  136275. u32 *aMatchinfo; /* Pre-allocated buffer */
  136276. };
  136277. /*
  136278. ** The snippet() and offsets() functions both return text values. An instance
  136279. ** of the following structure is used to accumulate those values while the
  136280. ** functions are running. See fts3StringAppend() for details.
  136281. */
  136282. typedef struct StrBuffer StrBuffer;
  136283. struct StrBuffer {
  136284. char *z; /* Pointer to buffer containing string */
  136285. int n; /* Length of z in bytes (excl. nul-term) */
  136286. int nAlloc; /* Allocated size of buffer z in bytes */
  136287. };
  136288. /*
  136289. ** This function is used to help iterate through a position-list. A position
  136290. ** list is a list of unique integers, sorted from smallest to largest. Each
  136291. ** element of the list is represented by an FTS3 varint that takes the value
  136292. ** of the difference between the current element and the previous one plus
  136293. ** two. For example, to store the position-list:
  136294. **
  136295. ** 4 9 113
  136296. **
  136297. ** the three varints:
  136298. **
  136299. ** 6 7 106
  136300. **
  136301. ** are encoded.
  136302. **
  136303. ** When this function is called, *pp points to the start of an element of
  136304. ** the list. *piPos contains the value of the previous entry in the list.
  136305. ** After it returns, *piPos contains the value of the next element of the
  136306. ** list and *pp is advanced to the following varint.
  136307. */
  136308. static void fts3GetDeltaPosition(char **pp, int *piPos){
  136309. int iVal;
  136310. *pp += fts3GetVarint32(*pp, &iVal);
  136311. *piPos += (iVal-2);
  136312. }
  136313. /*
  136314. ** Helper function for fts3ExprIterate() (see below).
  136315. */
  136316. static int fts3ExprIterate2(
  136317. Fts3Expr *pExpr, /* Expression to iterate phrases of */
  136318. int *piPhrase, /* Pointer to phrase counter */
  136319. int (*x)(Fts3Expr*,int,void*), /* Callback function to invoke for phrases */
  136320. void *pCtx /* Second argument to pass to callback */
  136321. ){
  136322. int rc; /* Return code */
  136323. int eType = pExpr->eType; /* Type of expression node pExpr */
  136324. if( eType!=FTSQUERY_PHRASE ){
  136325. assert( pExpr->pLeft && pExpr->pRight );
  136326. rc = fts3ExprIterate2(pExpr->pLeft, piPhrase, x, pCtx);
  136327. if( rc==SQLITE_OK && eType!=FTSQUERY_NOT ){
  136328. rc = fts3ExprIterate2(pExpr->pRight, piPhrase, x, pCtx);
  136329. }
  136330. }else{
  136331. rc = x(pExpr, *piPhrase, pCtx);
  136332. (*piPhrase)++;
  136333. }
  136334. return rc;
  136335. }
  136336. /*
  136337. ** Iterate through all phrase nodes in an FTS3 query, except those that
  136338. ** are part of a sub-tree that is the right-hand-side of a NOT operator.
  136339. ** For each phrase node found, the supplied callback function is invoked.
  136340. **
  136341. ** If the callback function returns anything other than SQLITE_OK,
  136342. ** the iteration is abandoned and the error code returned immediately.
  136343. ** Otherwise, SQLITE_OK is returned after a callback has been made for
  136344. ** all eligible phrase nodes.
  136345. */
  136346. static int fts3ExprIterate(
  136347. Fts3Expr *pExpr, /* Expression to iterate phrases of */
  136348. int (*x)(Fts3Expr*,int,void*), /* Callback function to invoke for phrases */
  136349. void *pCtx /* Second argument to pass to callback */
  136350. ){
  136351. int iPhrase = 0; /* Variable used as the phrase counter */
  136352. return fts3ExprIterate2(pExpr, &iPhrase, x, pCtx);
  136353. }
  136354. /*
  136355. ** This is an fts3ExprIterate() callback used while loading the doclists
  136356. ** for each phrase into Fts3Expr.aDoclist[]/nDoclist. See also
  136357. ** fts3ExprLoadDoclists().
  136358. */
  136359. static int fts3ExprLoadDoclistsCb(Fts3Expr *pExpr, int iPhrase, void *ctx){
  136360. int rc = SQLITE_OK;
  136361. Fts3Phrase *pPhrase = pExpr->pPhrase;
  136362. LoadDoclistCtx *p = (LoadDoclistCtx *)ctx;
  136363. UNUSED_PARAMETER(iPhrase);
  136364. p->nPhrase++;
  136365. p->nToken += pPhrase->nToken;
  136366. return rc;
  136367. }
  136368. /*
  136369. ** Load the doclists for each phrase in the query associated with FTS3 cursor
  136370. ** pCsr.
  136371. **
  136372. ** If pnPhrase is not NULL, then *pnPhrase is set to the number of matchable
  136373. ** phrases in the expression (all phrases except those directly or
  136374. ** indirectly descended from the right-hand-side of a NOT operator). If
  136375. ** pnToken is not NULL, then it is set to the number of tokens in all
  136376. ** matchable phrases of the expression.
  136377. */
  136378. static int fts3ExprLoadDoclists(
  136379. Fts3Cursor *pCsr, /* Fts3 cursor for current query */
  136380. int *pnPhrase, /* OUT: Number of phrases in query */
  136381. int *pnToken /* OUT: Number of tokens in query */
  136382. ){
  136383. int rc; /* Return Code */
  136384. LoadDoclistCtx sCtx = {0,0,0}; /* Context for fts3ExprIterate() */
  136385. sCtx.pCsr = pCsr;
  136386. rc = fts3ExprIterate(pCsr->pExpr, fts3ExprLoadDoclistsCb, (void *)&sCtx);
  136387. if( pnPhrase ) *pnPhrase = sCtx.nPhrase;
  136388. if( pnToken ) *pnToken = sCtx.nToken;
  136389. return rc;
  136390. }
  136391. static int fts3ExprPhraseCountCb(Fts3Expr *pExpr, int iPhrase, void *ctx){
  136392. (*(int *)ctx)++;
  136393. UNUSED_PARAMETER(pExpr);
  136394. UNUSED_PARAMETER(iPhrase);
  136395. return SQLITE_OK;
  136396. }
  136397. static int fts3ExprPhraseCount(Fts3Expr *pExpr){
  136398. int nPhrase = 0;
  136399. (void)fts3ExprIterate(pExpr, fts3ExprPhraseCountCb, (void *)&nPhrase);
  136400. return nPhrase;
  136401. }
  136402. /*
  136403. ** Advance the position list iterator specified by the first two
  136404. ** arguments so that it points to the first element with a value greater
  136405. ** than or equal to parameter iNext.
  136406. */
  136407. static void fts3SnippetAdvance(char **ppIter, int *piIter, int iNext){
  136408. char *pIter = *ppIter;
  136409. if( pIter ){
  136410. int iIter = *piIter;
  136411. while( iIter<iNext ){
  136412. if( 0==(*pIter & 0xFE) ){
  136413. iIter = -1;
  136414. pIter = 0;
  136415. break;
  136416. }
  136417. fts3GetDeltaPosition(&pIter, &iIter);
  136418. }
  136419. *piIter = iIter;
  136420. *ppIter = pIter;
  136421. }
  136422. }
  136423. /*
  136424. ** Advance the snippet iterator to the next candidate snippet.
  136425. */
  136426. static int fts3SnippetNextCandidate(SnippetIter *pIter){
  136427. int i; /* Loop counter */
  136428. if( pIter->iCurrent<0 ){
  136429. /* The SnippetIter object has just been initialized. The first snippet
  136430. ** candidate always starts at offset 0 (even if this candidate has a
  136431. ** score of 0.0).
  136432. */
  136433. pIter->iCurrent = 0;
  136434. /* Advance the 'head' iterator of each phrase to the first offset that
  136435. ** is greater than or equal to (iNext+nSnippet).
  136436. */
  136437. for(i=0; i<pIter->nPhrase; i++){
  136438. SnippetPhrase *pPhrase = &pIter->aPhrase[i];
  136439. fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, pIter->nSnippet);
  136440. }
  136441. }else{
  136442. int iStart;
  136443. int iEnd = 0x7FFFFFFF;
  136444. for(i=0; i<pIter->nPhrase; i++){
  136445. SnippetPhrase *pPhrase = &pIter->aPhrase[i];
  136446. if( pPhrase->pHead && pPhrase->iHead<iEnd ){
  136447. iEnd = pPhrase->iHead;
  136448. }
  136449. }
  136450. if( iEnd==0x7FFFFFFF ){
  136451. return 1;
  136452. }
  136453. pIter->iCurrent = iStart = iEnd - pIter->nSnippet + 1;
  136454. for(i=0; i<pIter->nPhrase; i++){
  136455. SnippetPhrase *pPhrase = &pIter->aPhrase[i];
  136456. fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, iEnd+1);
  136457. fts3SnippetAdvance(&pPhrase->pTail, &pPhrase->iTail, iStart);
  136458. }
  136459. }
  136460. return 0;
  136461. }
  136462. /*
  136463. ** Retrieve information about the current candidate snippet of snippet
  136464. ** iterator pIter.
  136465. */
  136466. static void fts3SnippetDetails(
  136467. SnippetIter *pIter, /* Snippet iterator */
  136468. u64 mCovered, /* Bitmask of phrases already covered */
  136469. int *piToken, /* OUT: First token of proposed snippet */
  136470. int *piScore, /* OUT: "Score" for this snippet */
  136471. u64 *pmCover, /* OUT: Bitmask of phrases covered */
  136472. u64 *pmHighlight /* OUT: Bitmask of terms to highlight */
  136473. ){
  136474. int iStart = pIter->iCurrent; /* First token of snippet */
  136475. int iScore = 0; /* Score of this snippet */
  136476. int i; /* Loop counter */
  136477. u64 mCover = 0; /* Mask of phrases covered by this snippet */
  136478. u64 mHighlight = 0; /* Mask of tokens to highlight in snippet */
  136479. for(i=0; i<pIter->nPhrase; i++){
  136480. SnippetPhrase *pPhrase = &pIter->aPhrase[i];
  136481. if( pPhrase->pTail ){
  136482. char *pCsr = pPhrase->pTail;
  136483. int iCsr = pPhrase->iTail;
  136484. while( iCsr<(iStart+pIter->nSnippet) ){
  136485. int j;
  136486. u64 mPhrase = (u64)1 << i;
  136487. u64 mPos = (u64)1 << (iCsr - iStart);
  136488. assert( iCsr>=iStart );
  136489. if( (mCover|mCovered)&mPhrase ){
  136490. iScore++;
  136491. }else{
  136492. iScore += 1000;
  136493. }
  136494. mCover |= mPhrase;
  136495. for(j=0; j<pPhrase->nToken; j++){
  136496. mHighlight |= (mPos>>j);
  136497. }
  136498. if( 0==(*pCsr & 0x0FE) ) break;
  136499. fts3GetDeltaPosition(&pCsr, &iCsr);
  136500. }
  136501. }
  136502. }
  136503. /* Set the output variables before returning. */
  136504. *piToken = iStart;
  136505. *piScore = iScore;
  136506. *pmCover = mCover;
  136507. *pmHighlight = mHighlight;
  136508. }
  136509. /*
  136510. ** This function is an fts3ExprIterate() callback used by fts3BestSnippet().
  136511. ** Each invocation populates an element of the SnippetIter.aPhrase[] array.
  136512. */
  136513. static int fts3SnippetFindPositions(Fts3Expr *pExpr, int iPhrase, void *ctx){
  136514. SnippetIter *p = (SnippetIter *)ctx;
  136515. SnippetPhrase *pPhrase = &p->aPhrase[iPhrase];
  136516. char *pCsr;
  136517. int rc;
  136518. pPhrase->nToken = pExpr->pPhrase->nToken;
  136519. rc = sqlite3Fts3EvalPhrasePoslist(p->pCsr, pExpr, p->iCol, &pCsr);
  136520. assert( rc==SQLITE_OK || pCsr==0 );
  136521. if( pCsr ){
  136522. int iFirst = 0;
  136523. pPhrase->pList = pCsr;
  136524. fts3GetDeltaPosition(&pCsr, &iFirst);
  136525. assert( iFirst>=0 );
  136526. pPhrase->pHead = pCsr;
  136527. pPhrase->pTail = pCsr;
  136528. pPhrase->iHead = iFirst;
  136529. pPhrase->iTail = iFirst;
  136530. }else{
  136531. assert( rc!=SQLITE_OK || (
  136532. pPhrase->pList==0 && pPhrase->pHead==0 && pPhrase->pTail==0
  136533. ));
  136534. }
  136535. return rc;
  136536. }
  136537. /*
  136538. ** Select the fragment of text consisting of nFragment contiguous tokens
  136539. ** from column iCol that represent the "best" snippet. The best snippet
  136540. ** is the snippet with the highest score, where scores are calculated
  136541. ** by adding:
  136542. **
  136543. ** (a) +1 point for each occurrence of a matchable phrase in the snippet.
  136544. **
  136545. ** (b) +1000 points for the first occurrence of each matchable phrase in
  136546. ** the snippet for which the corresponding mCovered bit is not set.
  136547. **
  136548. ** The selected snippet parameters are stored in structure *pFragment before
  136549. ** returning. The score of the selected snippet is stored in *piScore
  136550. ** before returning.
  136551. */
  136552. static int fts3BestSnippet(
  136553. int nSnippet, /* Desired snippet length */
  136554. Fts3Cursor *pCsr, /* Cursor to create snippet for */
  136555. int iCol, /* Index of column to create snippet from */
  136556. u64 mCovered, /* Mask of phrases already covered */
  136557. u64 *pmSeen, /* IN/OUT: Mask of phrases seen */
  136558. SnippetFragment *pFragment, /* OUT: Best snippet found */
  136559. int *piScore /* OUT: Score of snippet pFragment */
  136560. ){
  136561. int rc; /* Return Code */
  136562. int nList; /* Number of phrases in expression */
  136563. SnippetIter sIter; /* Iterates through snippet candidates */
  136564. int nByte; /* Number of bytes of space to allocate */
  136565. int iBestScore = -1; /* Best snippet score found so far */
  136566. int i; /* Loop counter */
  136567. memset(&sIter, 0, sizeof(sIter));
  136568. /* Iterate through the phrases in the expression to count them. The same
  136569. ** callback makes sure the doclists are loaded for each phrase.
  136570. */
  136571. rc = fts3ExprLoadDoclists(pCsr, &nList, 0);
  136572. if( rc!=SQLITE_OK ){
  136573. return rc;
  136574. }
  136575. /* Now that it is known how many phrases there are, allocate and zero
  136576. ** the required space using malloc().
  136577. */
  136578. nByte = sizeof(SnippetPhrase) * nList;
  136579. sIter.aPhrase = (SnippetPhrase *)sqlite3_malloc(nByte);
  136580. if( !sIter.aPhrase ){
  136581. return SQLITE_NOMEM;
  136582. }
  136583. memset(sIter.aPhrase, 0, nByte);
  136584. /* Initialize the contents of the SnippetIter object. Then iterate through
  136585. ** the set of phrases in the expression to populate the aPhrase[] array.
  136586. */
  136587. sIter.pCsr = pCsr;
  136588. sIter.iCol = iCol;
  136589. sIter.nSnippet = nSnippet;
  136590. sIter.nPhrase = nList;
  136591. sIter.iCurrent = -1;
  136592. (void)fts3ExprIterate(pCsr->pExpr, fts3SnippetFindPositions, (void *)&sIter);
  136593. /* Set the *pmSeen output variable. */
  136594. for(i=0; i<nList; i++){
  136595. if( sIter.aPhrase[i].pHead ){
  136596. *pmSeen |= (u64)1 << i;
  136597. }
  136598. }
  136599. /* Loop through all candidate snippets. Store the best snippet in
  136600. ** *pFragment. Store its associated 'score' in iBestScore.
  136601. */
  136602. pFragment->iCol = iCol;
  136603. while( !fts3SnippetNextCandidate(&sIter) ){
  136604. int iPos;
  136605. int iScore;
  136606. u64 mCover;
  136607. u64 mHighlight;
  136608. fts3SnippetDetails(&sIter, mCovered, &iPos, &iScore, &mCover, &mHighlight);
  136609. assert( iScore>=0 );
  136610. if( iScore>iBestScore ){
  136611. pFragment->iPos = iPos;
  136612. pFragment->hlmask = mHighlight;
  136613. pFragment->covered = mCover;
  136614. iBestScore = iScore;
  136615. }
  136616. }
  136617. sqlite3_free(sIter.aPhrase);
  136618. *piScore = iBestScore;
  136619. return SQLITE_OK;
  136620. }
  136621. /*
  136622. ** Append a string to the string-buffer passed as the first argument.
  136623. **
  136624. ** If nAppend is negative, then the length of the string zAppend is
  136625. ** determined using strlen().
  136626. */
  136627. static int fts3StringAppend(
  136628. StrBuffer *pStr, /* Buffer to append to */
  136629. const char *zAppend, /* Pointer to data to append to buffer */
  136630. int nAppend /* Size of zAppend in bytes (or -1) */
  136631. ){
  136632. if( nAppend<0 ){
  136633. nAppend = (int)strlen(zAppend);
  136634. }
  136635. /* If there is insufficient space allocated at StrBuffer.z, use realloc()
  136636. ** to grow the buffer until so that it is big enough to accomadate the
  136637. ** appended data.
  136638. */
  136639. if( pStr->n+nAppend+1>=pStr->nAlloc ){
  136640. int nAlloc = pStr->nAlloc+nAppend+100;
  136641. char *zNew = sqlite3_realloc(pStr->z, nAlloc);
  136642. if( !zNew ){
  136643. return SQLITE_NOMEM;
  136644. }
  136645. pStr->z = zNew;
  136646. pStr->nAlloc = nAlloc;
  136647. }
  136648. assert( pStr->z!=0 && (pStr->nAlloc >= pStr->n+nAppend+1) );
  136649. /* Append the data to the string buffer. */
  136650. memcpy(&pStr->z[pStr->n], zAppend, nAppend);
  136651. pStr->n += nAppend;
  136652. pStr->z[pStr->n] = '\0';
  136653. return SQLITE_OK;
  136654. }
  136655. /*
  136656. ** The fts3BestSnippet() function often selects snippets that end with a
  136657. ** query term. That is, the final term of the snippet is always a term
  136658. ** that requires highlighting. For example, if 'X' is a highlighted term
  136659. ** and '.' is a non-highlighted term, BestSnippet() may select:
  136660. **
  136661. ** ........X.....X
  136662. **
  136663. ** This function "shifts" the beginning of the snippet forward in the
  136664. ** document so that there are approximately the same number of
  136665. ** non-highlighted terms to the right of the final highlighted term as there
  136666. ** are to the left of the first highlighted term. For example, to this:
  136667. **
  136668. ** ....X.....X....
  136669. **
  136670. ** This is done as part of extracting the snippet text, not when selecting
  136671. ** the snippet. Snippet selection is done based on doclists only, so there
  136672. ** is no way for fts3BestSnippet() to know whether or not the document
  136673. ** actually contains terms that follow the final highlighted term.
  136674. */
  136675. static int fts3SnippetShift(
  136676. Fts3Table *pTab, /* FTS3 table snippet comes from */
  136677. int iLangid, /* Language id to use in tokenizing */
  136678. int nSnippet, /* Number of tokens desired for snippet */
  136679. const char *zDoc, /* Document text to extract snippet from */
  136680. int nDoc, /* Size of buffer zDoc in bytes */
  136681. int *piPos, /* IN/OUT: First token of snippet */
  136682. u64 *pHlmask /* IN/OUT: Mask of tokens to highlight */
  136683. ){
  136684. u64 hlmask = *pHlmask; /* Local copy of initial highlight-mask */
  136685. if( hlmask ){
  136686. int nLeft; /* Tokens to the left of first highlight */
  136687. int nRight; /* Tokens to the right of last highlight */
  136688. int nDesired; /* Ideal number of tokens to shift forward */
  136689. for(nLeft=0; !(hlmask & ((u64)1 << nLeft)); nLeft++);
  136690. for(nRight=0; !(hlmask & ((u64)1 << (nSnippet-1-nRight))); nRight++);
  136691. nDesired = (nLeft-nRight)/2;
  136692. /* Ideally, the start of the snippet should be pushed forward in the
  136693. ** document nDesired tokens. This block checks if there are actually
  136694. ** nDesired tokens to the right of the snippet. If so, *piPos and
  136695. ** *pHlMask are updated to shift the snippet nDesired tokens to the
  136696. ** right. Otherwise, the snippet is shifted by the number of tokens
  136697. ** available.
  136698. */
  136699. if( nDesired>0 ){
  136700. int nShift; /* Number of tokens to shift snippet by */
  136701. int iCurrent = 0; /* Token counter */
  136702. int rc; /* Return Code */
  136703. sqlite3_tokenizer_module *pMod;
  136704. sqlite3_tokenizer_cursor *pC;
  136705. pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
  136706. /* Open a cursor on zDoc/nDoc. Check if there are (nSnippet+nDesired)
  136707. ** or more tokens in zDoc/nDoc.
  136708. */
  136709. rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, iLangid, zDoc, nDoc, &pC);
  136710. if( rc!=SQLITE_OK ){
  136711. return rc;
  136712. }
  136713. while( rc==SQLITE_OK && iCurrent<(nSnippet+nDesired) ){
  136714. const char *ZDUMMY; int DUMMY1 = 0, DUMMY2 = 0, DUMMY3 = 0;
  136715. rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &DUMMY2, &DUMMY3, &iCurrent);
  136716. }
  136717. pMod->xClose(pC);
  136718. if( rc!=SQLITE_OK && rc!=SQLITE_DONE ){ return rc; }
  136719. nShift = (rc==SQLITE_DONE)+iCurrent-nSnippet;
  136720. assert( nShift<=nDesired );
  136721. if( nShift>0 ){
  136722. *piPos += nShift;
  136723. *pHlmask = hlmask >> nShift;
  136724. }
  136725. }
  136726. }
  136727. return SQLITE_OK;
  136728. }
  136729. /*
  136730. ** Extract the snippet text for fragment pFragment from cursor pCsr and
  136731. ** append it to string buffer pOut.
  136732. */
  136733. static int fts3SnippetText(
  136734. Fts3Cursor *pCsr, /* FTS3 Cursor */
  136735. SnippetFragment *pFragment, /* Snippet to extract */
  136736. int iFragment, /* Fragment number */
  136737. int isLast, /* True for final fragment in snippet */
  136738. int nSnippet, /* Number of tokens in extracted snippet */
  136739. const char *zOpen, /* String inserted before highlighted term */
  136740. const char *zClose, /* String inserted after highlighted term */
  136741. const char *zEllipsis, /* String inserted between snippets */
  136742. StrBuffer *pOut /* Write output here */
  136743. ){
  136744. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  136745. int rc; /* Return code */
  136746. const char *zDoc; /* Document text to extract snippet from */
  136747. int nDoc; /* Size of zDoc in bytes */
  136748. int iCurrent = 0; /* Current token number of document */
  136749. int iEnd = 0; /* Byte offset of end of current token */
  136750. int isShiftDone = 0; /* True after snippet is shifted */
  136751. int iPos = pFragment->iPos; /* First token of snippet */
  136752. u64 hlmask = pFragment->hlmask; /* Highlight-mask for snippet */
  136753. int iCol = pFragment->iCol+1; /* Query column to extract text from */
  136754. sqlite3_tokenizer_module *pMod; /* Tokenizer module methods object */
  136755. sqlite3_tokenizer_cursor *pC; /* Tokenizer cursor open on zDoc/nDoc */
  136756. zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol);
  136757. if( zDoc==0 ){
  136758. if( sqlite3_column_type(pCsr->pStmt, iCol)!=SQLITE_NULL ){
  136759. return SQLITE_NOMEM;
  136760. }
  136761. return SQLITE_OK;
  136762. }
  136763. nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol);
  136764. /* Open a token cursor on the document. */
  136765. pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
  136766. rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, pCsr->iLangid, zDoc,nDoc,&pC);
  136767. if( rc!=SQLITE_OK ){
  136768. return rc;
  136769. }
  136770. while( rc==SQLITE_OK ){
  136771. const char *ZDUMMY; /* Dummy argument used with tokenizer */
  136772. int DUMMY1 = -1; /* Dummy argument used with tokenizer */
  136773. int iBegin = 0; /* Offset in zDoc of start of token */
  136774. int iFin = 0; /* Offset in zDoc of end of token */
  136775. int isHighlight = 0; /* True for highlighted terms */
  136776. /* Variable DUMMY1 is initialized to a negative value above. Elsewhere
  136777. ** in the FTS code the variable that the third argument to xNext points to
  136778. ** is initialized to zero before the first (*but not necessarily
  136779. ** subsequent*) call to xNext(). This is done for a particular application
  136780. ** that needs to know whether or not the tokenizer is being used for
  136781. ** snippet generation or for some other purpose.
  136782. **
  136783. ** Extreme care is required when writing code to depend on this
  136784. ** initialization. It is not a documented part of the tokenizer interface.
  136785. ** If a tokenizer is used directly by any code outside of FTS, this
  136786. ** convention might not be respected. */
  136787. rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &iBegin, &iFin, &iCurrent);
  136788. if( rc!=SQLITE_OK ){
  136789. if( rc==SQLITE_DONE ){
  136790. /* Special case - the last token of the snippet is also the last token
  136791. ** of the column. Append any punctuation that occurred between the end
  136792. ** of the previous token and the end of the document to the output.
  136793. ** Then break out of the loop. */
  136794. rc = fts3StringAppend(pOut, &zDoc[iEnd], -1);
  136795. }
  136796. break;
  136797. }
  136798. if( iCurrent<iPos ){ continue; }
  136799. if( !isShiftDone ){
  136800. int n = nDoc - iBegin;
  136801. rc = fts3SnippetShift(
  136802. pTab, pCsr->iLangid, nSnippet, &zDoc[iBegin], n, &iPos, &hlmask
  136803. );
  136804. isShiftDone = 1;
  136805. /* Now that the shift has been done, check if the initial "..." are
  136806. ** required. They are required if (a) this is not the first fragment,
  136807. ** or (b) this fragment does not begin at position 0 of its column.
  136808. */
  136809. if( rc==SQLITE_OK && (iPos>0 || iFragment>0) ){
  136810. rc = fts3StringAppend(pOut, zEllipsis, -1);
  136811. }
  136812. if( rc!=SQLITE_OK || iCurrent<iPos ) continue;
  136813. }
  136814. if( iCurrent>=(iPos+nSnippet) ){
  136815. if( isLast ){
  136816. rc = fts3StringAppend(pOut, zEllipsis, -1);
  136817. }
  136818. break;
  136819. }
  136820. /* Set isHighlight to true if this term should be highlighted. */
  136821. isHighlight = (hlmask & ((u64)1 << (iCurrent-iPos)))!=0;
  136822. if( iCurrent>iPos ) rc = fts3StringAppend(pOut, &zDoc[iEnd], iBegin-iEnd);
  136823. if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zOpen, -1);
  136824. if( rc==SQLITE_OK ) rc = fts3StringAppend(pOut, &zDoc[iBegin], iFin-iBegin);
  136825. if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zClose, -1);
  136826. iEnd = iFin;
  136827. }
  136828. pMod->xClose(pC);
  136829. return rc;
  136830. }
  136831. /*
  136832. ** This function is used to count the entries in a column-list (a
  136833. ** delta-encoded list of term offsets within a single column of a single
  136834. ** row). When this function is called, *ppCollist should point to the
  136835. ** beginning of the first varint in the column-list (the varint that
  136836. ** contains the position of the first matching term in the column data).
  136837. ** Before returning, *ppCollist is set to point to the first byte after
  136838. ** the last varint in the column-list (either the 0x00 signifying the end
  136839. ** of the position-list, or the 0x01 that precedes the column number of
  136840. ** the next column in the position-list).
  136841. **
  136842. ** The number of elements in the column-list is returned.
  136843. */
  136844. static int fts3ColumnlistCount(char **ppCollist){
  136845. char *pEnd = *ppCollist;
  136846. char c = 0;
  136847. int nEntry = 0;
  136848. /* A column-list is terminated by either a 0x01 or 0x00. */
  136849. while( 0xFE & (*pEnd | c) ){
  136850. c = *pEnd++ & 0x80;
  136851. if( !c ) nEntry++;
  136852. }
  136853. *ppCollist = pEnd;
  136854. return nEntry;
  136855. }
  136856. /*
  136857. ** fts3ExprIterate() callback used to collect the "global" matchinfo stats
  136858. ** for a single query.
  136859. **
  136860. ** fts3ExprIterate() callback to load the 'global' elements of a
  136861. ** FTS3_MATCHINFO_HITS matchinfo array. The global stats are those elements
  136862. ** of the matchinfo array that are constant for all rows returned by the
  136863. ** current query.
  136864. **
  136865. ** Argument pCtx is actually a pointer to a struct of type MatchInfo. This
  136866. ** function populates Matchinfo.aMatchinfo[] as follows:
  136867. **
  136868. ** for(iCol=0; iCol<nCol; iCol++){
  136869. ** aMatchinfo[3*iPhrase*nCol + 3*iCol + 1] = X;
  136870. ** aMatchinfo[3*iPhrase*nCol + 3*iCol + 2] = Y;
  136871. ** }
  136872. **
  136873. ** where X is the number of matches for phrase iPhrase is column iCol of all
  136874. ** rows of the table. Y is the number of rows for which column iCol contains
  136875. ** at least one instance of phrase iPhrase.
  136876. **
  136877. ** If the phrase pExpr consists entirely of deferred tokens, then all X and
  136878. ** Y values are set to nDoc, where nDoc is the number of documents in the
  136879. ** file system. This is done because the full-text index doclist is required
  136880. ** to calculate these values properly, and the full-text index doclist is
  136881. ** not available for deferred tokens.
  136882. */
  136883. static int fts3ExprGlobalHitsCb(
  136884. Fts3Expr *pExpr, /* Phrase expression node */
  136885. int iPhrase, /* Phrase number (numbered from zero) */
  136886. void *pCtx /* Pointer to MatchInfo structure */
  136887. ){
  136888. MatchInfo *p = (MatchInfo *)pCtx;
  136889. return sqlite3Fts3EvalPhraseStats(
  136890. p->pCursor, pExpr, &p->aMatchinfo[3*iPhrase*p->nCol]
  136891. );
  136892. }
  136893. /*
  136894. ** fts3ExprIterate() callback used to collect the "local" part of the
  136895. ** FTS3_MATCHINFO_HITS array. The local stats are those elements of the
  136896. ** array that are different for each row returned by the query.
  136897. */
  136898. static int fts3ExprLocalHitsCb(
  136899. Fts3Expr *pExpr, /* Phrase expression node */
  136900. int iPhrase, /* Phrase number */
  136901. void *pCtx /* Pointer to MatchInfo structure */
  136902. ){
  136903. int rc = SQLITE_OK;
  136904. MatchInfo *p = (MatchInfo *)pCtx;
  136905. int iStart = iPhrase * p->nCol * 3;
  136906. int i;
  136907. for(i=0; i<p->nCol && rc==SQLITE_OK; i++){
  136908. char *pCsr;
  136909. rc = sqlite3Fts3EvalPhrasePoslist(p->pCursor, pExpr, i, &pCsr);
  136910. if( pCsr ){
  136911. p->aMatchinfo[iStart+i*3] = fts3ColumnlistCount(&pCsr);
  136912. }else{
  136913. p->aMatchinfo[iStart+i*3] = 0;
  136914. }
  136915. }
  136916. return rc;
  136917. }
  136918. static int fts3MatchinfoCheck(
  136919. Fts3Table *pTab,
  136920. char cArg,
  136921. char **pzErr
  136922. ){
  136923. if( (cArg==FTS3_MATCHINFO_NPHRASE)
  136924. || (cArg==FTS3_MATCHINFO_NCOL)
  136925. || (cArg==FTS3_MATCHINFO_NDOC && pTab->bFts4)
  136926. || (cArg==FTS3_MATCHINFO_AVGLENGTH && pTab->bFts4)
  136927. || (cArg==FTS3_MATCHINFO_LENGTH && pTab->bHasDocsize)
  136928. || (cArg==FTS3_MATCHINFO_LCS)
  136929. || (cArg==FTS3_MATCHINFO_HITS)
  136930. ){
  136931. return SQLITE_OK;
  136932. }
  136933. *pzErr = sqlite3_mprintf("unrecognized matchinfo request: %c", cArg);
  136934. return SQLITE_ERROR;
  136935. }
  136936. static int fts3MatchinfoSize(MatchInfo *pInfo, char cArg){
  136937. int nVal; /* Number of integers output by cArg */
  136938. switch( cArg ){
  136939. case FTS3_MATCHINFO_NDOC:
  136940. case FTS3_MATCHINFO_NPHRASE:
  136941. case FTS3_MATCHINFO_NCOL:
  136942. nVal = 1;
  136943. break;
  136944. case FTS3_MATCHINFO_AVGLENGTH:
  136945. case FTS3_MATCHINFO_LENGTH:
  136946. case FTS3_MATCHINFO_LCS:
  136947. nVal = pInfo->nCol;
  136948. break;
  136949. default:
  136950. assert( cArg==FTS3_MATCHINFO_HITS );
  136951. nVal = pInfo->nCol * pInfo->nPhrase * 3;
  136952. break;
  136953. }
  136954. return nVal;
  136955. }
  136956. static int fts3MatchinfoSelectDoctotal(
  136957. Fts3Table *pTab,
  136958. sqlite3_stmt **ppStmt,
  136959. sqlite3_int64 *pnDoc,
  136960. const char **paLen
  136961. ){
  136962. sqlite3_stmt *pStmt;
  136963. const char *a;
  136964. sqlite3_int64 nDoc;
  136965. if( !*ppStmt ){
  136966. int rc = sqlite3Fts3SelectDoctotal(pTab, ppStmt);
  136967. if( rc!=SQLITE_OK ) return rc;
  136968. }
  136969. pStmt = *ppStmt;
  136970. assert( sqlite3_data_count(pStmt)==1 );
  136971. a = sqlite3_column_blob(pStmt, 0);
  136972. a += sqlite3Fts3GetVarint(a, &nDoc);
  136973. if( nDoc==0 ) return FTS_CORRUPT_VTAB;
  136974. *pnDoc = (u32)nDoc;
  136975. if( paLen ) *paLen = a;
  136976. return SQLITE_OK;
  136977. }
  136978. /*
  136979. ** An instance of the following structure is used to store state while
  136980. ** iterating through a multi-column position-list corresponding to the
  136981. ** hits for a single phrase on a single row in order to calculate the
  136982. ** values for a matchinfo() FTS3_MATCHINFO_LCS request.
  136983. */
  136984. typedef struct LcsIterator LcsIterator;
  136985. struct LcsIterator {
  136986. Fts3Expr *pExpr; /* Pointer to phrase expression */
  136987. int iPosOffset; /* Tokens count up to end of this phrase */
  136988. char *pRead; /* Cursor used to iterate through aDoclist */
  136989. int iPos; /* Current position */
  136990. };
  136991. /*
  136992. ** If LcsIterator.iCol is set to the following value, the iterator has
  136993. ** finished iterating through all offsets for all columns.
  136994. */
  136995. #define LCS_ITERATOR_FINISHED 0x7FFFFFFF;
  136996. static int fts3MatchinfoLcsCb(
  136997. Fts3Expr *pExpr, /* Phrase expression node */
  136998. int iPhrase, /* Phrase number (numbered from zero) */
  136999. void *pCtx /* Pointer to MatchInfo structure */
  137000. ){
  137001. LcsIterator *aIter = (LcsIterator *)pCtx;
  137002. aIter[iPhrase].pExpr = pExpr;
  137003. return SQLITE_OK;
  137004. }
  137005. /*
  137006. ** Advance the iterator passed as an argument to the next position. Return
  137007. ** 1 if the iterator is at EOF or if it now points to the start of the
  137008. ** position list for the next column.
  137009. */
  137010. static int fts3LcsIteratorAdvance(LcsIterator *pIter){
  137011. char *pRead = pIter->pRead;
  137012. sqlite3_int64 iRead;
  137013. int rc = 0;
  137014. pRead += sqlite3Fts3GetVarint(pRead, &iRead);
  137015. if( iRead==0 || iRead==1 ){
  137016. pRead = 0;
  137017. rc = 1;
  137018. }else{
  137019. pIter->iPos += (int)(iRead-2);
  137020. }
  137021. pIter->pRead = pRead;
  137022. return rc;
  137023. }
  137024. /*
  137025. ** This function implements the FTS3_MATCHINFO_LCS matchinfo() flag.
  137026. **
  137027. ** If the call is successful, the longest-common-substring lengths for each
  137028. ** column are written into the first nCol elements of the pInfo->aMatchinfo[]
  137029. ** array before returning. SQLITE_OK is returned in this case.
  137030. **
  137031. ** Otherwise, if an error occurs, an SQLite error code is returned and the
  137032. ** data written to the first nCol elements of pInfo->aMatchinfo[] is
  137033. ** undefined.
  137034. */
  137035. static int fts3MatchinfoLcs(Fts3Cursor *pCsr, MatchInfo *pInfo){
  137036. LcsIterator *aIter;
  137037. int i;
  137038. int iCol;
  137039. int nToken = 0;
  137040. /* Allocate and populate the array of LcsIterator objects. The array
  137041. ** contains one element for each matchable phrase in the query.
  137042. **/
  137043. aIter = sqlite3_malloc(sizeof(LcsIterator) * pCsr->nPhrase);
  137044. if( !aIter ) return SQLITE_NOMEM;
  137045. memset(aIter, 0, sizeof(LcsIterator) * pCsr->nPhrase);
  137046. (void)fts3ExprIterate(pCsr->pExpr, fts3MatchinfoLcsCb, (void*)aIter);
  137047. for(i=0; i<pInfo->nPhrase; i++){
  137048. LcsIterator *pIter = &aIter[i];
  137049. nToken -= pIter->pExpr->pPhrase->nToken;
  137050. pIter->iPosOffset = nToken;
  137051. }
  137052. for(iCol=0; iCol<pInfo->nCol; iCol++){
  137053. int nLcs = 0; /* LCS value for this column */
  137054. int nLive = 0; /* Number of iterators in aIter not at EOF */
  137055. for(i=0; i<pInfo->nPhrase; i++){
  137056. int rc;
  137057. LcsIterator *pIt = &aIter[i];
  137058. rc = sqlite3Fts3EvalPhrasePoslist(pCsr, pIt->pExpr, iCol, &pIt->pRead);
  137059. if( rc!=SQLITE_OK ) return rc;
  137060. if( pIt->pRead ){
  137061. pIt->iPos = pIt->iPosOffset;
  137062. fts3LcsIteratorAdvance(&aIter[i]);
  137063. nLive++;
  137064. }
  137065. }
  137066. while( nLive>0 ){
  137067. LcsIterator *pAdv = 0; /* The iterator to advance by one position */
  137068. int nThisLcs = 0; /* LCS for the current iterator positions */
  137069. for(i=0; i<pInfo->nPhrase; i++){
  137070. LcsIterator *pIter = &aIter[i];
  137071. if( pIter->pRead==0 ){
  137072. /* This iterator is already at EOF for this column. */
  137073. nThisLcs = 0;
  137074. }else{
  137075. if( pAdv==0 || pIter->iPos<pAdv->iPos ){
  137076. pAdv = pIter;
  137077. }
  137078. if( nThisLcs==0 || pIter->iPos==pIter[-1].iPos ){
  137079. nThisLcs++;
  137080. }else{
  137081. nThisLcs = 1;
  137082. }
  137083. if( nThisLcs>nLcs ) nLcs = nThisLcs;
  137084. }
  137085. }
  137086. if( fts3LcsIteratorAdvance(pAdv) ) nLive--;
  137087. }
  137088. pInfo->aMatchinfo[iCol] = nLcs;
  137089. }
  137090. sqlite3_free(aIter);
  137091. return SQLITE_OK;
  137092. }
  137093. /*
  137094. ** Populate the buffer pInfo->aMatchinfo[] with an array of integers to
  137095. ** be returned by the matchinfo() function. Argument zArg contains the
  137096. ** format string passed as the second argument to matchinfo (or the
  137097. ** default value "pcx" if no second argument was specified). The format
  137098. ** string has already been validated and the pInfo->aMatchinfo[] array
  137099. ** is guaranteed to be large enough for the output.
  137100. **
  137101. ** If bGlobal is true, then populate all fields of the matchinfo() output.
  137102. ** If it is false, then assume that those fields that do not change between
  137103. ** rows (i.e. FTS3_MATCHINFO_NPHRASE, NCOL, NDOC, AVGLENGTH and part of HITS)
  137104. ** have already been populated.
  137105. **
  137106. ** Return SQLITE_OK if successful, or an SQLite error code if an error
  137107. ** occurs. If a value other than SQLITE_OK is returned, the state the
  137108. ** pInfo->aMatchinfo[] buffer is left in is undefined.
  137109. */
  137110. static int fts3MatchinfoValues(
  137111. Fts3Cursor *pCsr, /* FTS3 cursor object */
  137112. int bGlobal, /* True to grab the global stats */
  137113. MatchInfo *pInfo, /* Matchinfo context object */
  137114. const char *zArg /* Matchinfo format string */
  137115. ){
  137116. int rc = SQLITE_OK;
  137117. int i;
  137118. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  137119. sqlite3_stmt *pSelect = 0;
  137120. for(i=0; rc==SQLITE_OK && zArg[i]; i++){
  137121. switch( zArg[i] ){
  137122. case FTS3_MATCHINFO_NPHRASE:
  137123. if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nPhrase;
  137124. break;
  137125. case FTS3_MATCHINFO_NCOL:
  137126. if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nCol;
  137127. break;
  137128. case FTS3_MATCHINFO_NDOC:
  137129. if( bGlobal ){
  137130. sqlite3_int64 nDoc = 0;
  137131. rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, 0);
  137132. pInfo->aMatchinfo[0] = (u32)nDoc;
  137133. }
  137134. break;
  137135. case FTS3_MATCHINFO_AVGLENGTH:
  137136. if( bGlobal ){
  137137. sqlite3_int64 nDoc; /* Number of rows in table */
  137138. const char *a; /* Aggregate column length array */
  137139. rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, &a);
  137140. if( rc==SQLITE_OK ){
  137141. int iCol;
  137142. for(iCol=0; iCol<pInfo->nCol; iCol++){
  137143. u32 iVal;
  137144. sqlite3_int64 nToken;
  137145. a += sqlite3Fts3GetVarint(a, &nToken);
  137146. iVal = (u32)(((u32)(nToken&0xffffffff)+nDoc/2)/nDoc);
  137147. pInfo->aMatchinfo[iCol] = iVal;
  137148. }
  137149. }
  137150. }
  137151. break;
  137152. case FTS3_MATCHINFO_LENGTH: {
  137153. sqlite3_stmt *pSelectDocsize = 0;
  137154. rc = sqlite3Fts3SelectDocsize(pTab, pCsr->iPrevId, &pSelectDocsize);
  137155. if( rc==SQLITE_OK ){
  137156. int iCol;
  137157. const char *a = sqlite3_column_blob(pSelectDocsize, 0);
  137158. for(iCol=0; iCol<pInfo->nCol; iCol++){
  137159. sqlite3_int64 nToken;
  137160. a += sqlite3Fts3GetVarint(a, &nToken);
  137161. pInfo->aMatchinfo[iCol] = (u32)nToken;
  137162. }
  137163. }
  137164. sqlite3_reset(pSelectDocsize);
  137165. break;
  137166. }
  137167. case FTS3_MATCHINFO_LCS:
  137168. rc = fts3ExprLoadDoclists(pCsr, 0, 0);
  137169. if( rc==SQLITE_OK ){
  137170. rc = fts3MatchinfoLcs(pCsr, pInfo);
  137171. }
  137172. break;
  137173. default: {
  137174. Fts3Expr *pExpr;
  137175. assert( zArg[i]==FTS3_MATCHINFO_HITS );
  137176. pExpr = pCsr->pExpr;
  137177. rc = fts3ExprLoadDoclists(pCsr, 0, 0);
  137178. if( rc!=SQLITE_OK ) break;
  137179. if( bGlobal ){
  137180. if( pCsr->pDeferred ){
  137181. rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &pInfo->nDoc, 0);
  137182. if( rc!=SQLITE_OK ) break;
  137183. }
  137184. rc = fts3ExprIterate(pExpr, fts3ExprGlobalHitsCb,(void*)pInfo);
  137185. if( rc!=SQLITE_OK ) break;
  137186. }
  137187. (void)fts3ExprIterate(pExpr, fts3ExprLocalHitsCb,(void*)pInfo);
  137188. break;
  137189. }
  137190. }
  137191. pInfo->aMatchinfo += fts3MatchinfoSize(pInfo, zArg[i]);
  137192. }
  137193. sqlite3_reset(pSelect);
  137194. return rc;
  137195. }
  137196. /*
  137197. ** Populate pCsr->aMatchinfo[] with data for the current row. The
  137198. ** 'matchinfo' data is an array of 32-bit unsigned integers (C type u32).
  137199. */
  137200. static int fts3GetMatchinfo(
  137201. Fts3Cursor *pCsr, /* FTS3 Cursor object */
  137202. const char *zArg /* Second argument to matchinfo() function */
  137203. ){
  137204. MatchInfo sInfo;
  137205. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  137206. int rc = SQLITE_OK;
  137207. int bGlobal = 0; /* Collect 'global' stats as well as local */
  137208. memset(&sInfo, 0, sizeof(MatchInfo));
  137209. sInfo.pCursor = pCsr;
  137210. sInfo.nCol = pTab->nColumn;
  137211. /* If there is cached matchinfo() data, but the format string for the
  137212. ** cache does not match the format string for this request, discard
  137213. ** the cached data. */
  137214. if( pCsr->zMatchinfo && strcmp(pCsr->zMatchinfo, zArg) ){
  137215. assert( pCsr->aMatchinfo );
  137216. sqlite3_free(pCsr->aMatchinfo);
  137217. pCsr->zMatchinfo = 0;
  137218. pCsr->aMatchinfo = 0;
  137219. }
  137220. /* If Fts3Cursor.aMatchinfo[] is NULL, then this is the first time the
  137221. ** matchinfo function has been called for this query. In this case
  137222. ** allocate the array used to accumulate the matchinfo data and
  137223. ** initialize those elements that are constant for every row.
  137224. */
  137225. if( pCsr->aMatchinfo==0 ){
  137226. int nMatchinfo = 0; /* Number of u32 elements in match-info */
  137227. int nArg; /* Bytes in zArg */
  137228. int i; /* Used to iterate through zArg */
  137229. /* Determine the number of phrases in the query */
  137230. pCsr->nPhrase = fts3ExprPhraseCount(pCsr->pExpr);
  137231. sInfo.nPhrase = pCsr->nPhrase;
  137232. /* Determine the number of integers in the buffer returned by this call. */
  137233. for(i=0; zArg[i]; i++){
  137234. nMatchinfo += fts3MatchinfoSize(&sInfo, zArg[i]);
  137235. }
  137236. /* Allocate space for Fts3Cursor.aMatchinfo[] and Fts3Cursor.zMatchinfo. */
  137237. nArg = (int)strlen(zArg);
  137238. pCsr->aMatchinfo = (u32 *)sqlite3_malloc(sizeof(u32)*nMatchinfo + nArg + 1);
  137239. if( !pCsr->aMatchinfo ) return SQLITE_NOMEM;
  137240. pCsr->zMatchinfo = (char *)&pCsr->aMatchinfo[nMatchinfo];
  137241. pCsr->nMatchinfo = nMatchinfo;
  137242. memcpy(pCsr->zMatchinfo, zArg, nArg+1);
  137243. memset(pCsr->aMatchinfo, 0, sizeof(u32)*nMatchinfo);
  137244. pCsr->isMatchinfoNeeded = 1;
  137245. bGlobal = 1;
  137246. }
  137247. sInfo.aMatchinfo = pCsr->aMatchinfo;
  137248. sInfo.nPhrase = pCsr->nPhrase;
  137249. if( pCsr->isMatchinfoNeeded ){
  137250. rc = fts3MatchinfoValues(pCsr, bGlobal, &sInfo, zArg);
  137251. pCsr->isMatchinfoNeeded = 0;
  137252. }
  137253. return rc;
  137254. }
  137255. /*
  137256. ** Implementation of snippet() function.
  137257. */
  137258. SQLITE_PRIVATE void sqlite3Fts3Snippet(
  137259. sqlite3_context *pCtx, /* SQLite function call context */
  137260. Fts3Cursor *pCsr, /* Cursor object */
  137261. const char *zStart, /* Snippet start text - "<b>" */
  137262. const char *zEnd, /* Snippet end text - "</b>" */
  137263. const char *zEllipsis, /* Snippet ellipsis text - "<b>...</b>" */
  137264. int iCol, /* Extract snippet from this column */
  137265. int nToken /* Approximate number of tokens in snippet */
  137266. ){
  137267. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  137268. int rc = SQLITE_OK;
  137269. int i;
  137270. StrBuffer res = {0, 0, 0};
  137271. /* The returned text includes up to four fragments of text extracted from
  137272. ** the data in the current row. The first iteration of the for(...) loop
  137273. ** below attempts to locate a single fragment of text nToken tokens in
  137274. ** size that contains at least one instance of all phrases in the query
  137275. ** expression that appear in the current row. If such a fragment of text
  137276. ** cannot be found, the second iteration of the loop attempts to locate
  137277. ** a pair of fragments, and so on.
  137278. */
  137279. int nSnippet = 0; /* Number of fragments in this snippet */
  137280. SnippetFragment aSnippet[4]; /* Maximum of 4 fragments per snippet */
  137281. int nFToken = -1; /* Number of tokens in each fragment */
  137282. if( !pCsr->pExpr ){
  137283. sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
  137284. return;
  137285. }
  137286. for(nSnippet=1; 1; nSnippet++){
  137287. int iSnip; /* Loop counter 0..nSnippet-1 */
  137288. u64 mCovered = 0; /* Bitmask of phrases covered by snippet */
  137289. u64 mSeen = 0; /* Bitmask of phrases seen by BestSnippet() */
  137290. if( nToken>=0 ){
  137291. nFToken = (nToken+nSnippet-1) / nSnippet;
  137292. }else{
  137293. nFToken = -1 * nToken;
  137294. }
  137295. for(iSnip=0; iSnip<nSnippet; iSnip++){
  137296. int iBestScore = -1; /* Best score of columns checked so far */
  137297. int iRead; /* Used to iterate through columns */
  137298. SnippetFragment *pFragment = &aSnippet[iSnip];
  137299. memset(pFragment, 0, sizeof(*pFragment));
  137300. /* Loop through all columns of the table being considered for snippets.
  137301. ** If the iCol argument to this function was negative, this means all
  137302. ** columns of the FTS3 table. Otherwise, only column iCol is considered.
  137303. */
  137304. for(iRead=0; iRead<pTab->nColumn; iRead++){
  137305. SnippetFragment sF = {0, 0, 0, 0};
  137306. int iS;
  137307. if( iCol>=0 && iRead!=iCol ) continue;
  137308. /* Find the best snippet of nFToken tokens in column iRead. */
  137309. rc = fts3BestSnippet(nFToken, pCsr, iRead, mCovered, &mSeen, &sF, &iS);
  137310. if( rc!=SQLITE_OK ){
  137311. goto snippet_out;
  137312. }
  137313. if( iS>iBestScore ){
  137314. *pFragment = sF;
  137315. iBestScore = iS;
  137316. }
  137317. }
  137318. mCovered |= pFragment->covered;
  137319. }
  137320. /* If all query phrases seen by fts3BestSnippet() are present in at least
  137321. ** one of the nSnippet snippet fragments, break out of the loop.
  137322. */
  137323. assert( (mCovered&mSeen)==mCovered );
  137324. if( mSeen==mCovered || nSnippet==SizeofArray(aSnippet) ) break;
  137325. }
  137326. assert( nFToken>0 );
  137327. for(i=0; i<nSnippet && rc==SQLITE_OK; i++){
  137328. rc = fts3SnippetText(pCsr, &aSnippet[i],
  137329. i, (i==nSnippet-1), nFToken, zStart, zEnd, zEllipsis, &res
  137330. );
  137331. }
  137332. snippet_out:
  137333. sqlite3Fts3SegmentsClose(pTab);
  137334. if( rc!=SQLITE_OK ){
  137335. sqlite3_result_error_code(pCtx, rc);
  137336. sqlite3_free(res.z);
  137337. }else{
  137338. sqlite3_result_text(pCtx, res.z, -1, sqlite3_free);
  137339. }
  137340. }
  137341. typedef struct TermOffset TermOffset;
  137342. typedef struct TermOffsetCtx TermOffsetCtx;
  137343. struct TermOffset {
  137344. char *pList; /* Position-list */
  137345. int iPos; /* Position just read from pList */
  137346. int iOff; /* Offset of this term from read positions */
  137347. };
  137348. struct TermOffsetCtx {
  137349. Fts3Cursor *pCsr;
  137350. int iCol; /* Column of table to populate aTerm for */
  137351. int iTerm;
  137352. sqlite3_int64 iDocid;
  137353. TermOffset *aTerm;
  137354. };
  137355. /*
  137356. ** This function is an fts3ExprIterate() callback used by sqlite3Fts3Offsets().
  137357. */
  137358. static int fts3ExprTermOffsetInit(Fts3Expr *pExpr, int iPhrase, void *ctx){
  137359. TermOffsetCtx *p = (TermOffsetCtx *)ctx;
  137360. int nTerm; /* Number of tokens in phrase */
  137361. int iTerm; /* For looping through nTerm phrase terms */
  137362. char *pList; /* Pointer to position list for phrase */
  137363. int iPos = 0; /* First position in position-list */
  137364. int rc;
  137365. UNUSED_PARAMETER(iPhrase);
  137366. rc = sqlite3Fts3EvalPhrasePoslist(p->pCsr, pExpr, p->iCol, &pList);
  137367. nTerm = pExpr->pPhrase->nToken;
  137368. if( pList ){
  137369. fts3GetDeltaPosition(&pList, &iPos);
  137370. assert( iPos>=0 );
  137371. }
  137372. for(iTerm=0; iTerm<nTerm; iTerm++){
  137373. TermOffset *pT = &p->aTerm[p->iTerm++];
  137374. pT->iOff = nTerm-iTerm-1;
  137375. pT->pList = pList;
  137376. pT->iPos = iPos;
  137377. }
  137378. return rc;
  137379. }
  137380. /*
  137381. ** Implementation of offsets() function.
  137382. */
  137383. SQLITE_PRIVATE void sqlite3Fts3Offsets(
  137384. sqlite3_context *pCtx, /* SQLite function call context */
  137385. Fts3Cursor *pCsr /* Cursor object */
  137386. ){
  137387. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  137388. sqlite3_tokenizer_module const *pMod = pTab->pTokenizer->pModule;
  137389. int rc; /* Return Code */
  137390. int nToken; /* Number of tokens in query */
  137391. int iCol; /* Column currently being processed */
  137392. StrBuffer res = {0, 0, 0}; /* Result string */
  137393. TermOffsetCtx sCtx; /* Context for fts3ExprTermOffsetInit() */
  137394. if( !pCsr->pExpr ){
  137395. sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
  137396. return;
  137397. }
  137398. memset(&sCtx, 0, sizeof(sCtx));
  137399. assert( pCsr->isRequireSeek==0 );
  137400. /* Count the number of terms in the query */
  137401. rc = fts3ExprLoadDoclists(pCsr, 0, &nToken);
  137402. if( rc!=SQLITE_OK ) goto offsets_out;
  137403. /* Allocate the array of TermOffset iterators. */
  137404. sCtx.aTerm = (TermOffset *)sqlite3_malloc(sizeof(TermOffset)*nToken);
  137405. if( 0==sCtx.aTerm ){
  137406. rc = SQLITE_NOMEM;
  137407. goto offsets_out;
  137408. }
  137409. sCtx.iDocid = pCsr->iPrevId;
  137410. sCtx.pCsr = pCsr;
  137411. /* Loop through the table columns, appending offset information to
  137412. ** string-buffer res for each column.
  137413. */
  137414. for(iCol=0; iCol<pTab->nColumn; iCol++){
  137415. sqlite3_tokenizer_cursor *pC; /* Tokenizer cursor */
  137416. const char *ZDUMMY; /* Dummy argument used with xNext() */
  137417. int NDUMMY = 0; /* Dummy argument used with xNext() */
  137418. int iStart = 0;
  137419. int iEnd = 0;
  137420. int iCurrent = 0;
  137421. const char *zDoc;
  137422. int nDoc;
  137423. /* Initialize the contents of sCtx.aTerm[] for column iCol. There is
  137424. ** no way that this operation can fail, so the return code from
  137425. ** fts3ExprIterate() can be discarded.
  137426. */
  137427. sCtx.iCol = iCol;
  137428. sCtx.iTerm = 0;
  137429. (void)fts3ExprIterate(pCsr->pExpr, fts3ExprTermOffsetInit, (void *)&sCtx);
  137430. /* Retreive the text stored in column iCol. If an SQL NULL is stored
  137431. ** in column iCol, jump immediately to the next iteration of the loop.
  137432. ** If an OOM occurs while retrieving the data (this can happen if SQLite
  137433. ** needs to transform the data from utf-16 to utf-8), return SQLITE_NOMEM
  137434. ** to the caller.
  137435. */
  137436. zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol+1);
  137437. nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol+1);
  137438. if( zDoc==0 ){
  137439. if( sqlite3_column_type(pCsr->pStmt, iCol+1)==SQLITE_NULL ){
  137440. continue;
  137441. }
  137442. rc = SQLITE_NOMEM;
  137443. goto offsets_out;
  137444. }
  137445. /* Initialize a tokenizer iterator to iterate through column iCol. */
  137446. rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, pCsr->iLangid,
  137447. zDoc, nDoc, &pC
  137448. );
  137449. if( rc!=SQLITE_OK ) goto offsets_out;
  137450. rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
  137451. while( rc==SQLITE_OK ){
  137452. int i; /* Used to loop through terms */
  137453. int iMinPos = 0x7FFFFFFF; /* Position of next token */
  137454. TermOffset *pTerm = 0; /* TermOffset associated with next token */
  137455. for(i=0; i<nToken; i++){
  137456. TermOffset *pT = &sCtx.aTerm[i];
  137457. if( pT->pList && (pT->iPos-pT->iOff)<iMinPos ){
  137458. iMinPos = pT->iPos-pT->iOff;
  137459. pTerm = pT;
  137460. }
  137461. }
  137462. if( !pTerm ){
  137463. /* All offsets for this column have been gathered. */
  137464. rc = SQLITE_DONE;
  137465. }else{
  137466. assert( iCurrent<=iMinPos );
  137467. if( 0==(0xFE&*pTerm->pList) ){
  137468. pTerm->pList = 0;
  137469. }else{
  137470. fts3GetDeltaPosition(&pTerm->pList, &pTerm->iPos);
  137471. }
  137472. while( rc==SQLITE_OK && iCurrent<iMinPos ){
  137473. rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
  137474. }
  137475. if( rc==SQLITE_OK ){
  137476. char aBuffer[64];
  137477. sqlite3_snprintf(sizeof(aBuffer), aBuffer,
  137478. "%d %d %d %d ", iCol, pTerm-sCtx.aTerm, iStart, iEnd-iStart
  137479. );
  137480. rc = fts3StringAppend(&res, aBuffer, -1);
  137481. }else if( rc==SQLITE_DONE && pTab->zContentTbl==0 ){
  137482. rc = FTS_CORRUPT_VTAB;
  137483. }
  137484. }
  137485. }
  137486. if( rc==SQLITE_DONE ){
  137487. rc = SQLITE_OK;
  137488. }
  137489. pMod->xClose(pC);
  137490. if( rc!=SQLITE_OK ) goto offsets_out;
  137491. }
  137492. offsets_out:
  137493. sqlite3_free(sCtx.aTerm);
  137494. assert( rc!=SQLITE_DONE );
  137495. sqlite3Fts3SegmentsClose(pTab);
  137496. if( rc!=SQLITE_OK ){
  137497. sqlite3_result_error_code(pCtx, rc);
  137498. sqlite3_free(res.z);
  137499. }else{
  137500. sqlite3_result_text(pCtx, res.z, res.n-1, sqlite3_free);
  137501. }
  137502. return;
  137503. }
  137504. /*
  137505. ** Implementation of matchinfo() function.
  137506. */
  137507. SQLITE_PRIVATE void sqlite3Fts3Matchinfo(
  137508. sqlite3_context *pContext, /* Function call context */
  137509. Fts3Cursor *pCsr, /* FTS3 table cursor */
  137510. const char *zArg /* Second arg to matchinfo() function */
  137511. ){
  137512. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  137513. int rc;
  137514. int i;
  137515. const char *zFormat;
  137516. if( zArg ){
  137517. for(i=0; zArg[i]; i++){
  137518. char *zErr = 0;
  137519. if( fts3MatchinfoCheck(pTab, zArg[i], &zErr) ){
  137520. sqlite3_result_error(pContext, zErr, -1);
  137521. sqlite3_free(zErr);
  137522. return;
  137523. }
  137524. }
  137525. zFormat = zArg;
  137526. }else{
  137527. zFormat = FTS3_MATCHINFO_DEFAULT;
  137528. }
  137529. if( !pCsr->pExpr ){
  137530. sqlite3_result_blob(pContext, "", 0, SQLITE_STATIC);
  137531. return;
  137532. }
  137533. /* Retrieve matchinfo() data. */
  137534. rc = fts3GetMatchinfo(pCsr, zFormat);
  137535. sqlite3Fts3SegmentsClose(pTab);
  137536. if( rc!=SQLITE_OK ){
  137537. sqlite3_result_error_code(pContext, rc);
  137538. }else{
  137539. int n = pCsr->nMatchinfo * sizeof(u32);
  137540. sqlite3_result_blob(pContext, pCsr->aMatchinfo, n, SQLITE_TRANSIENT);
  137541. }
  137542. }
  137543. #endif
  137544. /************** End of fts3_snippet.c ****************************************/
  137545. /************** Begin file fts3_unicode.c ************************************/
  137546. /*
  137547. ** 2012 May 24
  137548. **
  137549. ** The author disclaims copyright to this source code. In place of
  137550. ** a legal notice, here is a blessing:
  137551. **
  137552. ** May you do good and not evil.
  137553. ** May you find forgiveness for yourself and forgive others.
  137554. ** May you share freely, never taking more than you give.
  137555. **
  137556. ******************************************************************************
  137557. **
  137558. ** Implementation of the "unicode" full-text-search tokenizer.
  137559. */
  137560. #ifndef SQLITE_DISABLE_FTS3_UNICODE
  137561. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  137562. /* #include <assert.h> */
  137563. /* #include <stdlib.h> */
  137564. /* #include <stdio.h> */
  137565. /* #include <string.h> */
  137566. /*
  137567. ** The following two macros - READ_UTF8 and WRITE_UTF8 - have been copied
  137568. ** from the sqlite3 source file utf.c. If this file is compiled as part
  137569. ** of the amalgamation, they are not required.
  137570. */
  137571. #ifndef SQLITE_AMALGAMATION
  137572. static const unsigned char sqlite3Utf8Trans1[] = {
  137573. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  137574. 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
  137575. 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
  137576. 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
  137577. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  137578. 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
  137579. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  137580. 0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
  137581. };
  137582. #define READ_UTF8(zIn, zTerm, c) \
  137583. c = *(zIn++); \
  137584. if( c>=0xc0 ){ \
  137585. c = sqlite3Utf8Trans1[c-0xc0]; \
  137586. while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){ \
  137587. c = (c<<6) + (0x3f & *(zIn++)); \
  137588. } \
  137589. if( c<0x80 \
  137590. || (c&0xFFFFF800)==0xD800 \
  137591. || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; } \
  137592. }
  137593. #define WRITE_UTF8(zOut, c) { \
  137594. if( c<0x00080 ){ \
  137595. *zOut++ = (u8)(c&0xFF); \
  137596. } \
  137597. else if( c<0x00800 ){ \
  137598. *zOut++ = 0xC0 + (u8)((c>>6)&0x1F); \
  137599. *zOut++ = 0x80 + (u8)(c & 0x3F); \
  137600. } \
  137601. else if( c<0x10000 ){ \
  137602. *zOut++ = 0xE0 + (u8)((c>>12)&0x0F); \
  137603. *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \
  137604. *zOut++ = 0x80 + (u8)(c & 0x3F); \
  137605. }else{ \
  137606. *zOut++ = 0xF0 + (u8)((c>>18) & 0x07); \
  137607. *zOut++ = 0x80 + (u8)((c>>12) & 0x3F); \
  137608. *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \
  137609. *zOut++ = 0x80 + (u8)(c & 0x3F); \
  137610. } \
  137611. }
  137612. #endif /* ifndef SQLITE_AMALGAMATION */
  137613. typedef struct unicode_tokenizer unicode_tokenizer;
  137614. typedef struct unicode_cursor unicode_cursor;
  137615. struct unicode_tokenizer {
  137616. sqlite3_tokenizer base;
  137617. int bRemoveDiacritic;
  137618. int nException;
  137619. int *aiException;
  137620. };
  137621. struct unicode_cursor {
  137622. sqlite3_tokenizer_cursor base;
  137623. const unsigned char *aInput; /* Input text being tokenized */
  137624. int nInput; /* Size of aInput[] in bytes */
  137625. int iOff; /* Current offset within aInput[] */
  137626. int iToken; /* Index of next token to be returned */
  137627. char *zToken; /* storage for current token */
  137628. int nAlloc; /* space allocated at zToken */
  137629. };
  137630. /*
  137631. ** Destroy a tokenizer allocated by unicodeCreate().
  137632. */
  137633. static int unicodeDestroy(sqlite3_tokenizer *pTokenizer){
  137634. if( pTokenizer ){
  137635. unicode_tokenizer *p = (unicode_tokenizer *)pTokenizer;
  137636. sqlite3_free(p->aiException);
  137637. sqlite3_free(p);
  137638. }
  137639. return SQLITE_OK;
  137640. }
  137641. /*
  137642. ** As part of a tokenchars= or separators= option, the CREATE VIRTUAL TABLE
  137643. ** statement has specified that the tokenizer for this table shall consider
  137644. ** all characters in string zIn/nIn to be separators (if bAlnum==0) or
  137645. ** token characters (if bAlnum==1).
  137646. **
  137647. ** For each codepoint in the zIn/nIn string, this function checks if the
  137648. ** sqlite3FtsUnicodeIsalnum() function already returns the desired result.
  137649. ** If so, no action is taken. Otherwise, the codepoint is added to the
  137650. ** unicode_tokenizer.aiException[] array. For the purposes of tokenization,
  137651. ** the return value of sqlite3FtsUnicodeIsalnum() is inverted for all
  137652. ** codepoints in the aiException[] array.
  137653. **
  137654. ** If a standalone diacritic mark (one that sqlite3FtsUnicodeIsdiacritic()
  137655. ** identifies as a diacritic) occurs in the zIn/nIn string it is ignored.
  137656. ** It is not possible to change the behavior of the tokenizer with respect
  137657. ** to these codepoints.
  137658. */
  137659. static int unicodeAddExceptions(
  137660. unicode_tokenizer *p, /* Tokenizer to add exceptions to */
  137661. int bAlnum, /* Replace Isalnum() return value with this */
  137662. const char *zIn, /* Array of characters to make exceptions */
  137663. int nIn /* Length of z in bytes */
  137664. ){
  137665. const unsigned char *z = (const unsigned char *)zIn;
  137666. const unsigned char *zTerm = &z[nIn];
  137667. int iCode;
  137668. int nEntry = 0;
  137669. assert( bAlnum==0 || bAlnum==1 );
  137670. while( z<zTerm ){
  137671. READ_UTF8(z, zTerm, iCode);
  137672. assert( (sqlite3FtsUnicodeIsalnum(iCode) & 0xFFFFFFFE)==0 );
  137673. if( sqlite3FtsUnicodeIsalnum(iCode)!=bAlnum
  137674. && sqlite3FtsUnicodeIsdiacritic(iCode)==0
  137675. ){
  137676. nEntry++;
  137677. }
  137678. }
  137679. if( nEntry ){
  137680. int *aNew; /* New aiException[] array */
  137681. int nNew; /* Number of valid entries in array aNew[] */
  137682. aNew = sqlite3_realloc(p->aiException, (p->nException+nEntry)*sizeof(int));
  137683. if( aNew==0 ) return SQLITE_NOMEM;
  137684. nNew = p->nException;
  137685. z = (const unsigned char *)zIn;
  137686. while( z<zTerm ){
  137687. READ_UTF8(z, zTerm, iCode);
  137688. if( sqlite3FtsUnicodeIsalnum(iCode)!=bAlnum
  137689. && sqlite3FtsUnicodeIsdiacritic(iCode)==0
  137690. ){
  137691. int i, j;
  137692. for(i=0; i<nNew && aNew[i]<iCode; i++);
  137693. for(j=nNew; j>i; j--) aNew[j] = aNew[j-1];
  137694. aNew[i] = iCode;
  137695. nNew++;
  137696. }
  137697. }
  137698. p->aiException = aNew;
  137699. p->nException = nNew;
  137700. }
  137701. return SQLITE_OK;
  137702. }
  137703. /*
  137704. ** Return true if the p->aiException[] array contains the value iCode.
  137705. */
  137706. static int unicodeIsException(unicode_tokenizer *p, int iCode){
  137707. if( p->nException>0 ){
  137708. int *a = p->aiException;
  137709. int iLo = 0;
  137710. int iHi = p->nException-1;
  137711. while( iHi>=iLo ){
  137712. int iTest = (iHi + iLo) / 2;
  137713. if( iCode==a[iTest] ){
  137714. return 1;
  137715. }else if( iCode>a[iTest] ){
  137716. iLo = iTest+1;
  137717. }else{
  137718. iHi = iTest-1;
  137719. }
  137720. }
  137721. }
  137722. return 0;
  137723. }
  137724. /*
  137725. ** Return true if, for the purposes of tokenization, codepoint iCode is
  137726. ** considered a token character (not a separator).
  137727. */
  137728. static int unicodeIsAlnum(unicode_tokenizer *p, int iCode){
  137729. assert( (sqlite3FtsUnicodeIsalnum(iCode) & 0xFFFFFFFE)==0 );
  137730. return sqlite3FtsUnicodeIsalnum(iCode) ^ unicodeIsException(p, iCode);
  137731. }
  137732. /*
  137733. ** Create a new tokenizer instance.
  137734. */
  137735. static int unicodeCreate(
  137736. int nArg, /* Size of array argv[] */
  137737. const char * const *azArg, /* Tokenizer creation arguments */
  137738. sqlite3_tokenizer **pp /* OUT: New tokenizer handle */
  137739. ){
  137740. unicode_tokenizer *pNew; /* New tokenizer object */
  137741. int i;
  137742. int rc = SQLITE_OK;
  137743. pNew = (unicode_tokenizer *) sqlite3_malloc(sizeof(unicode_tokenizer));
  137744. if( pNew==NULL ) return SQLITE_NOMEM;
  137745. memset(pNew, 0, sizeof(unicode_tokenizer));
  137746. pNew->bRemoveDiacritic = 1;
  137747. for(i=0; rc==SQLITE_OK && i<nArg; i++){
  137748. const char *z = azArg[i];
  137749. int n = (int)strlen(z);
  137750. if( n==19 && memcmp("remove_diacritics=1", z, 19)==0 ){
  137751. pNew->bRemoveDiacritic = 1;
  137752. }
  137753. else if( n==19 && memcmp("remove_diacritics=0", z, 19)==0 ){
  137754. pNew->bRemoveDiacritic = 0;
  137755. }
  137756. else if( n>=11 && memcmp("tokenchars=", z, 11)==0 ){
  137757. rc = unicodeAddExceptions(pNew, 1, &z[11], n-11);
  137758. }
  137759. else if( n>=11 && memcmp("separators=", z, 11)==0 ){
  137760. rc = unicodeAddExceptions(pNew, 0, &z[11], n-11);
  137761. }
  137762. else{
  137763. /* Unrecognized argument */
  137764. rc = SQLITE_ERROR;
  137765. }
  137766. }
  137767. if( rc!=SQLITE_OK ){
  137768. unicodeDestroy((sqlite3_tokenizer *)pNew);
  137769. pNew = 0;
  137770. }
  137771. *pp = (sqlite3_tokenizer *)pNew;
  137772. return rc;
  137773. }
  137774. /*
  137775. ** Prepare to begin tokenizing a particular string. The input
  137776. ** string to be tokenized is pInput[0..nBytes-1]. A cursor
  137777. ** used to incrementally tokenize this string is returned in
  137778. ** *ppCursor.
  137779. */
  137780. static int unicodeOpen(
  137781. sqlite3_tokenizer *p, /* The tokenizer */
  137782. const char *aInput, /* Input string */
  137783. int nInput, /* Size of string aInput in bytes */
  137784. sqlite3_tokenizer_cursor **pp /* OUT: New cursor object */
  137785. ){
  137786. unicode_cursor *pCsr;
  137787. pCsr = (unicode_cursor *)sqlite3_malloc(sizeof(unicode_cursor));
  137788. if( pCsr==0 ){
  137789. return SQLITE_NOMEM;
  137790. }
  137791. memset(pCsr, 0, sizeof(unicode_cursor));
  137792. pCsr->aInput = (const unsigned char *)aInput;
  137793. if( aInput==0 ){
  137794. pCsr->nInput = 0;
  137795. }else if( nInput<0 ){
  137796. pCsr->nInput = (int)strlen(aInput);
  137797. }else{
  137798. pCsr->nInput = nInput;
  137799. }
  137800. *pp = &pCsr->base;
  137801. UNUSED_PARAMETER(p);
  137802. return SQLITE_OK;
  137803. }
  137804. /*
  137805. ** Close a tokenization cursor previously opened by a call to
  137806. ** simpleOpen() above.
  137807. */
  137808. static int unicodeClose(sqlite3_tokenizer_cursor *pCursor){
  137809. unicode_cursor *pCsr = (unicode_cursor *) pCursor;
  137810. sqlite3_free(pCsr->zToken);
  137811. sqlite3_free(pCsr);
  137812. return SQLITE_OK;
  137813. }
  137814. /*
  137815. ** Extract the next token from a tokenization cursor. The cursor must
  137816. ** have been opened by a prior call to simpleOpen().
  137817. */
  137818. static int unicodeNext(
  137819. sqlite3_tokenizer_cursor *pC, /* Cursor returned by simpleOpen */
  137820. const char **paToken, /* OUT: Token text */
  137821. int *pnToken, /* OUT: Number of bytes at *paToken */
  137822. int *piStart, /* OUT: Starting offset of token */
  137823. int *piEnd, /* OUT: Ending offset of token */
  137824. int *piPos /* OUT: Position integer of token */
  137825. ){
  137826. unicode_cursor *pCsr = (unicode_cursor *)pC;
  137827. unicode_tokenizer *p = ((unicode_tokenizer *)pCsr->base.pTokenizer);
  137828. int iCode = 0;
  137829. char *zOut;
  137830. const unsigned char *z = &pCsr->aInput[pCsr->iOff];
  137831. const unsigned char *zStart = z;
  137832. const unsigned char *zEnd;
  137833. const unsigned char *zTerm = &pCsr->aInput[pCsr->nInput];
  137834. /* Scan past any delimiter characters before the start of the next token.
  137835. ** Return SQLITE_DONE early if this takes us all the way to the end of
  137836. ** the input. */
  137837. while( z<zTerm ){
  137838. READ_UTF8(z, zTerm, iCode);
  137839. if( unicodeIsAlnum(p, iCode) ) break;
  137840. zStart = z;
  137841. }
  137842. if( zStart>=zTerm ) return SQLITE_DONE;
  137843. zOut = pCsr->zToken;
  137844. do {
  137845. int iOut;
  137846. /* Grow the output buffer if required. */
  137847. if( (zOut-pCsr->zToken)>=(pCsr->nAlloc-4) ){
  137848. char *zNew = sqlite3_realloc(pCsr->zToken, pCsr->nAlloc+64);
  137849. if( !zNew ) return SQLITE_NOMEM;
  137850. zOut = &zNew[zOut - pCsr->zToken];
  137851. pCsr->zToken = zNew;
  137852. pCsr->nAlloc += 64;
  137853. }
  137854. /* Write the folded case of the last character read to the output */
  137855. zEnd = z;
  137856. iOut = sqlite3FtsUnicodeFold(iCode, p->bRemoveDiacritic);
  137857. if( iOut ){
  137858. WRITE_UTF8(zOut, iOut);
  137859. }
  137860. /* If the cursor is not at EOF, read the next character */
  137861. if( z>=zTerm ) break;
  137862. READ_UTF8(z, zTerm, iCode);
  137863. }while( unicodeIsAlnum(p, iCode)
  137864. || sqlite3FtsUnicodeIsdiacritic(iCode)
  137865. );
  137866. /* Set the output variables and return. */
  137867. pCsr->iOff = (int)(z - pCsr->aInput);
  137868. *paToken = pCsr->zToken;
  137869. *pnToken = (int)(zOut - pCsr->zToken);
  137870. *piStart = (int)(zStart - pCsr->aInput);
  137871. *piEnd = (int)(zEnd - pCsr->aInput);
  137872. *piPos = pCsr->iToken++;
  137873. return SQLITE_OK;
  137874. }
  137875. /*
  137876. ** Set *ppModule to a pointer to the sqlite3_tokenizer_module
  137877. ** structure for the unicode tokenizer.
  137878. */
  137879. SQLITE_PRIVATE void sqlite3Fts3UnicodeTokenizer(sqlite3_tokenizer_module const **ppModule){
  137880. static const sqlite3_tokenizer_module module = {
  137881. 0,
  137882. unicodeCreate,
  137883. unicodeDestroy,
  137884. unicodeOpen,
  137885. unicodeClose,
  137886. unicodeNext,
  137887. 0,
  137888. };
  137889. *ppModule = &module;
  137890. }
  137891. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  137892. #endif /* ifndef SQLITE_DISABLE_FTS3_UNICODE */
  137893. /************** End of fts3_unicode.c ****************************************/
  137894. /************** Begin file fts3_unicode2.c ***********************************/
  137895. /*
  137896. ** 2012 May 25
  137897. **
  137898. ** The author disclaims copyright to this source code. In place of
  137899. ** a legal notice, here is a blessing:
  137900. **
  137901. ** May you do good and not evil.
  137902. ** May you find forgiveness for yourself and forgive others.
  137903. ** May you share freely, never taking more than you give.
  137904. **
  137905. ******************************************************************************
  137906. */
  137907. /*
  137908. ** DO NOT EDIT THIS MACHINE GENERATED FILE.
  137909. */
  137910. #ifndef SQLITE_DISABLE_FTS3_UNICODE
  137911. #if defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4)
  137912. /* #include <assert.h> */
  137913. /*
  137914. ** Return true if the argument corresponds to a unicode codepoint
  137915. ** classified as either a letter or a number. Otherwise false.
  137916. **
  137917. ** The results are undefined if the value passed to this function
  137918. ** is less than zero.
  137919. */
  137920. SQLITE_PRIVATE int sqlite3FtsUnicodeIsalnum(int c){
  137921. /* Each unsigned integer in the following array corresponds to a contiguous
  137922. ** range of unicode codepoints that are not either letters or numbers (i.e.
  137923. ** codepoints for which this function should return 0).
  137924. **
  137925. ** The most significant 22 bits in each 32-bit value contain the first
  137926. ** codepoint in the range. The least significant 10 bits are used to store
  137927. ** the size of the range (always at least 1). In other words, the value
  137928. ** ((C<<22) + N) represents a range of N codepoints starting with codepoint
  137929. ** C. It is not possible to represent a range larger than 1023 codepoints
  137930. ** using this format.
  137931. */
  137932. static const unsigned int aEntry[] = {
  137933. 0x00000030, 0x0000E807, 0x00016C06, 0x0001EC2F, 0x0002AC07,
  137934. 0x0002D001, 0x0002D803, 0x0002EC01, 0x0002FC01, 0x00035C01,
  137935. 0x0003DC01, 0x000B0804, 0x000B480E, 0x000B9407, 0x000BB401,
  137936. 0x000BBC81, 0x000DD401, 0x000DF801, 0x000E1002, 0x000E1C01,
  137937. 0x000FD801, 0x00120808, 0x00156806, 0x00162402, 0x00163C01,
  137938. 0x00164437, 0x0017CC02, 0x00180005, 0x00181816, 0x00187802,
  137939. 0x00192C15, 0x0019A804, 0x0019C001, 0x001B5001, 0x001B580F,
  137940. 0x001B9C07, 0x001BF402, 0x001C000E, 0x001C3C01, 0x001C4401,
  137941. 0x001CC01B, 0x001E980B, 0x001FAC09, 0x001FD804, 0x00205804,
  137942. 0x00206C09, 0x00209403, 0x0020A405, 0x0020C00F, 0x00216403,
  137943. 0x00217801, 0x0023901B, 0x00240004, 0x0024E803, 0x0024F812,
  137944. 0x00254407, 0x00258804, 0x0025C001, 0x00260403, 0x0026F001,
  137945. 0x0026F807, 0x00271C02, 0x00272C03, 0x00275C01, 0x00278802,
  137946. 0x0027C802, 0x0027E802, 0x00280403, 0x0028F001, 0x0028F805,
  137947. 0x00291C02, 0x00292C03, 0x00294401, 0x0029C002, 0x0029D401,
  137948. 0x002A0403, 0x002AF001, 0x002AF808, 0x002B1C03, 0x002B2C03,
  137949. 0x002B8802, 0x002BC002, 0x002C0403, 0x002CF001, 0x002CF807,
  137950. 0x002D1C02, 0x002D2C03, 0x002D5802, 0x002D8802, 0x002DC001,
  137951. 0x002E0801, 0x002EF805, 0x002F1803, 0x002F2804, 0x002F5C01,
  137952. 0x002FCC08, 0x00300403, 0x0030F807, 0x00311803, 0x00312804,
  137953. 0x00315402, 0x00318802, 0x0031FC01, 0x00320802, 0x0032F001,
  137954. 0x0032F807, 0x00331803, 0x00332804, 0x00335402, 0x00338802,
  137955. 0x00340802, 0x0034F807, 0x00351803, 0x00352804, 0x00355C01,
  137956. 0x00358802, 0x0035E401, 0x00360802, 0x00372801, 0x00373C06,
  137957. 0x00375801, 0x00376008, 0x0037C803, 0x0038C401, 0x0038D007,
  137958. 0x0038FC01, 0x00391C09, 0x00396802, 0x003AC401, 0x003AD006,
  137959. 0x003AEC02, 0x003B2006, 0x003C041F, 0x003CD00C, 0x003DC417,
  137960. 0x003E340B, 0x003E6424, 0x003EF80F, 0x003F380D, 0x0040AC14,
  137961. 0x00412806, 0x00415804, 0x00417803, 0x00418803, 0x00419C07,
  137962. 0x0041C404, 0x0042080C, 0x00423C01, 0x00426806, 0x0043EC01,
  137963. 0x004D740C, 0x004E400A, 0x00500001, 0x0059B402, 0x005A0001,
  137964. 0x005A6C02, 0x005BAC03, 0x005C4803, 0x005CC805, 0x005D4802,
  137965. 0x005DC802, 0x005ED023, 0x005F6004, 0x005F7401, 0x0060000F,
  137966. 0x0062A401, 0x0064800C, 0x0064C00C, 0x00650001, 0x00651002,
  137967. 0x0066C011, 0x00672002, 0x00677822, 0x00685C05, 0x00687802,
  137968. 0x0069540A, 0x0069801D, 0x0069FC01, 0x006A8007, 0x006AA006,
  137969. 0x006C0005, 0x006CD011, 0x006D6823, 0x006E0003, 0x006E840D,
  137970. 0x006F980E, 0x006FF004, 0x00709014, 0x0070EC05, 0x0071F802,
  137971. 0x00730008, 0x00734019, 0x0073B401, 0x0073C803, 0x00770027,
  137972. 0x0077F004, 0x007EF401, 0x007EFC03, 0x007F3403, 0x007F7403,
  137973. 0x007FB403, 0x007FF402, 0x00800065, 0x0081A806, 0x0081E805,
  137974. 0x00822805, 0x0082801A, 0x00834021, 0x00840002, 0x00840C04,
  137975. 0x00842002, 0x00845001, 0x00845803, 0x00847806, 0x00849401,
  137976. 0x00849C01, 0x0084A401, 0x0084B801, 0x0084E802, 0x00850005,
  137977. 0x00852804, 0x00853C01, 0x00864264, 0x00900027, 0x0091000B,
  137978. 0x0092704E, 0x00940200, 0x009C0475, 0x009E53B9, 0x00AD400A,
  137979. 0x00B39406, 0x00B3BC03, 0x00B3E404, 0x00B3F802, 0x00B5C001,
  137980. 0x00B5FC01, 0x00B7804F, 0x00B8C00C, 0x00BA001A, 0x00BA6C59,
  137981. 0x00BC00D6, 0x00BFC00C, 0x00C00005, 0x00C02019, 0x00C0A807,
  137982. 0x00C0D802, 0x00C0F403, 0x00C26404, 0x00C28001, 0x00C3EC01,
  137983. 0x00C64002, 0x00C6580A, 0x00C70024, 0x00C8001F, 0x00C8A81E,
  137984. 0x00C94001, 0x00C98020, 0x00CA2827, 0x00CB003F, 0x00CC0100,
  137985. 0x01370040, 0x02924037, 0x0293F802, 0x02983403, 0x0299BC10,
  137986. 0x029A7C01, 0x029BC008, 0x029C0017, 0x029C8002, 0x029E2402,
  137987. 0x02A00801, 0x02A01801, 0x02A02C01, 0x02A08C09, 0x02A0D804,
  137988. 0x02A1D004, 0x02A20002, 0x02A2D011, 0x02A33802, 0x02A38012,
  137989. 0x02A3E003, 0x02A4980A, 0x02A51C0D, 0x02A57C01, 0x02A60004,
  137990. 0x02A6CC1B, 0x02A77802, 0x02A8A40E, 0x02A90C01, 0x02A93002,
  137991. 0x02A97004, 0x02A9DC03, 0x02A9EC01, 0x02AAC001, 0x02AAC803,
  137992. 0x02AADC02, 0x02AAF802, 0x02AB0401, 0x02AB7802, 0x02ABAC07,
  137993. 0x02ABD402, 0x02AF8C0B, 0x03600001, 0x036DFC02, 0x036FFC02,
  137994. 0x037FFC01, 0x03EC7801, 0x03ECA401, 0x03EEC810, 0x03F4F802,
  137995. 0x03F7F002, 0x03F8001A, 0x03F88007, 0x03F8C023, 0x03F95013,
  137996. 0x03F9A004, 0x03FBFC01, 0x03FC040F, 0x03FC6807, 0x03FCEC06,
  137997. 0x03FD6C0B, 0x03FF8007, 0x03FFA007, 0x03FFE405, 0x04040003,
  137998. 0x0404DC09, 0x0405E411, 0x0406400C, 0x0407402E, 0x040E7C01,
  137999. 0x040F4001, 0x04215C01, 0x04247C01, 0x0424FC01, 0x04280403,
  138000. 0x04281402, 0x04283004, 0x0428E003, 0x0428FC01, 0x04294009,
  138001. 0x0429FC01, 0x042CE407, 0x04400003, 0x0440E016, 0x04420003,
  138002. 0x0442C012, 0x04440003, 0x04449C0E, 0x04450004, 0x04460003,
  138003. 0x0446CC0E, 0x04471404, 0x045AAC0D, 0x0491C004, 0x05BD442E,
  138004. 0x05BE3C04, 0x074000F6, 0x07440027, 0x0744A4B5, 0x07480046,
  138005. 0x074C0057, 0x075B0401, 0x075B6C01, 0x075BEC01, 0x075C5401,
  138006. 0x075CD401, 0x075D3C01, 0x075DBC01, 0x075E2401, 0x075EA401,
  138007. 0x075F0C01, 0x07BBC002, 0x07C0002C, 0x07C0C064, 0x07C2800F,
  138008. 0x07C2C40E, 0x07C3040F, 0x07C3440F, 0x07C4401F, 0x07C4C03C,
  138009. 0x07C5C02B, 0x07C7981D, 0x07C8402B, 0x07C90009, 0x07C94002,
  138010. 0x07CC0021, 0x07CCC006, 0x07CCDC46, 0x07CE0014, 0x07CE8025,
  138011. 0x07CF1805, 0x07CF8011, 0x07D0003F, 0x07D10001, 0x07D108B6,
  138012. 0x07D3E404, 0x07D4003E, 0x07D50004, 0x07D54018, 0x07D7EC46,
  138013. 0x07D9140B, 0x07DA0046, 0x07DC0074, 0x38000401, 0x38008060,
  138014. 0x380400F0,
  138015. };
  138016. static const unsigned int aAscii[4] = {
  138017. 0xFFFFFFFF, 0xFC00FFFF, 0xF8000001, 0xF8000001,
  138018. };
  138019. if( c<128 ){
  138020. return ( (aAscii[c >> 5] & (1 << (c & 0x001F)))==0 );
  138021. }else if( c<(1<<22) ){
  138022. unsigned int key = (((unsigned int)c)<<10) | 0x000003FF;
  138023. int iRes = 0;
  138024. int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
  138025. int iLo = 0;
  138026. while( iHi>=iLo ){
  138027. int iTest = (iHi + iLo) / 2;
  138028. if( key >= aEntry[iTest] ){
  138029. iRes = iTest;
  138030. iLo = iTest+1;
  138031. }else{
  138032. iHi = iTest-1;
  138033. }
  138034. }
  138035. assert( aEntry[0]<key );
  138036. assert( key>=aEntry[iRes] );
  138037. return (((unsigned int)c) >= ((aEntry[iRes]>>10) + (aEntry[iRes]&0x3FF)));
  138038. }
  138039. return 1;
  138040. }
  138041. /*
  138042. ** If the argument is a codepoint corresponding to a lowercase letter
  138043. ** in the ASCII range with a diacritic added, return the codepoint
  138044. ** of the ASCII letter only. For example, if passed 235 - "LATIN
  138045. ** SMALL LETTER E WITH DIAERESIS" - return 65 ("LATIN SMALL LETTER
  138046. ** E"). The resuls of passing a codepoint that corresponds to an
  138047. ** uppercase letter are undefined.
  138048. */
  138049. static int remove_diacritic(int c){
  138050. unsigned short aDia[] = {
  138051. 0, 1797, 1848, 1859, 1891, 1928, 1940, 1995,
  138052. 2024, 2040, 2060, 2110, 2168, 2206, 2264, 2286,
  138053. 2344, 2383, 2472, 2488, 2516, 2596, 2668, 2732,
  138054. 2782, 2842, 2894, 2954, 2984, 3000, 3028, 3336,
  138055. 3456, 3696, 3712, 3728, 3744, 3896, 3912, 3928,
  138056. 3968, 4008, 4040, 4106, 4138, 4170, 4202, 4234,
  138057. 4266, 4296, 4312, 4344, 4408, 4424, 4472, 4504,
  138058. 6148, 6198, 6264, 6280, 6360, 6429, 6505, 6529,
  138059. 61448, 61468, 61534, 61592, 61642, 61688, 61704, 61726,
  138060. 61784, 61800, 61836, 61880, 61914, 61948, 61998, 62122,
  138061. 62154, 62200, 62218, 62302, 62364, 62442, 62478, 62536,
  138062. 62554, 62584, 62604, 62640, 62648, 62656, 62664, 62730,
  138063. 62924, 63050, 63082, 63274, 63390,
  138064. };
  138065. char aChar[] = {
  138066. '\0', 'a', 'c', 'e', 'i', 'n', 'o', 'u', 'y', 'y', 'a', 'c',
  138067. 'd', 'e', 'e', 'g', 'h', 'i', 'j', 'k', 'l', 'n', 'o', 'r',
  138068. 's', 't', 'u', 'u', 'w', 'y', 'z', 'o', 'u', 'a', 'i', 'o',
  138069. 'u', 'g', 'k', 'o', 'j', 'g', 'n', 'a', 'e', 'i', 'o', 'r',
  138070. 'u', 's', 't', 'h', 'a', 'e', 'o', 'y', '\0', '\0', '\0', '\0',
  138071. '\0', '\0', '\0', '\0', 'a', 'b', 'd', 'd', 'e', 'f', 'g', 'h',
  138072. 'h', 'i', 'k', 'l', 'l', 'm', 'n', 'p', 'r', 'r', 's', 't',
  138073. 'u', 'v', 'w', 'w', 'x', 'y', 'z', 'h', 't', 'w', 'y', 'a',
  138074. 'e', 'i', 'o', 'u', 'y',
  138075. };
  138076. unsigned int key = (((unsigned int)c)<<3) | 0x00000007;
  138077. int iRes = 0;
  138078. int iHi = sizeof(aDia)/sizeof(aDia[0]) - 1;
  138079. int iLo = 0;
  138080. while( iHi>=iLo ){
  138081. int iTest = (iHi + iLo) / 2;
  138082. if( key >= aDia[iTest] ){
  138083. iRes = iTest;
  138084. iLo = iTest+1;
  138085. }else{
  138086. iHi = iTest-1;
  138087. }
  138088. }
  138089. assert( key>=aDia[iRes] );
  138090. return ((c > (aDia[iRes]>>3) + (aDia[iRes]&0x07)) ? c : (int)aChar[iRes]);
  138091. }
  138092. /*
  138093. ** Return true if the argument interpreted as a unicode codepoint
  138094. ** is a diacritical modifier character.
  138095. */
  138096. SQLITE_PRIVATE int sqlite3FtsUnicodeIsdiacritic(int c){
  138097. unsigned int mask0 = 0x08029FDF;
  138098. unsigned int mask1 = 0x000361F8;
  138099. if( c<768 || c>817 ) return 0;
  138100. return (c < 768+32) ?
  138101. (mask0 & (1 << (c-768))) :
  138102. (mask1 & (1 << (c-768-32)));
  138103. }
  138104. /*
  138105. ** Interpret the argument as a unicode codepoint. If the codepoint
  138106. ** is an upper case character that has a lower case equivalent,
  138107. ** return the codepoint corresponding to the lower case version.
  138108. ** Otherwise, return a copy of the argument.
  138109. **
  138110. ** The results are undefined if the value passed to this function
  138111. ** is less than zero.
  138112. */
  138113. SQLITE_PRIVATE int sqlite3FtsUnicodeFold(int c, int bRemoveDiacritic){
  138114. /* Each entry in the following array defines a rule for folding a range
  138115. ** of codepoints to lower case. The rule applies to a range of nRange
  138116. ** codepoints starting at codepoint iCode.
  138117. **
  138118. ** If the least significant bit in flags is clear, then the rule applies
  138119. ** to all nRange codepoints (i.e. all nRange codepoints are upper case and
  138120. ** need to be folded). Or, if it is set, then the rule only applies to
  138121. ** every second codepoint in the range, starting with codepoint C.
  138122. **
  138123. ** The 7 most significant bits in flags are an index into the aiOff[]
  138124. ** array. If a specific codepoint C does require folding, then its lower
  138125. ** case equivalent is ((C + aiOff[flags>>1]) & 0xFFFF).
  138126. **
  138127. ** The contents of this array are generated by parsing the CaseFolding.txt
  138128. ** file distributed as part of the "Unicode Character Database". See
  138129. ** http://www.unicode.org for details.
  138130. */
  138131. static const struct TableEntry {
  138132. unsigned short iCode;
  138133. unsigned char flags;
  138134. unsigned char nRange;
  138135. } aEntry[] = {
  138136. {65, 14, 26}, {181, 64, 1}, {192, 14, 23},
  138137. {216, 14, 7}, {256, 1, 48}, {306, 1, 6},
  138138. {313, 1, 16}, {330, 1, 46}, {376, 116, 1},
  138139. {377, 1, 6}, {383, 104, 1}, {385, 50, 1},
  138140. {386, 1, 4}, {390, 44, 1}, {391, 0, 1},
  138141. {393, 42, 2}, {395, 0, 1}, {398, 32, 1},
  138142. {399, 38, 1}, {400, 40, 1}, {401, 0, 1},
  138143. {403, 42, 1}, {404, 46, 1}, {406, 52, 1},
  138144. {407, 48, 1}, {408, 0, 1}, {412, 52, 1},
  138145. {413, 54, 1}, {415, 56, 1}, {416, 1, 6},
  138146. {422, 60, 1}, {423, 0, 1}, {425, 60, 1},
  138147. {428, 0, 1}, {430, 60, 1}, {431, 0, 1},
  138148. {433, 58, 2}, {435, 1, 4}, {439, 62, 1},
  138149. {440, 0, 1}, {444, 0, 1}, {452, 2, 1},
  138150. {453, 0, 1}, {455, 2, 1}, {456, 0, 1},
  138151. {458, 2, 1}, {459, 1, 18}, {478, 1, 18},
  138152. {497, 2, 1}, {498, 1, 4}, {502, 122, 1},
  138153. {503, 134, 1}, {504, 1, 40}, {544, 110, 1},
  138154. {546, 1, 18}, {570, 70, 1}, {571, 0, 1},
  138155. {573, 108, 1}, {574, 68, 1}, {577, 0, 1},
  138156. {579, 106, 1}, {580, 28, 1}, {581, 30, 1},
  138157. {582, 1, 10}, {837, 36, 1}, {880, 1, 4},
  138158. {886, 0, 1}, {902, 18, 1}, {904, 16, 3},
  138159. {908, 26, 1}, {910, 24, 2}, {913, 14, 17},
  138160. {931, 14, 9}, {962, 0, 1}, {975, 4, 1},
  138161. {976, 140, 1}, {977, 142, 1}, {981, 146, 1},
  138162. {982, 144, 1}, {984, 1, 24}, {1008, 136, 1},
  138163. {1009, 138, 1}, {1012, 130, 1}, {1013, 128, 1},
  138164. {1015, 0, 1}, {1017, 152, 1}, {1018, 0, 1},
  138165. {1021, 110, 3}, {1024, 34, 16}, {1040, 14, 32},
  138166. {1120, 1, 34}, {1162, 1, 54}, {1216, 6, 1},
  138167. {1217, 1, 14}, {1232, 1, 88}, {1329, 22, 38},
  138168. {4256, 66, 38}, {4295, 66, 1}, {4301, 66, 1},
  138169. {7680, 1, 150}, {7835, 132, 1}, {7838, 96, 1},
  138170. {7840, 1, 96}, {7944, 150, 8}, {7960, 150, 6},
  138171. {7976, 150, 8}, {7992, 150, 8}, {8008, 150, 6},
  138172. {8025, 151, 8}, {8040, 150, 8}, {8072, 150, 8},
  138173. {8088, 150, 8}, {8104, 150, 8}, {8120, 150, 2},
  138174. {8122, 126, 2}, {8124, 148, 1}, {8126, 100, 1},
  138175. {8136, 124, 4}, {8140, 148, 1}, {8152, 150, 2},
  138176. {8154, 120, 2}, {8168, 150, 2}, {8170, 118, 2},
  138177. {8172, 152, 1}, {8184, 112, 2}, {8186, 114, 2},
  138178. {8188, 148, 1}, {8486, 98, 1}, {8490, 92, 1},
  138179. {8491, 94, 1}, {8498, 12, 1}, {8544, 8, 16},
  138180. {8579, 0, 1}, {9398, 10, 26}, {11264, 22, 47},
  138181. {11360, 0, 1}, {11362, 88, 1}, {11363, 102, 1},
  138182. {11364, 90, 1}, {11367, 1, 6}, {11373, 84, 1},
  138183. {11374, 86, 1}, {11375, 80, 1}, {11376, 82, 1},
  138184. {11378, 0, 1}, {11381, 0, 1}, {11390, 78, 2},
  138185. {11392, 1, 100}, {11499, 1, 4}, {11506, 0, 1},
  138186. {42560, 1, 46}, {42624, 1, 24}, {42786, 1, 14},
  138187. {42802, 1, 62}, {42873, 1, 4}, {42877, 76, 1},
  138188. {42878, 1, 10}, {42891, 0, 1}, {42893, 74, 1},
  138189. {42896, 1, 4}, {42912, 1, 10}, {42922, 72, 1},
  138190. {65313, 14, 26},
  138191. };
  138192. static const unsigned short aiOff[] = {
  138193. 1, 2, 8, 15, 16, 26, 28, 32,
  138194. 37, 38, 40, 48, 63, 64, 69, 71,
  138195. 79, 80, 116, 202, 203, 205, 206, 207,
  138196. 209, 210, 211, 213, 214, 217, 218, 219,
  138197. 775, 7264, 10792, 10795, 23228, 23256, 30204, 54721,
  138198. 54753, 54754, 54756, 54787, 54793, 54809, 57153, 57274,
  138199. 57921, 58019, 58363, 61722, 65268, 65341, 65373, 65406,
  138200. 65408, 65410, 65415, 65424, 65436, 65439, 65450, 65462,
  138201. 65472, 65476, 65478, 65480, 65482, 65488, 65506, 65511,
  138202. 65514, 65521, 65527, 65528, 65529,
  138203. };
  138204. int ret = c;
  138205. assert( c>=0 );
  138206. assert( sizeof(unsigned short)==2 && sizeof(unsigned char)==1 );
  138207. if( c<128 ){
  138208. if( c>='A' && c<='Z' ) ret = c + ('a' - 'A');
  138209. }else if( c<65536 ){
  138210. int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
  138211. int iLo = 0;
  138212. int iRes = -1;
  138213. while( iHi>=iLo ){
  138214. int iTest = (iHi + iLo) / 2;
  138215. int cmp = (c - aEntry[iTest].iCode);
  138216. if( cmp>=0 ){
  138217. iRes = iTest;
  138218. iLo = iTest+1;
  138219. }else{
  138220. iHi = iTest-1;
  138221. }
  138222. }
  138223. assert( iRes<0 || c>=aEntry[iRes].iCode );
  138224. if( iRes>=0 ){
  138225. const struct TableEntry *p = &aEntry[iRes];
  138226. if( c<(p->iCode + p->nRange) && 0==(0x01 & p->flags & (p->iCode ^ c)) ){
  138227. ret = (c + (aiOff[p->flags>>1])) & 0x0000FFFF;
  138228. assert( ret>0 );
  138229. }
  138230. }
  138231. if( bRemoveDiacritic ) ret = remove_diacritic(ret);
  138232. }
  138233. else if( c>=66560 && c<66600 ){
  138234. ret = c + 40;
  138235. }
  138236. return ret;
  138237. }
  138238. #endif /* defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4) */
  138239. #endif /* !defined(SQLITE_DISABLE_FTS3_UNICODE) */
  138240. /************** End of fts3_unicode2.c ***************************************/
  138241. /************** Begin file rtree.c *******************************************/
  138242. /*
  138243. ** 2001 September 15
  138244. **
  138245. ** The author disclaims copyright to this source code. In place of
  138246. ** a legal notice, here is a blessing:
  138247. **
  138248. ** May you do good and not evil.
  138249. ** May you find forgiveness for yourself and forgive others.
  138250. ** May you share freely, never taking more than you give.
  138251. **
  138252. *************************************************************************
  138253. ** This file contains code for implementations of the r-tree and r*-tree
  138254. ** algorithms packaged as an SQLite virtual table module.
  138255. */
  138256. /*
  138257. ** Database Format of R-Tree Tables
  138258. ** --------------------------------
  138259. **
  138260. ** The data structure for a single virtual r-tree table is stored in three
  138261. ** native SQLite tables declared as follows. In each case, the '%' character
  138262. ** in the table name is replaced with the user-supplied name of the r-tree
  138263. ** table.
  138264. **
  138265. ** CREATE TABLE %_node(nodeno INTEGER PRIMARY KEY, data BLOB)
  138266. ** CREATE TABLE %_parent(nodeno INTEGER PRIMARY KEY, parentnode INTEGER)
  138267. ** CREATE TABLE %_rowid(rowid INTEGER PRIMARY KEY, nodeno INTEGER)
  138268. **
  138269. ** The data for each node of the r-tree structure is stored in the %_node
  138270. ** table. For each node that is not the root node of the r-tree, there is
  138271. ** an entry in the %_parent table associating the node with its parent.
  138272. ** And for each row of data in the table, there is an entry in the %_rowid
  138273. ** table that maps from the entries rowid to the id of the node that it
  138274. ** is stored on.
  138275. **
  138276. ** The root node of an r-tree always exists, even if the r-tree table is
  138277. ** empty. The nodeno of the root node is always 1. All other nodes in the
  138278. ** table must be the same size as the root node. The content of each node
  138279. ** is formatted as follows:
  138280. **
  138281. ** 1. If the node is the root node (node 1), then the first 2 bytes
  138282. ** of the node contain the tree depth as a big-endian integer.
  138283. ** For non-root nodes, the first 2 bytes are left unused.
  138284. **
  138285. ** 2. The next 2 bytes contain the number of entries currently
  138286. ** stored in the node.
  138287. **
  138288. ** 3. The remainder of the node contains the node entries. Each entry
  138289. ** consists of a single 8-byte integer followed by an even number
  138290. ** of 4-byte coordinates. For leaf nodes the integer is the rowid
  138291. ** of a record. For internal nodes it is the node number of a
  138292. ** child page.
  138293. */
  138294. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RTREE)
  138295. #ifndef SQLITE_CORE
  138296. SQLITE_EXTENSION_INIT1
  138297. #else
  138298. #endif
  138299. /* #include <string.h> */
  138300. /* #include <assert.h> */
  138301. /* #include <stdio.h> */
  138302. #ifndef SQLITE_AMALGAMATION
  138303. #include "sqlite3rtree.h"
  138304. typedef sqlite3_int64 i64;
  138305. typedef unsigned char u8;
  138306. typedef unsigned short u16;
  138307. typedef unsigned int u32;
  138308. #endif
  138309. /* The following macro is used to suppress compiler warnings.
  138310. */
  138311. #ifndef UNUSED_PARAMETER
  138312. # define UNUSED_PARAMETER(x) (void)(x)
  138313. #endif
  138314. typedef struct Rtree Rtree;
  138315. typedef struct RtreeCursor RtreeCursor;
  138316. typedef struct RtreeNode RtreeNode;
  138317. typedef struct RtreeCell RtreeCell;
  138318. typedef struct RtreeConstraint RtreeConstraint;
  138319. typedef struct RtreeMatchArg RtreeMatchArg;
  138320. typedef struct RtreeGeomCallback RtreeGeomCallback;
  138321. typedef union RtreeCoord RtreeCoord;
  138322. typedef struct RtreeSearchPoint RtreeSearchPoint;
  138323. /* The rtree may have between 1 and RTREE_MAX_DIMENSIONS dimensions. */
  138324. #define RTREE_MAX_DIMENSIONS 5
  138325. /* Size of hash table Rtree.aHash. This hash table is not expected to
  138326. ** ever contain very many entries, so a fixed number of buckets is
  138327. ** used.
  138328. */
  138329. #define HASHSIZE 97
  138330. /* The xBestIndex method of this virtual table requires an estimate of
  138331. ** the number of rows in the virtual table to calculate the costs of
  138332. ** various strategies. If possible, this estimate is loaded from the
  138333. ** sqlite_stat1 table (with RTREE_MIN_ROWEST as a hard-coded minimum).
  138334. ** Otherwise, if no sqlite_stat1 entry is available, use
  138335. ** RTREE_DEFAULT_ROWEST.
  138336. */
  138337. #define RTREE_DEFAULT_ROWEST 1048576
  138338. #define RTREE_MIN_ROWEST 100
  138339. /*
  138340. ** An rtree virtual-table object.
  138341. */
  138342. struct Rtree {
  138343. sqlite3_vtab base; /* Base class. Must be first */
  138344. sqlite3 *db; /* Host database connection */
  138345. int iNodeSize; /* Size in bytes of each node in the node table */
  138346. u8 nDim; /* Number of dimensions */
  138347. u8 eCoordType; /* RTREE_COORD_REAL32 or RTREE_COORD_INT32 */
  138348. u8 nBytesPerCell; /* Bytes consumed per cell */
  138349. int iDepth; /* Current depth of the r-tree structure */
  138350. char *zDb; /* Name of database containing r-tree table */
  138351. char *zName; /* Name of r-tree table */
  138352. int nBusy; /* Current number of users of this structure */
  138353. i64 nRowEst; /* Estimated number of rows in this table */
  138354. /* List of nodes removed during a CondenseTree operation. List is
  138355. ** linked together via the pointer normally used for hash chains -
  138356. ** RtreeNode.pNext. RtreeNode.iNode stores the depth of the sub-tree
  138357. ** headed by the node (leaf nodes have RtreeNode.iNode==0).
  138358. */
  138359. RtreeNode *pDeleted;
  138360. int iReinsertHeight; /* Height of sub-trees Reinsert() has run on */
  138361. /* Statements to read/write/delete a record from xxx_node */
  138362. sqlite3_stmt *pReadNode;
  138363. sqlite3_stmt *pWriteNode;
  138364. sqlite3_stmt *pDeleteNode;
  138365. /* Statements to read/write/delete a record from xxx_rowid */
  138366. sqlite3_stmt *pReadRowid;
  138367. sqlite3_stmt *pWriteRowid;
  138368. sqlite3_stmt *pDeleteRowid;
  138369. /* Statements to read/write/delete a record from xxx_parent */
  138370. sqlite3_stmt *pReadParent;
  138371. sqlite3_stmt *pWriteParent;
  138372. sqlite3_stmt *pDeleteParent;
  138373. RtreeNode *aHash[HASHSIZE]; /* Hash table of in-memory nodes. */
  138374. };
  138375. /* Possible values for Rtree.eCoordType: */
  138376. #define RTREE_COORD_REAL32 0
  138377. #define RTREE_COORD_INT32 1
  138378. /*
  138379. ** If SQLITE_RTREE_INT_ONLY is defined, then this virtual table will
  138380. ** only deal with integer coordinates. No floating point operations
  138381. ** will be done.
  138382. */
  138383. #ifdef SQLITE_RTREE_INT_ONLY
  138384. typedef sqlite3_int64 RtreeDValue; /* High accuracy coordinate */
  138385. typedef int RtreeValue; /* Low accuracy coordinate */
  138386. # define RTREE_ZERO 0
  138387. #else
  138388. typedef double RtreeDValue; /* High accuracy coordinate */
  138389. typedef float RtreeValue; /* Low accuracy coordinate */
  138390. # define RTREE_ZERO 0.0
  138391. #endif
  138392. /*
  138393. ** When doing a search of an r-tree, instances of the following structure
  138394. ** record intermediate results from the tree walk.
  138395. **
  138396. ** The id is always a node-id. For iLevel>=1 the id is the node-id of
  138397. ** the node that the RtreeSearchPoint represents. When iLevel==0, however,
  138398. ** the id is of the parent node and the cell that RtreeSearchPoint
  138399. ** represents is the iCell-th entry in the parent node.
  138400. */
  138401. struct RtreeSearchPoint {
  138402. RtreeDValue rScore; /* The score for this node. Smallest goes first. */
  138403. sqlite3_int64 id; /* Node ID */
  138404. u8 iLevel; /* 0=entries. 1=leaf node. 2+ for higher */
  138405. u8 eWithin; /* PARTLY_WITHIN or FULLY_WITHIN */
  138406. u8 iCell; /* Cell index within the node */
  138407. };
  138408. /*
  138409. ** The minimum number of cells allowed for a node is a third of the
  138410. ** maximum. In Gutman's notation:
  138411. **
  138412. ** m = M/3
  138413. **
  138414. ** If an R*-tree "Reinsert" operation is required, the same number of
  138415. ** cells are removed from the overfull node and reinserted into the tree.
  138416. */
  138417. #define RTREE_MINCELLS(p) ((((p)->iNodeSize-4)/(p)->nBytesPerCell)/3)
  138418. #define RTREE_REINSERT(p) RTREE_MINCELLS(p)
  138419. #define RTREE_MAXCELLS 51
  138420. /*
  138421. ** The smallest possible node-size is (512-64)==448 bytes. And the largest
  138422. ** supported cell size is 48 bytes (8 byte rowid + ten 4 byte coordinates).
  138423. ** Therefore all non-root nodes must contain at least 3 entries. Since
  138424. ** 2^40 is greater than 2^64, an r-tree structure always has a depth of
  138425. ** 40 or less.
  138426. */
  138427. #define RTREE_MAX_DEPTH 40
  138428. /*
  138429. ** Number of entries in the cursor RtreeNode cache. The first entry is
  138430. ** used to cache the RtreeNode for RtreeCursor.sPoint. The remaining
  138431. ** entries cache the RtreeNode for the first elements of the priority queue.
  138432. */
  138433. #define RTREE_CACHE_SZ 5
  138434. /*
  138435. ** An rtree cursor object.
  138436. */
  138437. struct RtreeCursor {
  138438. sqlite3_vtab_cursor base; /* Base class. Must be first */
  138439. u8 atEOF; /* True if at end of search */
  138440. u8 bPoint; /* True if sPoint is valid */
  138441. int iStrategy; /* Copy of idxNum search parameter */
  138442. int nConstraint; /* Number of entries in aConstraint */
  138443. RtreeConstraint *aConstraint; /* Search constraints. */
  138444. int nPointAlloc; /* Number of slots allocated for aPoint[] */
  138445. int nPoint; /* Number of slots used in aPoint[] */
  138446. int mxLevel; /* iLevel value for root of the tree */
  138447. RtreeSearchPoint *aPoint; /* Priority queue for search points */
  138448. RtreeSearchPoint sPoint; /* Cached next search point */
  138449. RtreeNode *aNode[RTREE_CACHE_SZ]; /* Rtree node cache */
  138450. u32 anQueue[RTREE_MAX_DEPTH+1]; /* Number of queued entries by iLevel */
  138451. };
  138452. /* Return the Rtree of a RtreeCursor */
  138453. #define RTREE_OF_CURSOR(X) ((Rtree*)((X)->base.pVtab))
  138454. /*
  138455. ** A coordinate can be either a floating point number or a integer. All
  138456. ** coordinates within a single R-Tree are always of the same time.
  138457. */
  138458. union RtreeCoord {
  138459. RtreeValue f; /* Floating point value */
  138460. int i; /* Integer value */
  138461. u32 u; /* Unsigned for byte-order conversions */
  138462. };
  138463. /*
  138464. ** The argument is an RtreeCoord. Return the value stored within the RtreeCoord
  138465. ** formatted as a RtreeDValue (double or int64). This macro assumes that local
  138466. ** variable pRtree points to the Rtree structure associated with the
  138467. ** RtreeCoord.
  138468. */
  138469. #ifdef SQLITE_RTREE_INT_ONLY
  138470. # define DCOORD(coord) ((RtreeDValue)coord.i)
  138471. #else
  138472. # define DCOORD(coord) ( \
  138473. (pRtree->eCoordType==RTREE_COORD_REAL32) ? \
  138474. ((double)coord.f) : \
  138475. ((double)coord.i) \
  138476. )
  138477. #endif
  138478. /*
  138479. ** A search constraint.
  138480. */
  138481. struct RtreeConstraint {
  138482. int iCoord; /* Index of constrained coordinate */
  138483. int op; /* Constraining operation */
  138484. union {
  138485. RtreeDValue rValue; /* Constraint value. */
  138486. int (*xGeom)(sqlite3_rtree_geometry*,int,RtreeDValue*,int*);
  138487. int (*xQueryFunc)(sqlite3_rtree_query_info*);
  138488. } u;
  138489. sqlite3_rtree_query_info *pInfo; /* xGeom and xQueryFunc argument */
  138490. };
  138491. /* Possible values for RtreeConstraint.op */
  138492. #define RTREE_EQ 0x41 /* A */
  138493. #define RTREE_LE 0x42 /* B */
  138494. #define RTREE_LT 0x43 /* C */
  138495. #define RTREE_GE 0x44 /* D */
  138496. #define RTREE_GT 0x45 /* E */
  138497. #define RTREE_MATCH 0x46 /* F: Old-style sqlite3_rtree_geometry_callback() */
  138498. #define RTREE_QUERY 0x47 /* G: New-style sqlite3_rtree_query_callback() */
  138499. /*
  138500. ** An rtree structure node.
  138501. */
  138502. struct RtreeNode {
  138503. RtreeNode *pParent; /* Parent node */
  138504. i64 iNode; /* The node number */
  138505. int nRef; /* Number of references to this node */
  138506. int isDirty; /* True if the node needs to be written to disk */
  138507. u8 *zData; /* Content of the node, as should be on disk */
  138508. RtreeNode *pNext; /* Next node in this hash collision chain */
  138509. };
  138510. /* Return the number of cells in a node */
  138511. #define NCELL(pNode) readInt16(&(pNode)->zData[2])
  138512. /*
  138513. ** A single cell from a node, deserialized
  138514. */
  138515. struct RtreeCell {
  138516. i64 iRowid; /* Node or entry ID */
  138517. RtreeCoord aCoord[RTREE_MAX_DIMENSIONS*2]; /* Bounding box coordinates */
  138518. };
  138519. /*
  138520. ** This object becomes the sqlite3_user_data() for the SQL functions
  138521. ** that are created by sqlite3_rtree_geometry_callback() and
  138522. ** sqlite3_rtree_query_callback() and which appear on the right of MATCH
  138523. ** operators in order to constrain a search.
  138524. **
  138525. ** xGeom and xQueryFunc are the callback functions. Exactly one of
  138526. ** xGeom and xQueryFunc fields is non-NULL, depending on whether the
  138527. ** SQL function was created using sqlite3_rtree_geometry_callback() or
  138528. ** sqlite3_rtree_query_callback().
  138529. **
  138530. ** This object is deleted automatically by the destructor mechanism in
  138531. ** sqlite3_create_function_v2().
  138532. */
  138533. struct RtreeGeomCallback {
  138534. int (*xGeom)(sqlite3_rtree_geometry*, int, RtreeDValue*, int*);
  138535. int (*xQueryFunc)(sqlite3_rtree_query_info*);
  138536. void (*xDestructor)(void*);
  138537. void *pContext;
  138538. };
  138539. /*
  138540. ** Value for the first field of every RtreeMatchArg object. The MATCH
  138541. ** operator tests that the first field of a blob operand matches this
  138542. ** value to avoid operating on invalid blobs (which could cause a segfault).
  138543. */
  138544. #define RTREE_GEOMETRY_MAGIC 0x891245AB
  138545. /*
  138546. ** An instance of this structure (in the form of a BLOB) is returned by
  138547. ** the SQL functions that sqlite3_rtree_geometry_callback() and
  138548. ** sqlite3_rtree_query_callback() create, and is read as the right-hand
  138549. ** operand to the MATCH operator of an R-Tree.
  138550. */
  138551. struct RtreeMatchArg {
  138552. u32 magic; /* Always RTREE_GEOMETRY_MAGIC */
  138553. RtreeGeomCallback cb; /* Info about the callback functions */
  138554. int nParam; /* Number of parameters to the SQL function */
  138555. RtreeDValue aParam[1]; /* Values for parameters to the SQL function */
  138556. };
  138557. #ifndef MAX
  138558. # define MAX(x,y) ((x) < (y) ? (y) : (x))
  138559. #endif
  138560. #ifndef MIN
  138561. # define MIN(x,y) ((x) > (y) ? (y) : (x))
  138562. #endif
  138563. /*
  138564. ** Functions to deserialize a 16 bit integer, 32 bit real number and
  138565. ** 64 bit integer. The deserialized value is returned.
  138566. */
  138567. static int readInt16(u8 *p){
  138568. return (p[0]<<8) + p[1];
  138569. }
  138570. static void readCoord(u8 *p, RtreeCoord *pCoord){
  138571. u32 i = (
  138572. (((u32)p[0]) << 24) +
  138573. (((u32)p[1]) << 16) +
  138574. (((u32)p[2]) << 8) +
  138575. (((u32)p[3]) << 0)
  138576. );
  138577. *(u32 *)pCoord = i;
  138578. }
  138579. static i64 readInt64(u8 *p){
  138580. return (
  138581. (((i64)p[0]) << 56) +
  138582. (((i64)p[1]) << 48) +
  138583. (((i64)p[2]) << 40) +
  138584. (((i64)p[3]) << 32) +
  138585. (((i64)p[4]) << 24) +
  138586. (((i64)p[5]) << 16) +
  138587. (((i64)p[6]) << 8) +
  138588. (((i64)p[7]) << 0)
  138589. );
  138590. }
  138591. /*
  138592. ** Functions to serialize a 16 bit integer, 32 bit real number and
  138593. ** 64 bit integer. The value returned is the number of bytes written
  138594. ** to the argument buffer (always 2, 4 and 8 respectively).
  138595. */
  138596. static int writeInt16(u8 *p, int i){
  138597. p[0] = (i>> 8)&0xFF;
  138598. p[1] = (i>> 0)&0xFF;
  138599. return 2;
  138600. }
  138601. static int writeCoord(u8 *p, RtreeCoord *pCoord){
  138602. u32 i;
  138603. assert( sizeof(RtreeCoord)==4 );
  138604. assert( sizeof(u32)==4 );
  138605. i = *(u32 *)pCoord;
  138606. p[0] = (i>>24)&0xFF;
  138607. p[1] = (i>>16)&0xFF;
  138608. p[2] = (i>> 8)&0xFF;
  138609. p[3] = (i>> 0)&0xFF;
  138610. return 4;
  138611. }
  138612. static int writeInt64(u8 *p, i64 i){
  138613. p[0] = (i>>56)&0xFF;
  138614. p[1] = (i>>48)&0xFF;
  138615. p[2] = (i>>40)&0xFF;
  138616. p[3] = (i>>32)&0xFF;
  138617. p[4] = (i>>24)&0xFF;
  138618. p[5] = (i>>16)&0xFF;
  138619. p[6] = (i>> 8)&0xFF;
  138620. p[7] = (i>> 0)&0xFF;
  138621. return 8;
  138622. }
  138623. /*
  138624. ** Increment the reference count of node p.
  138625. */
  138626. static void nodeReference(RtreeNode *p){
  138627. if( p ){
  138628. p->nRef++;
  138629. }
  138630. }
  138631. /*
  138632. ** Clear the content of node p (set all bytes to 0x00).
  138633. */
  138634. static void nodeZero(Rtree *pRtree, RtreeNode *p){
  138635. memset(&p->zData[2], 0, pRtree->iNodeSize-2);
  138636. p->isDirty = 1;
  138637. }
  138638. /*
  138639. ** Given a node number iNode, return the corresponding key to use
  138640. ** in the Rtree.aHash table.
  138641. */
  138642. static int nodeHash(i64 iNode){
  138643. return iNode % HASHSIZE;
  138644. }
  138645. /*
  138646. ** Search the node hash table for node iNode. If found, return a pointer
  138647. ** to it. Otherwise, return 0.
  138648. */
  138649. static RtreeNode *nodeHashLookup(Rtree *pRtree, i64 iNode){
  138650. RtreeNode *p;
  138651. for(p=pRtree->aHash[nodeHash(iNode)]; p && p->iNode!=iNode; p=p->pNext);
  138652. return p;
  138653. }
  138654. /*
  138655. ** Add node pNode to the node hash table.
  138656. */
  138657. static void nodeHashInsert(Rtree *pRtree, RtreeNode *pNode){
  138658. int iHash;
  138659. assert( pNode->pNext==0 );
  138660. iHash = nodeHash(pNode->iNode);
  138661. pNode->pNext = pRtree->aHash[iHash];
  138662. pRtree->aHash[iHash] = pNode;
  138663. }
  138664. /*
  138665. ** Remove node pNode from the node hash table.
  138666. */
  138667. static void nodeHashDelete(Rtree *pRtree, RtreeNode *pNode){
  138668. RtreeNode **pp;
  138669. if( pNode->iNode!=0 ){
  138670. pp = &pRtree->aHash[nodeHash(pNode->iNode)];
  138671. for( ; (*pp)!=pNode; pp = &(*pp)->pNext){ assert(*pp); }
  138672. *pp = pNode->pNext;
  138673. pNode->pNext = 0;
  138674. }
  138675. }
  138676. /*
  138677. ** Allocate and return new r-tree node. Initially, (RtreeNode.iNode==0),
  138678. ** indicating that node has not yet been assigned a node number. It is
  138679. ** assigned a node number when nodeWrite() is called to write the
  138680. ** node contents out to the database.
  138681. */
  138682. static RtreeNode *nodeNew(Rtree *pRtree, RtreeNode *pParent){
  138683. RtreeNode *pNode;
  138684. pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode) + pRtree->iNodeSize);
  138685. if( pNode ){
  138686. memset(pNode, 0, sizeof(RtreeNode) + pRtree->iNodeSize);
  138687. pNode->zData = (u8 *)&pNode[1];
  138688. pNode->nRef = 1;
  138689. pNode->pParent = pParent;
  138690. pNode->isDirty = 1;
  138691. nodeReference(pParent);
  138692. }
  138693. return pNode;
  138694. }
  138695. /*
  138696. ** Obtain a reference to an r-tree node.
  138697. */
  138698. static int nodeAcquire(
  138699. Rtree *pRtree, /* R-tree structure */
  138700. i64 iNode, /* Node number to load */
  138701. RtreeNode *pParent, /* Either the parent node or NULL */
  138702. RtreeNode **ppNode /* OUT: Acquired node */
  138703. ){
  138704. int rc;
  138705. int rc2 = SQLITE_OK;
  138706. RtreeNode *pNode;
  138707. /* Check if the requested node is already in the hash table. If so,
  138708. ** increase its reference count and return it.
  138709. */
  138710. if( (pNode = nodeHashLookup(pRtree, iNode)) ){
  138711. assert( !pParent || !pNode->pParent || pNode->pParent==pParent );
  138712. if( pParent && !pNode->pParent ){
  138713. nodeReference(pParent);
  138714. pNode->pParent = pParent;
  138715. }
  138716. pNode->nRef++;
  138717. *ppNode = pNode;
  138718. return SQLITE_OK;
  138719. }
  138720. sqlite3_bind_int64(pRtree->pReadNode, 1, iNode);
  138721. rc = sqlite3_step(pRtree->pReadNode);
  138722. if( rc==SQLITE_ROW ){
  138723. const u8 *zBlob = sqlite3_column_blob(pRtree->pReadNode, 0);
  138724. if( pRtree->iNodeSize==sqlite3_column_bytes(pRtree->pReadNode, 0) ){
  138725. pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode)+pRtree->iNodeSize);
  138726. if( !pNode ){
  138727. rc2 = SQLITE_NOMEM;
  138728. }else{
  138729. pNode->pParent = pParent;
  138730. pNode->zData = (u8 *)&pNode[1];
  138731. pNode->nRef = 1;
  138732. pNode->iNode = iNode;
  138733. pNode->isDirty = 0;
  138734. pNode->pNext = 0;
  138735. memcpy(pNode->zData, zBlob, pRtree->iNodeSize);
  138736. nodeReference(pParent);
  138737. }
  138738. }
  138739. }
  138740. rc = sqlite3_reset(pRtree->pReadNode);
  138741. if( rc==SQLITE_OK ) rc = rc2;
  138742. /* If the root node was just loaded, set pRtree->iDepth to the height
  138743. ** of the r-tree structure. A height of zero means all data is stored on
  138744. ** the root node. A height of one means the children of the root node
  138745. ** are the leaves, and so on. If the depth as specified on the root node
  138746. ** is greater than RTREE_MAX_DEPTH, the r-tree structure must be corrupt.
  138747. */
  138748. if( pNode && iNode==1 ){
  138749. pRtree->iDepth = readInt16(pNode->zData);
  138750. if( pRtree->iDepth>RTREE_MAX_DEPTH ){
  138751. rc = SQLITE_CORRUPT_VTAB;
  138752. }
  138753. }
  138754. /* If no error has occurred so far, check if the "number of entries"
  138755. ** field on the node is too large. If so, set the return code to
  138756. ** SQLITE_CORRUPT_VTAB.
  138757. */
  138758. if( pNode && rc==SQLITE_OK ){
  138759. if( NCELL(pNode)>((pRtree->iNodeSize-4)/pRtree->nBytesPerCell) ){
  138760. rc = SQLITE_CORRUPT_VTAB;
  138761. }
  138762. }
  138763. if( rc==SQLITE_OK ){
  138764. if( pNode!=0 ){
  138765. nodeHashInsert(pRtree, pNode);
  138766. }else{
  138767. rc = SQLITE_CORRUPT_VTAB;
  138768. }
  138769. *ppNode = pNode;
  138770. }else{
  138771. sqlite3_free(pNode);
  138772. *ppNode = 0;
  138773. }
  138774. return rc;
  138775. }
  138776. /*
  138777. ** Overwrite cell iCell of node pNode with the contents of pCell.
  138778. */
  138779. static void nodeOverwriteCell(
  138780. Rtree *pRtree, /* The overall R-Tree */
  138781. RtreeNode *pNode, /* The node into which the cell is to be written */
  138782. RtreeCell *pCell, /* The cell to write */
  138783. int iCell /* Index into pNode into which pCell is written */
  138784. ){
  138785. int ii;
  138786. u8 *p = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
  138787. p += writeInt64(p, pCell->iRowid);
  138788. for(ii=0; ii<(pRtree->nDim*2); ii++){
  138789. p += writeCoord(p, &pCell->aCoord[ii]);
  138790. }
  138791. pNode->isDirty = 1;
  138792. }
  138793. /*
  138794. ** Remove the cell with index iCell from node pNode.
  138795. */
  138796. static void nodeDeleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell){
  138797. u8 *pDst = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
  138798. u8 *pSrc = &pDst[pRtree->nBytesPerCell];
  138799. int nByte = (NCELL(pNode) - iCell - 1) * pRtree->nBytesPerCell;
  138800. memmove(pDst, pSrc, nByte);
  138801. writeInt16(&pNode->zData[2], NCELL(pNode)-1);
  138802. pNode->isDirty = 1;
  138803. }
  138804. /*
  138805. ** Insert the contents of cell pCell into node pNode. If the insert
  138806. ** is successful, return SQLITE_OK.
  138807. **
  138808. ** If there is not enough free space in pNode, return SQLITE_FULL.
  138809. */
  138810. static int nodeInsertCell(
  138811. Rtree *pRtree, /* The overall R-Tree */
  138812. RtreeNode *pNode, /* Write new cell into this node */
  138813. RtreeCell *pCell /* The cell to be inserted */
  138814. ){
  138815. int nCell; /* Current number of cells in pNode */
  138816. int nMaxCell; /* Maximum number of cells for pNode */
  138817. nMaxCell = (pRtree->iNodeSize-4)/pRtree->nBytesPerCell;
  138818. nCell = NCELL(pNode);
  138819. assert( nCell<=nMaxCell );
  138820. if( nCell<nMaxCell ){
  138821. nodeOverwriteCell(pRtree, pNode, pCell, nCell);
  138822. writeInt16(&pNode->zData[2], nCell+1);
  138823. pNode->isDirty = 1;
  138824. }
  138825. return (nCell==nMaxCell);
  138826. }
  138827. /*
  138828. ** If the node is dirty, write it out to the database.
  138829. */
  138830. static int nodeWrite(Rtree *pRtree, RtreeNode *pNode){
  138831. int rc = SQLITE_OK;
  138832. if( pNode->isDirty ){
  138833. sqlite3_stmt *p = pRtree->pWriteNode;
  138834. if( pNode->iNode ){
  138835. sqlite3_bind_int64(p, 1, pNode->iNode);
  138836. }else{
  138837. sqlite3_bind_null(p, 1);
  138838. }
  138839. sqlite3_bind_blob(p, 2, pNode->zData, pRtree->iNodeSize, SQLITE_STATIC);
  138840. sqlite3_step(p);
  138841. pNode->isDirty = 0;
  138842. rc = sqlite3_reset(p);
  138843. if( pNode->iNode==0 && rc==SQLITE_OK ){
  138844. pNode->iNode = sqlite3_last_insert_rowid(pRtree->db);
  138845. nodeHashInsert(pRtree, pNode);
  138846. }
  138847. }
  138848. return rc;
  138849. }
  138850. /*
  138851. ** Release a reference to a node. If the node is dirty and the reference
  138852. ** count drops to zero, the node data is written to the database.
  138853. */
  138854. static int nodeRelease(Rtree *pRtree, RtreeNode *pNode){
  138855. int rc = SQLITE_OK;
  138856. if( pNode ){
  138857. assert( pNode->nRef>0 );
  138858. pNode->nRef--;
  138859. if( pNode->nRef==0 ){
  138860. if( pNode->iNode==1 ){
  138861. pRtree->iDepth = -1;
  138862. }
  138863. if( pNode->pParent ){
  138864. rc = nodeRelease(pRtree, pNode->pParent);
  138865. }
  138866. if( rc==SQLITE_OK ){
  138867. rc = nodeWrite(pRtree, pNode);
  138868. }
  138869. nodeHashDelete(pRtree, pNode);
  138870. sqlite3_free(pNode);
  138871. }
  138872. }
  138873. return rc;
  138874. }
  138875. /*
  138876. ** Return the 64-bit integer value associated with cell iCell of
  138877. ** node pNode. If pNode is a leaf node, this is a rowid. If it is
  138878. ** an internal node, then the 64-bit integer is a child page number.
  138879. */
  138880. static i64 nodeGetRowid(
  138881. Rtree *pRtree, /* The overall R-Tree */
  138882. RtreeNode *pNode, /* The node from which to extract the ID */
  138883. int iCell /* The cell index from which to extract the ID */
  138884. ){
  138885. assert( iCell<NCELL(pNode) );
  138886. return readInt64(&pNode->zData[4 + pRtree->nBytesPerCell*iCell]);
  138887. }
  138888. /*
  138889. ** Return coordinate iCoord from cell iCell in node pNode.
  138890. */
  138891. static void nodeGetCoord(
  138892. Rtree *pRtree, /* The overall R-Tree */
  138893. RtreeNode *pNode, /* The node from which to extract a coordinate */
  138894. int iCell, /* The index of the cell within the node */
  138895. int iCoord, /* Which coordinate to extract */
  138896. RtreeCoord *pCoord /* OUT: Space to write result to */
  138897. ){
  138898. readCoord(&pNode->zData[12 + pRtree->nBytesPerCell*iCell + 4*iCoord], pCoord);
  138899. }
  138900. /*
  138901. ** Deserialize cell iCell of node pNode. Populate the structure pointed
  138902. ** to by pCell with the results.
  138903. */
  138904. static void nodeGetCell(
  138905. Rtree *pRtree, /* The overall R-Tree */
  138906. RtreeNode *pNode, /* The node containing the cell to be read */
  138907. int iCell, /* Index of the cell within the node */
  138908. RtreeCell *pCell /* OUT: Write the cell contents here */
  138909. ){
  138910. u8 *pData;
  138911. u8 *pEnd;
  138912. RtreeCoord *pCoord;
  138913. pCell->iRowid = nodeGetRowid(pRtree, pNode, iCell);
  138914. pData = pNode->zData + (12 + pRtree->nBytesPerCell*iCell);
  138915. pEnd = pData + pRtree->nDim*8;
  138916. pCoord = pCell->aCoord;
  138917. for(; pData<pEnd; pData+=4, pCoord++){
  138918. readCoord(pData, pCoord);
  138919. }
  138920. }
  138921. /* Forward declaration for the function that does the work of
  138922. ** the virtual table module xCreate() and xConnect() methods.
  138923. */
  138924. static int rtreeInit(
  138925. sqlite3 *, void *, int, const char *const*, sqlite3_vtab **, char **, int
  138926. );
  138927. /*
  138928. ** Rtree virtual table module xCreate method.
  138929. */
  138930. static int rtreeCreate(
  138931. sqlite3 *db,
  138932. void *pAux,
  138933. int argc, const char *const*argv,
  138934. sqlite3_vtab **ppVtab,
  138935. char **pzErr
  138936. ){
  138937. return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 1);
  138938. }
  138939. /*
  138940. ** Rtree virtual table module xConnect method.
  138941. */
  138942. static int rtreeConnect(
  138943. sqlite3 *db,
  138944. void *pAux,
  138945. int argc, const char *const*argv,
  138946. sqlite3_vtab **ppVtab,
  138947. char **pzErr
  138948. ){
  138949. return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 0);
  138950. }
  138951. /*
  138952. ** Increment the r-tree reference count.
  138953. */
  138954. static void rtreeReference(Rtree *pRtree){
  138955. pRtree->nBusy++;
  138956. }
  138957. /*
  138958. ** Decrement the r-tree reference count. When the reference count reaches
  138959. ** zero the structure is deleted.
  138960. */
  138961. static void rtreeRelease(Rtree *pRtree){
  138962. pRtree->nBusy--;
  138963. if( pRtree->nBusy==0 ){
  138964. sqlite3_finalize(pRtree->pReadNode);
  138965. sqlite3_finalize(pRtree->pWriteNode);
  138966. sqlite3_finalize(pRtree->pDeleteNode);
  138967. sqlite3_finalize(pRtree->pReadRowid);
  138968. sqlite3_finalize(pRtree->pWriteRowid);
  138969. sqlite3_finalize(pRtree->pDeleteRowid);
  138970. sqlite3_finalize(pRtree->pReadParent);
  138971. sqlite3_finalize(pRtree->pWriteParent);
  138972. sqlite3_finalize(pRtree->pDeleteParent);
  138973. sqlite3_free(pRtree);
  138974. }
  138975. }
  138976. /*
  138977. ** Rtree virtual table module xDisconnect method.
  138978. */
  138979. static int rtreeDisconnect(sqlite3_vtab *pVtab){
  138980. rtreeRelease((Rtree *)pVtab);
  138981. return SQLITE_OK;
  138982. }
  138983. /*
  138984. ** Rtree virtual table module xDestroy method.
  138985. */
  138986. static int rtreeDestroy(sqlite3_vtab *pVtab){
  138987. Rtree *pRtree = (Rtree *)pVtab;
  138988. int rc;
  138989. char *zCreate = sqlite3_mprintf(
  138990. "DROP TABLE '%q'.'%q_node';"
  138991. "DROP TABLE '%q'.'%q_rowid';"
  138992. "DROP TABLE '%q'.'%q_parent';",
  138993. pRtree->zDb, pRtree->zName,
  138994. pRtree->zDb, pRtree->zName,
  138995. pRtree->zDb, pRtree->zName
  138996. );
  138997. if( !zCreate ){
  138998. rc = SQLITE_NOMEM;
  138999. }else{
  139000. rc = sqlite3_exec(pRtree->db, zCreate, 0, 0, 0);
  139001. sqlite3_free(zCreate);
  139002. }
  139003. if( rc==SQLITE_OK ){
  139004. rtreeRelease(pRtree);
  139005. }
  139006. return rc;
  139007. }
  139008. /*
  139009. ** Rtree virtual table module xOpen method.
  139010. */
  139011. static int rtreeOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
  139012. int rc = SQLITE_NOMEM;
  139013. RtreeCursor *pCsr;
  139014. pCsr = (RtreeCursor *)sqlite3_malloc(sizeof(RtreeCursor));
  139015. if( pCsr ){
  139016. memset(pCsr, 0, sizeof(RtreeCursor));
  139017. pCsr->base.pVtab = pVTab;
  139018. rc = SQLITE_OK;
  139019. }
  139020. *ppCursor = (sqlite3_vtab_cursor *)pCsr;
  139021. return rc;
  139022. }
  139023. /*
  139024. ** Free the RtreeCursor.aConstraint[] array and its contents.
  139025. */
  139026. static void freeCursorConstraints(RtreeCursor *pCsr){
  139027. if( pCsr->aConstraint ){
  139028. int i; /* Used to iterate through constraint array */
  139029. for(i=0; i<pCsr->nConstraint; i++){
  139030. sqlite3_rtree_query_info *pInfo = pCsr->aConstraint[i].pInfo;
  139031. if( pInfo ){
  139032. if( pInfo->xDelUser ) pInfo->xDelUser(pInfo->pUser);
  139033. sqlite3_free(pInfo);
  139034. }
  139035. }
  139036. sqlite3_free(pCsr->aConstraint);
  139037. pCsr->aConstraint = 0;
  139038. }
  139039. }
  139040. /*
  139041. ** Rtree virtual table module xClose method.
  139042. */
  139043. static int rtreeClose(sqlite3_vtab_cursor *cur){
  139044. Rtree *pRtree = (Rtree *)(cur->pVtab);
  139045. int ii;
  139046. RtreeCursor *pCsr = (RtreeCursor *)cur;
  139047. freeCursorConstraints(pCsr);
  139048. sqlite3_free(pCsr->aPoint);
  139049. for(ii=0; ii<RTREE_CACHE_SZ; ii++) nodeRelease(pRtree, pCsr->aNode[ii]);
  139050. sqlite3_free(pCsr);
  139051. return SQLITE_OK;
  139052. }
  139053. /*
  139054. ** Rtree virtual table module xEof method.
  139055. **
  139056. ** Return non-zero if the cursor does not currently point to a valid
  139057. ** record (i.e if the scan has finished), or zero otherwise.
  139058. */
  139059. static int rtreeEof(sqlite3_vtab_cursor *cur){
  139060. RtreeCursor *pCsr = (RtreeCursor *)cur;
  139061. return pCsr->atEOF;
  139062. }
  139063. /*
  139064. ** Convert raw bits from the on-disk RTree record into a coordinate value.
  139065. ** The on-disk format is big-endian and needs to be converted for little-
  139066. ** endian platforms. The on-disk record stores integer coordinates if
  139067. ** eInt is true and it stores 32-bit floating point records if eInt is
  139068. ** false. a[] is the four bytes of the on-disk record to be decoded.
  139069. ** Store the results in "r".
  139070. **
  139071. ** There are three versions of this macro, one each for little-endian and
  139072. ** big-endian processors and a third generic implementation. The endian-
  139073. ** specific implementations are much faster and are preferred if the
  139074. ** processor endianness is known at compile-time. The SQLITE_BYTEORDER
  139075. ** macro is part of sqliteInt.h and hence the endian-specific
  139076. ** implementation will only be used if this module is compiled as part
  139077. ** of the amalgamation.
  139078. */
  139079. #if defined(SQLITE_BYTEORDER) && SQLITE_BYTEORDER==1234
  139080. #define RTREE_DECODE_COORD(eInt, a, r) { \
  139081. RtreeCoord c; /* Coordinate decoded */ \
  139082. memcpy(&c.u,a,4); \
  139083. c.u = ((c.u>>24)&0xff)|((c.u>>8)&0xff00)| \
  139084. ((c.u&0xff)<<24)|((c.u&0xff00)<<8); \
  139085. r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
  139086. }
  139087. #elif defined(SQLITE_BYTEORDER) && SQLITE_BYTEORDER==4321
  139088. #define RTREE_DECODE_COORD(eInt, a, r) { \
  139089. RtreeCoord c; /* Coordinate decoded */ \
  139090. memcpy(&c.u,a,4); \
  139091. r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
  139092. }
  139093. #else
  139094. #define RTREE_DECODE_COORD(eInt, a, r) { \
  139095. RtreeCoord c; /* Coordinate decoded */ \
  139096. c.u = ((u32)a[0]<<24) + ((u32)a[1]<<16) \
  139097. +((u32)a[2]<<8) + a[3]; \
  139098. r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
  139099. }
  139100. #endif
  139101. /*
  139102. ** Check the RTree node or entry given by pCellData and p against the MATCH
  139103. ** constraint pConstraint.
  139104. */
  139105. static int rtreeCallbackConstraint(
  139106. RtreeConstraint *pConstraint, /* The constraint to test */
  139107. int eInt, /* True if RTree holding integer coordinates */
  139108. u8 *pCellData, /* Raw cell content */
  139109. RtreeSearchPoint *pSearch, /* Container of this cell */
  139110. sqlite3_rtree_dbl *prScore, /* OUT: score for the cell */
  139111. int *peWithin /* OUT: visibility of the cell */
  139112. ){
  139113. int i; /* Loop counter */
  139114. sqlite3_rtree_query_info *pInfo = pConstraint->pInfo; /* Callback info */
  139115. int nCoord = pInfo->nCoord; /* No. of coordinates */
  139116. int rc; /* Callback return code */
  139117. sqlite3_rtree_dbl aCoord[RTREE_MAX_DIMENSIONS*2]; /* Decoded coordinates */
  139118. assert( pConstraint->op==RTREE_MATCH || pConstraint->op==RTREE_QUERY );
  139119. assert( nCoord==2 || nCoord==4 || nCoord==6 || nCoord==8 || nCoord==10 );
  139120. if( pConstraint->op==RTREE_QUERY && pSearch->iLevel==1 ){
  139121. pInfo->iRowid = readInt64(pCellData);
  139122. }
  139123. pCellData += 8;
  139124. for(i=0; i<nCoord; i++, pCellData += 4){
  139125. RTREE_DECODE_COORD(eInt, pCellData, aCoord[i]);
  139126. }
  139127. if( pConstraint->op==RTREE_MATCH ){
  139128. rc = pConstraint->u.xGeom((sqlite3_rtree_geometry*)pInfo,
  139129. nCoord, aCoord, &i);
  139130. if( i==0 ) *peWithin = NOT_WITHIN;
  139131. *prScore = RTREE_ZERO;
  139132. }else{
  139133. pInfo->aCoord = aCoord;
  139134. pInfo->iLevel = pSearch->iLevel - 1;
  139135. pInfo->rScore = pInfo->rParentScore = pSearch->rScore;
  139136. pInfo->eWithin = pInfo->eParentWithin = pSearch->eWithin;
  139137. rc = pConstraint->u.xQueryFunc(pInfo);
  139138. if( pInfo->eWithin<*peWithin ) *peWithin = pInfo->eWithin;
  139139. if( pInfo->rScore<*prScore || *prScore<RTREE_ZERO ){
  139140. *prScore = pInfo->rScore;
  139141. }
  139142. }
  139143. return rc;
  139144. }
  139145. /*
  139146. ** Check the internal RTree node given by pCellData against constraint p.
  139147. ** If this constraint cannot be satisfied by any child within the node,
  139148. ** set *peWithin to NOT_WITHIN.
  139149. */
  139150. static void rtreeNonleafConstraint(
  139151. RtreeConstraint *p, /* The constraint to test */
  139152. int eInt, /* True if RTree holds integer coordinates */
  139153. u8 *pCellData, /* Raw cell content as appears on disk */
  139154. int *peWithin /* Adjust downward, as appropriate */
  139155. ){
  139156. sqlite3_rtree_dbl val; /* Coordinate value convert to a double */
  139157. /* p->iCoord might point to either a lower or upper bound coordinate
  139158. ** in a coordinate pair. But make pCellData point to the lower bound.
  139159. */
  139160. pCellData += 8 + 4*(p->iCoord&0xfe);
  139161. assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE
  139162. || p->op==RTREE_GT || p->op==RTREE_EQ );
  139163. switch( p->op ){
  139164. case RTREE_LE:
  139165. case RTREE_LT:
  139166. case RTREE_EQ:
  139167. RTREE_DECODE_COORD(eInt, pCellData, val);
  139168. /* val now holds the lower bound of the coordinate pair */
  139169. if( p->u.rValue>=val ) return;
  139170. if( p->op!=RTREE_EQ ) break; /* RTREE_LE and RTREE_LT end here */
  139171. /* Fall through for the RTREE_EQ case */
  139172. default: /* RTREE_GT or RTREE_GE, or fallthrough of RTREE_EQ */
  139173. pCellData += 4;
  139174. RTREE_DECODE_COORD(eInt, pCellData, val);
  139175. /* val now holds the upper bound of the coordinate pair */
  139176. if( p->u.rValue<=val ) return;
  139177. }
  139178. *peWithin = NOT_WITHIN;
  139179. }
  139180. /*
  139181. ** Check the leaf RTree cell given by pCellData against constraint p.
  139182. ** If this constraint is not satisfied, set *peWithin to NOT_WITHIN.
  139183. ** If the constraint is satisfied, leave *peWithin unchanged.
  139184. **
  139185. ** The constraint is of the form: xN op $val
  139186. **
  139187. ** The op is given by p->op. The xN is p->iCoord-th coordinate in
  139188. ** pCellData. $val is given by p->u.rValue.
  139189. */
  139190. static void rtreeLeafConstraint(
  139191. RtreeConstraint *p, /* The constraint to test */
  139192. int eInt, /* True if RTree holds integer coordinates */
  139193. u8 *pCellData, /* Raw cell content as appears on disk */
  139194. int *peWithin /* Adjust downward, as appropriate */
  139195. ){
  139196. RtreeDValue xN; /* Coordinate value converted to a double */
  139197. assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE
  139198. || p->op==RTREE_GT || p->op==RTREE_EQ );
  139199. pCellData += 8 + p->iCoord*4;
  139200. RTREE_DECODE_COORD(eInt, pCellData, xN);
  139201. switch( p->op ){
  139202. case RTREE_LE: if( xN <= p->u.rValue ) return; break;
  139203. case RTREE_LT: if( xN < p->u.rValue ) return; break;
  139204. case RTREE_GE: if( xN >= p->u.rValue ) return; break;
  139205. case RTREE_GT: if( xN > p->u.rValue ) return; break;
  139206. default: if( xN == p->u.rValue ) return; break;
  139207. }
  139208. *peWithin = NOT_WITHIN;
  139209. }
  139210. /*
  139211. ** One of the cells in node pNode is guaranteed to have a 64-bit
  139212. ** integer value equal to iRowid. Return the index of this cell.
  139213. */
  139214. static int nodeRowidIndex(
  139215. Rtree *pRtree,
  139216. RtreeNode *pNode,
  139217. i64 iRowid,
  139218. int *piIndex
  139219. ){
  139220. int ii;
  139221. int nCell = NCELL(pNode);
  139222. assert( nCell<200 );
  139223. for(ii=0; ii<nCell; ii++){
  139224. if( nodeGetRowid(pRtree, pNode, ii)==iRowid ){
  139225. *piIndex = ii;
  139226. return SQLITE_OK;
  139227. }
  139228. }
  139229. return SQLITE_CORRUPT_VTAB;
  139230. }
  139231. /*
  139232. ** Return the index of the cell containing a pointer to node pNode
  139233. ** in its parent. If pNode is the root node, return -1.
  139234. */
  139235. static int nodeParentIndex(Rtree *pRtree, RtreeNode *pNode, int *piIndex){
  139236. RtreeNode *pParent = pNode->pParent;
  139237. if( pParent ){
  139238. return nodeRowidIndex(pRtree, pParent, pNode->iNode, piIndex);
  139239. }
  139240. *piIndex = -1;
  139241. return SQLITE_OK;
  139242. }
  139243. /*
  139244. ** Compare two search points. Return negative, zero, or positive if the first
  139245. ** is less than, equal to, or greater than the second.
  139246. **
  139247. ** The rScore is the primary key. Smaller rScore values come first.
  139248. ** If the rScore is a tie, then use iLevel as the tie breaker with smaller
  139249. ** iLevel values coming first. In this way, if rScore is the same for all
  139250. ** SearchPoints, then iLevel becomes the deciding factor and the result
  139251. ** is a depth-first search, which is the desired default behavior.
  139252. */
  139253. static int rtreeSearchPointCompare(
  139254. const RtreeSearchPoint *pA,
  139255. const RtreeSearchPoint *pB
  139256. ){
  139257. if( pA->rScore<pB->rScore ) return -1;
  139258. if( pA->rScore>pB->rScore ) return +1;
  139259. if( pA->iLevel<pB->iLevel ) return -1;
  139260. if( pA->iLevel>pB->iLevel ) return +1;
  139261. return 0;
  139262. }
  139263. /*
  139264. ** Interchange to search points in a cursor.
  139265. */
  139266. static void rtreeSearchPointSwap(RtreeCursor *p, int i, int j){
  139267. RtreeSearchPoint t = p->aPoint[i];
  139268. assert( i<j );
  139269. p->aPoint[i] = p->aPoint[j];
  139270. p->aPoint[j] = t;
  139271. i++; j++;
  139272. if( i<RTREE_CACHE_SZ ){
  139273. if( j>=RTREE_CACHE_SZ ){
  139274. nodeRelease(RTREE_OF_CURSOR(p), p->aNode[i]);
  139275. p->aNode[i] = 0;
  139276. }else{
  139277. RtreeNode *pTemp = p->aNode[i];
  139278. p->aNode[i] = p->aNode[j];
  139279. p->aNode[j] = pTemp;
  139280. }
  139281. }
  139282. }
  139283. /*
  139284. ** Return the search point with the lowest current score.
  139285. */
  139286. static RtreeSearchPoint *rtreeSearchPointFirst(RtreeCursor *pCur){
  139287. return pCur->bPoint ? &pCur->sPoint : pCur->nPoint ? pCur->aPoint : 0;
  139288. }
  139289. /*
  139290. ** Get the RtreeNode for the search point with the lowest score.
  139291. */
  139292. static RtreeNode *rtreeNodeOfFirstSearchPoint(RtreeCursor *pCur, int *pRC){
  139293. sqlite3_int64 id;
  139294. int ii = 1 - pCur->bPoint;
  139295. assert( ii==0 || ii==1 );
  139296. assert( pCur->bPoint || pCur->nPoint );
  139297. if( pCur->aNode[ii]==0 ){
  139298. assert( pRC!=0 );
  139299. id = ii ? pCur->aPoint[0].id : pCur->sPoint.id;
  139300. *pRC = nodeAcquire(RTREE_OF_CURSOR(pCur), id, 0, &pCur->aNode[ii]);
  139301. }
  139302. return pCur->aNode[ii];
  139303. }
  139304. /*
  139305. ** Push a new element onto the priority queue
  139306. */
  139307. static RtreeSearchPoint *rtreeEnqueue(
  139308. RtreeCursor *pCur, /* The cursor */
  139309. RtreeDValue rScore, /* Score for the new search point */
  139310. u8 iLevel /* Level for the new search point */
  139311. ){
  139312. int i, j;
  139313. RtreeSearchPoint *pNew;
  139314. if( pCur->nPoint>=pCur->nPointAlloc ){
  139315. int nNew = pCur->nPointAlloc*2 + 8;
  139316. pNew = sqlite3_realloc(pCur->aPoint, nNew*sizeof(pCur->aPoint[0]));
  139317. if( pNew==0 ) return 0;
  139318. pCur->aPoint = pNew;
  139319. pCur->nPointAlloc = nNew;
  139320. }
  139321. i = pCur->nPoint++;
  139322. pNew = pCur->aPoint + i;
  139323. pNew->rScore = rScore;
  139324. pNew->iLevel = iLevel;
  139325. assert( iLevel>=0 && iLevel<=RTREE_MAX_DEPTH );
  139326. while( i>0 ){
  139327. RtreeSearchPoint *pParent;
  139328. j = (i-1)/2;
  139329. pParent = pCur->aPoint + j;
  139330. if( rtreeSearchPointCompare(pNew, pParent)>=0 ) break;
  139331. rtreeSearchPointSwap(pCur, j, i);
  139332. i = j;
  139333. pNew = pParent;
  139334. }
  139335. return pNew;
  139336. }
  139337. /*
  139338. ** Allocate a new RtreeSearchPoint and return a pointer to it. Return
  139339. ** NULL if malloc fails.
  139340. */
  139341. static RtreeSearchPoint *rtreeSearchPointNew(
  139342. RtreeCursor *pCur, /* The cursor */
  139343. RtreeDValue rScore, /* Score for the new search point */
  139344. u8 iLevel /* Level for the new search point */
  139345. ){
  139346. RtreeSearchPoint *pNew, *pFirst;
  139347. pFirst = rtreeSearchPointFirst(pCur);
  139348. pCur->anQueue[iLevel]++;
  139349. if( pFirst==0
  139350. || pFirst->rScore>rScore
  139351. || (pFirst->rScore==rScore && pFirst->iLevel>iLevel)
  139352. ){
  139353. if( pCur->bPoint ){
  139354. int ii;
  139355. pNew = rtreeEnqueue(pCur, rScore, iLevel);
  139356. if( pNew==0 ) return 0;
  139357. ii = (int)(pNew - pCur->aPoint) + 1;
  139358. if( ii<RTREE_CACHE_SZ ){
  139359. assert( pCur->aNode[ii]==0 );
  139360. pCur->aNode[ii] = pCur->aNode[0];
  139361. }else{
  139362. nodeRelease(RTREE_OF_CURSOR(pCur), pCur->aNode[0]);
  139363. }
  139364. pCur->aNode[0] = 0;
  139365. *pNew = pCur->sPoint;
  139366. }
  139367. pCur->sPoint.rScore = rScore;
  139368. pCur->sPoint.iLevel = iLevel;
  139369. pCur->bPoint = 1;
  139370. return &pCur->sPoint;
  139371. }else{
  139372. return rtreeEnqueue(pCur, rScore, iLevel);
  139373. }
  139374. }
  139375. #if 0
  139376. /* Tracing routines for the RtreeSearchPoint queue */
  139377. static void tracePoint(RtreeSearchPoint *p, int idx, RtreeCursor *pCur){
  139378. if( idx<0 ){ printf(" s"); }else{ printf("%2d", idx); }
  139379. printf(" %d.%05lld.%02d %g %d",
  139380. p->iLevel, p->id, p->iCell, p->rScore, p->eWithin
  139381. );
  139382. idx++;
  139383. if( idx<RTREE_CACHE_SZ ){
  139384. printf(" %p\n", pCur->aNode[idx]);
  139385. }else{
  139386. printf("\n");
  139387. }
  139388. }
  139389. static void traceQueue(RtreeCursor *pCur, const char *zPrefix){
  139390. int ii;
  139391. printf("=== %9s ", zPrefix);
  139392. if( pCur->bPoint ){
  139393. tracePoint(&pCur->sPoint, -1, pCur);
  139394. }
  139395. for(ii=0; ii<pCur->nPoint; ii++){
  139396. if( ii>0 || pCur->bPoint ) printf(" ");
  139397. tracePoint(&pCur->aPoint[ii], ii, pCur);
  139398. }
  139399. }
  139400. # define RTREE_QUEUE_TRACE(A,B) traceQueue(A,B)
  139401. #else
  139402. # define RTREE_QUEUE_TRACE(A,B) /* no-op */
  139403. #endif
  139404. /* Remove the search point with the lowest current score.
  139405. */
  139406. static void rtreeSearchPointPop(RtreeCursor *p){
  139407. int i, j, k, n;
  139408. i = 1 - p->bPoint;
  139409. assert( i==0 || i==1 );
  139410. if( p->aNode[i] ){
  139411. nodeRelease(RTREE_OF_CURSOR(p), p->aNode[i]);
  139412. p->aNode[i] = 0;
  139413. }
  139414. if( p->bPoint ){
  139415. p->anQueue[p->sPoint.iLevel]--;
  139416. p->bPoint = 0;
  139417. }else if( p->nPoint ){
  139418. p->anQueue[p->aPoint[0].iLevel]--;
  139419. n = --p->nPoint;
  139420. p->aPoint[0] = p->aPoint[n];
  139421. if( n<RTREE_CACHE_SZ-1 ){
  139422. p->aNode[1] = p->aNode[n+1];
  139423. p->aNode[n+1] = 0;
  139424. }
  139425. i = 0;
  139426. while( (j = i*2+1)<n ){
  139427. k = j+1;
  139428. if( k<n && rtreeSearchPointCompare(&p->aPoint[k], &p->aPoint[j])<0 ){
  139429. if( rtreeSearchPointCompare(&p->aPoint[k], &p->aPoint[i])<0 ){
  139430. rtreeSearchPointSwap(p, i, k);
  139431. i = k;
  139432. }else{
  139433. break;
  139434. }
  139435. }else{
  139436. if( rtreeSearchPointCompare(&p->aPoint[j], &p->aPoint[i])<0 ){
  139437. rtreeSearchPointSwap(p, i, j);
  139438. i = j;
  139439. }else{
  139440. break;
  139441. }
  139442. }
  139443. }
  139444. }
  139445. }
  139446. /*
  139447. ** Continue the search on cursor pCur until the front of the queue
  139448. ** contains an entry suitable for returning as a result-set row,
  139449. ** or until the RtreeSearchPoint queue is empty, indicating that the
  139450. ** query has completed.
  139451. */
  139452. static int rtreeStepToLeaf(RtreeCursor *pCur){
  139453. RtreeSearchPoint *p;
  139454. Rtree *pRtree = RTREE_OF_CURSOR(pCur);
  139455. RtreeNode *pNode;
  139456. int eWithin;
  139457. int rc = SQLITE_OK;
  139458. int nCell;
  139459. int nConstraint = pCur->nConstraint;
  139460. int ii;
  139461. int eInt;
  139462. RtreeSearchPoint x;
  139463. eInt = pRtree->eCoordType==RTREE_COORD_INT32;
  139464. while( (p = rtreeSearchPointFirst(pCur))!=0 && p->iLevel>0 ){
  139465. pNode = rtreeNodeOfFirstSearchPoint(pCur, &rc);
  139466. if( rc ) return rc;
  139467. nCell = NCELL(pNode);
  139468. assert( nCell<200 );
  139469. while( p->iCell<nCell ){
  139470. sqlite3_rtree_dbl rScore = (sqlite3_rtree_dbl)-1;
  139471. u8 *pCellData = pNode->zData + (4+pRtree->nBytesPerCell*p->iCell);
  139472. eWithin = FULLY_WITHIN;
  139473. for(ii=0; ii<nConstraint; ii++){
  139474. RtreeConstraint *pConstraint = pCur->aConstraint + ii;
  139475. if( pConstraint->op>=RTREE_MATCH ){
  139476. rc = rtreeCallbackConstraint(pConstraint, eInt, pCellData, p,
  139477. &rScore, &eWithin);
  139478. if( rc ) return rc;
  139479. }else if( p->iLevel==1 ){
  139480. rtreeLeafConstraint(pConstraint, eInt, pCellData, &eWithin);
  139481. }else{
  139482. rtreeNonleafConstraint(pConstraint, eInt, pCellData, &eWithin);
  139483. }
  139484. if( eWithin==NOT_WITHIN ) break;
  139485. }
  139486. p->iCell++;
  139487. if( eWithin==NOT_WITHIN ) continue;
  139488. x.iLevel = p->iLevel - 1;
  139489. if( x.iLevel ){
  139490. x.id = readInt64(pCellData);
  139491. x.iCell = 0;
  139492. }else{
  139493. x.id = p->id;
  139494. x.iCell = p->iCell - 1;
  139495. }
  139496. if( p->iCell>=nCell ){
  139497. RTREE_QUEUE_TRACE(pCur, "POP-S:");
  139498. rtreeSearchPointPop(pCur);
  139499. }
  139500. if( rScore<RTREE_ZERO ) rScore = RTREE_ZERO;
  139501. p = rtreeSearchPointNew(pCur, rScore, x.iLevel);
  139502. if( p==0 ) return SQLITE_NOMEM;
  139503. p->eWithin = eWithin;
  139504. p->id = x.id;
  139505. p->iCell = x.iCell;
  139506. RTREE_QUEUE_TRACE(pCur, "PUSH-S:");
  139507. break;
  139508. }
  139509. if( p->iCell>=nCell ){
  139510. RTREE_QUEUE_TRACE(pCur, "POP-Se:");
  139511. rtreeSearchPointPop(pCur);
  139512. }
  139513. }
  139514. pCur->atEOF = p==0;
  139515. return SQLITE_OK;
  139516. }
  139517. /*
  139518. ** Rtree virtual table module xNext method.
  139519. */
  139520. static int rtreeNext(sqlite3_vtab_cursor *pVtabCursor){
  139521. RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
  139522. int rc = SQLITE_OK;
  139523. /* Move to the next entry that matches the configured constraints. */
  139524. RTREE_QUEUE_TRACE(pCsr, "POP-Nx:");
  139525. rtreeSearchPointPop(pCsr);
  139526. rc = rtreeStepToLeaf(pCsr);
  139527. return rc;
  139528. }
  139529. /*
  139530. ** Rtree virtual table module xRowid method.
  139531. */
  139532. static int rtreeRowid(sqlite3_vtab_cursor *pVtabCursor, sqlite_int64 *pRowid){
  139533. RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
  139534. RtreeSearchPoint *p = rtreeSearchPointFirst(pCsr);
  139535. int rc = SQLITE_OK;
  139536. RtreeNode *pNode = rtreeNodeOfFirstSearchPoint(pCsr, &rc);
  139537. if( rc==SQLITE_OK && p ){
  139538. *pRowid = nodeGetRowid(RTREE_OF_CURSOR(pCsr), pNode, p->iCell);
  139539. }
  139540. return rc;
  139541. }
  139542. /*
  139543. ** Rtree virtual table module xColumn method.
  139544. */
  139545. static int rtreeColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
  139546. Rtree *pRtree = (Rtree *)cur->pVtab;
  139547. RtreeCursor *pCsr = (RtreeCursor *)cur;
  139548. RtreeSearchPoint *p = rtreeSearchPointFirst(pCsr);
  139549. RtreeCoord c;
  139550. int rc = SQLITE_OK;
  139551. RtreeNode *pNode = rtreeNodeOfFirstSearchPoint(pCsr, &rc);
  139552. if( rc ) return rc;
  139553. if( p==0 ) return SQLITE_OK;
  139554. if( i==0 ){
  139555. sqlite3_result_int64(ctx, nodeGetRowid(pRtree, pNode, p->iCell));
  139556. }else{
  139557. if( rc ) return rc;
  139558. nodeGetCoord(pRtree, pNode, p->iCell, i-1, &c);
  139559. #ifndef SQLITE_RTREE_INT_ONLY
  139560. if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
  139561. sqlite3_result_double(ctx, c.f);
  139562. }else
  139563. #endif
  139564. {
  139565. assert( pRtree->eCoordType==RTREE_COORD_INT32 );
  139566. sqlite3_result_int(ctx, c.i);
  139567. }
  139568. }
  139569. return SQLITE_OK;
  139570. }
  139571. /*
  139572. ** Use nodeAcquire() to obtain the leaf node containing the record with
  139573. ** rowid iRowid. If successful, set *ppLeaf to point to the node and
  139574. ** return SQLITE_OK. If there is no such record in the table, set
  139575. ** *ppLeaf to 0 and return SQLITE_OK. If an error occurs, set *ppLeaf
  139576. ** to zero and return an SQLite error code.
  139577. */
  139578. static int findLeafNode(
  139579. Rtree *pRtree, /* RTree to search */
  139580. i64 iRowid, /* The rowid searching for */
  139581. RtreeNode **ppLeaf, /* Write the node here */
  139582. sqlite3_int64 *piNode /* Write the node-id here */
  139583. ){
  139584. int rc;
  139585. *ppLeaf = 0;
  139586. sqlite3_bind_int64(pRtree->pReadRowid, 1, iRowid);
  139587. if( sqlite3_step(pRtree->pReadRowid)==SQLITE_ROW ){
  139588. i64 iNode = sqlite3_column_int64(pRtree->pReadRowid, 0);
  139589. if( piNode ) *piNode = iNode;
  139590. rc = nodeAcquire(pRtree, iNode, 0, ppLeaf);
  139591. sqlite3_reset(pRtree->pReadRowid);
  139592. }else{
  139593. rc = sqlite3_reset(pRtree->pReadRowid);
  139594. }
  139595. return rc;
  139596. }
  139597. /*
  139598. ** This function is called to configure the RtreeConstraint object passed
  139599. ** as the second argument for a MATCH constraint. The value passed as the
  139600. ** first argument to this function is the right-hand operand to the MATCH
  139601. ** operator.
  139602. */
  139603. static int deserializeGeometry(sqlite3_value *pValue, RtreeConstraint *pCons){
  139604. RtreeMatchArg *pBlob; /* BLOB returned by geometry function */
  139605. sqlite3_rtree_query_info *pInfo; /* Callback information */
  139606. int nBlob; /* Size of the geometry function blob */
  139607. int nExpected; /* Expected size of the BLOB */
  139608. /* Check that value is actually a blob. */
  139609. if( sqlite3_value_type(pValue)!=SQLITE_BLOB ) return SQLITE_ERROR;
  139610. /* Check that the blob is roughly the right size. */
  139611. nBlob = sqlite3_value_bytes(pValue);
  139612. if( nBlob<(int)sizeof(RtreeMatchArg)
  139613. || ((nBlob-sizeof(RtreeMatchArg))%sizeof(RtreeDValue))!=0
  139614. ){
  139615. return SQLITE_ERROR;
  139616. }
  139617. pInfo = (sqlite3_rtree_query_info*)sqlite3_malloc( sizeof(*pInfo)+nBlob );
  139618. if( !pInfo ) return SQLITE_NOMEM;
  139619. memset(pInfo, 0, sizeof(*pInfo));
  139620. pBlob = (RtreeMatchArg*)&pInfo[1];
  139621. memcpy(pBlob, sqlite3_value_blob(pValue), nBlob);
  139622. nExpected = (int)(sizeof(RtreeMatchArg) +
  139623. (pBlob->nParam-1)*sizeof(RtreeDValue));
  139624. if( pBlob->magic!=RTREE_GEOMETRY_MAGIC || nBlob!=nExpected ){
  139625. sqlite3_free(pInfo);
  139626. return SQLITE_ERROR;
  139627. }
  139628. pInfo->pContext = pBlob->cb.pContext;
  139629. pInfo->nParam = pBlob->nParam;
  139630. pInfo->aParam = pBlob->aParam;
  139631. if( pBlob->cb.xGeom ){
  139632. pCons->u.xGeom = pBlob->cb.xGeom;
  139633. }else{
  139634. pCons->op = RTREE_QUERY;
  139635. pCons->u.xQueryFunc = pBlob->cb.xQueryFunc;
  139636. }
  139637. pCons->pInfo = pInfo;
  139638. return SQLITE_OK;
  139639. }
  139640. /*
  139641. ** Rtree virtual table module xFilter method.
  139642. */
  139643. static int rtreeFilter(
  139644. sqlite3_vtab_cursor *pVtabCursor,
  139645. int idxNum, const char *idxStr,
  139646. int argc, sqlite3_value **argv
  139647. ){
  139648. Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
  139649. RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
  139650. RtreeNode *pRoot = 0;
  139651. int ii;
  139652. int rc = SQLITE_OK;
  139653. int iCell = 0;
  139654. rtreeReference(pRtree);
  139655. /* Reset the cursor to the same state as rtreeOpen() leaves it in. */
  139656. freeCursorConstraints(pCsr);
  139657. sqlite3_free(pCsr->aPoint);
  139658. memset(pCsr, 0, sizeof(RtreeCursor));
  139659. pCsr->base.pVtab = (sqlite3_vtab*)pRtree;
  139660. pCsr->iStrategy = idxNum;
  139661. if( idxNum==1 ){
  139662. /* Special case - lookup by rowid. */
  139663. RtreeNode *pLeaf; /* Leaf on which the required cell resides */
  139664. RtreeSearchPoint *p; /* Search point for the the leaf */
  139665. i64 iRowid = sqlite3_value_int64(argv[0]);
  139666. i64 iNode = 0;
  139667. rc = findLeafNode(pRtree, iRowid, &pLeaf, &iNode);
  139668. if( rc==SQLITE_OK && pLeaf!=0 ){
  139669. p = rtreeSearchPointNew(pCsr, RTREE_ZERO, 0);
  139670. assert( p!=0 ); /* Always returns pCsr->sPoint */
  139671. pCsr->aNode[0] = pLeaf;
  139672. p->id = iNode;
  139673. p->eWithin = PARTLY_WITHIN;
  139674. rc = nodeRowidIndex(pRtree, pLeaf, iRowid, &iCell);
  139675. p->iCell = iCell;
  139676. RTREE_QUEUE_TRACE(pCsr, "PUSH-F1:");
  139677. }else{
  139678. pCsr->atEOF = 1;
  139679. }
  139680. }else{
  139681. /* Normal case - r-tree scan. Set up the RtreeCursor.aConstraint array
  139682. ** with the configured constraints.
  139683. */
  139684. rc = nodeAcquire(pRtree, 1, 0, &pRoot);
  139685. if( rc==SQLITE_OK && argc>0 ){
  139686. pCsr->aConstraint = sqlite3_malloc(sizeof(RtreeConstraint)*argc);
  139687. pCsr->nConstraint = argc;
  139688. if( !pCsr->aConstraint ){
  139689. rc = SQLITE_NOMEM;
  139690. }else{
  139691. memset(pCsr->aConstraint, 0, sizeof(RtreeConstraint)*argc);
  139692. memset(pCsr->anQueue, 0, sizeof(u32)*(pRtree->iDepth + 1));
  139693. assert( (idxStr==0 && argc==0)
  139694. || (idxStr && (int)strlen(idxStr)==argc*2) );
  139695. for(ii=0; ii<argc; ii++){
  139696. RtreeConstraint *p = &pCsr->aConstraint[ii];
  139697. p->op = idxStr[ii*2];
  139698. p->iCoord = idxStr[ii*2+1]-'0';
  139699. if( p->op>=RTREE_MATCH ){
  139700. /* A MATCH operator. The right-hand-side must be a blob that
  139701. ** can be cast into an RtreeMatchArg object. One created using
  139702. ** an sqlite3_rtree_geometry_callback() SQL user function.
  139703. */
  139704. rc = deserializeGeometry(argv[ii], p);
  139705. if( rc!=SQLITE_OK ){
  139706. break;
  139707. }
  139708. p->pInfo->nCoord = pRtree->nDim*2;
  139709. p->pInfo->anQueue = pCsr->anQueue;
  139710. p->pInfo->mxLevel = pRtree->iDepth + 1;
  139711. }else{
  139712. #ifdef SQLITE_RTREE_INT_ONLY
  139713. p->u.rValue = sqlite3_value_int64(argv[ii]);
  139714. #else
  139715. p->u.rValue = sqlite3_value_double(argv[ii]);
  139716. #endif
  139717. }
  139718. }
  139719. }
  139720. }
  139721. if( rc==SQLITE_OK ){
  139722. RtreeSearchPoint *pNew;
  139723. pNew = rtreeSearchPointNew(pCsr, RTREE_ZERO, pRtree->iDepth+1);
  139724. if( pNew==0 ) return SQLITE_NOMEM;
  139725. pNew->id = 1;
  139726. pNew->iCell = 0;
  139727. pNew->eWithin = PARTLY_WITHIN;
  139728. assert( pCsr->bPoint==1 );
  139729. pCsr->aNode[0] = pRoot;
  139730. pRoot = 0;
  139731. RTREE_QUEUE_TRACE(pCsr, "PUSH-Fm:");
  139732. rc = rtreeStepToLeaf(pCsr);
  139733. }
  139734. }
  139735. nodeRelease(pRtree, pRoot);
  139736. rtreeRelease(pRtree);
  139737. return rc;
  139738. }
  139739. /*
  139740. ** Set the pIdxInfo->estimatedRows variable to nRow. Unless this
  139741. ** extension is currently being used by a version of SQLite too old to
  139742. ** support estimatedRows. In that case this function is a no-op.
  139743. */
  139744. static void setEstimatedRows(sqlite3_index_info *pIdxInfo, i64 nRow){
  139745. #if SQLITE_VERSION_NUMBER>=3008002
  139746. if( sqlite3_libversion_number()>=3008002 ){
  139747. pIdxInfo->estimatedRows = nRow;
  139748. }
  139749. #endif
  139750. }
  139751. /*
  139752. ** Rtree virtual table module xBestIndex method. There are three
  139753. ** table scan strategies to choose from (in order from most to
  139754. ** least desirable):
  139755. **
  139756. ** idxNum idxStr Strategy
  139757. ** ------------------------------------------------
  139758. ** 1 Unused Direct lookup by rowid.
  139759. ** 2 See below R-tree query or full-table scan.
  139760. ** ------------------------------------------------
  139761. **
  139762. ** If strategy 1 is used, then idxStr is not meaningful. If strategy
  139763. ** 2 is used, idxStr is formatted to contain 2 bytes for each
  139764. ** constraint used. The first two bytes of idxStr correspond to
  139765. ** the constraint in sqlite3_index_info.aConstraintUsage[] with
  139766. ** (argvIndex==1) etc.
  139767. **
  139768. ** The first of each pair of bytes in idxStr identifies the constraint
  139769. ** operator as follows:
  139770. **
  139771. ** Operator Byte Value
  139772. ** ----------------------
  139773. ** = 0x41 ('A')
  139774. ** <= 0x42 ('B')
  139775. ** < 0x43 ('C')
  139776. ** >= 0x44 ('D')
  139777. ** > 0x45 ('E')
  139778. ** MATCH 0x46 ('F')
  139779. ** ----------------------
  139780. **
  139781. ** The second of each pair of bytes identifies the coordinate column
  139782. ** to which the constraint applies. The leftmost coordinate column
  139783. ** is 'a', the second from the left 'b' etc.
  139784. */
  139785. static int rtreeBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
  139786. Rtree *pRtree = (Rtree*)tab;
  139787. int rc = SQLITE_OK;
  139788. int ii;
  139789. i64 nRow; /* Estimated rows returned by this scan */
  139790. int iIdx = 0;
  139791. char zIdxStr[RTREE_MAX_DIMENSIONS*8+1];
  139792. memset(zIdxStr, 0, sizeof(zIdxStr));
  139793. assert( pIdxInfo->idxStr==0 );
  139794. for(ii=0; ii<pIdxInfo->nConstraint && iIdx<(int)(sizeof(zIdxStr)-1); ii++){
  139795. struct sqlite3_index_constraint *p = &pIdxInfo->aConstraint[ii];
  139796. if( p->usable && p->iColumn==0 && p->op==SQLITE_INDEX_CONSTRAINT_EQ ){
  139797. /* We have an equality constraint on the rowid. Use strategy 1. */
  139798. int jj;
  139799. for(jj=0; jj<ii; jj++){
  139800. pIdxInfo->aConstraintUsage[jj].argvIndex = 0;
  139801. pIdxInfo->aConstraintUsage[jj].omit = 0;
  139802. }
  139803. pIdxInfo->idxNum = 1;
  139804. pIdxInfo->aConstraintUsage[ii].argvIndex = 1;
  139805. pIdxInfo->aConstraintUsage[jj].omit = 1;
  139806. /* This strategy involves a two rowid lookups on an B-Tree structures
  139807. ** and then a linear search of an R-Tree node. This should be
  139808. ** considered almost as quick as a direct rowid lookup (for which
  139809. ** sqlite uses an internal cost of 0.0). It is expected to return
  139810. ** a single row.
  139811. */
  139812. pIdxInfo->estimatedCost = 30.0;
  139813. setEstimatedRows(pIdxInfo, 1);
  139814. return SQLITE_OK;
  139815. }
  139816. if( p->usable && (p->iColumn>0 || p->op==SQLITE_INDEX_CONSTRAINT_MATCH) ){
  139817. u8 op;
  139818. switch( p->op ){
  139819. case SQLITE_INDEX_CONSTRAINT_EQ: op = RTREE_EQ; break;
  139820. case SQLITE_INDEX_CONSTRAINT_GT: op = RTREE_GT; break;
  139821. case SQLITE_INDEX_CONSTRAINT_LE: op = RTREE_LE; break;
  139822. case SQLITE_INDEX_CONSTRAINT_LT: op = RTREE_LT; break;
  139823. case SQLITE_INDEX_CONSTRAINT_GE: op = RTREE_GE; break;
  139824. default:
  139825. assert( p->op==SQLITE_INDEX_CONSTRAINT_MATCH );
  139826. op = RTREE_MATCH;
  139827. break;
  139828. }
  139829. zIdxStr[iIdx++] = op;
  139830. zIdxStr[iIdx++] = p->iColumn - 1 + '0';
  139831. pIdxInfo->aConstraintUsage[ii].argvIndex = (iIdx/2);
  139832. pIdxInfo->aConstraintUsage[ii].omit = 1;
  139833. }
  139834. }
  139835. pIdxInfo->idxNum = 2;
  139836. pIdxInfo->needToFreeIdxStr = 1;
  139837. if( iIdx>0 && 0==(pIdxInfo->idxStr = sqlite3_mprintf("%s", zIdxStr)) ){
  139838. return SQLITE_NOMEM;
  139839. }
  139840. nRow = pRtree->nRowEst / (iIdx + 1);
  139841. pIdxInfo->estimatedCost = (double)6.0 * (double)nRow;
  139842. setEstimatedRows(pIdxInfo, nRow);
  139843. return rc;
  139844. }
  139845. /*
  139846. ** Return the N-dimensional volumn of the cell stored in *p.
  139847. */
  139848. static RtreeDValue cellArea(Rtree *pRtree, RtreeCell *p){
  139849. RtreeDValue area = (RtreeDValue)1;
  139850. int ii;
  139851. for(ii=0; ii<(pRtree->nDim*2); ii+=2){
  139852. area = (area * (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii])));
  139853. }
  139854. return area;
  139855. }
  139856. /*
  139857. ** Return the margin length of cell p. The margin length is the sum
  139858. ** of the objects size in each dimension.
  139859. */
  139860. static RtreeDValue cellMargin(Rtree *pRtree, RtreeCell *p){
  139861. RtreeDValue margin = (RtreeDValue)0;
  139862. int ii;
  139863. for(ii=0; ii<(pRtree->nDim*2); ii+=2){
  139864. margin += (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii]));
  139865. }
  139866. return margin;
  139867. }
  139868. /*
  139869. ** Store the union of cells p1 and p2 in p1.
  139870. */
  139871. static void cellUnion(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
  139872. int ii;
  139873. if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
  139874. for(ii=0; ii<(pRtree->nDim*2); ii+=2){
  139875. p1->aCoord[ii].f = MIN(p1->aCoord[ii].f, p2->aCoord[ii].f);
  139876. p1->aCoord[ii+1].f = MAX(p1->aCoord[ii+1].f, p2->aCoord[ii+1].f);
  139877. }
  139878. }else{
  139879. for(ii=0; ii<(pRtree->nDim*2); ii+=2){
  139880. p1->aCoord[ii].i = MIN(p1->aCoord[ii].i, p2->aCoord[ii].i);
  139881. p1->aCoord[ii+1].i = MAX(p1->aCoord[ii+1].i, p2->aCoord[ii+1].i);
  139882. }
  139883. }
  139884. }
  139885. /*
  139886. ** Return true if the area covered by p2 is a subset of the area covered
  139887. ** by p1. False otherwise.
  139888. */
  139889. static int cellContains(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
  139890. int ii;
  139891. int isInt = (pRtree->eCoordType==RTREE_COORD_INT32);
  139892. for(ii=0; ii<(pRtree->nDim*2); ii+=2){
  139893. RtreeCoord *a1 = &p1->aCoord[ii];
  139894. RtreeCoord *a2 = &p2->aCoord[ii];
  139895. if( (!isInt && (a2[0].f<a1[0].f || a2[1].f>a1[1].f))
  139896. || ( isInt && (a2[0].i<a1[0].i || a2[1].i>a1[1].i))
  139897. ){
  139898. return 0;
  139899. }
  139900. }
  139901. return 1;
  139902. }
  139903. /*
  139904. ** Return the amount cell p would grow by if it were unioned with pCell.
  139905. */
  139906. static RtreeDValue cellGrowth(Rtree *pRtree, RtreeCell *p, RtreeCell *pCell){
  139907. RtreeDValue area;
  139908. RtreeCell cell;
  139909. memcpy(&cell, p, sizeof(RtreeCell));
  139910. area = cellArea(pRtree, &cell);
  139911. cellUnion(pRtree, &cell, pCell);
  139912. return (cellArea(pRtree, &cell)-area);
  139913. }
  139914. static RtreeDValue cellOverlap(
  139915. Rtree *pRtree,
  139916. RtreeCell *p,
  139917. RtreeCell *aCell,
  139918. int nCell
  139919. ){
  139920. int ii;
  139921. RtreeDValue overlap = RTREE_ZERO;
  139922. for(ii=0; ii<nCell; ii++){
  139923. int jj;
  139924. RtreeDValue o = (RtreeDValue)1;
  139925. for(jj=0; jj<(pRtree->nDim*2); jj+=2){
  139926. RtreeDValue x1, x2;
  139927. x1 = MAX(DCOORD(p->aCoord[jj]), DCOORD(aCell[ii].aCoord[jj]));
  139928. x2 = MIN(DCOORD(p->aCoord[jj+1]), DCOORD(aCell[ii].aCoord[jj+1]));
  139929. if( x2<x1 ){
  139930. o = (RtreeDValue)0;
  139931. break;
  139932. }else{
  139933. o = o * (x2-x1);
  139934. }
  139935. }
  139936. overlap += o;
  139937. }
  139938. return overlap;
  139939. }
  139940. /*
  139941. ** This function implements the ChooseLeaf algorithm from Gutman[84].
  139942. ** ChooseSubTree in r*tree terminology.
  139943. */
  139944. static int ChooseLeaf(
  139945. Rtree *pRtree, /* Rtree table */
  139946. RtreeCell *pCell, /* Cell to insert into rtree */
  139947. int iHeight, /* Height of sub-tree rooted at pCell */
  139948. RtreeNode **ppLeaf /* OUT: Selected leaf page */
  139949. ){
  139950. int rc;
  139951. int ii;
  139952. RtreeNode *pNode;
  139953. rc = nodeAcquire(pRtree, 1, 0, &pNode);
  139954. for(ii=0; rc==SQLITE_OK && ii<(pRtree->iDepth-iHeight); ii++){
  139955. int iCell;
  139956. sqlite3_int64 iBest = 0;
  139957. RtreeDValue fMinGrowth = RTREE_ZERO;
  139958. RtreeDValue fMinArea = RTREE_ZERO;
  139959. int nCell = NCELL(pNode);
  139960. RtreeCell cell;
  139961. RtreeNode *pChild;
  139962. RtreeCell *aCell = 0;
  139963. /* Select the child node which will be enlarged the least if pCell
  139964. ** is inserted into it. Resolve ties by choosing the entry with
  139965. ** the smallest area.
  139966. */
  139967. for(iCell=0; iCell<nCell; iCell++){
  139968. int bBest = 0;
  139969. RtreeDValue growth;
  139970. RtreeDValue area;
  139971. nodeGetCell(pRtree, pNode, iCell, &cell);
  139972. growth = cellGrowth(pRtree, &cell, pCell);
  139973. area = cellArea(pRtree, &cell);
  139974. if( iCell==0||growth<fMinGrowth||(growth==fMinGrowth && area<fMinArea) ){
  139975. bBest = 1;
  139976. }
  139977. if( bBest ){
  139978. fMinGrowth = growth;
  139979. fMinArea = area;
  139980. iBest = cell.iRowid;
  139981. }
  139982. }
  139983. sqlite3_free(aCell);
  139984. rc = nodeAcquire(pRtree, iBest, pNode, &pChild);
  139985. nodeRelease(pRtree, pNode);
  139986. pNode = pChild;
  139987. }
  139988. *ppLeaf = pNode;
  139989. return rc;
  139990. }
  139991. /*
  139992. ** A cell with the same content as pCell has just been inserted into
  139993. ** the node pNode. This function updates the bounding box cells in
  139994. ** all ancestor elements.
  139995. */
  139996. static int AdjustTree(
  139997. Rtree *pRtree, /* Rtree table */
  139998. RtreeNode *pNode, /* Adjust ancestry of this node. */
  139999. RtreeCell *pCell /* This cell was just inserted */
  140000. ){
  140001. RtreeNode *p = pNode;
  140002. while( p->pParent ){
  140003. RtreeNode *pParent = p->pParent;
  140004. RtreeCell cell;
  140005. int iCell;
  140006. if( nodeParentIndex(pRtree, p, &iCell) ){
  140007. return SQLITE_CORRUPT_VTAB;
  140008. }
  140009. nodeGetCell(pRtree, pParent, iCell, &cell);
  140010. if( !cellContains(pRtree, &cell, pCell) ){
  140011. cellUnion(pRtree, &cell, pCell);
  140012. nodeOverwriteCell(pRtree, pParent, &cell, iCell);
  140013. }
  140014. p = pParent;
  140015. }
  140016. return SQLITE_OK;
  140017. }
  140018. /*
  140019. ** Write mapping (iRowid->iNode) to the <rtree>_rowid table.
  140020. */
  140021. static int rowidWrite(Rtree *pRtree, sqlite3_int64 iRowid, sqlite3_int64 iNode){
  140022. sqlite3_bind_int64(pRtree->pWriteRowid, 1, iRowid);
  140023. sqlite3_bind_int64(pRtree->pWriteRowid, 2, iNode);
  140024. sqlite3_step(pRtree->pWriteRowid);
  140025. return sqlite3_reset(pRtree->pWriteRowid);
  140026. }
  140027. /*
  140028. ** Write mapping (iNode->iPar) to the <rtree>_parent table.
  140029. */
  140030. static int parentWrite(Rtree *pRtree, sqlite3_int64 iNode, sqlite3_int64 iPar){
  140031. sqlite3_bind_int64(pRtree->pWriteParent, 1, iNode);
  140032. sqlite3_bind_int64(pRtree->pWriteParent, 2, iPar);
  140033. sqlite3_step(pRtree->pWriteParent);
  140034. return sqlite3_reset(pRtree->pWriteParent);
  140035. }
  140036. static int rtreeInsertCell(Rtree *, RtreeNode *, RtreeCell *, int);
  140037. /*
  140038. ** Arguments aIdx, aDistance and aSpare all point to arrays of size
  140039. ** nIdx. The aIdx array contains the set of integers from 0 to
  140040. ** (nIdx-1) in no particular order. This function sorts the values
  140041. ** in aIdx according to the indexed values in aDistance. For
  140042. ** example, assuming the inputs:
  140043. **
  140044. ** aIdx = { 0, 1, 2, 3 }
  140045. ** aDistance = { 5.0, 2.0, 7.0, 6.0 }
  140046. **
  140047. ** this function sets the aIdx array to contain:
  140048. **
  140049. ** aIdx = { 0, 1, 2, 3 }
  140050. **
  140051. ** The aSpare array is used as temporary working space by the
  140052. ** sorting algorithm.
  140053. */
  140054. static void SortByDistance(
  140055. int *aIdx,
  140056. int nIdx,
  140057. RtreeDValue *aDistance,
  140058. int *aSpare
  140059. ){
  140060. if( nIdx>1 ){
  140061. int iLeft = 0;
  140062. int iRight = 0;
  140063. int nLeft = nIdx/2;
  140064. int nRight = nIdx-nLeft;
  140065. int *aLeft = aIdx;
  140066. int *aRight = &aIdx[nLeft];
  140067. SortByDistance(aLeft, nLeft, aDistance, aSpare);
  140068. SortByDistance(aRight, nRight, aDistance, aSpare);
  140069. memcpy(aSpare, aLeft, sizeof(int)*nLeft);
  140070. aLeft = aSpare;
  140071. while( iLeft<nLeft || iRight<nRight ){
  140072. if( iLeft==nLeft ){
  140073. aIdx[iLeft+iRight] = aRight[iRight];
  140074. iRight++;
  140075. }else if( iRight==nRight ){
  140076. aIdx[iLeft+iRight] = aLeft[iLeft];
  140077. iLeft++;
  140078. }else{
  140079. RtreeDValue fLeft = aDistance[aLeft[iLeft]];
  140080. RtreeDValue fRight = aDistance[aRight[iRight]];
  140081. if( fLeft<fRight ){
  140082. aIdx[iLeft+iRight] = aLeft[iLeft];
  140083. iLeft++;
  140084. }else{
  140085. aIdx[iLeft+iRight] = aRight[iRight];
  140086. iRight++;
  140087. }
  140088. }
  140089. }
  140090. #if 0
  140091. /* Check that the sort worked */
  140092. {
  140093. int jj;
  140094. for(jj=1; jj<nIdx; jj++){
  140095. RtreeDValue left = aDistance[aIdx[jj-1]];
  140096. RtreeDValue right = aDistance[aIdx[jj]];
  140097. assert( left<=right );
  140098. }
  140099. }
  140100. #endif
  140101. }
  140102. }
  140103. /*
  140104. ** Arguments aIdx, aCell and aSpare all point to arrays of size
  140105. ** nIdx. The aIdx array contains the set of integers from 0 to
  140106. ** (nIdx-1) in no particular order. This function sorts the values
  140107. ** in aIdx according to dimension iDim of the cells in aCell. The
  140108. ** minimum value of dimension iDim is considered first, the
  140109. ** maximum used to break ties.
  140110. **
  140111. ** The aSpare array is used as temporary working space by the
  140112. ** sorting algorithm.
  140113. */
  140114. static void SortByDimension(
  140115. Rtree *pRtree,
  140116. int *aIdx,
  140117. int nIdx,
  140118. int iDim,
  140119. RtreeCell *aCell,
  140120. int *aSpare
  140121. ){
  140122. if( nIdx>1 ){
  140123. int iLeft = 0;
  140124. int iRight = 0;
  140125. int nLeft = nIdx/2;
  140126. int nRight = nIdx-nLeft;
  140127. int *aLeft = aIdx;
  140128. int *aRight = &aIdx[nLeft];
  140129. SortByDimension(pRtree, aLeft, nLeft, iDim, aCell, aSpare);
  140130. SortByDimension(pRtree, aRight, nRight, iDim, aCell, aSpare);
  140131. memcpy(aSpare, aLeft, sizeof(int)*nLeft);
  140132. aLeft = aSpare;
  140133. while( iLeft<nLeft || iRight<nRight ){
  140134. RtreeDValue xleft1 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2]);
  140135. RtreeDValue xleft2 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2+1]);
  140136. RtreeDValue xright1 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2]);
  140137. RtreeDValue xright2 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2+1]);
  140138. if( (iLeft!=nLeft) && ((iRight==nRight)
  140139. || (xleft1<xright1)
  140140. || (xleft1==xright1 && xleft2<xright2)
  140141. )){
  140142. aIdx[iLeft+iRight] = aLeft[iLeft];
  140143. iLeft++;
  140144. }else{
  140145. aIdx[iLeft+iRight] = aRight[iRight];
  140146. iRight++;
  140147. }
  140148. }
  140149. #if 0
  140150. /* Check that the sort worked */
  140151. {
  140152. int jj;
  140153. for(jj=1; jj<nIdx; jj++){
  140154. RtreeDValue xleft1 = aCell[aIdx[jj-1]].aCoord[iDim*2];
  140155. RtreeDValue xleft2 = aCell[aIdx[jj-1]].aCoord[iDim*2+1];
  140156. RtreeDValue xright1 = aCell[aIdx[jj]].aCoord[iDim*2];
  140157. RtreeDValue xright2 = aCell[aIdx[jj]].aCoord[iDim*2+1];
  140158. assert( xleft1<=xright1 && (xleft1<xright1 || xleft2<=xright2) );
  140159. }
  140160. }
  140161. #endif
  140162. }
  140163. }
  140164. /*
  140165. ** Implementation of the R*-tree variant of SplitNode from Beckman[1990].
  140166. */
  140167. static int splitNodeStartree(
  140168. Rtree *pRtree,
  140169. RtreeCell *aCell,
  140170. int nCell,
  140171. RtreeNode *pLeft,
  140172. RtreeNode *pRight,
  140173. RtreeCell *pBboxLeft,
  140174. RtreeCell *pBboxRight
  140175. ){
  140176. int **aaSorted;
  140177. int *aSpare;
  140178. int ii;
  140179. int iBestDim = 0;
  140180. int iBestSplit = 0;
  140181. RtreeDValue fBestMargin = RTREE_ZERO;
  140182. int nByte = (pRtree->nDim+1)*(sizeof(int*)+nCell*sizeof(int));
  140183. aaSorted = (int **)sqlite3_malloc(nByte);
  140184. if( !aaSorted ){
  140185. return SQLITE_NOMEM;
  140186. }
  140187. aSpare = &((int *)&aaSorted[pRtree->nDim])[pRtree->nDim*nCell];
  140188. memset(aaSorted, 0, nByte);
  140189. for(ii=0; ii<pRtree->nDim; ii++){
  140190. int jj;
  140191. aaSorted[ii] = &((int *)&aaSorted[pRtree->nDim])[ii*nCell];
  140192. for(jj=0; jj<nCell; jj++){
  140193. aaSorted[ii][jj] = jj;
  140194. }
  140195. SortByDimension(pRtree, aaSorted[ii], nCell, ii, aCell, aSpare);
  140196. }
  140197. for(ii=0; ii<pRtree->nDim; ii++){
  140198. RtreeDValue margin = RTREE_ZERO;
  140199. RtreeDValue fBestOverlap = RTREE_ZERO;
  140200. RtreeDValue fBestArea = RTREE_ZERO;
  140201. int iBestLeft = 0;
  140202. int nLeft;
  140203. for(
  140204. nLeft=RTREE_MINCELLS(pRtree);
  140205. nLeft<=(nCell-RTREE_MINCELLS(pRtree));
  140206. nLeft++
  140207. ){
  140208. RtreeCell left;
  140209. RtreeCell right;
  140210. int kk;
  140211. RtreeDValue overlap;
  140212. RtreeDValue area;
  140213. memcpy(&left, &aCell[aaSorted[ii][0]], sizeof(RtreeCell));
  140214. memcpy(&right, &aCell[aaSorted[ii][nCell-1]], sizeof(RtreeCell));
  140215. for(kk=1; kk<(nCell-1); kk++){
  140216. if( kk<nLeft ){
  140217. cellUnion(pRtree, &left, &aCell[aaSorted[ii][kk]]);
  140218. }else{
  140219. cellUnion(pRtree, &right, &aCell[aaSorted[ii][kk]]);
  140220. }
  140221. }
  140222. margin += cellMargin(pRtree, &left);
  140223. margin += cellMargin(pRtree, &right);
  140224. overlap = cellOverlap(pRtree, &left, &right, 1);
  140225. area = cellArea(pRtree, &left) + cellArea(pRtree, &right);
  140226. if( (nLeft==RTREE_MINCELLS(pRtree))
  140227. || (overlap<fBestOverlap)
  140228. || (overlap==fBestOverlap && area<fBestArea)
  140229. ){
  140230. iBestLeft = nLeft;
  140231. fBestOverlap = overlap;
  140232. fBestArea = area;
  140233. }
  140234. }
  140235. if( ii==0 || margin<fBestMargin ){
  140236. iBestDim = ii;
  140237. fBestMargin = margin;
  140238. iBestSplit = iBestLeft;
  140239. }
  140240. }
  140241. memcpy(pBboxLeft, &aCell[aaSorted[iBestDim][0]], sizeof(RtreeCell));
  140242. memcpy(pBboxRight, &aCell[aaSorted[iBestDim][iBestSplit]], sizeof(RtreeCell));
  140243. for(ii=0; ii<nCell; ii++){
  140244. RtreeNode *pTarget = (ii<iBestSplit)?pLeft:pRight;
  140245. RtreeCell *pBbox = (ii<iBestSplit)?pBboxLeft:pBboxRight;
  140246. RtreeCell *pCell = &aCell[aaSorted[iBestDim][ii]];
  140247. nodeInsertCell(pRtree, pTarget, pCell);
  140248. cellUnion(pRtree, pBbox, pCell);
  140249. }
  140250. sqlite3_free(aaSorted);
  140251. return SQLITE_OK;
  140252. }
  140253. static int updateMapping(
  140254. Rtree *pRtree,
  140255. i64 iRowid,
  140256. RtreeNode *pNode,
  140257. int iHeight
  140258. ){
  140259. int (*xSetMapping)(Rtree *, sqlite3_int64, sqlite3_int64);
  140260. xSetMapping = ((iHeight==0)?rowidWrite:parentWrite);
  140261. if( iHeight>0 ){
  140262. RtreeNode *pChild = nodeHashLookup(pRtree, iRowid);
  140263. if( pChild ){
  140264. nodeRelease(pRtree, pChild->pParent);
  140265. nodeReference(pNode);
  140266. pChild->pParent = pNode;
  140267. }
  140268. }
  140269. return xSetMapping(pRtree, iRowid, pNode->iNode);
  140270. }
  140271. static int SplitNode(
  140272. Rtree *pRtree,
  140273. RtreeNode *pNode,
  140274. RtreeCell *pCell,
  140275. int iHeight
  140276. ){
  140277. int i;
  140278. int newCellIsRight = 0;
  140279. int rc = SQLITE_OK;
  140280. int nCell = NCELL(pNode);
  140281. RtreeCell *aCell;
  140282. int *aiUsed;
  140283. RtreeNode *pLeft = 0;
  140284. RtreeNode *pRight = 0;
  140285. RtreeCell leftbbox;
  140286. RtreeCell rightbbox;
  140287. /* Allocate an array and populate it with a copy of pCell and
  140288. ** all cells from node pLeft. Then zero the original node.
  140289. */
  140290. aCell = sqlite3_malloc((sizeof(RtreeCell)+sizeof(int))*(nCell+1));
  140291. if( !aCell ){
  140292. rc = SQLITE_NOMEM;
  140293. goto splitnode_out;
  140294. }
  140295. aiUsed = (int *)&aCell[nCell+1];
  140296. memset(aiUsed, 0, sizeof(int)*(nCell+1));
  140297. for(i=0; i<nCell; i++){
  140298. nodeGetCell(pRtree, pNode, i, &aCell[i]);
  140299. }
  140300. nodeZero(pRtree, pNode);
  140301. memcpy(&aCell[nCell], pCell, sizeof(RtreeCell));
  140302. nCell++;
  140303. if( pNode->iNode==1 ){
  140304. pRight = nodeNew(pRtree, pNode);
  140305. pLeft = nodeNew(pRtree, pNode);
  140306. pRtree->iDepth++;
  140307. pNode->isDirty = 1;
  140308. writeInt16(pNode->zData, pRtree->iDepth);
  140309. }else{
  140310. pLeft = pNode;
  140311. pRight = nodeNew(pRtree, pLeft->pParent);
  140312. nodeReference(pLeft);
  140313. }
  140314. if( !pLeft || !pRight ){
  140315. rc = SQLITE_NOMEM;
  140316. goto splitnode_out;
  140317. }
  140318. memset(pLeft->zData, 0, pRtree->iNodeSize);
  140319. memset(pRight->zData, 0, pRtree->iNodeSize);
  140320. rc = splitNodeStartree(pRtree, aCell, nCell, pLeft, pRight,
  140321. &leftbbox, &rightbbox);
  140322. if( rc!=SQLITE_OK ){
  140323. goto splitnode_out;
  140324. }
  140325. /* Ensure both child nodes have node numbers assigned to them by calling
  140326. ** nodeWrite(). Node pRight always needs a node number, as it was created
  140327. ** by nodeNew() above. But node pLeft sometimes already has a node number.
  140328. ** In this case avoid the all to nodeWrite().
  140329. */
  140330. if( SQLITE_OK!=(rc = nodeWrite(pRtree, pRight))
  140331. || (0==pLeft->iNode && SQLITE_OK!=(rc = nodeWrite(pRtree, pLeft)))
  140332. ){
  140333. goto splitnode_out;
  140334. }
  140335. rightbbox.iRowid = pRight->iNode;
  140336. leftbbox.iRowid = pLeft->iNode;
  140337. if( pNode->iNode==1 ){
  140338. rc = rtreeInsertCell(pRtree, pLeft->pParent, &leftbbox, iHeight+1);
  140339. if( rc!=SQLITE_OK ){
  140340. goto splitnode_out;
  140341. }
  140342. }else{
  140343. RtreeNode *pParent = pLeft->pParent;
  140344. int iCell;
  140345. rc = nodeParentIndex(pRtree, pLeft, &iCell);
  140346. if( rc==SQLITE_OK ){
  140347. nodeOverwriteCell(pRtree, pParent, &leftbbox, iCell);
  140348. rc = AdjustTree(pRtree, pParent, &leftbbox);
  140349. }
  140350. if( rc!=SQLITE_OK ){
  140351. goto splitnode_out;
  140352. }
  140353. }
  140354. if( (rc = rtreeInsertCell(pRtree, pRight->pParent, &rightbbox, iHeight+1)) ){
  140355. goto splitnode_out;
  140356. }
  140357. for(i=0; i<NCELL(pRight); i++){
  140358. i64 iRowid = nodeGetRowid(pRtree, pRight, i);
  140359. rc = updateMapping(pRtree, iRowid, pRight, iHeight);
  140360. if( iRowid==pCell->iRowid ){
  140361. newCellIsRight = 1;
  140362. }
  140363. if( rc!=SQLITE_OK ){
  140364. goto splitnode_out;
  140365. }
  140366. }
  140367. if( pNode->iNode==1 ){
  140368. for(i=0; i<NCELL(pLeft); i++){
  140369. i64 iRowid = nodeGetRowid(pRtree, pLeft, i);
  140370. rc = updateMapping(pRtree, iRowid, pLeft, iHeight);
  140371. if( rc!=SQLITE_OK ){
  140372. goto splitnode_out;
  140373. }
  140374. }
  140375. }else if( newCellIsRight==0 ){
  140376. rc = updateMapping(pRtree, pCell->iRowid, pLeft, iHeight);
  140377. }
  140378. if( rc==SQLITE_OK ){
  140379. rc = nodeRelease(pRtree, pRight);
  140380. pRight = 0;
  140381. }
  140382. if( rc==SQLITE_OK ){
  140383. rc = nodeRelease(pRtree, pLeft);
  140384. pLeft = 0;
  140385. }
  140386. splitnode_out:
  140387. nodeRelease(pRtree, pRight);
  140388. nodeRelease(pRtree, pLeft);
  140389. sqlite3_free(aCell);
  140390. return rc;
  140391. }
  140392. /*
  140393. ** If node pLeaf is not the root of the r-tree and its pParent pointer is
  140394. ** still NULL, load all ancestor nodes of pLeaf into memory and populate
  140395. ** the pLeaf->pParent chain all the way up to the root node.
  140396. **
  140397. ** This operation is required when a row is deleted (or updated - an update
  140398. ** is implemented as a delete followed by an insert). SQLite provides the
  140399. ** rowid of the row to delete, which can be used to find the leaf on which
  140400. ** the entry resides (argument pLeaf). Once the leaf is located, this
  140401. ** function is called to determine its ancestry.
  140402. */
  140403. static int fixLeafParent(Rtree *pRtree, RtreeNode *pLeaf){
  140404. int rc = SQLITE_OK;
  140405. RtreeNode *pChild = pLeaf;
  140406. while( rc==SQLITE_OK && pChild->iNode!=1 && pChild->pParent==0 ){
  140407. int rc2 = SQLITE_OK; /* sqlite3_reset() return code */
  140408. sqlite3_bind_int64(pRtree->pReadParent, 1, pChild->iNode);
  140409. rc = sqlite3_step(pRtree->pReadParent);
  140410. if( rc==SQLITE_ROW ){
  140411. RtreeNode *pTest; /* Used to test for reference loops */
  140412. i64 iNode; /* Node number of parent node */
  140413. /* Before setting pChild->pParent, test that we are not creating a
  140414. ** loop of references (as we would if, say, pChild==pParent). We don't
  140415. ** want to do this as it leads to a memory leak when trying to delete
  140416. ** the referenced counted node structures.
  140417. */
  140418. iNode = sqlite3_column_int64(pRtree->pReadParent, 0);
  140419. for(pTest=pLeaf; pTest && pTest->iNode!=iNode; pTest=pTest->pParent);
  140420. if( !pTest ){
  140421. rc2 = nodeAcquire(pRtree, iNode, 0, &pChild->pParent);
  140422. }
  140423. }
  140424. rc = sqlite3_reset(pRtree->pReadParent);
  140425. if( rc==SQLITE_OK ) rc = rc2;
  140426. if( rc==SQLITE_OK && !pChild->pParent ) rc = SQLITE_CORRUPT_VTAB;
  140427. pChild = pChild->pParent;
  140428. }
  140429. return rc;
  140430. }
  140431. static int deleteCell(Rtree *, RtreeNode *, int, int);
  140432. static int removeNode(Rtree *pRtree, RtreeNode *pNode, int iHeight){
  140433. int rc;
  140434. int rc2;
  140435. RtreeNode *pParent = 0;
  140436. int iCell;
  140437. assert( pNode->nRef==1 );
  140438. /* Remove the entry in the parent cell. */
  140439. rc = nodeParentIndex(pRtree, pNode, &iCell);
  140440. if( rc==SQLITE_OK ){
  140441. pParent = pNode->pParent;
  140442. pNode->pParent = 0;
  140443. rc = deleteCell(pRtree, pParent, iCell, iHeight+1);
  140444. }
  140445. rc2 = nodeRelease(pRtree, pParent);
  140446. if( rc==SQLITE_OK ){
  140447. rc = rc2;
  140448. }
  140449. if( rc!=SQLITE_OK ){
  140450. return rc;
  140451. }
  140452. /* Remove the xxx_node entry. */
  140453. sqlite3_bind_int64(pRtree->pDeleteNode, 1, pNode->iNode);
  140454. sqlite3_step(pRtree->pDeleteNode);
  140455. if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteNode)) ){
  140456. return rc;
  140457. }
  140458. /* Remove the xxx_parent entry. */
  140459. sqlite3_bind_int64(pRtree->pDeleteParent, 1, pNode->iNode);
  140460. sqlite3_step(pRtree->pDeleteParent);
  140461. if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteParent)) ){
  140462. return rc;
  140463. }
  140464. /* Remove the node from the in-memory hash table and link it into
  140465. ** the Rtree.pDeleted list. Its contents will be re-inserted later on.
  140466. */
  140467. nodeHashDelete(pRtree, pNode);
  140468. pNode->iNode = iHeight;
  140469. pNode->pNext = pRtree->pDeleted;
  140470. pNode->nRef++;
  140471. pRtree->pDeleted = pNode;
  140472. return SQLITE_OK;
  140473. }
  140474. static int fixBoundingBox(Rtree *pRtree, RtreeNode *pNode){
  140475. RtreeNode *pParent = pNode->pParent;
  140476. int rc = SQLITE_OK;
  140477. if( pParent ){
  140478. int ii;
  140479. int nCell = NCELL(pNode);
  140480. RtreeCell box; /* Bounding box for pNode */
  140481. nodeGetCell(pRtree, pNode, 0, &box);
  140482. for(ii=1; ii<nCell; ii++){
  140483. RtreeCell cell;
  140484. nodeGetCell(pRtree, pNode, ii, &cell);
  140485. cellUnion(pRtree, &box, &cell);
  140486. }
  140487. box.iRowid = pNode->iNode;
  140488. rc = nodeParentIndex(pRtree, pNode, &ii);
  140489. if( rc==SQLITE_OK ){
  140490. nodeOverwriteCell(pRtree, pParent, &box, ii);
  140491. rc = fixBoundingBox(pRtree, pParent);
  140492. }
  140493. }
  140494. return rc;
  140495. }
  140496. /*
  140497. ** Delete the cell at index iCell of node pNode. After removing the
  140498. ** cell, adjust the r-tree data structure if required.
  140499. */
  140500. static int deleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell, int iHeight){
  140501. RtreeNode *pParent;
  140502. int rc;
  140503. if( SQLITE_OK!=(rc = fixLeafParent(pRtree, pNode)) ){
  140504. return rc;
  140505. }
  140506. /* Remove the cell from the node. This call just moves bytes around
  140507. ** the in-memory node image, so it cannot fail.
  140508. */
  140509. nodeDeleteCell(pRtree, pNode, iCell);
  140510. /* If the node is not the tree root and now has less than the minimum
  140511. ** number of cells, remove it from the tree. Otherwise, update the
  140512. ** cell in the parent node so that it tightly contains the updated
  140513. ** node.
  140514. */
  140515. pParent = pNode->pParent;
  140516. assert( pParent || pNode->iNode==1 );
  140517. if( pParent ){
  140518. if( NCELL(pNode)<RTREE_MINCELLS(pRtree) ){
  140519. rc = removeNode(pRtree, pNode, iHeight);
  140520. }else{
  140521. rc = fixBoundingBox(pRtree, pNode);
  140522. }
  140523. }
  140524. return rc;
  140525. }
  140526. static int Reinsert(
  140527. Rtree *pRtree,
  140528. RtreeNode *pNode,
  140529. RtreeCell *pCell,
  140530. int iHeight
  140531. ){
  140532. int *aOrder;
  140533. int *aSpare;
  140534. RtreeCell *aCell;
  140535. RtreeDValue *aDistance;
  140536. int nCell;
  140537. RtreeDValue aCenterCoord[RTREE_MAX_DIMENSIONS];
  140538. int iDim;
  140539. int ii;
  140540. int rc = SQLITE_OK;
  140541. int n;
  140542. memset(aCenterCoord, 0, sizeof(RtreeDValue)*RTREE_MAX_DIMENSIONS);
  140543. nCell = NCELL(pNode)+1;
  140544. n = (nCell+1)&(~1);
  140545. /* Allocate the buffers used by this operation. The allocation is
  140546. ** relinquished before this function returns.
  140547. */
  140548. aCell = (RtreeCell *)sqlite3_malloc(n * (
  140549. sizeof(RtreeCell) + /* aCell array */
  140550. sizeof(int) + /* aOrder array */
  140551. sizeof(int) + /* aSpare array */
  140552. sizeof(RtreeDValue) /* aDistance array */
  140553. ));
  140554. if( !aCell ){
  140555. return SQLITE_NOMEM;
  140556. }
  140557. aOrder = (int *)&aCell[n];
  140558. aSpare = (int *)&aOrder[n];
  140559. aDistance = (RtreeDValue *)&aSpare[n];
  140560. for(ii=0; ii<nCell; ii++){
  140561. if( ii==(nCell-1) ){
  140562. memcpy(&aCell[ii], pCell, sizeof(RtreeCell));
  140563. }else{
  140564. nodeGetCell(pRtree, pNode, ii, &aCell[ii]);
  140565. }
  140566. aOrder[ii] = ii;
  140567. for(iDim=0; iDim<pRtree->nDim; iDim++){
  140568. aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2]);
  140569. aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2+1]);
  140570. }
  140571. }
  140572. for(iDim=0; iDim<pRtree->nDim; iDim++){
  140573. aCenterCoord[iDim] = (aCenterCoord[iDim]/(nCell*(RtreeDValue)2));
  140574. }
  140575. for(ii=0; ii<nCell; ii++){
  140576. aDistance[ii] = RTREE_ZERO;
  140577. for(iDim=0; iDim<pRtree->nDim; iDim++){
  140578. RtreeDValue coord = (DCOORD(aCell[ii].aCoord[iDim*2+1]) -
  140579. DCOORD(aCell[ii].aCoord[iDim*2]));
  140580. aDistance[ii] += (coord-aCenterCoord[iDim])*(coord-aCenterCoord[iDim]);
  140581. }
  140582. }
  140583. SortByDistance(aOrder, nCell, aDistance, aSpare);
  140584. nodeZero(pRtree, pNode);
  140585. for(ii=0; rc==SQLITE_OK && ii<(nCell-(RTREE_MINCELLS(pRtree)+1)); ii++){
  140586. RtreeCell *p = &aCell[aOrder[ii]];
  140587. nodeInsertCell(pRtree, pNode, p);
  140588. if( p->iRowid==pCell->iRowid ){
  140589. if( iHeight==0 ){
  140590. rc = rowidWrite(pRtree, p->iRowid, pNode->iNode);
  140591. }else{
  140592. rc = parentWrite(pRtree, p->iRowid, pNode->iNode);
  140593. }
  140594. }
  140595. }
  140596. if( rc==SQLITE_OK ){
  140597. rc = fixBoundingBox(pRtree, pNode);
  140598. }
  140599. for(; rc==SQLITE_OK && ii<nCell; ii++){
  140600. /* Find a node to store this cell in. pNode->iNode currently contains
  140601. ** the height of the sub-tree headed by the cell.
  140602. */
  140603. RtreeNode *pInsert;
  140604. RtreeCell *p = &aCell[aOrder[ii]];
  140605. rc = ChooseLeaf(pRtree, p, iHeight, &pInsert);
  140606. if( rc==SQLITE_OK ){
  140607. int rc2;
  140608. rc = rtreeInsertCell(pRtree, pInsert, p, iHeight);
  140609. rc2 = nodeRelease(pRtree, pInsert);
  140610. if( rc==SQLITE_OK ){
  140611. rc = rc2;
  140612. }
  140613. }
  140614. }
  140615. sqlite3_free(aCell);
  140616. return rc;
  140617. }
  140618. /*
  140619. ** Insert cell pCell into node pNode. Node pNode is the head of a
  140620. ** subtree iHeight high (leaf nodes have iHeight==0).
  140621. */
  140622. static int rtreeInsertCell(
  140623. Rtree *pRtree,
  140624. RtreeNode *pNode,
  140625. RtreeCell *pCell,
  140626. int iHeight
  140627. ){
  140628. int rc = SQLITE_OK;
  140629. if( iHeight>0 ){
  140630. RtreeNode *pChild = nodeHashLookup(pRtree, pCell->iRowid);
  140631. if( pChild ){
  140632. nodeRelease(pRtree, pChild->pParent);
  140633. nodeReference(pNode);
  140634. pChild->pParent = pNode;
  140635. }
  140636. }
  140637. if( nodeInsertCell(pRtree, pNode, pCell) ){
  140638. if( iHeight<=pRtree->iReinsertHeight || pNode->iNode==1){
  140639. rc = SplitNode(pRtree, pNode, pCell, iHeight);
  140640. }else{
  140641. pRtree->iReinsertHeight = iHeight;
  140642. rc = Reinsert(pRtree, pNode, pCell, iHeight);
  140643. }
  140644. }else{
  140645. rc = AdjustTree(pRtree, pNode, pCell);
  140646. if( rc==SQLITE_OK ){
  140647. if( iHeight==0 ){
  140648. rc = rowidWrite(pRtree, pCell->iRowid, pNode->iNode);
  140649. }else{
  140650. rc = parentWrite(pRtree, pCell->iRowid, pNode->iNode);
  140651. }
  140652. }
  140653. }
  140654. return rc;
  140655. }
  140656. static int reinsertNodeContent(Rtree *pRtree, RtreeNode *pNode){
  140657. int ii;
  140658. int rc = SQLITE_OK;
  140659. int nCell = NCELL(pNode);
  140660. for(ii=0; rc==SQLITE_OK && ii<nCell; ii++){
  140661. RtreeNode *pInsert;
  140662. RtreeCell cell;
  140663. nodeGetCell(pRtree, pNode, ii, &cell);
  140664. /* Find a node to store this cell in. pNode->iNode currently contains
  140665. ** the height of the sub-tree headed by the cell.
  140666. */
  140667. rc = ChooseLeaf(pRtree, &cell, (int)pNode->iNode, &pInsert);
  140668. if( rc==SQLITE_OK ){
  140669. int rc2;
  140670. rc = rtreeInsertCell(pRtree, pInsert, &cell, (int)pNode->iNode);
  140671. rc2 = nodeRelease(pRtree, pInsert);
  140672. if( rc==SQLITE_OK ){
  140673. rc = rc2;
  140674. }
  140675. }
  140676. }
  140677. return rc;
  140678. }
  140679. /*
  140680. ** Select a currently unused rowid for a new r-tree record.
  140681. */
  140682. static int newRowid(Rtree *pRtree, i64 *piRowid){
  140683. int rc;
  140684. sqlite3_bind_null(pRtree->pWriteRowid, 1);
  140685. sqlite3_bind_null(pRtree->pWriteRowid, 2);
  140686. sqlite3_step(pRtree->pWriteRowid);
  140687. rc = sqlite3_reset(pRtree->pWriteRowid);
  140688. *piRowid = sqlite3_last_insert_rowid(pRtree->db);
  140689. return rc;
  140690. }
  140691. /*
  140692. ** Remove the entry with rowid=iDelete from the r-tree structure.
  140693. */
  140694. static int rtreeDeleteRowid(Rtree *pRtree, sqlite3_int64 iDelete){
  140695. int rc; /* Return code */
  140696. RtreeNode *pLeaf = 0; /* Leaf node containing record iDelete */
  140697. int iCell; /* Index of iDelete cell in pLeaf */
  140698. RtreeNode *pRoot; /* Root node of rtree structure */
  140699. /* Obtain a reference to the root node to initialize Rtree.iDepth */
  140700. rc = nodeAcquire(pRtree, 1, 0, &pRoot);
  140701. /* Obtain a reference to the leaf node that contains the entry
  140702. ** about to be deleted.
  140703. */
  140704. if( rc==SQLITE_OK ){
  140705. rc = findLeafNode(pRtree, iDelete, &pLeaf, 0);
  140706. }
  140707. /* Delete the cell in question from the leaf node. */
  140708. if( rc==SQLITE_OK ){
  140709. int rc2;
  140710. rc = nodeRowidIndex(pRtree, pLeaf, iDelete, &iCell);
  140711. if( rc==SQLITE_OK ){
  140712. rc = deleteCell(pRtree, pLeaf, iCell, 0);
  140713. }
  140714. rc2 = nodeRelease(pRtree, pLeaf);
  140715. if( rc==SQLITE_OK ){
  140716. rc = rc2;
  140717. }
  140718. }
  140719. /* Delete the corresponding entry in the <rtree>_rowid table. */
  140720. if( rc==SQLITE_OK ){
  140721. sqlite3_bind_int64(pRtree->pDeleteRowid, 1, iDelete);
  140722. sqlite3_step(pRtree->pDeleteRowid);
  140723. rc = sqlite3_reset(pRtree->pDeleteRowid);
  140724. }
  140725. /* Check if the root node now has exactly one child. If so, remove
  140726. ** it, schedule the contents of the child for reinsertion and
  140727. ** reduce the tree height by one.
  140728. **
  140729. ** This is equivalent to copying the contents of the child into
  140730. ** the root node (the operation that Gutman's paper says to perform
  140731. ** in this scenario).
  140732. */
  140733. if( rc==SQLITE_OK && pRtree->iDepth>0 && NCELL(pRoot)==1 ){
  140734. int rc2;
  140735. RtreeNode *pChild;
  140736. i64 iChild = nodeGetRowid(pRtree, pRoot, 0);
  140737. rc = nodeAcquire(pRtree, iChild, pRoot, &pChild);
  140738. if( rc==SQLITE_OK ){
  140739. rc = removeNode(pRtree, pChild, pRtree->iDepth-1);
  140740. }
  140741. rc2 = nodeRelease(pRtree, pChild);
  140742. if( rc==SQLITE_OK ) rc = rc2;
  140743. if( rc==SQLITE_OK ){
  140744. pRtree->iDepth--;
  140745. writeInt16(pRoot->zData, pRtree->iDepth);
  140746. pRoot->isDirty = 1;
  140747. }
  140748. }
  140749. /* Re-insert the contents of any underfull nodes removed from the tree. */
  140750. for(pLeaf=pRtree->pDeleted; pLeaf; pLeaf=pRtree->pDeleted){
  140751. if( rc==SQLITE_OK ){
  140752. rc = reinsertNodeContent(pRtree, pLeaf);
  140753. }
  140754. pRtree->pDeleted = pLeaf->pNext;
  140755. sqlite3_free(pLeaf);
  140756. }
  140757. /* Release the reference to the root node. */
  140758. if( rc==SQLITE_OK ){
  140759. rc = nodeRelease(pRtree, pRoot);
  140760. }else{
  140761. nodeRelease(pRtree, pRoot);
  140762. }
  140763. return rc;
  140764. }
  140765. /*
  140766. ** Rounding constants for float->double conversion.
  140767. */
  140768. #define RNDTOWARDS (1.0 - 1.0/8388608.0) /* Round towards zero */
  140769. #define RNDAWAY (1.0 + 1.0/8388608.0) /* Round away from zero */
  140770. #if !defined(SQLITE_RTREE_INT_ONLY)
  140771. /*
  140772. ** Convert an sqlite3_value into an RtreeValue (presumably a float)
  140773. ** while taking care to round toward negative or positive, respectively.
  140774. */
  140775. static RtreeValue rtreeValueDown(sqlite3_value *v){
  140776. double d = sqlite3_value_double(v);
  140777. float f = (float)d;
  140778. if( f>d ){
  140779. f = (float)(d*(d<0 ? RNDAWAY : RNDTOWARDS));
  140780. }
  140781. return f;
  140782. }
  140783. static RtreeValue rtreeValueUp(sqlite3_value *v){
  140784. double d = sqlite3_value_double(v);
  140785. float f = (float)d;
  140786. if( f<d ){
  140787. f = (float)(d*(d<0 ? RNDTOWARDS : RNDAWAY));
  140788. }
  140789. return f;
  140790. }
  140791. #endif /* !defined(SQLITE_RTREE_INT_ONLY) */
  140792. /*
  140793. ** The xUpdate method for rtree module virtual tables.
  140794. */
  140795. static int rtreeUpdate(
  140796. sqlite3_vtab *pVtab,
  140797. int nData,
  140798. sqlite3_value **azData,
  140799. sqlite_int64 *pRowid
  140800. ){
  140801. Rtree *pRtree = (Rtree *)pVtab;
  140802. int rc = SQLITE_OK;
  140803. RtreeCell cell; /* New cell to insert if nData>1 */
  140804. int bHaveRowid = 0; /* Set to 1 after new rowid is determined */
  140805. rtreeReference(pRtree);
  140806. assert(nData>=1);
  140807. /* Constraint handling. A write operation on an r-tree table may return
  140808. ** SQLITE_CONSTRAINT for two reasons:
  140809. **
  140810. ** 1. A duplicate rowid value, or
  140811. ** 2. The supplied data violates the "x2>=x1" constraint.
  140812. **
  140813. ** In the first case, if the conflict-handling mode is REPLACE, then
  140814. ** the conflicting row can be removed before proceeding. In the second
  140815. ** case, SQLITE_CONSTRAINT must be returned regardless of the
  140816. ** conflict-handling mode specified by the user.
  140817. */
  140818. if( nData>1 ){
  140819. int ii;
  140820. /* Populate the cell.aCoord[] array. The first coordinate is azData[3]. */
  140821. assert( nData==(pRtree->nDim*2 + 3) );
  140822. #ifndef SQLITE_RTREE_INT_ONLY
  140823. if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
  140824. for(ii=0; ii<(pRtree->nDim*2); ii+=2){
  140825. cell.aCoord[ii].f = rtreeValueDown(azData[ii+3]);
  140826. cell.aCoord[ii+1].f = rtreeValueUp(azData[ii+4]);
  140827. if( cell.aCoord[ii].f>cell.aCoord[ii+1].f ){
  140828. rc = SQLITE_CONSTRAINT;
  140829. goto constraint;
  140830. }
  140831. }
  140832. }else
  140833. #endif
  140834. {
  140835. for(ii=0; ii<(pRtree->nDim*2); ii+=2){
  140836. cell.aCoord[ii].i = sqlite3_value_int(azData[ii+3]);
  140837. cell.aCoord[ii+1].i = sqlite3_value_int(azData[ii+4]);
  140838. if( cell.aCoord[ii].i>cell.aCoord[ii+1].i ){
  140839. rc = SQLITE_CONSTRAINT;
  140840. goto constraint;
  140841. }
  140842. }
  140843. }
  140844. /* If a rowid value was supplied, check if it is already present in
  140845. ** the table. If so, the constraint has failed. */
  140846. if( sqlite3_value_type(azData[2])!=SQLITE_NULL ){
  140847. cell.iRowid = sqlite3_value_int64(azData[2]);
  140848. if( sqlite3_value_type(azData[0])==SQLITE_NULL
  140849. || sqlite3_value_int64(azData[0])!=cell.iRowid
  140850. ){
  140851. int steprc;
  140852. sqlite3_bind_int64(pRtree->pReadRowid, 1, cell.iRowid);
  140853. steprc = sqlite3_step(pRtree->pReadRowid);
  140854. rc = sqlite3_reset(pRtree->pReadRowid);
  140855. if( SQLITE_ROW==steprc ){
  140856. if( sqlite3_vtab_on_conflict(pRtree->db)==SQLITE_REPLACE ){
  140857. rc = rtreeDeleteRowid(pRtree, cell.iRowid);
  140858. }else{
  140859. rc = SQLITE_CONSTRAINT;
  140860. goto constraint;
  140861. }
  140862. }
  140863. }
  140864. bHaveRowid = 1;
  140865. }
  140866. }
  140867. /* If azData[0] is not an SQL NULL value, it is the rowid of a
  140868. ** record to delete from the r-tree table. The following block does
  140869. ** just that.
  140870. */
  140871. if( sqlite3_value_type(azData[0])!=SQLITE_NULL ){
  140872. rc = rtreeDeleteRowid(pRtree, sqlite3_value_int64(azData[0]));
  140873. }
  140874. /* If the azData[] array contains more than one element, elements
  140875. ** (azData[2]..azData[argc-1]) contain a new record to insert into
  140876. ** the r-tree structure.
  140877. */
  140878. if( rc==SQLITE_OK && nData>1 ){
  140879. /* Insert the new record into the r-tree */
  140880. RtreeNode *pLeaf = 0;
  140881. /* Figure out the rowid of the new row. */
  140882. if( bHaveRowid==0 ){
  140883. rc = newRowid(pRtree, &cell.iRowid);
  140884. }
  140885. *pRowid = cell.iRowid;
  140886. if( rc==SQLITE_OK ){
  140887. rc = ChooseLeaf(pRtree, &cell, 0, &pLeaf);
  140888. }
  140889. if( rc==SQLITE_OK ){
  140890. int rc2;
  140891. pRtree->iReinsertHeight = -1;
  140892. rc = rtreeInsertCell(pRtree, pLeaf, &cell, 0);
  140893. rc2 = nodeRelease(pRtree, pLeaf);
  140894. if( rc==SQLITE_OK ){
  140895. rc = rc2;
  140896. }
  140897. }
  140898. }
  140899. constraint:
  140900. rtreeRelease(pRtree);
  140901. return rc;
  140902. }
  140903. /*
  140904. ** The xRename method for rtree module virtual tables.
  140905. */
  140906. static int rtreeRename(sqlite3_vtab *pVtab, const char *zNewName){
  140907. Rtree *pRtree = (Rtree *)pVtab;
  140908. int rc = SQLITE_NOMEM;
  140909. char *zSql = sqlite3_mprintf(
  140910. "ALTER TABLE %Q.'%q_node' RENAME TO \"%w_node\";"
  140911. "ALTER TABLE %Q.'%q_parent' RENAME TO \"%w_parent\";"
  140912. "ALTER TABLE %Q.'%q_rowid' RENAME TO \"%w_rowid\";"
  140913. , pRtree->zDb, pRtree->zName, zNewName
  140914. , pRtree->zDb, pRtree->zName, zNewName
  140915. , pRtree->zDb, pRtree->zName, zNewName
  140916. );
  140917. if( zSql ){
  140918. rc = sqlite3_exec(pRtree->db, zSql, 0, 0, 0);
  140919. sqlite3_free(zSql);
  140920. }
  140921. return rc;
  140922. }
  140923. /*
  140924. ** This function populates the pRtree->nRowEst variable with an estimate
  140925. ** of the number of rows in the virtual table. If possible, this is based
  140926. ** on sqlite_stat1 data. Otherwise, use RTREE_DEFAULT_ROWEST.
  140927. */
  140928. static int rtreeQueryStat1(sqlite3 *db, Rtree *pRtree){
  140929. const char *zFmt = "SELECT stat FROM %Q.sqlite_stat1 WHERE tbl = '%q_rowid'";
  140930. char *zSql;
  140931. sqlite3_stmt *p;
  140932. int rc;
  140933. i64 nRow = 0;
  140934. zSql = sqlite3_mprintf(zFmt, pRtree->zDb, pRtree->zName);
  140935. if( zSql==0 ){
  140936. rc = SQLITE_NOMEM;
  140937. }else{
  140938. rc = sqlite3_prepare_v2(db, zSql, -1, &p, 0);
  140939. if( rc==SQLITE_OK ){
  140940. if( sqlite3_step(p)==SQLITE_ROW ) nRow = sqlite3_column_int64(p, 0);
  140941. rc = sqlite3_finalize(p);
  140942. }else if( rc!=SQLITE_NOMEM ){
  140943. rc = SQLITE_OK;
  140944. }
  140945. if( rc==SQLITE_OK ){
  140946. if( nRow==0 ){
  140947. pRtree->nRowEst = RTREE_DEFAULT_ROWEST;
  140948. }else{
  140949. pRtree->nRowEst = MAX(nRow, RTREE_MIN_ROWEST);
  140950. }
  140951. }
  140952. sqlite3_free(zSql);
  140953. }
  140954. return rc;
  140955. }
  140956. static sqlite3_module rtreeModule = {
  140957. 0, /* iVersion */
  140958. rtreeCreate, /* xCreate - create a table */
  140959. rtreeConnect, /* xConnect - connect to an existing table */
  140960. rtreeBestIndex, /* xBestIndex - Determine search strategy */
  140961. rtreeDisconnect, /* xDisconnect - Disconnect from a table */
  140962. rtreeDestroy, /* xDestroy - Drop a table */
  140963. rtreeOpen, /* xOpen - open a cursor */
  140964. rtreeClose, /* xClose - close a cursor */
  140965. rtreeFilter, /* xFilter - configure scan constraints */
  140966. rtreeNext, /* xNext - advance a cursor */
  140967. rtreeEof, /* xEof */
  140968. rtreeColumn, /* xColumn - read data */
  140969. rtreeRowid, /* xRowid - read data */
  140970. rtreeUpdate, /* xUpdate - write data */
  140971. 0, /* xBegin - begin transaction */
  140972. 0, /* xSync - sync transaction */
  140973. 0, /* xCommit - commit transaction */
  140974. 0, /* xRollback - rollback transaction */
  140975. 0, /* xFindFunction - function overloading */
  140976. rtreeRename, /* xRename - rename the table */
  140977. 0, /* xSavepoint */
  140978. 0, /* xRelease */
  140979. 0 /* xRollbackTo */
  140980. };
  140981. static int rtreeSqlInit(
  140982. Rtree *pRtree,
  140983. sqlite3 *db,
  140984. const char *zDb,
  140985. const char *zPrefix,
  140986. int isCreate
  140987. ){
  140988. int rc = SQLITE_OK;
  140989. #define N_STATEMENT 9
  140990. static const char *azSql[N_STATEMENT] = {
  140991. /* Read and write the xxx_node table */
  140992. "SELECT data FROM '%q'.'%q_node' WHERE nodeno = :1",
  140993. "INSERT OR REPLACE INTO '%q'.'%q_node' VALUES(:1, :2)",
  140994. "DELETE FROM '%q'.'%q_node' WHERE nodeno = :1",
  140995. /* Read and write the xxx_rowid table */
  140996. "SELECT nodeno FROM '%q'.'%q_rowid' WHERE rowid = :1",
  140997. "INSERT OR REPLACE INTO '%q'.'%q_rowid' VALUES(:1, :2)",
  140998. "DELETE FROM '%q'.'%q_rowid' WHERE rowid = :1",
  140999. /* Read and write the xxx_parent table */
  141000. "SELECT parentnode FROM '%q'.'%q_parent' WHERE nodeno = :1",
  141001. "INSERT OR REPLACE INTO '%q'.'%q_parent' VALUES(:1, :2)",
  141002. "DELETE FROM '%q'.'%q_parent' WHERE nodeno = :1"
  141003. };
  141004. sqlite3_stmt **appStmt[N_STATEMENT];
  141005. int i;
  141006. pRtree->db = db;
  141007. if( isCreate ){
  141008. char *zCreate = sqlite3_mprintf(
  141009. "CREATE TABLE \"%w\".\"%w_node\"(nodeno INTEGER PRIMARY KEY, data BLOB);"
  141010. "CREATE TABLE \"%w\".\"%w_rowid\"(rowid INTEGER PRIMARY KEY, nodeno INTEGER);"
  141011. "CREATE TABLE \"%w\".\"%w_parent\"(nodeno INTEGER PRIMARY KEY,"
  141012. " parentnode INTEGER);"
  141013. "INSERT INTO '%q'.'%q_node' VALUES(1, zeroblob(%d))",
  141014. zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, pRtree->iNodeSize
  141015. );
  141016. if( !zCreate ){
  141017. return SQLITE_NOMEM;
  141018. }
  141019. rc = sqlite3_exec(db, zCreate, 0, 0, 0);
  141020. sqlite3_free(zCreate);
  141021. if( rc!=SQLITE_OK ){
  141022. return rc;
  141023. }
  141024. }
  141025. appStmt[0] = &pRtree->pReadNode;
  141026. appStmt[1] = &pRtree->pWriteNode;
  141027. appStmt[2] = &pRtree->pDeleteNode;
  141028. appStmt[3] = &pRtree->pReadRowid;
  141029. appStmt[4] = &pRtree->pWriteRowid;
  141030. appStmt[5] = &pRtree->pDeleteRowid;
  141031. appStmt[6] = &pRtree->pReadParent;
  141032. appStmt[7] = &pRtree->pWriteParent;
  141033. appStmt[8] = &pRtree->pDeleteParent;
  141034. rc = rtreeQueryStat1(db, pRtree);
  141035. for(i=0; i<N_STATEMENT && rc==SQLITE_OK; i++){
  141036. char *zSql = sqlite3_mprintf(azSql[i], zDb, zPrefix);
  141037. if( zSql ){
  141038. rc = sqlite3_prepare_v2(db, zSql, -1, appStmt[i], 0);
  141039. }else{
  141040. rc = SQLITE_NOMEM;
  141041. }
  141042. sqlite3_free(zSql);
  141043. }
  141044. return rc;
  141045. }
  141046. /*
  141047. ** The second argument to this function contains the text of an SQL statement
  141048. ** that returns a single integer value. The statement is compiled and executed
  141049. ** using database connection db. If successful, the integer value returned
  141050. ** is written to *piVal and SQLITE_OK returned. Otherwise, an SQLite error
  141051. ** code is returned and the value of *piVal after returning is not defined.
  141052. */
  141053. static int getIntFromStmt(sqlite3 *db, const char *zSql, int *piVal){
  141054. int rc = SQLITE_NOMEM;
  141055. if( zSql ){
  141056. sqlite3_stmt *pStmt = 0;
  141057. rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
  141058. if( rc==SQLITE_OK ){
  141059. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  141060. *piVal = sqlite3_column_int(pStmt, 0);
  141061. }
  141062. rc = sqlite3_finalize(pStmt);
  141063. }
  141064. }
  141065. return rc;
  141066. }
  141067. /*
  141068. ** This function is called from within the xConnect() or xCreate() method to
  141069. ** determine the node-size used by the rtree table being created or connected
  141070. ** to. If successful, pRtree->iNodeSize is populated and SQLITE_OK returned.
  141071. ** Otherwise, an SQLite error code is returned.
  141072. **
  141073. ** If this function is being called as part of an xConnect(), then the rtree
  141074. ** table already exists. In this case the node-size is determined by inspecting
  141075. ** the root node of the tree.
  141076. **
  141077. ** Otherwise, for an xCreate(), use 64 bytes less than the database page-size.
  141078. ** This ensures that each node is stored on a single database page. If the
  141079. ** database page-size is so large that more than RTREE_MAXCELLS entries
  141080. ** would fit in a single node, use a smaller node-size.
  141081. */
  141082. static int getNodeSize(
  141083. sqlite3 *db, /* Database handle */
  141084. Rtree *pRtree, /* Rtree handle */
  141085. int isCreate, /* True for xCreate, false for xConnect */
  141086. char **pzErr /* OUT: Error message, if any */
  141087. ){
  141088. int rc;
  141089. char *zSql;
  141090. if( isCreate ){
  141091. int iPageSize = 0;
  141092. zSql = sqlite3_mprintf("PRAGMA %Q.page_size", pRtree->zDb);
  141093. rc = getIntFromStmt(db, zSql, &iPageSize);
  141094. if( rc==SQLITE_OK ){
  141095. pRtree->iNodeSize = iPageSize-64;
  141096. if( (4+pRtree->nBytesPerCell*RTREE_MAXCELLS)<pRtree->iNodeSize ){
  141097. pRtree->iNodeSize = 4+pRtree->nBytesPerCell*RTREE_MAXCELLS;
  141098. }
  141099. }else{
  141100. *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  141101. }
  141102. }else{
  141103. zSql = sqlite3_mprintf(
  141104. "SELECT length(data) FROM '%q'.'%q_node' WHERE nodeno = 1",
  141105. pRtree->zDb, pRtree->zName
  141106. );
  141107. rc = getIntFromStmt(db, zSql, &pRtree->iNodeSize);
  141108. if( rc!=SQLITE_OK ){
  141109. *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  141110. }
  141111. }
  141112. sqlite3_free(zSql);
  141113. return rc;
  141114. }
  141115. /*
  141116. ** This function is the implementation of both the xConnect and xCreate
  141117. ** methods of the r-tree virtual table.
  141118. **
  141119. ** argv[0] -> module name
  141120. ** argv[1] -> database name
  141121. ** argv[2] -> table name
  141122. ** argv[...] -> column names...
  141123. */
  141124. static int rtreeInit(
  141125. sqlite3 *db, /* Database connection */
  141126. void *pAux, /* One of the RTREE_COORD_* constants */
  141127. int argc, const char *const*argv, /* Parameters to CREATE TABLE statement */
  141128. sqlite3_vtab **ppVtab, /* OUT: New virtual table */
  141129. char **pzErr, /* OUT: Error message, if any */
  141130. int isCreate /* True for xCreate, false for xConnect */
  141131. ){
  141132. int rc = SQLITE_OK;
  141133. Rtree *pRtree;
  141134. int nDb; /* Length of string argv[1] */
  141135. int nName; /* Length of string argv[2] */
  141136. int eCoordType = (pAux ? RTREE_COORD_INT32 : RTREE_COORD_REAL32);
  141137. const char *aErrMsg[] = {
  141138. 0, /* 0 */
  141139. "Wrong number of columns for an rtree table", /* 1 */
  141140. "Too few columns for an rtree table", /* 2 */
  141141. "Too many columns for an rtree table" /* 3 */
  141142. };
  141143. int iErr = (argc<6) ? 2 : argc>(RTREE_MAX_DIMENSIONS*2+4) ? 3 : argc%2;
  141144. if( aErrMsg[iErr] ){
  141145. *pzErr = sqlite3_mprintf("%s", aErrMsg[iErr]);
  141146. return SQLITE_ERROR;
  141147. }
  141148. sqlite3_vtab_config(db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1);
  141149. /* Allocate the sqlite3_vtab structure */
  141150. nDb = (int)strlen(argv[1]);
  141151. nName = (int)strlen(argv[2]);
  141152. pRtree = (Rtree *)sqlite3_malloc(sizeof(Rtree)+nDb+nName+2);
  141153. if( !pRtree ){
  141154. return SQLITE_NOMEM;
  141155. }
  141156. memset(pRtree, 0, sizeof(Rtree)+nDb+nName+2);
  141157. pRtree->nBusy = 1;
  141158. pRtree->base.pModule = &rtreeModule;
  141159. pRtree->zDb = (char *)&pRtree[1];
  141160. pRtree->zName = &pRtree->zDb[nDb+1];
  141161. pRtree->nDim = (argc-4)/2;
  141162. pRtree->nBytesPerCell = 8 + pRtree->nDim*4*2;
  141163. pRtree->eCoordType = eCoordType;
  141164. memcpy(pRtree->zDb, argv[1], nDb);
  141165. memcpy(pRtree->zName, argv[2], nName);
  141166. /* Figure out the node size to use. */
  141167. rc = getNodeSize(db, pRtree, isCreate, pzErr);
  141168. /* Create/Connect to the underlying relational database schema. If
  141169. ** that is successful, call sqlite3_declare_vtab() to configure
  141170. ** the r-tree table schema.
  141171. */
  141172. if( rc==SQLITE_OK ){
  141173. if( (rc = rtreeSqlInit(pRtree, db, argv[1], argv[2], isCreate)) ){
  141174. *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  141175. }else{
  141176. char *zSql = sqlite3_mprintf("CREATE TABLE x(%s", argv[3]);
  141177. char *zTmp;
  141178. int ii;
  141179. for(ii=4; zSql && ii<argc; ii++){
  141180. zTmp = zSql;
  141181. zSql = sqlite3_mprintf("%s, %s", zTmp, argv[ii]);
  141182. sqlite3_free(zTmp);
  141183. }
  141184. if( zSql ){
  141185. zTmp = zSql;
  141186. zSql = sqlite3_mprintf("%s);", zTmp);
  141187. sqlite3_free(zTmp);
  141188. }
  141189. if( !zSql ){
  141190. rc = SQLITE_NOMEM;
  141191. }else if( SQLITE_OK!=(rc = sqlite3_declare_vtab(db, zSql)) ){
  141192. *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  141193. }
  141194. sqlite3_free(zSql);
  141195. }
  141196. }
  141197. if( rc==SQLITE_OK ){
  141198. *ppVtab = (sqlite3_vtab *)pRtree;
  141199. }else{
  141200. assert( *ppVtab==0 );
  141201. assert( pRtree->nBusy==1 );
  141202. rtreeRelease(pRtree);
  141203. }
  141204. return rc;
  141205. }
  141206. /*
  141207. ** Implementation of a scalar function that decodes r-tree nodes to
  141208. ** human readable strings. This can be used for debugging and analysis.
  141209. **
  141210. ** The scalar function takes two arguments: (1) the number of dimensions
  141211. ** to the rtree (between 1 and 5, inclusive) and (2) a blob of data containing
  141212. ** an r-tree node. For a two-dimensional r-tree structure called "rt", to
  141213. ** deserialize all nodes, a statement like:
  141214. **
  141215. ** SELECT rtreenode(2, data) FROM rt_node;
  141216. **
  141217. ** The human readable string takes the form of a Tcl list with one
  141218. ** entry for each cell in the r-tree node. Each entry is itself a
  141219. ** list, containing the 8-byte rowid/pageno followed by the
  141220. ** <num-dimension>*2 coordinates.
  141221. */
  141222. static void rtreenode(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
  141223. char *zText = 0;
  141224. RtreeNode node;
  141225. Rtree tree;
  141226. int ii;
  141227. UNUSED_PARAMETER(nArg);
  141228. memset(&node, 0, sizeof(RtreeNode));
  141229. memset(&tree, 0, sizeof(Rtree));
  141230. tree.nDim = sqlite3_value_int(apArg[0]);
  141231. tree.nBytesPerCell = 8 + 8 * tree.nDim;
  141232. node.zData = (u8 *)sqlite3_value_blob(apArg[1]);
  141233. for(ii=0; ii<NCELL(&node); ii++){
  141234. char zCell[512];
  141235. int nCell = 0;
  141236. RtreeCell cell;
  141237. int jj;
  141238. nodeGetCell(&tree, &node, ii, &cell);
  141239. sqlite3_snprintf(512-nCell,&zCell[nCell],"%lld", cell.iRowid);
  141240. nCell = (int)strlen(zCell);
  141241. for(jj=0; jj<tree.nDim*2; jj++){
  141242. #ifndef SQLITE_RTREE_INT_ONLY
  141243. sqlite3_snprintf(512-nCell,&zCell[nCell], " %g",
  141244. (double)cell.aCoord[jj].f);
  141245. #else
  141246. sqlite3_snprintf(512-nCell,&zCell[nCell], " %d",
  141247. cell.aCoord[jj].i);
  141248. #endif
  141249. nCell = (int)strlen(zCell);
  141250. }
  141251. if( zText ){
  141252. char *zTextNew = sqlite3_mprintf("%s {%s}", zText, zCell);
  141253. sqlite3_free(zText);
  141254. zText = zTextNew;
  141255. }else{
  141256. zText = sqlite3_mprintf("{%s}", zCell);
  141257. }
  141258. }
  141259. sqlite3_result_text(ctx, zText, -1, sqlite3_free);
  141260. }
  141261. /* This routine implements an SQL function that returns the "depth" parameter
  141262. ** from the front of a blob that is an r-tree node. For example:
  141263. **
  141264. ** SELECT rtreedepth(data) FROM rt_node WHERE nodeno=1;
  141265. **
  141266. ** The depth value is 0 for all nodes other than the root node, and the root
  141267. ** node always has nodeno=1, so the example above is the primary use for this
  141268. ** routine. This routine is intended for testing and analysis only.
  141269. */
  141270. static void rtreedepth(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
  141271. UNUSED_PARAMETER(nArg);
  141272. if( sqlite3_value_type(apArg[0])!=SQLITE_BLOB
  141273. || sqlite3_value_bytes(apArg[0])<2
  141274. ){
  141275. sqlite3_result_error(ctx, "Invalid argument to rtreedepth()", -1);
  141276. }else{
  141277. u8 *zBlob = (u8 *)sqlite3_value_blob(apArg[0]);
  141278. sqlite3_result_int(ctx, readInt16(zBlob));
  141279. }
  141280. }
  141281. /*
  141282. ** Register the r-tree module with database handle db. This creates the
  141283. ** virtual table module "rtree" and the debugging/analysis scalar
  141284. ** function "rtreenode".
  141285. */
  141286. SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db){
  141287. const int utf8 = SQLITE_UTF8;
  141288. int rc;
  141289. rc = sqlite3_create_function(db, "rtreenode", 2, utf8, 0, rtreenode, 0, 0);
  141290. if( rc==SQLITE_OK ){
  141291. rc = sqlite3_create_function(db, "rtreedepth", 1, utf8, 0,rtreedepth, 0, 0);
  141292. }
  141293. if( rc==SQLITE_OK ){
  141294. #ifdef SQLITE_RTREE_INT_ONLY
  141295. void *c = (void *)RTREE_COORD_INT32;
  141296. #else
  141297. void *c = (void *)RTREE_COORD_REAL32;
  141298. #endif
  141299. rc = sqlite3_create_module_v2(db, "rtree", &rtreeModule, c, 0);
  141300. }
  141301. if( rc==SQLITE_OK ){
  141302. void *c = (void *)RTREE_COORD_INT32;
  141303. rc = sqlite3_create_module_v2(db, "rtree_i32", &rtreeModule, c, 0);
  141304. }
  141305. return rc;
  141306. }
  141307. /*
  141308. ** This routine deletes the RtreeGeomCallback object that was attached
  141309. ** one of the SQL functions create by sqlite3_rtree_geometry_callback()
  141310. ** or sqlite3_rtree_query_callback(). In other words, this routine is the
  141311. ** destructor for an RtreeGeomCallback objecct. This routine is called when
  141312. ** the corresponding SQL function is deleted.
  141313. */
  141314. static void rtreeFreeCallback(void *p){
  141315. RtreeGeomCallback *pInfo = (RtreeGeomCallback*)p;
  141316. if( pInfo->xDestructor ) pInfo->xDestructor(pInfo->pContext);
  141317. sqlite3_free(p);
  141318. }
  141319. /*
  141320. ** Each call to sqlite3_rtree_geometry_callback() or
  141321. ** sqlite3_rtree_query_callback() creates an ordinary SQLite
  141322. ** scalar function that is implemented by this routine.
  141323. **
  141324. ** All this function does is construct an RtreeMatchArg object that
  141325. ** contains the geometry-checking callback routines and a list of
  141326. ** parameters to this function, then return that RtreeMatchArg object
  141327. ** as a BLOB.
  141328. **
  141329. ** The R-Tree MATCH operator will read the returned BLOB, deserialize
  141330. ** the RtreeMatchArg object, and use the RtreeMatchArg object to figure
  141331. ** out which elements of the R-Tree should be returned by the query.
  141332. */
  141333. static void geomCallback(sqlite3_context *ctx, int nArg, sqlite3_value **aArg){
  141334. RtreeGeomCallback *pGeomCtx = (RtreeGeomCallback *)sqlite3_user_data(ctx);
  141335. RtreeMatchArg *pBlob;
  141336. int nBlob;
  141337. nBlob = sizeof(RtreeMatchArg) + (nArg-1)*sizeof(RtreeDValue);
  141338. pBlob = (RtreeMatchArg *)sqlite3_malloc(nBlob);
  141339. if( !pBlob ){
  141340. sqlite3_result_error_nomem(ctx);
  141341. }else{
  141342. int i;
  141343. pBlob->magic = RTREE_GEOMETRY_MAGIC;
  141344. pBlob->cb = pGeomCtx[0];
  141345. pBlob->nParam = nArg;
  141346. for(i=0; i<nArg; i++){
  141347. #ifdef SQLITE_RTREE_INT_ONLY
  141348. pBlob->aParam[i] = sqlite3_value_int64(aArg[i]);
  141349. #else
  141350. pBlob->aParam[i] = sqlite3_value_double(aArg[i]);
  141351. #endif
  141352. }
  141353. sqlite3_result_blob(ctx, pBlob, nBlob, sqlite3_free);
  141354. }
  141355. }
  141356. /*
  141357. ** Register a new geometry function for use with the r-tree MATCH operator.
  141358. */
  141359. SQLITE_API int sqlite3_rtree_geometry_callback(
  141360. sqlite3 *db, /* Register SQL function on this connection */
  141361. const char *zGeom, /* Name of the new SQL function */
  141362. int (*xGeom)(sqlite3_rtree_geometry*,int,RtreeDValue*,int*), /* Callback */
  141363. void *pContext /* Extra data associated with the callback */
  141364. ){
  141365. RtreeGeomCallback *pGeomCtx; /* Context object for new user-function */
  141366. /* Allocate and populate the context object. */
  141367. pGeomCtx = (RtreeGeomCallback *)sqlite3_malloc(sizeof(RtreeGeomCallback));
  141368. if( !pGeomCtx ) return SQLITE_NOMEM;
  141369. pGeomCtx->xGeom = xGeom;
  141370. pGeomCtx->xQueryFunc = 0;
  141371. pGeomCtx->xDestructor = 0;
  141372. pGeomCtx->pContext = pContext;
  141373. return sqlite3_create_function_v2(db, zGeom, -1, SQLITE_ANY,
  141374. (void *)pGeomCtx, geomCallback, 0, 0, rtreeFreeCallback
  141375. );
  141376. }
  141377. /*
  141378. ** Register a new 2nd-generation geometry function for use with the
  141379. ** r-tree MATCH operator.
  141380. */
  141381. SQLITE_API int sqlite3_rtree_query_callback(
  141382. sqlite3 *db, /* Register SQL function on this connection */
  141383. const char *zQueryFunc, /* Name of new SQL function */
  141384. int (*xQueryFunc)(sqlite3_rtree_query_info*), /* Callback */
  141385. void *pContext, /* Extra data passed into the callback */
  141386. void (*xDestructor)(void*) /* Destructor for the extra data */
  141387. ){
  141388. RtreeGeomCallback *pGeomCtx; /* Context object for new user-function */
  141389. /* Allocate and populate the context object. */
  141390. pGeomCtx = (RtreeGeomCallback *)sqlite3_malloc(sizeof(RtreeGeomCallback));
  141391. if( !pGeomCtx ) return SQLITE_NOMEM;
  141392. pGeomCtx->xGeom = 0;
  141393. pGeomCtx->xQueryFunc = xQueryFunc;
  141394. pGeomCtx->xDestructor = xDestructor;
  141395. pGeomCtx->pContext = pContext;
  141396. return sqlite3_create_function_v2(db, zQueryFunc, -1, SQLITE_ANY,
  141397. (void *)pGeomCtx, geomCallback, 0, 0, rtreeFreeCallback
  141398. );
  141399. }
  141400. #if !SQLITE_CORE
  141401. #ifdef _WIN32
  141402. __declspec(dllexport)
  141403. #endif
  141404. SQLITE_API int sqlite3_rtree_init(
  141405. sqlite3 *db,
  141406. char **pzErrMsg,
  141407. const sqlite3_api_routines *pApi
  141408. ){
  141409. SQLITE_EXTENSION_INIT2(pApi)
  141410. return sqlite3RtreeInit(db);
  141411. }
  141412. #endif
  141413. #endif
  141414. /************** End of rtree.c ***********************************************/
  141415. /************** Begin file icu.c *********************************************/
  141416. /*
  141417. ** 2007 May 6
  141418. **
  141419. ** The author disclaims copyright to this source code. In place of
  141420. ** a legal notice, here is a blessing:
  141421. **
  141422. ** May you do good and not evil.
  141423. ** May you find forgiveness for yourself and forgive others.
  141424. ** May you share freely, never taking more than you give.
  141425. **
  141426. *************************************************************************
  141427. ** $Id: icu.c,v 1.7 2007/12/13 21:54:11 drh Exp $
  141428. **
  141429. ** This file implements an integration between the ICU library
  141430. ** ("International Components for Unicode", an open-source library
  141431. ** for handling unicode data) and SQLite. The integration uses
  141432. ** ICU to provide the following to SQLite:
  141433. **
  141434. ** * An implementation of the SQL regexp() function (and hence REGEXP
  141435. ** operator) using the ICU uregex_XX() APIs.
  141436. **
  141437. ** * Implementations of the SQL scalar upper() and lower() functions
  141438. ** for case mapping.
  141439. **
  141440. ** * Integration of ICU and SQLite collation sequences.
  141441. **
  141442. ** * An implementation of the LIKE operator that uses ICU to
  141443. ** provide case-independent matching.
  141444. */
  141445. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ICU)
  141446. /* Include ICU headers */
  141447. #include <unicode/utypes.h>
  141448. #include <unicode/uregex.h>
  141449. #include <unicode/ustring.h>
  141450. #include <unicode/ucol.h>
  141451. /* #include <assert.h> */
  141452. #ifndef SQLITE_CORE
  141453. SQLITE_EXTENSION_INIT1
  141454. #else
  141455. #endif
  141456. /*
  141457. ** Maximum length (in bytes) of the pattern in a LIKE or GLOB
  141458. ** operator.
  141459. */
  141460. #ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
  141461. # define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
  141462. #endif
  141463. /*
  141464. ** Version of sqlite3_free() that is always a function, never a macro.
  141465. */
  141466. static void xFree(void *p){
  141467. sqlite3_free(p);
  141468. }
  141469. /*
  141470. ** Compare two UTF-8 strings for equality where the first string is
  141471. ** a "LIKE" expression. Return true (1) if they are the same and
  141472. ** false (0) if they are different.
  141473. */
  141474. static int icuLikeCompare(
  141475. const uint8_t *zPattern, /* LIKE pattern */
  141476. const uint8_t *zString, /* The UTF-8 string to compare against */
  141477. const UChar32 uEsc /* The escape character */
  141478. ){
  141479. static const int MATCH_ONE = (UChar32)'_';
  141480. static const int MATCH_ALL = (UChar32)'%';
  141481. int iPattern = 0; /* Current byte index in zPattern */
  141482. int iString = 0; /* Current byte index in zString */
  141483. int prevEscape = 0; /* True if the previous character was uEsc */
  141484. while( zPattern[iPattern]!=0 ){
  141485. /* Read (and consume) the next character from the input pattern. */
  141486. UChar32 uPattern;
  141487. U8_NEXT_UNSAFE(zPattern, iPattern, uPattern);
  141488. assert(uPattern!=0);
  141489. /* There are now 4 possibilities:
  141490. **
  141491. ** 1. uPattern is an unescaped match-all character "%",
  141492. ** 2. uPattern is an unescaped match-one character "_",
  141493. ** 3. uPattern is an unescaped escape character, or
  141494. ** 4. uPattern is to be handled as an ordinary character
  141495. */
  141496. if( !prevEscape && uPattern==MATCH_ALL ){
  141497. /* Case 1. */
  141498. uint8_t c;
  141499. /* Skip any MATCH_ALL or MATCH_ONE characters that follow a
  141500. ** MATCH_ALL. For each MATCH_ONE, skip one character in the
  141501. ** test string.
  141502. */
  141503. while( (c=zPattern[iPattern]) == MATCH_ALL || c == MATCH_ONE ){
  141504. if( c==MATCH_ONE ){
  141505. if( zString[iString]==0 ) return 0;
  141506. U8_FWD_1_UNSAFE(zString, iString);
  141507. }
  141508. iPattern++;
  141509. }
  141510. if( zPattern[iPattern]==0 ) return 1;
  141511. while( zString[iString] ){
  141512. if( icuLikeCompare(&zPattern[iPattern], &zString[iString], uEsc) ){
  141513. return 1;
  141514. }
  141515. U8_FWD_1_UNSAFE(zString, iString);
  141516. }
  141517. return 0;
  141518. }else if( !prevEscape && uPattern==MATCH_ONE ){
  141519. /* Case 2. */
  141520. if( zString[iString]==0 ) return 0;
  141521. U8_FWD_1_UNSAFE(zString, iString);
  141522. }else if( !prevEscape && uPattern==uEsc){
  141523. /* Case 3. */
  141524. prevEscape = 1;
  141525. }else{
  141526. /* Case 4. */
  141527. UChar32 uString;
  141528. U8_NEXT_UNSAFE(zString, iString, uString);
  141529. uString = u_foldCase(uString, U_FOLD_CASE_DEFAULT);
  141530. uPattern = u_foldCase(uPattern, U_FOLD_CASE_DEFAULT);
  141531. if( uString!=uPattern ){
  141532. return 0;
  141533. }
  141534. prevEscape = 0;
  141535. }
  141536. }
  141537. return zString[iString]==0;
  141538. }
  141539. /*
  141540. ** Implementation of the like() SQL function. This function implements
  141541. ** the build-in LIKE operator. The first argument to the function is the
  141542. ** pattern and the second argument is the string. So, the SQL statements:
  141543. **
  141544. ** A LIKE B
  141545. **
  141546. ** is implemented as like(B, A). If there is an escape character E,
  141547. **
  141548. ** A LIKE B ESCAPE E
  141549. **
  141550. ** is mapped to like(B, A, E).
  141551. */
  141552. static void icuLikeFunc(
  141553. sqlite3_context *context,
  141554. int argc,
  141555. sqlite3_value **argv
  141556. ){
  141557. const unsigned char *zA = sqlite3_value_text(argv[0]);
  141558. const unsigned char *zB = sqlite3_value_text(argv[1]);
  141559. UChar32 uEsc = 0;
  141560. /* Limit the length of the LIKE or GLOB pattern to avoid problems
  141561. ** of deep recursion and N*N behavior in patternCompare().
  141562. */
  141563. if( sqlite3_value_bytes(argv[0])>SQLITE_MAX_LIKE_PATTERN_LENGTH ){
  141564. sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
  141565. return;
  141566. }
  141567. if( argc==3 ){
  141568. /* The escape character string must consist of a single UTF-8 character.
  141569. ** Otherwise, return an error.
  141570. */
  141571. int nE= sqlite3_value_bytes(argv[2]);
  141572. const unsigned char *zE = sqlite3_value_text(argv[2]);
  141573. int i = 0;
  141574. if( zE==0 ) return;
  141575. U8_NEXT(zE, i, nE, uEsc);
  141576. if( i!=nE){
  141577. sqlite3_result_error(context,
  141578. "ESCAPE expression must be a single character", -1);
  141579. return;
  141580. }
  141581. }
  141582. if( zA && zB ){
  141583. sqlite3_result_int(context, icuLikeCompare(zA, zB, uEsc));
  141584. }
  141585. }
  141586. /*
  141587. ** This function is called when an ICU function called from within
  141588. ** the implementation of an SQL scalar function returns an error.
  141589. **
  141590. ** The scalar function context passed as the first argument is
  141591. ** loaded with an error message based on the following two args.
  141592. */
  141593. static void icuFunctionError(
  141594. sqlite3_context *pCtx, /* SQLite scalar function context */
  141595. const char *zName, /* Name of ICU function that failed */
  141596. UErrorCode e /* Error code returned by ICU function */
  141597. ){
  141598. char zBuf[128];
  141599. sqlite3_snprintf(128, zBuf, "ICU error: %s(): %s", zName, u_errorName(e));
  141600. zBuf[127] = '\0';
  141601. sqlite3_result_error(pCtx, zBuf, -1);
  141602. }
  141603. /*
  141604. ** Function to delete compiled regexp objects. Registered as
  141605. ** a destructor function with sqlite3_set_auxdata().
  141606. */
  141607. static void icuRegexpDelete(void *p){
  141608. URegularExpression *pExpr = (URegularExpression *)p;
  141609. uregex_close(pExpr);
  141610. }
  141611. /*
  141612. ** Implementation of SQLite REGEXP operator. This scalar function takes
  141613. ** two arguments. The first is a regular expression pattern to compile
  141614. ** the second is a string to match against that pattern. If either
  141615. ** argument is an SQL NULL, then NULL Is returned. Otherwise, the result
  141616. ** is 1 if the string matches the pattern, or 0 otherwise.
  141617. **
  141618. ** SQLite maps the regexp() function to the regexp() operator such
  141619. ** that the following two are equivalent:
  141620. **
  141621. ** zString REGEXP zPattern
  141622. ** regexp(zPattern, zString)
  141623. **
  141624. ** Uses the following ICU regexp APIs:
  141625. **
  141626. ** uregex_open()
  141627. ** uregex_matches()
  141628. ** uregex_close()
  141629. */
  141630. static void icuRegexpFunc(sqlite3_context *p, int nArg, sqlite3_value **apArg){
  141631. UErrorCode status = U_ZERO_ERROR;
  141632. URegularExpression *pExpr;
  141633. UBool res;
  141634. const UChar *zString = sqlite3_value_text16(apArg[1]);
  141635. (void)nArg; /* Unused parameter */
  141636. /* If the left hand side of the regexp operator is NULL,
  141637. ** then the result is also NULL.
  141638. */
  141639. if( !zString ){
  141640. return;
  141641. }
  141642. pExpr = sqlite3_get_auxdata(p, 0);
  141643. if( !pExpr ){
  141644. const UChar *zPattern = sqlite3_value_text16(apArg[0]);
  141645. if( !zPattern ){
  141646. return;
  141647. }
  141648. pExpr = uregex_open(zPattern, -1, 0, 0, &status);
  141649. if( U_SUCCESS(status) ){
  141650. sqlite3_set_auxdata(p, 0, pExpr, icuRegexpDelete);
  141651. }else{
  141652. assert(!pExpr);
  141653. icuFunctionError(p, "uregex_open", status);
  141654. return;
  141655. }
  141656. }
  141657. /* Configure the text that the regular expression operates on. */
  141658. uregex_setText(pExpr, zString, -1, &status);
  141659. if( !U_SUCCESS(status) ){
  141660. icuFunctionError(p, "uregex_setText", status);
  141661. return;
  141662. }
  141663. /* Attempt the match */
  141664. res = uregex_matches(pExpr, 0, &status);
  141665. if( !U_SUCCESS(status) ){
  141666. icuFunctionError(p, "uregex_matches", status);
  141667. return;
  141668. }
  141669. /* Set the text that the regular expression operates on to a NULL
  141670. ** pointer. This is not really necessary, but it is tidier than
  141671. ** leaving the regular expression object configured with an invalid
  141672. ** pointer after this function returns.
  141673. */
  141674. uregex_setText(pExpr, 0, 0, &status);
  141675. /* Return 1 or 0. */
  141676. sqlite3_result_int(p, res ? 1 : 0);
  141677. }
  141678. /*
  141679. ** Implementations of scalar functions for case mapping - upper() and
  141680. ** lower(). Function upper() converts its input to upper-case (ABC).
  141681. ** Function lower() converts to lower-case (abc).
  141682. **
  141683. ** ICU provides two types of case mapping, "general" case mapping and
  141684. ** "language specific". Refer to ICU documentation for the differences
  141685. ** between the two.
  141686. **
  141687. ** To utilise "general" case mapping, the upper() or lower() scalar
  141688. ** functions are invoked with one argument:
  141689. **
  141690. ** upper('ABC') -> 'abc'
  141691. ** lower('abc') -> 'ABC'
  141692. **
  141693. ** To access ICU "language specific" case mapping, upper() or lower()
  141694. ** should be invoked with two arguments. The second argument is the name
  141695. ** of the locale to use. Passing an empty string ("") or SQL NULL value
  141696. ** as the second argument is the same as invoking the 1 argument version
  141697. ** of upper() or lower().
  141698. **
  141699. ** lower('I', 'en_us') -> 'i'
  141700. ** lower('I', 'tr_tr') -> 'ı' (small dotless i)
  141701. **
  141702. ** http://www.icu-project.org/userguide/posix.html#case_mappings
  141703. */
  141704. static void icuCaseFunc16(sqlite3_context *p, int nArg, sqlite3_value **apArg){
  141705. const UChar *zInput;
  141706. UChar *zOutput;
  141707. int nInput;
  141708. int nOutput;
  141709. UErrorCode status = U_ZERO_ERROR;
  141710. const char *zLocale = 0;
  141711. assert(nArg==1 || nArg==2);
  141712. if( nArg==2 ){
  141713. zLocale = (const char *)sqlite3_value_text(apArg[1]);
  141714. }
  141715. zInput = sqlite3_value_text16(apArg[0]);
  141716. if( !zInput ){
  141717. return;
  141718. }
  141719. nInput = sqlite3_value_bytes16(apArg[0]);
  141720. nOutput = nInput * 2 + 2;
  141721. zOutput = sqlite3_malloc(nOutput);
  141722. if( !zOutput ){
  141723. return;
  141724. }
  141725. if( sqlite3_user_data(p) ){
  141726. u_strToUpper(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status);
  141727. }else{
  141728. u_strToLower(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status);
  141729. }
  141730. if( !U_SUCCESS(status) ){
  141731. icuFunctionError(p, "u_strToLower()/u_strToUpper", status);
  141732. return;
  141733. }
  141734. sqlite3_result_text16(p, zOutput, -1, xFree);
  141735. }
  141736. /*
  141737. ** Collation sequence destructor function. The pCtx argument points to
  141738. ** a UCollator structure previously allocated using ucol_open().
  141739. */
  141740. static void icuCollationDel(void *pCtx){
  141741. UCollator *p = (UCollator *)pCtx;
  141742. ucol_close(p);
  141743. }
  141744. /*
  141745. ** Collation sequence comparison function. The pCtx argument points to
  141746. ** a UCollator structure previously allocated using ucol_open().
  141747. */
  141748. static int icuCollationColl(
  141749. void *pCtx,
  141750. int nLeft,
  141751. const void *zLeft,
  141752. int nRight,
  141753. const void *zRight
  141754. ){
  141755. UCollationResult res;
  141756. UCollator *p = (UCollator *)pCtx;
  141757. res = ucol_strcoll(p, (UChar *)zLeft, nLeft/2, (UChar *)zRight, nRight/2);
  141758. switch( res ){
  141759. case UCOL_LESS: return -1;
  141760. case UCOL_GREATER: return +1;
  141761. case UCOL_EQUAL: return 0;
  141762. }
  141763. assert(!"Unexpected return value from ucol_strcoll()");
  141764. return 0;
  141765. }
  141766. /*
  141767. ** Implementation of the scalar function icu_load_collation().
  141768. **
  141769. ** This scalar function is used to add ICU collation based collation
  141770. ** types to an SQLite database connection. It is intended to be called
  141771. ** as follows:
  141772. **
  141773. ** SELECT icu_load_collation(<locale>, <collation-name>);
  141774. **
  141775. ** Where <locale> is a string containing an ICU locale identifier (i.e.
  141776. ** "en_AU", "tr_TR" etc.) and <collation-name> is the name of the
  141777. ** collation sequence to create.
  141778. */
  141779. static void icuLoadCollation(
  141780. sqlite3_context *p,
  141781. int nArg,
  141782. sqlite3_value **apArg
  141783. ){
  141784. sqlite3 *db = (sqlite3 *)sqlite3_user_data(p);
  141785. UErrorCode status = U_ZERO_ERROR;
  141786. const char *zLocale; /* Locale identifier - (eg. "jp_JP") */
  141787. const char *zName; /* SQL Collation sequence name (eg. "japanese") */
  141788. UCollator *pUCollator; /* ICU library collation object */
  141789. int rc; /* Return code from sqlite3_create_collation_x() */
  141790. assert(nArg==2);
  141791. zLocale = (const char *)sqlite3_value_text(apArg[0]);
  141792. zName = (const char *)sqlite3_value_text(apArg[1]);
  141793. if( !zLocale || !zName ){
  141794. return;
  141795. }
  141796. pUCollator = ucol_open(zLocale, &status);
  141797. if( !U_SUCCESS(status) ){
  141798. icuFunctionError(p, "ucol_open", status);
  141799. return;
  141800. }
  141801. assert(p);
  141802. rc = sqlite3_create_collation_v2(db, zName, SQLITE_UTF16, (void *)pUCollator,
  141803. icuCollationColl, icuCollationDel
  141804. );
  141805. if( rc!=SQLITE_OK ){
  141806. ucol_close(pUCollator);
  141807. sqlite3_result_error(p, "Error registering collation function", -1);
  141808. }
  141809. }
  141810. /*
  141811. ** Register the ICU extension functions with database db.
  141812. */
  141813. SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db){
  141814. struct IcuScalar {
  141815. const char *zName; /* Function name */
  141816. int nArg; /* Number of arguments */
  141817. int enc; /* Optimal text encoding */
  141818. void *pContext; /* sqlite3_user_data() context */
  141819. void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
  141820. } scalars[] = {
  141821. {"regexp", 2, SQLITE_ANY, 0, icuRegexpFunc},
  141822. {"lower", 1, SQLITE_UTF16, 0, icuCaseFunc16},
  141823. {"lower", 2, SQLITE_UTF16, 0, icuCaseFunc16},
  141824. {"upper", 1, SQLITE_UTF16, (void*)1, icuCaseFunc16},
  141825. {"upper", 2, SQLITE_UTF16, (void*)1, icuCaseFunc16},
  141826. {"lower", 1, SQLITE_UTF8, 0, icuCaseFunc16},
  141827. {"lower", 2, SQLITE_UTF8, 0, icuCaseFunc16},
  141828. {"upper", 1, SQLITE_UTF8, (void*)1, icuCaseFunc16},
  141829. {"upper", 2, SQLITE_UTF8, (void*)1, icuCaseFunc16},
  141830. {"like", 2, SQLITE_UTF8, 0, icuLikeFunc},
  141831. {"like", 3, SQLITE_UTF8, 0, icuLikeFunc},
  141832. {"icu_load_collation", 2, SQLITE_UTF8, (void*)db, icuLoadCollation},
  141833. };
  141834. int rc = SQLITE_OK;
  141835. int i;
  141836. for(i=0; rc==SQLITE_OK && i<(int)(sizeof(scalars)/sizeof(scalars[0])); i++){
  141837. struct IcuScalar *p = &scalars[i];
  141838. rc = sqlite3_create_function(
  141839. db, p->zName, p->nArg, p->enc, p->pContext, p->xFunc, 0, 0
  141840. );
  141841. }
  141842. return rc;
  141843. }
  141844. #if !SQLITE_CORE
  141845. #ifdef _WIN32
  141846. __declspec(dllexport)
  141847. #endif
  141848. SQLITE_API int sqlite3_icu_init(
  141849. sqlite3 *db,
  141850. char **pzErrMsg,
  141851. const sqlite3_api_routines *pApi
  141852. ){
  141853. SQLITE_EXTENSION_INIT2(pApi)
  141854. return sqlite3IcuInit(db);
  141855. }
  141856. #endif
  141857. #endif
  141858. /************** End of icu.c *************************************************/
  141859. /************** Begin file fts3_icu.c ****************************************/
  141860. /*
  141861. ** 2007 June 22
  141862. **
  141863. ** The author disclaims copyright to this source code. In place of
  141864. ** a legal notice, here is a blessing:
  141865. **
  141866. ** May you do good and not evil.
  141867. ** May you find forgiveness for yourself and forgive others.
  141868. ** May you share freely, never taking more than you give.
  141869. **
  141870. *************************************************************************
  141871. ** This file implements a tokenizer for fts3 based on the ICU library.
  141872. */
  141873. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  141874. #ifdef SQLITE_ENABLE_ICU
  141875. /* #include <assert.h> */
  141876. /* #include <string.h> */
  141877. #include <unicode/ubrk.h>
  141878. /* #include <unicode/ucol.h> */
  141879. /* #include <unicode/ustring.h> */
  141880. #include <unicode/utf16.h>
  141881. typedef struct IcuTokenizer IcuTokenizer;
  141882. typedef struct IcuCursor IcuCursor;
  141883. struct IcuTokenizer {
  141884. sqlite3_tokenizer base;
  141885. char *zLocale;
  141886. };
  141887. struct IcuCursor {
  141888. sqlite3_tokenizer_cursor base;
  141889. UBreakIterator *pIter; /* ICU break-iterator object */
  141890. int nChar; /* Number of UChar elements in pInput */
  141891. UChar *aChar; /* Copy of input using utf-16 encoding */
  141892. int *aOffset; /* Offsets of each character in utf-8 input */
  141893. int nBuffer;
  141894. char *zBuffer;
  141895. int iToken;
  141896. };
  141897. /*
  141898. ** Create a new tokenizer instance.
  141899. */
  141900. static int icuCreate(
  141901. int argc, /* Number of entries in argv[] */
  141902. const char * const *argv, /* Tokenizer creation arguments */
  141903. sqlite3_tokenizer **ppTokenizer /* OUT: Created tokenizer */
  141904. ){
  141905. IcuTokenizer *p;
  141906. int n = 0;
  141907. if( argc>0 ){
  141908. n = strlen(argv[0])+1;
  141909. }
  141910. p = (IcuTokenizer *)sqlite3_malloc(sizeof(IcuTokenizer)+n);
  141911. if( !p ){
  141912. return SQLITE_NOMEM;
  141913. }
  141914. memset(p, 0, sizeof(IcuTokenizer));
  141915. if( n ){
  141916. p->zLocale = (char *)&p[1];
  141917. memcpy(p->zLocale, argv[0], n);
  141918. }
  141919. *ppTokenizer = (sqlite3_tokenizer *)p;
  141920. return SQLITE_OK;
  141921. }
  141922. /*
  141923. ** Destroy a tokenizer
  141924. */
  141925. static int icuDestroy(sqlite3_tokenizer *pTokenizer){
  141926. IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
  141927. sqlite3_free(p);
  141928. return SQLITE_OK;
  141929. }
  141930. /*
  141931. ** Prepare to begin tokenizing a particular string. The input
  141932. ** string to be tokenized is pInput[0..nBytes-1]. A cursor
  141933. ** used to incrementally tokenize this string is returned in
  141934. ** *ppCursor.
  141935. */
  141936. static int icuOpen(
  141937. sqlite3_tokenizer *pTokenizer, /* The tokenizer */
  141938. const char *zInput, /* Input string */
  141939. int nInput, /* Length of zInput in bytes */
  141940. sqlite3_tokenizer_cursor **ppCursor /* OUT: Tokenization cursor */
  141941. ){
  141942. IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
  141943. IcuCursor *pCsr;
  141944. const int32_t opt = U_FOLD_CASE_DEFAULT;
  141945. UErrorCode status = U_ZERO_ERROR;
  141946. int nChar;
  141947. UChar32 c;
  141948. int iInput = 0;
  141949. int iOut = 0;
  141950. *ppCursor = 0;
  141951. if( zInput==0 ){
  141952. nInput = 0;
  141953. zInput = "";
  141954. }else if( nInput<0 ){
  141955. nInput = strlen(zInput);
  141956. }
  141957. nChar = nInput+1;
  141958. pCsr = (IcuCursor *)sqlite3_malloc(
  141959. sizeof(IcuCursor) + /* IcuCursor */
  141960. ((nChar+3)&~3) * sizeof(UChar) + /* IcuCursor.aChar[] */
  141961. (nChar+1) * sizeof(int) /* IcuCursor.aOffset[] */
  141962. );
  141963. if( !pCsr ){
  141964. return SQLITE_NOMEM;
  141965. }
  141966. memset(pCsr, 0, sizeof(IcuCursor));
  141967. pCsr->aChar = (UChar *)&pCsr[1];
  141968. pCsr->aOffset = (int *)&pCsr->aChar[(nChar+3)&~3];
  141969. pCsr->aOffset[iOut] = iInput;
  141970. U8_NEXT(zInput, iInput, nInput, c);
  141971. while( c>0 ){
  141972. int isError = 0;
  141973. c = u_foldCase(c, opt);
  141974. U16_APPEND(pCsr->aChar, iOut, nChar, c, isError);
  141975. if( isError ){
  141976. sqlite3_free(pCsr);
  141977. return SQLITE_ERROR;
  141978. }
  141979. pCsr->aOffset[iOut] = iInput;
  141980. if( iInput<nInput ){
  141981. U8_NEXT(zInput, iInput, nInput, c);
  141982. }else{
  141983. c = 0;
  141984. }
  141985. }
  141986. pCsr->pIter = ubrk_open(UBRK_WORD, p->zLocale, pCsr->aChar, iOut, &status);
  141987. if( !U_SUCCESS(status) ){
  141988. sqlite3_free(pCsr);
  141989. return SQLITE_ERROR;
  141990. }
  141991. pCsr->nChar = iOut;
  141992. ubrk_first(pCsr->pIter);
  141993. *ppCursor = (sqlite3_tokenizer_cursor *)pCsr;
  141994. return SQLITE_OK;
  141995. }
  141996. /*
  141997. ** Close a tokenization cursor previously opened by a call to icuOpen().
  141998. */
  141999. static int icuClose(sqlite3_tokenizer_cursor *pCursor){
  142000. IcuCursor *pCsr = (IcuCursor *)pCursor;
  142001. ubrk_close(pCsr->pIter);
  142002. sqlite3_free(pCsr->zBuffer);
  142003. sqlite3_free(pCsr);
  142004. return SQLITE_OK;
  142005. }
  142006. /*
  142007. ** Extract the next token from a tokenization cursor.
  142008. */
  142009. static int icuNext(
  142010. sqlite3_tokenizer_cursor *pCursor, /* Cursor returned by simpleOpen */
  142011. const char **ppToken, /* OUT: *ppToken is the token text */
  142012. int *pnBytes, /* OUT: Number of bytes in token */
  142013. int *piStartOffset, /* OUT: Starting offset of token */
  142014. int *piEndOffset, /* OUT: Ending offset of token */
  142015. int *piPosition /* OUT: Position integer of token */
  142016. ){
  142017. IcuCursor *pCsr = (IcuCursor *)pCursor;
  142018. int iStart = 0;
  142019. int iEnd = 0;
  142020. int nByte = 0;
  142021. while( iStart==iEnd ){
  142022. UChar32 c;
  142023. iStart = ubrk_current(pCsr->pIter);
  142024. iEnd = ubrk_next(pCsr->pIter);
  142025. if( iEnd==UBRK_DONE ){
  142026. return SQLITE_DONE;
  142027. }
  142028. while( iStart<iEnd ){
  142029. int iWhite = iStart;
  142030. U16_NEXT(pCsr->aChar, iWhite, pCsr->nChar, c);
  142031. if( u_isspace(c) ){
  142032. iStart = iWhite;
  142033. }else{
  142034. break;
  142035. }
  142036. }
  142037. assert(iStart<=iEnd);
  142038. }
  142039. do {
  142040. UErrorCode status = U_ZERO_ERROR;
  142041. if( nByte ){
  142042. char *zNew = sqlite3_realloc(pCsr->zBuffer, nByte);
  142043. if( !zNew ){
  142044. return SQLITE_NOMEM;
  142045. }
  142046. pCsr->zBuffer = zNew;
  142047. pCsr->nBuffer = nByte;
  142048. }
  142049. u_strToUTF8(
  142050. pCsr->zBuffer, pCsr->nBuffer, &nByte, /* Output vars */
  142051. &pCsr->aChar[iStart], iEnd-iStart, /* Input vars */
  142052. &status /* Output success/failure */
  142053. );
  142054. } while( nByte>pCsr->nBuffer );
  142055. *ppToken = pCsr->zBuffer;
  142056. *pnBytes = nByte;
  142057. *piStartOffset = pCsr->aOffset[iStart];
  142058. *piEndOffset = pCsr->aOffset[iEnd];
  142059. *piPosition = pCsr->iToken++;
  142060. return SQLITE_OK;
  142061. }
  142062. /*
  142063. ** The set of routines that implement the simple tokenizer
  142064. */
  142065. static const sqlite3_tokenizer_module icuTokenizerModule = {
  142066. 0, /* iVersion */
  142067. icuCreate, /* xCreate */
  142068. icuDestroy, /* xCreate */
  142069. icuOpen, /* xOpen */
  142070. icuClose, /* xClose */
  142071. icuNext, /* xNext */
  142072. };
  142073. /*
  142074. ** Set *ppModule to point at the implementation of the ICU tokenizer.
  142075. */
  142076. SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(
  142077. sqlite3_tokenizer_module const**ppModule
  142078. ){
  142079. *ppModule = &icuTokenizerModule;
  142080. }
  142081. #endif /* defined(SQLITE_ENABLE_ICU) */
  142082. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  142083. /************** End of fts3_icu.c ********************************************/